PageRenderTime 34ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 0ms

/system/classes/Kohana/Arr.php

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