PageRenderTime 68ms CodeModel.GetById 34ms RepoModel.GetById 1ms app.codeStats 0ms

/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Utility/Set.php

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