PageRenderTime 62ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/public_html/system/classes/Kohana/Arr.php

https://bitbucket.org/rybadour/todo_list_site
PHP | 625 lines | 318 code | 50 blank | 257 comment | 35 complexity | 05d29a90ff0bca0eb2ec781424c2d4bd MD5 | raw file
  1. <?php defined('SYSPATH') OR die('No direct script access.');
  2. /**
  3. * Array helper.
  4. *
  5. * @package Kohana
  6. * @category Helpers
  7. * @author Kohana Team
  8. * @copyright (c) 2007-2012 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 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 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 array to search
  79. * @param mixed $path key path string (delimiter separated) or array of keys
  80. * @param mixed $default default value if the path is not set
  81. * @param string $delimiter 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. * Set a value on an array by path.
  178. *
  179. * @see Arr::path()
  180. * @param array $array Array to update
  181. * @param string $path Path
  182. * @param mixed $value Value to set
  183. * @param string $delimiter Path delimiter
  184. */
  185. public static function set_path( & $array, $path, $value, $delimiter = NULL)
  186. {
  187. if ( ! $delimiter)
  188. {
  189. // Use the default delimiter
  190. $delimiter = Arr::$delimiter;
  191. }
  192. // The path has already been separated into keys
  193. $keys = $path;
  194. if ( ! is_array($path))
  195. {
  196. // Split the keys by delimiter
  197. $keys = explode($delimiter, $path);
  198. }
  199. // Set current $array to inner-most array path
  200. while (count($keys) > 1)
  201. {
  202. $key = array_shift($keys);
  203. if (ctype_digit($key))
  204. {
  205. // Make the key an integer
  206. $key = (int) $key;
  207. }
  208. if ( ! isset($array[$key]))
  209. {
  210. $array[$key] = array();
  211. }
  212. $array = & $array[$key];
  213. }
  214. // Set key on inner-most array
  215. $array[array_shift($keys)] = $value;
  216. }
  217. /**
  218. * Fill an array with a range of numbers.
  219. *
  220. * // Fill an array with values 5, 10, 15, 20
  221. * $values = Arr::range(5, 20);
  222. *
  223. * @param integer $step stepping
  224. * @param integer $max ending number
  225. * @return array
  226. */
  227. public static function range($step = 10, $max = 100)
  228. {
  229. if ($step < 1)
  230. return array();
  231. $array = array();
  232. for ($i = $step; $i <= $max; $i += $step)
  233. {
  234. $array[$i] = $i;
  235. }
  236. return $array;
  237. }
  238. /**
  239. * Retrieve a single key from an array. If the key does not exist in the
  240. * array, the default value will be returned instead.
  241. *
  242. * // Get the value "username" from $_POST, if it exists
  243. * $username = Arr::get($_POST, 'username');
  244. *
  245. * // Get the value "sorting" from $_GET, if it exists
  246. * $sorting = Arr::get($_GET, 'sorting');
  247. *
  248. * @param array $array array to extract from
  249. * @param string $key key name
  250. * @param mixed $default default value
  251. * @return mixed
  252. */
  253. public static function get($array, $key, $default = NULL)
  254. {
  255. return isset($array[$key]) ? $array[$key] : $default;
  256. }
  257. /**
  258. * Retrieves multiple paths from an array. If the path does not exist in the
  259. * array, the default value will be added instead.
  260. *
  261. * // Get the values "username", "password" from $_POST
  262. * $auth = Arr::extract($_POST, array('username', 'password'));
  263. *
  264. * // Get the value "level1.level2a" from $data
  265. * $data = array('level1' => array('level2a' => 'value 1', 'level2b' => 'value 2'));
  266. * Arr::extract($data, array('level1.level2a', 'password'));
  267. *
  268. * @param array $array array to extract paths from
  269. * @param array $paths list of path
  270. * @param mixed $default default value
  271. * @return array
  272. */
  273. public static function extract($array, array $paths, $default = NULL)
  274. {
  275. $found = array();
  276. foreach ($paths as $path)
  277. {
  278. Arr::set_path($found, $path, Arr::path($array, $path, $default));
  279. }
  280. return $found;
  281. }
  282. /**
  283. * Retrieves muliple single-key values from a list of arrays.
  284. *
  285. * // Get all of the "id" values from a result
  286. * $ids = Arr::pluck($result, 'id');
  287. *
  288. * [!!] A list of arrays is an array that contains arrays, eg: array(array $a, array $b, array $c, ...)
  289. *
  290. * @param array $array list of arrays to check
  291. * @param string $key key to pluck
  292. * @return array
  293. */
  294. public static function pluck($array, $key)
  295. {
  296. $values = array();
  297. foreach ($array as $row)
  298. {
  299. if (isset($row[$key]))
  300. {
  301. // Found a value in this row
  302. $values[] = $row[$key];
  303. }
  304. }
  305. return $values;
  306. }
  307. /**
  308. * Adds a value to the beginning of an associative array.
  309. *
  310. * // Add an empty value to the start of a select list
  311. * Arr::unshift($array, 'none', 'Select a value');
  312. *
  313. * @param array $array array to modify
  314. * @param string $key array key name
  315. * @param mixed $val array value
  316. * @return array
  317. */
  318. public static function unshift( array & $array, $key, $val)
  319. {
  320. $array = array_reverse($array, TRUE);
  321. $array[$key] = $val;
  322. $array = array_reverse($array, TRUE);
  323. return $array;
  324. }
  325. /**
  326. * Recursive version of [array_map](http://php.net/array_map), applies one or more
  327. * callbacks to all elements in an array, including sub-arrays.
  328. *
  329. * // Apply "strip_tags" to every element in the array
  330. * $array = Arr::map('strip_tags', $array);
  331. *
  332. * // Apply $this->filter to every element in the array
  333. * $array = Arr::map(array(array($this,'filter')), $array);
  334. *
  335. * // Apply strip_tags and $this->filter to every element
  336. * $array = Arr::map(array('strip_tags',array($this,'filter')), $array);
  337. *
  338. * [!!] Because you can pass an array of callbacks, if you wish to use an array-form callback
  339. * you must nest it in an additional array as above. Calling Arr::map(array($this,'filter'), $array)
  340. * will cause an error.
  341. * [!!] Unlike `array_map`, this method requires a callback and will only map
  342. * a single array.
  343. *
  344. * @param mixed $callbacks array of callbacks to apply to every element in the array
  345. * @param array $array array to map
  346. * @param array $keys array of keys to apply to
  347. * @return array
  348. */
  349. public static function map($callbacks, $array, $keys = NULL)
  350. {
  351. foreach ($array as $key => $val)
  352. {
  353. if (is_array($val))
  354. {
  355. $array[$key] = Arr::map($callbacks, $array[$key]);
  356. }
  357. elseif ( ! is_array($keys) OR in_array($key, $keys))
  358. {
  359. if (is_array($callbacks))
  360. {
  361. foreach ($callbacks as $cb)
  362. {
  363. $array[$key] = call_user_func($cb, $array[$key]);
  364. }
  365. }
  366. else
  367. {
  368. $array[$key] = call_user_func($callbacks, $array[$key]);
  369. }
  370. }
  371. }
  372. return $array;
  373. }
  374. /**
  375. * Recursively merge two or more arrays. Values in an associative array
  376. * overwrite previous values with the same key. Values in an indexed array
  377. * are appended, but only when they do not already exist in the result.
  378. *
  379. * Note that this does not work the same as [array_merge_recursive](http://php.net/array_merge_recursive)!
  380. *
  381. * $john = array('name' => 'john', 'children' => array('fred', 'paul', 'sally', 'jane'));
  382. * $mary = array('name' => 'mary', 'children' => array('jane'));
  383. *
  384. * // John and Mary are married, merge them together
  385. * $john = Arr::merge($john, $mary);
  386. *
  387. * // The output of $john will now be:
  388. * array('name' => 'mary', 'children' => array('fred', 'paul', 'sally', 'jane'))
  389. *
  390. * @param array $array1 initial array
  391. * @param array $array2,... array to merge
  392. * @return array
  393. */
  394. public static function merge($array1, $array2)
  395. {
  396. if (Arr::is_assoc($array2))
  397. {
  398. foreach ($array2 as $key => $value)
  399. {
  400. if (is_array($value)
  401. AND isset($array1[$key])
  402. AND is_array($array1[$key])
  403. )
  404. {
  405. $array1[$key] = Arr::merge($array1[$key], $value);
  406. }
  407. else
  408. {
  409. $array1[$key] = $value;
  410. }
  411. }
  412. }
  413. else
  414. {
  415. foreach ($array2 as $value)
  416. {
  417. if ( ! in_array($value, $array1, TRUE))
  418. {
  419. $array1[] = $value;
  420. }
  421. }
  422. }
  423. if (func_num_args() > 2)
  424. {
  425. foreach (array_slice(func_get_args(), 2) as $array2)
  426. {
  427. if (Arr::is_assoc($array2))
  428. {
  429. foreach ($array2 as $key => $value)
  430. {
  431. if (is_array($value)
  432. AND isset($array1[$key])
  433. AND is_array($array1[$key])
  434. )
  435. {
  436. $array1[$key] = Arr::merge($array1[$key], $value);
  437. }
  438. else
  439. {
  440. $array1[$key] = $value;
  441. }
  442. }
  443. }
  444. else
  445. {
  446. foreach ($array2 as $value)
  447. {
  448. if ( ! in_array($value, $array1, TRUE))
  449. {
  450. $array1[] = $value;
  451. }
  452. }
  453. }
  454. }
  455. }
  456. return $array1;
  457. }
  458. /**
  459. * Overwrites an array with values from input arrays.
  460. * Keys that do not exist in the first array will not be added!
  461. *
  462. * $a1 = array('name' => 'john', 'mood' => 'happy', 'food' => 'bacon');
  463. * $a2 = array('name' => 'jack', 'food' => 'tacos', 'drink' => 'beer');
  464. *
  465. * // Overwrite the values of $a1 with $a2
  466. * $array = Arr::overwrite($a1, $a2);
  467. *
  468. * // The output of $array will now be:
  469. * array('name' => 'jack', 'mood' => 'happy', 'food' => 'tacos')
  470. *
  471. * @param array $array1 master array
  472. * @param array $array2 input arrays that will overwrite existing values
  473. * @return array
  474. */
  475. public static function overwrite($array1, $array2)
  476. {
  477. foreach (array_intersect_key($array2, $array1) as $key => $value)
  478. {
  479. $array1[$key] = $value;
  480. }
  481. if (func_num_args() > 2)
  482. {
  483. foreach (array_slice(func_get_args(), 2) as $array2)
  484. {
  485. foreach (array_intersect_key($array2, $array1) as $key => $value)
  486. {
  487. $array1[$key] = $value;
  488. }
  489. }
  490. }
  491. return $array1;
  492. }
  493. /**
  494. * Creates a callable function and parameter list from a string representation.
  495. * Note that this function does not validate the callback string.
  496. *
  497. * // Get the callback function and parameters
  498. * list($func, $params) = Arr::callback('Foo::bar(apple,orange)');
  499. *
  500. * // Get the result of the callback
  501. * $result = call_user_func_array($func, $params);
  502. *
  503. * @param string $str callback string
  504. * @return array function, params
  505. */
  506. public static function callback($str)
  507. {
  508. // Overloaded as parts are found
  509. $command = $params = NULL;
  510. // command[param,param]
  511. if (preg_match('/^([^\(]*+)\((.*)\)$/', $str, $match))
  512. {
  513. // command
  514. $command = $match[1];
  515. if ($match[2] !== '')
  516. {
  517. // param,param
  518. $params = preg_split('/(?<!\\\\),/', $match[2]);
  519. $params = str_replace('\,', ',', $params);
  520. }
  521. }
  522. else
  523. {
  524. // command
  525. $command = $str;
  526. }
  527. if (strpos($command, '::') !== FALSE)
  528. {
  529. // Create a static method callable command
  530. $command = explode('::', $command, 2);
  531. }
  532. return array($command, $params);
  533. }
  534. /**
  535. * Convert a multi-dimensional array into a single-dimensional array.
  536. *
  537. * $array = array('set' => array('one' => 'something'), 'two' => 'other');
  538. *
  539. * // Flatten the array
  540. * $array = Arr::flatten($array);
  541. *
  542. * // The array will now be
  543. * array('one' => 'something', 'two' => 'other');
  544. *
  545. * [!!] The keys of array values will be discarded.
  546. *
  547. * @param array $array array to flatten
  548. * @return array
  549. * @since 3.0.6
  550. */
  551. public static function flatten($array)
  552. {
  553. $is_assoc = Arr::is_assoc($array);
  554. $flat = array();
  555. foreach ($array as $key => $value)
  556. {
  557. if (is_array($value))
  558. {
  559. $flat = array_merge($flat, Arr::flatten($value));
  560. }
  561. else
  562. {
  563. if ($is_assoc)
  564. {
  565. $flat[$key] = $value;
  566. }
  567. else
  568. {
  569. $flat[] = $value;
  570. }
  571. }
  572. }
  573. return $flat;
  574. }
  575. }