1: <?php
2:
3: /**
4: * Jyxo PHP Library
5: *
6: * LICENSE
7: *
8: * This source file is subject to the new BSD license that is bundled
9: * with this package in the file license.txt.
10: * It is also available through the world-wide-web at this URL:
11: * https://github.com/jyxo/php/blob/master/license.txt
12: */
13:
14: /**
15: * Utilities for working with arrays.
16: *
17: * @category Jyxo
18: * @package Jyxo_Spl
19: * @copyright Copyright (c) 2005-2011 Jyxo, s.r.o.
20: * @license https://github.com/jyxo/php/blob/master/license.txt
21: * @author Jakub Tománek
22: */
23: class Jyxo_Spl_ArrayUtil
24: {
25: /**
26: * Creates an array containing item range. Similar to range() but with closures.
27: * Params $low and $high are inclusive. If $low > $high, resulting array will be in descending order.
28: *
29: * @param mixed $low Minimal value
30: * @param mixed $high Maximal value
31: * @param Closure $step Closure which creates next value from current
32: * @param Closure $compare comparing closure for detecting if we're at the end of the range (Optional)
33: * @return array
34: */
35: public static function range($low, $high, Closure $step, Closure $compare = null)
36: {
37: $data = array($low);
38: $stepDown = $low > $high;
39: $compare = $compare ?: function ($a, $b) use ($stepDown) {
40: return $stepDown ? $a > $b : $a < $b;
41: };
42:
43: $current = $low;
44: while ($compare($current, $high)) {
45: $data[] = $current = $step($current);
46: }
47: return $data;
48: }
49:
50: /**
51: * Creates an associative array from iterator which doesn't return proper keys.
52: * Keys are generated by applying callback $key to the current value.
53: * It is also possible to apply another callback directly to the value.
54: * Key callback is called BEFORE value callback.
55: *
56: * Example:
57: * <code>
58: * $data = Jyxo_Spl_ArrayUtil::keymap($iterator, function(Object $object) {
59: * return $object->getId();
60: * });
61: * </code>
62: *
63: * @param Traversable $traversable Iterator
64: * @param Closure $key Closure for generating keys
65: * @param Closure $value Closure for modifying data (Optional)
66: * @return array
67: */
68: public static function keymap(Traversable $traversable, Closure $key, Closure $value = null)
69: {
70: $data = array();
71: foreach ($traversable as $item) {
72: $data[$key($item)] = $value ? $value($item) : $item;
73: }
74: return $data;
75: }
76: }
77: