PageRenderTime 38ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/classes/kohana/arr.php

https://github.com/sittercity/core
PHP | 543 lines | 256 code | 44 blank | 243 comment | 26 complexity | bd0062d9e2e032c5352ece17d8274859 MD5 | raw file
  1. <?php defined('SYSPATH') or die('No direct access allowed.');
  2. /**
  3. * Array helper.
  4. *
  5. * @package Kohana
  6. * @category Helpers
  7. * @author Kohana Team
  8. * @copyright (c) 2007-2010 Kohana Team
  9. * @license http://kohanaframework.org/license
  10. */
  11. class Kohana_Arr {
  12. /**
  13. * @var string default delimiter for path()
  14. */
  15. public static $delimiter = '.';
  16. /**
  17. * Tests if an array is associative or not.
  18. *
  19. * // Returns TRUE
  20. * Arr::is_assoc(array('username' => 'john.doe'));
  21. *
  22. * // Returns FALSE
  23. * Arr::is_assoc('foo', 'bar');
  24. *
  25. * @param array array to check
  26. * @return boolean
  27. */
  28. public static function is_assoc(array $array)
  29. {
  30. // Keys of the array
  31. $keys = array_keys($array);
  32. // If the array keys of the keys match the keys, then the array must
  33. // not be associative (e.g. the keys array looked like {0:0, 1:1...}).
  34. return array_keys($keys) !== $keys;
  35. }
  36. /**
  37. * Test if a value is an array with an additional check for array-like objects.
  38. *
  39. * // Returns TRUE
  40. * Arr::is_array(array());
  41. * Arr::is_array(new ArrayObject);
  42. *
  43. * // Returns FALSE
  44. * Arr::is_array(FALSE);
  45. * Arr::is_array('not an array!');
  46. * Arr::is_array(Database::instance());
  47. *
  48. * @param mixed value to check
  49. * @return boolean
  50. */
  51. public static function is_array($value)
  52. {
  53. if (is_array($value))
  54. {
  55. // Definitely an array
  56. return TRUE;
  57. }
  58. else
  59. {
  60. // Possibly a Traversable object, functionally the same as an array
  61. return (is_object($value) AND $value instanceof Traversable);
  62. }
  63. }
  64. /**
  65. * Gets a value from an array using a dot separated path.
  66. *
  67. * // Get the value of $array['foo']['bar']
  68. * $value = Arr::path($array, 'foo.bar');
  69. *
  70. * Using a wildcard "*" will search intermediate arrays and return an array.
  71. *
  72. * // Get the values of "color" in theme
  73. * $colors = Arr::path($array, 'theme.*.color');
  74. *
  75. * // Using an array of keys
  76. * $colors = Arr::path($array, array('theme', '*', 'color'));
  77. *
  78. * @param array array to search
  79. * @param mixed key path string (delimiter separated) or array of keys
  80. * @param mixed default value if the path is not set
  81. * @param string key path delimiter
  82. * @return mixed
  83. */
  84. public static function path($array, $path, $default = NULL, $delimiter = NULL)
  85. {
  86. if ( ! Arr::is_array($array))
  87. {
  88. // This is not an array!
  89. return $default;
  90. }
  91. if (is_array($path))
  92. {
  93. // The path has already been separated into keys
  94. $keys = $path;
  95. }
  96. else
  97. {
  98. if (array_key_exists($path, $array))
  99. {
  100. // No need to do extra processing
  101. return $array[$path];
  102. }
  103. if ($delimiter === NULL)
  104. {
  105. // Use the default delimiter
  106. $delimiter = Arr::$delimiter;
  107. }
  108. // Remove starting delimiters and spaces
  109. $path = ltrim($path, "{$delimiter} ");
  110. // Remove ending delimiters, spaces, and wildcards
  111. $path = rtrim($path, "{$delimiter} *");
  112. // Split the keys by delimiter
  113. $keys = explode($delimiter, $path);
  114. }
  115. do
  116. {
  117. $key = array_shift($keys);
  118. if (ctype_digit($key))
  119. {
  120. // Make the key an integer
  121. $key = (int) $key;
  122. }
  123. if (isset($array[$key]))
  124. {
  125. if ($keys)
  126. {
  127. if (Arr::is_array($array[$key]))
  128. {
  129. // Dig down into the next part of the path
  130. $array = $array[$key];
  131. }
  132. else
  133. {
  134. // Unable to dig deeper
  135. break;
  136. }
  137. }
  138. else
  139. {
  140. // Found the path requested
  141. return $array[$key];
  142. }
  143. }
  144. elseif ($key === '*')
  145. {
  146. // Handle wildcards
  147. $values = array();
  148. foreach ($array as $arr)
  149. {
  150. if ($value = Arr::path($arr, implode('.', $keys)))
  151. {
  152. $values[] = $value;
  153. }
  154. }
  155. if ($values)
  156. {
  157. // Found the values requested
  158. return $values;
  159. }
  160. else
  161. {
  162. // Unable to dig deeper
  163. break;
  164. }
  165. }
  166. else
  167. {
  168. // Unable to dig deeper
  169. break;
  170. }
  171. }
  172. while ($keys);
  173. // Unable to find the value requested
  174. return $default;
  175. }
  176. /**
  177. * Fill an array with a range of numbers.
  178. *
  179. * // Fill an array with values 5, 10, 15, 20
  180. * $values = Arr::range(5, 20);
  181. *
  182. * @param integer stepping
  183. * @param integer ending number
  184. * @return array
  185. */
  186. public static function range($step = 10, $max = 100)
  187. {
  188. if ($step < 1)
  189. return array();
  190. $array = array();
  191. for ($i = $step; $i <= $max; $i += $step)
  192. {
  193. $array[$i] = $i;
  194. }
  195. return $array;
  196. }
  197. /**
  198. * Retrieve a single key from an array. If the key does not exist in the
  199. * array, the default value will be returned instead.
  200. *
  201. * // Get the value "username" from $_POST, if it exists
  202. * $username = Arr::get($_POST, 'username');
  203. *
  204. * // Get the value "sorting" from $_GET, if it exists
  205. * $sorting = Arr::get($_GET, 'sorting');
  206. *
  207. * @param array array to extract from
  208. * @param string key name
  209. * @param mixed default value
  210. * @return mixed
  211. */
  212. public static function get($array, $key, $default = NULL)
  213. {
  214. return isset($array[$key]) ? $array[$key] : $default;
  215. }
  216. /**
  217. * Retrieves multiple keys from an array. If the key does not exist in the
  218. * array, the default value will be added instead.
  219. *
  220. * // Get the values "username", "password" from $_POST
  221. * $auth = Arr::extract($_POST, array('username', 'password'));
  222. *
  223. * @param array array to extract keys from
  224. * @param array list of key names
  225. * @param mixed default value
  226. * @return array
  227. */
  228. public static function extract($array, array $keys, $default = NULL)
  229. {
  230. $found = array();
  231. foreach ($keys as $key)
  232. {
  233. $found[$key] = isset($array[$key]) ? $array[$key] : $default;
  234. }
  235. return $found;
  236. }
  237. /**
  238. * Retrieves muliple single-key values from a list of arrays.
  239. *
  240. * // Get all of the "id" values from a result
  241. * $ids = Arr::pluck($result, 'id');
  242. *
  243. * [!!] A list of arrays is an array that contains arrays, eg: array(array $a, array $b, array $c, ...)
  244. *
  245. * @param array list of arrays to check
  246. * @param string key to pluck
  247. * @return array
  248. */
  249. public static function pluck($array, $key)
  250. {
  251. $values = array();
  252. foreach ($array as $row)
  253. {
  254. if (isset($row[$key]))
  255. {
  256. // Found a value in this row
  257. $values[] = $row[$key];
  258. }
  259. }
  260. return $values;
  261. }
  262. /**
  263. * Binary search algorithm.
  264. *
  265. * @deprecated Use [array_search](http://php.net/array_search) instead
  266. *
  267. * @param mixed the value to search for
  268. * @param array an array of values to search in
  269. * @param boolean sort the array now
  270. * @return integer the index of the match
  271. * @return FALSE no matching index found
  272. */
  273. public static function binary_search($needle, $haystack, $sort = FALSE)
  274. {
  275. return array_search($needle, $haystack);
  276. }
  277. /**
  278. * Adds a value to the beginning of an associative array.
  279. *
  280. * // Add an empty value to the start of a select list
  281. * Arr::unshift_assoc($array, 'none', 'Select a value');
  282. *
  283. * @param array array to modify
  284. * @param string array key name
  285. * @param mixed array value
  286. * @return array
  287. */
  288. public static function unshift( array & $array, $key, $val)
  289. {
  290. $array = array_reverse($array, TRUE);
  291. $array[$key] = $val;
  292. $array = array_reverse($array, TRUE);
  293. return $array;
  294. }
  295. /**
  296. * Recursive version of [array_map](http://php.net/array_map), applies the
  297. * same callback to all elements in an array, including sub-arrays.
  298. *
  299. * // Apply "strip_tags" to every element in the array
  300. * $array = Arr::map('strip_tags', $array);
  301. *
  302. * [!!] Unlike `array_map`, this method requires a callback and will only map
  303. * a single array.
  304. *
  305. * @param mixed callback applied to every element in the array
  306. * @param array array to map
  307. * @return array
  308. */
  309. public static function map($callback, $array)
  310. {
  311. foreach ($array as $key => $val)
  312. {
  313. if (is_array($val))
  314. {
  315. $array[$key] = Arr::map($callback, $val);
  316. }
  317. else
  318. {
  319. $array[$key] = call_user_func($callback, $val);
  320. }
  321. }
  322. return $array;
  323. }
  324. /**
  325. * Merges one or more arrays recursively and preserves all keys.
  326. * Note that this does not work the same as [array_merge_recursive](http://php.net/array_merge_recursive)!
  327. *
  328. * $john = array('name' => 'john', 'children' => array('fred', 'paul', 'sally', 'jane'));
  329. * $mary = array('name' => 'mary', 'children' => array('jane'));
  330. *
  331. * // John and Mary are married, merge them together
  332. * $john = Arr::merge($john, $mary);
  333. *
  334. * // The output of $john will now be:
  335. * array('name' => 'mary', 'children' => array('fred', 'paul', 'sally', 'jane'))
  336. *
  337. * @param array initial array
  338. * @param array array to merge
  339. * @param array ...
  340. * @return array
  341. */
  342. public static function merge(array $a1, array $a2)
  343. {
  344. $result = array();
  345. for ($i = 0, $total = func_num_args(); $i < $total; $i++)
  346. {
  347. // Get the next array
  348. $arr = func_get_arg($i);
  349. // Is the array associative?
  350. $assoc = Arr::is_assoc($arr);
  351. foreach ($arr as $key => $val)
  352. {
  353. if (isset($result[$key]))
  354. {
  355. if (is_array($val) AND is_array($result[$key]))
  356. {
  357. if (Arr::is_assoc($val))
  358. {
  359. // Associative arrays are merged recursively
  360. $result[$key] = Arr::merge($result[$key], $val);
  361. }
  362. else
  363. {
  364. $result[$key] = Arr::merge($result[$key], $val);
  365. }
  366. }
  367. else
  368. {
  369. if ($assoc)
  370. {
  371. // Associative values are replaced
  372. $result[$key] = $val;
  373. }
  374. elseif ( ! in_array($val, $result, TRUE))
  375. {
  376. // Indexed values are added only if they do not yet exist
  377. $result[] = $val;
  378. }
  379. }
  380. }
  381. else
  382. {
  383. // New values are added
  384. $result[$key] = $val;
  385. }
  386. }
  387. }
  388. return $result;
  389. }
  390. /**
  391. * Overwrites an array with values from input arrays.
  392. * Keys that do not exist in the first array will not be added!
  393. *
  394. * $a1 = array('name' => 'john', 'mood' => 'happy', 'food' => 'bacon');
  395. * $a2 = array('name' => 'jack', 'food' => 'tacos', 'drink' => 'beer');
  396. *
  397. * // Overwrite the values of $a1 with $a2
  398. * $array = Arr::overwrite($a1, $a2);
  399. *
  400. * // The output of $array will now be:
  401. * array('name' => 'jack', 'mood' => 'happy', 'food' => 'bacon')
  402. *
  403. * @param array master array
  404. * @param array input arrays that will overwrite existing values
  405. * @return array
  406. */
  407. public static function overwrite($array1, $array2)
  408. {
  409. foreach (array_intersect_key($array2, $array1) as $key => $value)
  410. {
  411. $array1[$key] = $value;
  412. }
  413. if (func_num_args() > 2)
  414. {
  415. foreach (array_slice(func_get_args(), 2) as $array2)
  416. {
  417. foreach (array_intersect_key($array2, $array1) as $key => $value)
  418. {
  419. $array1[$key] = $value;
  420. }
  421. }
  422. }
  423. return $array1;
  424. }
  425. /**
  426. * Creates a callable function and parameter list from a string representation.
  427. * Note that this function does not validate the callback string.
  428. *
  429. * // Get the callback function and parameters
  430. * list($func, $params) = Arr::callback('Foo::bar(apple,orange)');
  431. *
  432. * // Get the result of the callback
  433. * $result = call_user_func_array($func, $params);
  434. *
  435. * @param string callback string
  436. * @return array function, params
  437. */
  438. public static function callback($str)
  439. {
  440. // Overloaded as parts are found
  441. $command = $params = NULL;
  442. // command[param,param]
  443. if (preg_match('/^([^\(]*+)\((.*)\)$/', $str, $match))
  444. {
  445. // command
  446. $command = $match[1];
  447. if ($match[2] !== '')
  448. {
  449. // param,param
  450. $params = preg_split('/(?<!\\\\),/', $match[2]);
  451. $params = str_replace('\,', ',', $params);
  452. }
  453. }
  454. else
  455. {
  456. // command
  457. $command = $str;
  458. }
  459. if (strpos($command, '::') !== FALSE)
  460. {
  461. // Create a static method callable command
  462. $command = explode('::', $command, 2);
  463. }
  464. return array($command, $params);
  465. }
  466. /**
  467. * Convert a multi-dimensional array into a single-dimensional array.
  468. *
  469. * $array = array('set' => array('one' => 'something'), 'two' => 'other');
  470. *
  471. * // Flatten the array
  472. * $array = Arr::flatten($array);
  473. *
  474. * // The array will now be
  475. * array('one' => 'something', 'two' => 'other');
  476. *
  477. * [!!] The keys of array values will be discarded.
  478. *
  479. * @param array array to flatten
  480. * @return array
  481. * @since 3.0.6
  482. */
  483. public static function flatten($array)
  484. {
  485. $flat = array();
  486. foreach ($array as $key => $value)
  487. {
  488. if (is_array($value))
  489. {
  490. $flat += Arr::flatten($value);
  491. }
  492. else
  493. {
  494. $flat[$key] = $value;
  495. }
  496. }
  497. return $flat;
  498. }
  499. } // End arr