PageRenderTime 53ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/code/web/public_php/webtt/cake/libs/set.php

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