CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.5 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.5
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

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

Generated using CakePHP API Docs