PageRenderTime 71ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/cake/libs/set.php

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