PageRenderTime 60ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Utility/Set.php

https://bitbucket.org/dosm123/crm
PHP | 1218 lines | 832 code | 78 blank | 308 comment | 268 complexity | efb25df233c2adcbcadb3d73cc777598 MD5 | raw file
Possible License(s): LGPL-3.0, GPL-3.0, LGPL-2.1
  1. <?php
  2. /**
  3. * Library of array functions for Cake.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package Cake.Utility
  16. * @since CakePHP(tm) v 1.2.0
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('String', 'Utility');
  20. /**
  21. * Class used for manipulation of arrays.
  22. *
  23. * @package Cake.Utility
  24. */
  25. class Set {
  26. /**
  27. * This function can be thought of as a hybrid between PHP's array_merge and array_merge_recursive. The difference
  28. * to the two is that if an array key contains another array then the function behaves recursive (unlike array_merge)
  29. * but does not do if for keys containing strings (unlike array_merge_recursive).
  30. *
  31. * Since this method emulates `array_merge`, it will re-order numeric keys. When combined with out of
  32. * order numeric keys containing arrays, results can be lossy.
  33. *
  34. * Note: This function will work with an unlimited amount of arguments and typecasts non-array
  35. * parameters into arrays.
  36. *
  37. * @param array $arr1 Array to be merged
  38. * @param array $arr2 Array to merge with
  39. * @return array Merged array
  40. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::merge
  41. */
  42. public static function merge($arr1, $arr2 = null) {
  43. $args = func_get_args();
  44. $r = (array)current($args);
  45. while (($arg = next($args)) !== false) {
  46. foreach ((array)$arg as $key => $val) {
  47. if (!empty($r[$key]) && is_array($r[$key]) && is_array($val)) {
  48. $r[$key] = Set::merge($r[$key], $val);
  49. } elseif (is_int($key)) {
  50. $r[] = $val;
  51. } else {
  52. $r[$key] = $val;
  53. }
  54. }
  55. }
  56. return $r;
  57. }
  58. /**
  59. * Filters empty elements out of a route array, excluding '0'.
  60. *
  61. * @param array $var Either an array to filter, or value when in callback
  62. * @return mixed Either filtered array, or true/false when in callback
  63. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::filter
  64. */
  65. public static function filter(array $var) {
  66. foreach ($var as $k => $v) {
  67. if (is_array($v)) {
  68. $var[$k] = Set::filter($v);
  69. }
  70. }
  71. return array_filter($var, array('Set', '_filter'));
  72. }
  73. /**
  74. * Set::filter callback function
  75. *
  76. * @param array $var Array to filter.
  77. * @return boolean
  78. */
  79. protected static function _filter($var) {
  80. if ($var === 0 || $var === '0' || !empty($var)) {
  81. return true;
  82. }
  83. return false;
  84. }
  85. /**
  86. * Pushes the differences in $array2 onto the end of $array
  87. *
  88. * @param mixed $array Original array
  89. * @param mixed $array2 Differences to push
  90. * @return array Combined array
  91. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::pushDiff
  92. */
  93. public static function pushDiff($array, $array2) {
  94. if (empty($array) && !empty($array2)) {
  95. return $array2;
  96. }
  97. if (!empty($array) && !empty($array2)) {
  98. foreach ($array2 as $key => $value) {
  99. if (!array_key_exists($key, $array)) {
  100. $array[$key] = $value;
  101. } else {
  102. if (is_array($value)) {
  103. $array[$key] = Set::pushDiff($array[$key], $array2[$key]);
  104. }
  105. }
  106. }
  107. }
  108. return $array;
  109. }
  110. /**
  111. * Maps the contents of the Set object to an object hierarchy.
  112. * Maintains numeric keys as arrays of objects
  113. *
  114. * @param string $class A class name of the type of object to map to
  115. * @param string $tmp A temporary class name used as $class if $class is an array
  116. * @return object Hierarchical object
  117. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::map
  118. */
  119. public static function map($class = 'stdClass', $tmp = 'stdClass') {
  120. if (is_array($class)) {
  121. $val = $class;
  122. $class = $tmp;
  123. }
  124. if (empty($val)) {
  125. return null;
  126. }
  127. return Set::_map($val, $class);
  128. }
  129. /**
  130. * Maps the given value as an object. If $value is an object,
  131. * it returns $value. Otherwise it maps $value as an object of
  132. * type $class, and if primary assign _name_ $key on first array.
  133. * If $value is not empty, it will be used to set properties of
  134. * returned object (recursively). If $key is numeric will maintain array
  135. * structure
  136. *
  137. * @param array $array Array to map
  138. * @param string $class Class name
  139. * @param boolean $primary whether to assign first array key as the _name_
  140. * @return mixed Mapped object
  141. */
  142. protected static function _map(&$array, $class, $primary = false) {
  143. if ($class === true) {
  144. $out = new stdClass;
  145. } else {
  146. $out = new $class;
  147. }
  148. if (is_array($array)) {
  149. $keys = array_keys($array);
  150. foreach ($array as $key => $value) {
  151. if ($keys[0] === $key && $class !== true) {
  152. $primary = true;
  153. }
  154. if (is_numeric($key)) {
  155. if (is_object($out)) {
  156. $out = get_object_vars($out);
  157. }
  158. $out[$key] = Set::_map($value, $class);
  159. if (is_object($out[$key])) {
  160. if ($primary !== true && is_array($value) && Set::countDim($value, true) === 2) {
  161. if (!isset($out[$key]->_name_)) {
  162. $out[$key]->_name_ = $primary;
  163. }
  164. }
  165. }
  166. } elseif (is_array($value)) {
  167. if ($primary === true) {
  168. if (!isset($out->_name_)) {
  169. $out->_name_ = $key;
  170. }
  171. $primary = false;
  172. foreach ($value as $key2 => $value2) {
  173. $out->{$key2} = Set::_map($value2, true);
  174. }
  175. } else {
  176. if (!is_numeric($key)) {
  177. $out->{$key} = Set::_map($value, true, $key);
  178. if (is_object($out->{$key}) && !is_numeric($key)) {
  179. if (!isset($out->{$key}->_name_)) {
  180. $out->{$key}->_name_ = $key;
  181. }
  182. }
  183. } else {
  184. $out->{$key} = Set::_map($value, true);
  185. }
  186. }
  187. } else {
  188. $out->{$key} = $value;
  189. }
  190. }
  191. } else {
  192. $out = $array;
  193. }
  194. return $out;
  195. }
  196. /**
  197. * Checks to see if all the values in the array are numeric
  198. *
  199. * @param array $array The array to check. If null, the value of the current Set object
  200. * @return boolean true if values are numeric, false otherwise
  201. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::numeric
  202. */
  203. public static function numeric($array = null) {
  204. if (empty($array)) {
  205. return null;
  206. }
  207. if ($array === range(0, count($array) - 1)) {
  208. return true;
  209. }
  210. $numeric = true;
  211. $keys = array_keys($array);
  212. $count = count($keys);
  213. for ($i = 0; $i < $count; $i++) {
  214. if (!is_numeric($array[$keys[$i]])) {
  215. $numeric = false;
  216. break;
  217. }
  218. }
  219. return $numeric;
  220. }
  221. /**
  222. * Return a value from an array list if the key exists.
  223. *
  224. * If a comma separated $list is passed arrays are numeric with the key of the first being 0
  225. * $list = 'no, yes' would translate to $list = array(0 => 'no', 1 => 'yes');
  226. *
  227. * If an array is used, keys can be strings example: array('no' => 0, 'yes' => 1);
  228. *
  229. * $list defaults to 0 = no 1 = yes if param is not passed
  230. *
  231. * @param mixed $select Key in $list to return
  232. * @param mixed $list can be an array or a comma-separated list.
  233. * @return string the value of the array key or null if no match
  234. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::enum
  235. */
  236. public static function enum($select, $list = null) {
  237. if (empty($list)) {
  238. $list = array('no', 'yes');
  239. }
  240. $return = null;
  241. $list = Set::normalize($list, false);
  242. if (array_key_exists($select, $list)) {
  243. $return = $list[$select];
  244. }
  245. return $return;
  246. }
  247. /**
  248. * Returns a series of values extracted from an array, formatted in a format string.
  249. *
  250. * @param array $data Source array from which to extract the data
  251. * @param string $format Format string into which values will be inserted, see sprintf()
  252. * @param array $keys An array containing one or more Set::extract()-style key paths
  253. * @return array An array of strings extracted from $keys and formatted with $format
  254. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::format
  255. */
  256. public static function format($data, $format, $keys) {
  257. $extracted = array();
  258. $count = count($keys);
  259. if (!$count) {
  260. return;
  261. }
  262. for ($i = 0; $i < $count; $i++) {
  263. $extracted[] = Set::extract($data, $keys[$i]);
  264. }
  265. $out = array();
  266. $data = $extracted;
  267. $count = count($data[0]);
  268. if (preg_match_all('/\{([0-9]+)\}/msi', $format, $keys2) && isset($keys2[1])) {
  269. $keys = $keys2[1];
  270. $format = preg_split('/\{([0-9]+)\}/msi', $format);
  271. $count2 = count($format);
  272. for ($j = 0; $j < $count; $j++) {
  273. $formatted = '';
  274. for ($i = 0; $i <= $count2; $i++) {
  275. if (isset($format[$i])) {
  276. $formatted .= $format[$i];
  277. }
  278. if (isset($keys[$i]) && isset($data[$keys[$i]][$j])) {
  279. $formatted .= $data[$keys[$i]][$j];
  280. }
  281. }
  282. $out[] = $formatted;
  283. }
  284. } else {
  285. $count2 = count($data);
  286. for ($j = 0; $j < $count; $j++) {
  287. $args = array();
  288. for ($i = 0; $i < $count2; $i++) {
  289. if (array_key_exists($j, $data[$i])) {
  290. $args[] = $data[$i][$j];
  291. }
  292. }
  293. $out[] = vsprintf($format, $args);
  294. }
  295. }
  296. return $out;
  297. }
  298. /**
  299. * Implements partial support for XPath 2.0. If $path does not contain a '/' the call
  300. * is delegated to Set::classicExtract(). Also the $path and $data arguments are
  301. * reversible.
  302. *
  303. * #### Currently implemented selectors:
  304. *
  305. * - /User/id (similar to the classic {n}.User.id)
  306. * - /User[2]/name (selects the name of the second User)
  307. * - /User[id>2] (selects all Users with an id > 2)
  308. * - /User[id>2][<5] (selects all Users with an id > 2 but < 5)
  309. * - /Post/Comment[author_name=john]/../name (Selects the name of all Posts that have at least one Comment written by john)
  310. * - /Posts[name] (Selects all Posts that have a 'name' key)
  311. * - /Comment/.[1] (Selects the contents of the first comment)
  312. * - /Comment/.[:last] (Selects the last comment)
  313. * - /Comment/.[:first] (Selects the first comment)
  314. * - /Comment[text=/cakephp/i] (Selects the all comments that have a text matching the regex /cakephp/i)
  315. * - /Comment/@* (Selects the all key names of all comments)
  316. *
  317. * #### Other limitations:
  318. *
  319. * - Only absolute paths starting with a single '/' are supported right now
  320. *
  321. * **Warning**: Even so it has plenty of unit tests the XPath support has not gone through a lot of
  322. * real-world testing. Please report Bugs as you find them. Suggestions for additional features to
  323. * implement are also very welcome!
  324. *
  325. * @param string $path An absolute XPath 2.0 path
  326. * @param array $data An array of data to extract from
  327. * @param array $options Currently only supports 'flatten' which can be disabled for higher XPath-ness
  328. * @return array An array of matched items
  329. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::extract
  330. */
  331. public static function extract($path, $data = null, $options = array()) {
  332. if (is_string($data)) {
  333. $tmp = $data;
  334. $data = $path;
  335. $path = $tmp;
  336. }
  337. if (strpos($path, '/') === false) {
  338. return Set::classicExtract($data, $path);
  339. }
  340. if (empty($data)) {
  341. return array();
  342. }
  343. if ($path === '/') {
  344. return $data;
  345. }
  346. $contexts = $data;
  347. $options = array_merge(array('flatten' => true), $options);
  348. if (!isset($contexts[0])) {
  349. $current = current($data);
  350. if ((is_array($current) && count($data) < 1) || !is_array($current) || !Set::numeric(array_keys($data))) {
  351. $contexts = array($data);
  352. }
  353. }
  354. $tokens = array_slice(preg_split('/(?<!=|\\\\)\/(?![a-z-\s]*\])/', $path), 1);
  355. do {
  356. $token = array_shift($tokens);
  357. $conditions = false;
  358. if (preg_match_all('/\[([^=]+=\/[^\/]+\/|[^\]]+)\]/', $token, $m)) {
  359. $conditions = $m[1];
  360. $token = substr($token, 0, strpos($token, '['));
  361. }
  362. $matches = array();
  363. foreach ($contexts as $key => $context) {
  364. if (!isset($context['trace'])) {
  365. $context = array('trace' => array(null), 'item' => $context, 'key' => $key);
  366. }
  367. if ($token === '..') {
  368. if (count($context['trace']) == 1) {
  369. $context['trace'][] = $context['key'];
  370. }
  371. $parent = implode('/', $context['trace']) . '/.';
  372. $context['item'] = Set::extract($parent, $data);
  373. $context['key'] = array_pop($context['trace']);
  374. if (isset($context['trace'][1]) && $context['trace'][1] > 0) {
  375. $context['item'] = $context['item'][0];
  376. } elseif (!empty($context['item'][$key])) {
  377. $context['item'] = $context['item'][$key];
  378. } else {
  379. $context['item'] = array_shift($context['item']);
  380. }
  381. $matches[] = $context;
  382. continue;
  383. }
  384. if ($token === '@*' && is_array($context['item'])) {
  385. $matches[] = array(
  386. 'trace' => array_merge($context['trace'], (array)$key),
  387. 'key' => $key,
  388. 'item' => array_keys($context['item']),
  389. );
  390. } elseif (is_array($context['item'])
  391. && array_key_exists($token, $context['item'])
  392. && !(strval($key) === strval($token) && count($tokens) == 1 && $tokens[0] === '.')) {
  393. $items = $context['item'][$token];
  394. if (!is_array($items)) {
  395. $items = array($items);
  396. } elseif (!isset($items[0])) {
  397. $current = current($items);
  398. $currentKey = key($items);
  399. if (!is_array($current) || (is_array($current) && count($items) <= 1 && !is_numeric($currentKey))) {
  400. $items = array($items);
  401. }
  402. }
  403. foreach ($items as $key => $item) {
  404. $ctext = array($context['key']);
  405. if (!is_numeric($key)) {
  406. $ctext[] = $token;
  407. $tok = array_shift($tokens);
  408. if (isset($items[$tok])) {
  409. $ctext[] = $tok;
  410. $item = $items[$tok];
  411. $matches[] = array(
  412. 'trace' => array_merge($context['trace'], $ctext),
  413. 'key' => $tok,
  414. 'item' => $item,
  415. );
  416. break;
  417. } elseif ($tok !== null) {
  418. array_unshift($tokens, $tok);
  419. }
  420. } else {
  421. $key = $token;
  422. }
  423. $matches[] = array(
  424. 'trace' => array_merge($context['trace'], $ctext),
  425. 'key' => $key,
  426. 'item' => $item,
  427. );
  428. }
  429. } elseif ($key === $token || (ctype_digit($token) && $key == $token) || $token === '.') {
  430. $context['trace'][] = $key;
  431. $matches[] = array(
  432. 'trace' => $context['trace'],
  433. 'key' => $key,
  434. 'item' => $context['item'],
  435. );
  436. }
  437. }
  438. if ($conditions) {
  439. foreach ($conditions as $condition) {
  440. $filtered = array();
  441. $length = count($matches);
  442. foreach ($matches as $i => $match) {
  443. if (Set::matches(array($condition), $match['item'], $i + 1, $length)) {
  444. $filtered[$i] = $match;
  445. }
  446. }
  447. $matches = $filtered;
  448. }
  449. }
  450. $contexts = $matches;
  451. if (empty($tokens)) {
  452. break;
  453. }
  454. } while (1);
  455. $r = array();
  456. foreach ($matches as $match) {
  457. if ((!$options['flatten'] || is_array($match['item'])) && !is_int($match['key'])) {
  458. $r[] = array($match['key'] => $match['item']);
  459. } else {
  460. $r[] = $match['item'];
  461. }
  462. }
  463. return $r;
  464. }
  465. /**
  466. * This function can be used to see if a single item or a given xpath match certain conditions.
  467. *
  468. * @param mixed $conditions An array of condition strings or an XPath expression
  469. * @param array $data An array of data to execute the match on
  470. * @param integer $i Optional: The 'nth'-number of the item being matched.
  471. * @param integer $length
  472. * @return boolean
  473. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::matches
  474. */
  475. public static function matches($conditions, $data = array(), $i = null, $length = null) {
  476. if (empty($conditions)) {
  477. return true;
  478. }
  479. if (is_string($conditions)) {
  480. return !!Set::extract($conditions, $data);
  481. }
  482. foreach ($conditions as $condition) {
  483. if ($condition === ':last') {
  484. if ($i != $length) {
  485. return false;
  486. }
  487. continue;
  488. } elseif ($condition === ':first') {
  489. if ($i != 1) {
  490. return false;
  491. }
  492. continue;
  493. }
  494. if (!preg_match('/(.+?)([><!]?[=]|[><])(.*)/', $condition, $match)) {
  495. if (ctype_digit($condition)) {
  496. if ($i != $condition) {
  497. return false;
  498. }
  499. } elseif (preg_match_all('/(?:^[0-9]+|(?<=,)[0-9]+)/', $condition, $matches)) {
  500. return in_array($i, $matches[0]);
  501. } elseif (!array_key_exists($condition, $data)) {
  502. return false;
  503. }
  504. continue;
  505. }
  506. list(, $key, $op, $expected) = $match;
  507. if (!isset($data[$key])) {
  508. return false;
  509. }
  510. $val = $data[$key];
  511. if ($op === '=' && $expected && $expected{0} === '/') {
  512. return preg_match($expected, $val);
  513. }
  514. if ($op === '=' && $val != $expected) {
  515. return false;
  516. }
  517. if ($op === '!=' && $val == $expected) {
  518. return false;
  519. }
  520. if ($op === '>' && $val <= $expected) {
  521. return false;
  522. }
  523. if ($op === '<' && $val >= $expected) {
  524. return false;
  525. }
  526. if ($op === '<=' && $val > $expected) {
  527. return false;
  528. }
  529. if ($op === '>=' && $val < $expected) {
  530. return false;
  531. }
  532. }
  533. return true;
  534. }
  535. /**
  536. * Gets a value from an array or object that is contained in a given path using an array path syntax, i.e.:
  537. * "{n}.Person.{[a-z]+}" - Where "{n}" represents a numeric key, "Person" represents a string literal,
  538. * and "{[a-z]+}" (i.e. any string literal enclosed in brackets besides {n} and {s}) is interpreted as
  539. * a regular expression.
  540. *
  541. * @param array $data Array from where to extract
  542. * @param mixed $path As an array, or as a dot-separated string.
  543. * @return array Extracted data
  544. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::classicExtract
  545. */
  546. public static function classicExtract($data, $path = null) {
  547. if (empty($path)) {
  548. return $data;
  549. }
  550. if (is_object($data)) {
  551. if (!($data instanceof ArrayAccess || $data instanceof Traversable)) {
  552. $data = get_object_vars($data);
  553. }
  554. }
  555. if (empty($data)) {
  556. return null;
  557. }
  558. if (is_string($path) && strpos($path, '{') !== false) {
  559. $path = String::tokenize($path, '.', '{', '}');
  560. } elseif (is_string($path)) {
  561. $path = explode('.', $path);
  562. }
  563. $tmp = array();
  564. if (empty($path)) {
  565. return null;
  566. }
  567. foreach ($path as $i => $key) {
  568. if (is_numeric($key) && intval($key) > 0 || $key === '0') {
  569. if (isset($data[intval($key)])) {
  570. $data = $data[intval($key)];
  571. } else {
  572. return null;
  573. }
  574. } elseif ($key === '{n}') {
  575. foreach ($data as $j => $val) {
  576. if (is_int($j)) {
  577. $tmpPath = array_slice($path, $i + 1);
  578. if (empty($tmpPath)) {
  579. $tmp[] = $val;
  580. } else {
  581. $tmp[] = Set::classicExtract($val, $tmpPath);
  582. }
  583. }
  584. }
  585. return $tmp;
  586. } elseif ($key === '{s}') {
  587. foreach ($data as $j => $val) {
  588. if (is_string($j)) {
  589. $tmpPath = array_slice($path, $i + 1);
  590. if (empty($tmpPath)) {
  591. $tmp[] = $val;
  592. } else {
  593. $tmp[] = Set::classicExtract($val, $tmpPath);
  594. }
  595. }
  596. }
  597. return $tmp;
  598. } elseif (false !== strpos($key, '{') && false !== strpos($key, '}')) {
  599. $pattern = substr($key, 1, -1);
  600. foreach ($data as $j => $val) {
  601. if (preg_match('/^' . $pattern . '/s', $j) !== 0) {
  602. $tmpPath = array_slice($path, $i + 1);
  603. if (empty($tmpPath)) {
  604. $tmp[$j] = $val;
  605. } else {
  606. $tmp[$j] = Set::classicExtract($val, $tmpPath);
  607. }
  608. }
  609. }
  610. return $tmp;
  611. } else {
  612. if (isset($data[$key])) {
  613. $data = $data[$key];
  614. } else {
  615. return null;
  616. }
  617. }
  618. }
  619. return $data;
  620. }
  621. /**
  622. * Inserts $data into an array as defined by $path.
  623. *
  624. * @param mixed $list Where to insert into
  625. * @param mixed $path A dot-separated string.
  626. * @param array $data Data to insert
  627. * @return array
  628. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::insert
  629. */
  630. public static function insert($list, $path, $data = null) {
  631. if (!is_array($path)) {
  632. $path = explode('.', $path);
  633. }
  634. $_list =& $list;
  635. $count = count($path);
  636. foreach ($path as $i => $key) {
  637. if (is_numeric($key) && intval($key) > 0 || $key === '0') {
  638. $key = intval($key);
  639. }
  640. if ($i === $count - 1 && is_array($_list)) {
  641. $_list[$key] = $data;
  642. } else {
  643. if (!isset($_list[$key])) {
  644. $_list[$key] = array();
  645. }
  646. $_list =& $_list[$key];
  647. }
  648. if (!is_array($_list)) {
  649. return array();
  650. }
  651. }
  652. return $list;
  653. }
  654. /**
  655. * Removes an element from a Set or array as defined by $path.
  656. *
  657. * @param mixed $list From where to remove
  658. * @param mixed $path A dot-separated string.
  659. * @return array Array with $path removed from its value
  660. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::remove
  661. */
  662. public static function remove($list, $path = null) {
  663. if (empty($path)) {
  664. return $list;
  665. }
  666. if (!is_array($path)) {
  667. $path = explode('.', $path);
  668. }
  669. $_list =& $list;
  670. foreach ($path as $i => $key) {
  671. if (is_numeric($key) && intval($key) > 0 || $key === '0') {
  672. $key = intval($key);
  673. }
  674. if ($i === count($path) - 1) {
  675. unset($_list[$key]);
  676. } else {
  677. if (!isset($_list[$key])) {
  678. return $list;
  679. }
  680. $_list =& $_list[$key];
  681. }
  682. }
  683. return $list;
  684. }
  685. /**
  686. * Checks if a particular path is set in an array
  687. *
  688. * @param mixed $data Data to check on
  689. * @param mixed $path A dot-separated string.
  690. * @return boolean true if path is found, false otherwise
  691. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::check
  692. */
  693. public static function check($data, $path = null) {
  694. if (empty($path)) {
  695. return $data;
  696. }
  697. if (!is_array($path)) {
  698. $path = explode('.', $path);
  699. }
  700. foreach ($path as $i => $key) {
  701. if (is_numeric($key) && intval($key) > 0 || $key === '0') {
  702. $key = intval($key);
  703. }
  704. if ($i === count($path) - 1) {
  705. return (is_array($data) && array_key_exists($key, $data));
  706. }
  707. if (!is_array($data) || !array_key_exists($key, $data)) {
  708. return false;
  709. }
  710. $data =& $data[$key];
  711. }
  712. return true;
  713. }
  714. /**
  715. * Computes the difference between a Set and an array, two Sets, or two arrays
  716. *
  717. * @param mixed $val1 First value
  718. * @param mixed $val2 Second value
  719. * @return array Returns the key => value pairs that are not common in $val1 and $val2
  720. * The expression for this function is($val1 - $val2) + ($val2 - ($val1 - $val2))
  721. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::diff
  722. */
  723. public static function diff($val1, $val2 = null) {
  724. if (empty($val1)) {
  725. return (array)$val2;
  726. }
  727. if (empty($val2)) {
  728. return (array)$val1;
  729. }
  730. $intersection = array_intersect_key($val1, $val2);
  731. while (($key = key($intersection)) !== null) {
  732. if ($val1[$key] == $val2[$key]) {
  733. unset($val1[$key]);
  734. unset($val2[$key]);
  735. }
  736. next($intersection);
  737. }
  738. return $val1 + $val2;
  739. }
  740. /**
  741. * Determines if one Set or array contains the exact keys and values of another.
  742. *
  743. * @param array $val1 First value
  744. * @param array $val2 Second value
  745. * @return boolean true if $val1 contains $val2, false otherwise
  746. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::contains
  747. */
  748. public static function contains($val1, $val2 = null) {
  749. if (empty($val1) || empty($val2)) {
  750. return false;
  751. }
  752. foreach ($val2 as $key => $val) {
  753. if (is_numeric($key)) {
  754. Set::contains($val, $val1);
  755. } else {
  756. if (!isset($val1[$key]) || $val1[$key] != $val) {
  757. return false;
  758. }
  759. }
  760. }
  761. return true;
  762. }
  763. /**
  764. * Counts the dimensions of an array. If $all is set to false (which is the default) it will
  765. * only consider the dimension of the first element in the array.
  766. *
  767. * @param array $array Array to count dimensions on
  768. * @param boolean $all Set to true to count the dimension considering all elements in array
  769. * @param integer $count Start the dimension count at this number
  770. * @return integer The number of dimensions in $array
  771. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::countDim
  772. */
  773. public static function countDim($array = null, $all = false, $count = 0) {
  774. if ($all) {
  775. $depth = array($count);
  776. if (is_array($array) && reset($array) !== false) {
  777. foreach ($array as $value) {
  778. $depth[] = Set::countDim($value, true, $count + 1);
  779. }
  780. }
  781. $return = max($depth);
  782. } else {
  783. if (is_array(reset($array))) {
  784. $return = Set::countDim(reset($array)) + 1;
  785. } else {
  786. $return = 1;
  787. }
  788. }
  789. return $return;
  790. }
  791. /**
  792. * Normalizes a string or array list.
  793. *
  794. * @param mixed $list List to normalize
  795. * @param boolean $assoc If true, $list will be converted to an associative array
  796. * @param string $sep If $list is a string, it will be split into an array with $sep
  797. * @param boolean $trim If true, separated strings will be trimmed
  798. * @return array
  799. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::normalize
  800. */
  801. public static function normalize($list, $assoc = true, $sep = ',', $trim = true) {
  802. if (is_string($list)) {
  803. $list = explode($sep, $list);
  804. if ($trim) {
  805. foreach ($list as $key => $value) {
  806. $list[$key] = trim($value);
  807. }
  808. }
  809. if ($assoc) {
  810. return Set::normalize($list);
  811. }
  812. } elseif (is_array($list)) {
  813. $keys = array_keys($list);
  814. $count = count($keys);
  815. $numeric = true;
  816. if (!$assoc) {
  817. for ($i = 0; $i < $count; $i++) {
  818. if (!is_int($keys[$i])) {
  819. $numeric = false;
  820. break;
  821. }
  822. }
  823. }
  824. if (!$numeric || $assoc) {
  825. $newList = array();
  826. for ($i = 0; $i < $count; $i++) {
  827. if (is_int($keys[$i])) {
  828. $newList[$list[$keys[$i]]] = null;
  829. } else {
  830. $newList[$keys[$i]] = $list[$keys[$i]];
  831. }
  832. }
  833. $list = $newList;
  834. }
  835. }
  836. return $list;
  837. }
  838. /**
  839. * Creates an associative array using a $path1 as the path to build its keys, and optionally
  840. * $path2 as path to get the values. If $path2 is not specified, all values will be initialized
  841. * to null (useful for Set::merge). You can optionally group the values by what is obtained when
  842. * following the path specified in $groupPath.
  843. *
  844. * @param mixed $data Array or object from where to extract keys and values
  845. * @param mixed $path1 As an array, or as a dot-separated string.
  846. * @param mixed $path2 As an array, or as a dot-separated string.
  847. * @param string $groupPath As an array, or as a dot-separated string.
  848. * @return array Combined array
  849. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::combine
  850. */
  851. public static function combine($data, $path1 = null, $path2 = null, $groupPath = null) {
  852. if (empty($data)) {
  853. return array();
  854. }
  855. if (is_object($data)) {
  856. if (!($data instanceof ArrayAccess || $data instanceof Traversable)) {
  857. $data = get_object_vars($data);
  858. }
  859. }
  860. if (is_array($path1)) {
  861. $format = array_shift($path1);
  862. $keys = Set::format($data, $format, $path1);
  863. } else {
  864. $keys = Set::extract($data, $path1);
  865. }
  866. if (empty($keys)) {
  867. return array();
  868. }
  869. if (!empty($path2) && is_array($path2)) {
  870. $format = array_shift($path2);
  871. $vals = Set::format($data, $format, $path2);
  872. } elseif (!empty($path2)) {
  873. $vals = Set::extract($data, $path2);
  874. } else {
  875. $count = count($keys);
  876. for ($i = 0; $i < $count; $i++) {
  877. $vals[$i] = null;
  878. }
  879. }
  880. if ($groupPath != null) {
  881. $group = Set::extract($data, $groupPath);
  882. if (!empty($group)) {
  883. $c = count($keys);
  884. for ($i = 0; $i < $c; $i++) {
  885. if (!isset($group[$i])) {
  886. $group[$i] = 0;
  887. }
  888. if (!isset($out[$group[$i]])) {
  889. $out[$group[$i]] = array();
  890. }
  891. $out[$group[$i]][$keys[$i]] = $vals[$i];
  892. }
  893. return $out;
  894. }
  895. }
  896. if (empty($vals)) {
  897. return array();
  898. }
  899. return array_combine($keys, $vals);
  900. }
  901. /**
  902. * Converts an object into an array.
  903. * @param object $object Object to reverse
  904. * @return array Array representation of given object
  905. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::reverse
  906. */
  907. public static function reverse($object) {
  908. $out = array();
  909. if ($object instanceof SimpleXMLElement) {
  910. return Xml::toArray($object);
  911. } elseif (is_object($object)) {
  912. $keys = get_object_vars($object);
  913. if (isset($keys['_name_'])) {
  914. $identity = $keys['_name_'];
  915. unset($keys['_name_']);
  916. }
  917. $new = array();
  918. foreach ($keys as $key => $value) {
  919. if (is_array($value)) {
  920. $new[$key] = (array)Set::reverse($value);
  921. } else {
  922. if (isset($value->_name_)) {
  923. $new = array_merge($new, Set::reverse($value));
  924. } else {
  925. $new[$key] = Set::reverse($value);
  926. }
  927. }
  928. }
  929. if (isset($identity)) {
  930. $out[$identity] = $new;
  931. } else {
  932. $out = $new;
  933. }
  934. } elseif (is_array($object)) {
  935. foreach ($object as $key => $value) {
  936. $out[$key] = Set::reverse($value);
  937. }
  938. } else {
  939. $out = $object;
  940. }
  941. return $out;
  942. }
  943. /**
  944. * Collapses a multi-dimensional array into a single dimension, using a delimited array path for
  945. * each array element's key, i.e. array(array('Foo' => array('Bar' => 'Far'))) becomes
  946. * array('0.Foo.Bar' => 'Far').
  947. *
  948. * @param array $data Array to flatten
  949. * @param string $separator String used to separate array key elements in a path, defaults to '.'
  950. * @return array
  951. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::flatten
  952. */
  953. public static function flatten($data, $separator = '.') {
  954. $result = array();
  955. $path = null;
  956. if (is_array($separator)) {
  957. extract($separator, EXTR_OVERWRITE);
  958. }
  959. if (!is_null($path)) {
  960. $path .= $separator;
  961. }
  962. foreach ($data as $key => $val) {
  963. if (is_array($val)) {
  964. $result += (array)Set::flatten($val, array(
  965. 'separator' => $separator,
  966. 'path' => $path . $key
  967. ));
  968. } else {
  969. $result[$path . $key] = $val;
  970. }
  971. }
  972. return $result;
  973. }
  974. /**
  975. * Flattens an array for sorting
  976. *
  977. * @param array $results
  978. * @param string $key
  979. * @return array
  980. */
  981. protected static function _flatten($results, $key = null) {
  982. $stack = array();
  983. foreach ($results as $k => $r) {
  984. $id = $k;
  985. if (!is_null($key)) {
  986. $id = $key;
  987. }
  988. if (is_array($r) && !empty($r)) {
  989. $stack = array_merge($stack, Set::_flatten($r, $id));
  990. } else {
  991. $stack[] = array('id' => $id, 'value' => $r);
  992. }
  993. }
  994. return $stack;
  995. }
  996. /**
  997. * Sorts an array by any value, determined by a Set-compatible path
  998. *
  999. * @param array $data An array of data to sort
  1000. * @param string $path A Set-compatible path to the array value
  1001. * @param string $dir Direction of sorting - either ascending (ASC), or descending (DESC)
  1002. * @return array Sorted array of data
  1003. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::sort
  1004. */
  1005. public static function sort($data, $path, $dir) {
  1006. $originalKeys = array_keys($data);
  1007. if (is_numeric(implode('', $originalKeys))) {
  1008. $data = array_values($data);
  1009. }
  1010. $result = Set::_flatten(Set::extract($data, $path));
  1011. list($keys, $values) = array(Set::extract($result, '{n}.id'), Set::extract($result, '{n}.value'));
  1012. $dir = strtolower($dir);
  1013. if ($dir === 'asc') {
  1014. $dir = SORT_ASC;
  1015. } elseif ($dir === 'desc') {
  1016. $dir = SORT_DESC;
  1017. }
  1018. array_multisort($values, $dir, $keys, $dir);
  1019. $sorted = array();
  1020. $keys = array_unique($keys);
  1021. foreach ($keys as $k) {
  1022. $sorted[] = $data[$k];
  1023. }
  1024. return $sorted;
  1025. }
  1026. /**
  1027. * Allows the application of a callback method to elements of an
  1028. * array extracted by a Set::extract() compatible path.
  1029. *
  1030. * @param mixed $path Set-compatible path to the array value
  1031. * @param array $data An array of data to extract from & then process with the $callback.
  1032. * @param mixed $callback Callback method to be applied to extracted data.
  1033. * See http://ca2.php.net/manual/en/language.pseudo-types.php#language.types.callback for examples
  1034. * of callback formats.
  1035. * @param array $options Options are:
  1036. * - type : can be pass, map, or reduce. Map will handoff the given callback
  1037. * to array_map, reduce will handoff to array_reduce, and pass will
  1038. * use call_user_func_array().
  1039. * @return mixed Result of the callback when applied to extracted data
  1040. * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::apply
  1041. */
  1042. public static function apply($path, $data, $callback, $options = array()) {
  1043. $defaults = array('type' => 'pass');
  1044. $options = array_merge($defaults, $options);
  1045. $extracted = Set::extract($path, $data);
  1046. if ($options['type'] === 'map') {
  1047. return array_map($callback, $extracted);
  1048. } elseif ($options['type'] === 'reduce') {
  1049. return array_reduce($extracted, $callback);
  1050. } elseif ($options['type'] === 'pass') {
  1051. return call_user_func_array($callback, array($extracted));
  1052. }
  1053. return null;
  1054. }
  1055. /**
  1056. * Takes in a flat array and returns a nested array
  1057. *
  1058. * @param mixed $data
  1059. * @param array $options Options are:
  1060. * children - the key name to use in the resultset for children
  1061. * idPath - the path to a key that identifies each entry
  1062. * parentPath - the path to a key that identifies the parent of each entry
  1063. * root - the id of the desired top-most result
  1064. * @return array of results, nested
  1065. * @link
  1066. */
  1067. public static function nest($data, $options = array()) {
  1068. if (!$data) {
  1069. return $data;
  1070. }
  1071. $alias = key(current($data));
  1072. $options += array(
  1073. 'idPath' => "/$alias/id",
  1074. 'parentPath' => "/$alias/parent_id",
  1075. 'children' => 'children',
  1076. 'root' => null
  1077. );
  1078. $return = $idMap = array();
  1079. $ids = Set::extract($data, $options['idPath']);
  1080. $idKeys = explode('/', trim($options['idPath'], '/'));
  1081. $parentKeys = explode('/', trim($options['parentPath'], '/'));
  1082. foreach ($data as $result) {
  1083. $result[$options['children']] = array();
  1084. $id = Set::get($result, $idKeys);
  1085. $parentId = Set::get($result, $parentKeys);
  1086. if (isset($idMap[$id][$options['children']])) {
  1087. $idMap[$id] = array_merge($result, (array)$idMap[$id]);
  1088. } else {
  1089. $idMap[$id] = array_merge($result, array($options['children'] => array()));
  1090. }
  1091. if (!$parentId || !in_array($parentId, $ids)) {
  1092. $return[] =& $idMap[$id];
  1093. } else {
  1094. $idMap[$parentId][$options['children']][] =& $idMap[$id];
  1095. }
  1096. }
  1097. if ($options['root']) {
  1098. $root = $options['root'];
  1099. } else {
  1100. $root = Set::get($return[0], $parentKeys);
  1101. }
  1102. foreach ($return as $i => $result) {
  1103. $id = Set::get($result, $idKeys);
  1104. $parentId = Set::get($result, $parentKeys);
  1105. if ($id !== $root && $parentId != $root) {
  1106. unset($return[$i]);
  1107. }
  1108. }
  1109. return array_values($return);
  1110. }
  1111. /**
  1112. * Return the value at the specified position
  1113. *
  1114. * @param mixed $input an array
  1115. * @param mixed $path string or array of array keys
  1116. * @return the value at the specified position or null if it doesn't exist
  1117. */
  1118. public static function get($input, $path = null) {
  1119. if (is_string($path)) {
  1120. if (strpos($path, '/') !== false) {
  1121. $keys = explode('/', trim($path, '/'));
  1122. } else {
  1123. $keys = explode('.', trim($path, '.'));
  1124. }
  1125. } else {
  1126. $keys = $path;
  1127. }
  1128. if (!$keys) {
  1129. return $input;
  1130. }
  1131. $return = $input;
  1132. foreach ($keys as $key) {
  1133. if (!isset($return[$key])) {
  1134. return null;
  1135. }
  1136. $return = $return[$key];
  1137. }
  1138. return $return;
  1139. }
  1140. }