PageRenderTime 52ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Utility/Set.php

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