CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Team
    • Issues (Github)
    • YouTube Channel
    • Get Involved
    • Bakery
    • Featured Resources
    • Newsletter
    • Certification
    • My CakePHP
    • CakeFest
    • Facebook
    • Twitter
    • Help & Support
    • Forum
    • Stack Overflow
    • IRC
    • Slack
    • Paid Support
CakePHP

C CakePHP 3.8 Red Velvet API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 3.8
      • 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

Namespaces

  • Cake
    • Auth
      • Storage
    • Cache
      • Engine
    • Collection
      • Iterator
    • Command
    • Console
      • Exception
    • Controller
      • Component
      • Exception
    • Core
      • Configure
        • Engine
      • Exception
      • Retry
    • Database
      • Driver
      • Exception
      • Expression
      • Schema
      • Statement
      • Type
    • Datasource
      • Exception
    • Error
      • Middleware
    • Event
      • Decorator
    • Filesystem
    • Form
    • Http
      • Client
        • Adapter
        • Auth
      • Cookie
      • Exception
      • Middleware
      • Session
    • I18n
      • Formatter
      • Middleware
      • Parser
    • Log
      • Engine
    • Mailer
      • Exception
      • Transport
    • Network
      • Exception
    • ORM
      • Association
      • Behavior
        • Translate
      • Exception
      • Locator
      • Rule
    • Routing
      • Exception
      • Filter
      • Middleware
      • Route
    • Shell
      • Helper
      • Task
    • TestSuite
      • Fixture
      • Stub
    • Utility
      • Exception
    • Validation
    • View
      • Exception
      • Form
      • Helper
      • Widget
  • None

Classes

  • Collection

Interfaces

  • CollectionInterface

Traits

  • CollectionTrait
  • ExtractTrait
   1: <?php
   2: /**
   3:  * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
   4:  * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
   5:  *
   6:  * Licensed under The MIT License
   7:  * For full copyright and license information, please see the LICENSE.txt
   8:  * Redistributions of files must retain the above copyright notice.
   9:  *
  10:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11:  * @link          https://cakephp.org CakePHP(tm) Project
  12:  * @since         3.0.0
  13:  * @license       https://opensource.org/licenses/mit-license.php MIT License
  14:  */
  15: namespace Cake\Collection;
  16: 
  17: use Iterator;
  18: use JsonSerializable;
  19: 
  20: /**
  21:  * Describes the methods a Collection should implement. A collection is an immutable
  22:  * list of elements exposing a number of traversing and extracting method for
  23:  * generating other collections.
  24:  *
  25:  * @method \Cake\Collection\CollectionInterface cartesianProduct(callable $operation = null, callable $filter = null)
  26:  */
  27: interface CollectionInterface extends Iterator, JsonSerializable
  28: {
  29:     /**
  30:      * Executes the passed callable for each of the elements in this collection
  31:      * and passes both the value and key for them on each step.
  32:      * Returns the same collection for chaining.
  33:      *
  34:      * ### Example:
  35:      *
  36:      * ```
  37:      * $collection = (new Collection($items))->each(function ($value, $key) {
  38:      *  echo "Element $key: $value";
  39:      * });
  40:      * ```
  41:      *
  42:      * @param callable $c callable function that will receive each of the elements
  43:      * in this collection
  44:      * @return \Cake\Collection\CollectionInterface
  45:      */
  46:     public function each(callable $c);
  47: 
  48:     /**
  49:      * Looks through each value in the collection, and returns another collection with
  50:      * all the values that pass a truth test. Only the values for which the callback
  51:      * returns true will be present in the resulting collection.
  52:      *
  53:      * Each time the callback is executed it will receive the value of the element
  54:      * in the current iteration, the key of the element and this collection as
  55:      * arguments, in that order.
  56:      *
  57:      * ### Example:
  58:      *
  59:      * Filtering odd numbers in an array, at the end only the value 2 will
  60:      * be present in the resulting collection:
  61:      *
  62:      * ```
  63:      * $collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
  64:      *  return $value % 2 === 0;
  65:      * });
  66:      * ```
  67:      *
  68:      * @param callable|null $c the method that will receive each of the elements and
  69:      *   returns true whether or not they should be in the resulting collection.
  70:      *   If left null, a callback that filters out falsey values will be used.
  71:      * @return \Cake\Collection\CollectionInterface
  72:      */
  73:     public function filter(callable $c = null);
  74: 
  75:     /**
  76:      * Looks through each value in the collection, and returns another collection with
  77:      * all the values that do not pass a truth test. This is the opposite of `filter`.
  78:      *
  79:      * Each time the callback is executed it will receive the value of the element
  80:      * in the current iteration, the key of the element and this collection as
  81:      * arguments, in that order.
  82:      *
  83:      * ### Example:
  84:      *
  85:      * Filtering even numbers in an array, at the end only values 1 and 3 will
  86:      * be present in the resulting collection:
  87:      *
  88:      * ```
  89:      * $collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
  90:      *  return $value % 2 === 0;
  91:      * });
  92:      * ```
  93:      *
  94:      * @param callable $c the method that will receive each of the elements and
  95:      * returns true whether or not they should be out of the resulting collection.
  96:      * @return \Cake\Collection\CollectionInterface
  97:      */
  98:     public function reject(callable $c);
  99: 
 100:     /**
 101:      * Returns true if all values in this collection pass the truth test provided
 102:      * in the callback.
 103:      *
 104:      * Each time the callback is executed it will receive the value of the element
 105:      * in the current iteration and  the key of the element as arguments, in that
 106:      * order.
 107:      *
 108:      * ### Example:
 109:      *
 110:      * ```
 111:      * $overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
 112:      *  return $value > 21;
 113:      * });
 114:      * ```
 115:      *
 116:      * Empty collections always return true because it is a vacuous truth.
 117:      *
 118:      * @param callable $c a callback function
 119:      * @return bool true if for all elements in this collection the provided
 120:      *   callback returns true, false otherwise.
 121:      */
 122:     public function every(callable $c);
 123: 
 124:     /**
 125:      * Returns true if any of the values in this collection pass the truth test
 126:      * provided in the callback.
 127:      *
 128:      * Each time the callback is executed it will receive the value of the element
 129:      * in the current iteration and the key of the element as arguments, in that
 130:      * order.
 131:      *
 132:      * ### Example:
 133:      *
 134:      * ```
 135:      * $hasYoungPeople = (new Collection([24, 45, 15]))->every(function ($value, $key) {
 136:      *  return $value < 21;
 137:      * });
 138:      * ```
 139:      *
 140:      * @param callable $c a callback function
 141:      * @return bool true if the provided callback returns true for any element in this
 142:      * collection, false otherwise
 143:      */
 144:     public function some(callable $c);
 145: 
 146:     /**
 147:      * Returns true if $value is present in this collection. Comparisons are made
 148:      * both by value and type.
 149:      *
 150:      * @param mixed $value The value to check for
 151:      * @return bool true if $value is present in this collection
 152:      */
 153:     public function contains($value);
 154: 
 155:     /**
 156:      * Returns another collection after modifying each of the values in this one using
 157:      * the provided callable.
 158:      *
 159:      * Each time the callback is executed it will receive the value of the element
 160:      * in the current iteration, the key of the element and this collection as
 161:      * arguments, in that order.
 162:      *
 163:      * ### Example:
 164:      *
 165:      * Getting a collection of booleans where true indicates if a person is female:
 166:      *
 167:      * ```
 168:      * $collection = (new Collection($people))->map(function ($person, $key) {
 169:      *  return $person->gender === 'female';
 170:      * });
 171:      * ```
 172:      *
 173:      * @param callable $c the method that will receive each of the elements and
 174:      * returns the new value for the key that is being iterated
 175:      * @return \Cake\Collection\CollectionInterface
 176:      */
 177:     public function map(callable $c);
 178: 
 179:     /**
 180:      * Folds the values in this collection to a single value, as the result of
 181:      * applying the callback function to all elements. $zero is the initial state
 182:      * of the reduction, and each successive step of it should be returned
 183:      * by the callback function.
 184:      * If $zero is omitted the first value of the collection will be used in its place
 185:      * and reduction will start from the second item.
 186:      *
 187:      * @param callable $c The callback function to be called
 188:      * @param mixed $zero The state of reduction
 189:      * @return mixed
 190:      */
 191:     public function reduce(callable $c, $zero = null);
 192: 
 193:     /**
 194:      * Returns a new collection containing the column or property value found in each
 195:      * of the elements, as requested in the $matcher param.
 196:      *
 197:      * The matcher can be a string with a property name to extract or a dot separated
 198:      * path of properties that should be followed to get the last one in the path.
 199:      *
 200:      * If a column or property could not be found for a particular element in the
 201:      * collection, that position is filled with null.
 202:      *
 203:      * ### Example:
 204:      *
 205:      * Extract the user name for all comments in the array:
 206:      *
 207:      * ```
 208:      * $items = [
 209:      *  ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
 210:      *  ['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
 211:      * ];
 212:      * $extracted = (new Collection($items))->extract('comment.user.name');
 213:      *
 214:      * // Result will look like this when converted to array
 215:      * ['Mark', 'Renan']
 216:      * ```
 217:      *
 218:      * It is also possible to extract a flattened collection out of nested properties
 219:      *
 220:      * ```
 221:      *  $items = [
 222:      *      ['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
 223:      *      ['comment' => ['votes' => [['value' => 4]]
 224:      * ];
 225:      * $extracted = (new Collection($items))->extract('comment.votes.{*}.value');
 226:      *
 227:      * // Result will contain
 228:      * [1, 2, 3, 4]
 229:      * ```
 230:      *
 231:      * @param string $matcher a dot separated string symbolizing the path to follow
 232:      * inside the hierarchy of each value so that the column can be extracted.
 233:      * @return \Cake\Collection\CollectionInterface
 234:      */
 235:     public function extract($matcher);
 236: 
 237:     /**
 238:      * Returns the top element in this collection after being sorted by a property.
 239:      * Check the sortBy method for information on the callback and $type parameters
 240:      *
 241:      * ### Examples:
 242:      *
 243:      * ```
 244:      * // For a collection of employees
 245:      * $max = $collection->max('age');
 246:      * $max = $collection->max('user.salary');
 247:      * $max = $collection->max(function ($e) {
 248:      *  return $e->get('user')->get('salary');
 249:      * });
 250:      *
 251:      * // Display employee name
 252:      * echo $max->name;
 253:      * ```
 254:      *
 255:      * @param callable|string $callback the callback or column name to use for sorting
 256:      * @param int $type the type of comparison to perform, either SORT_STRING
 257:      * SORT_NUMERIC or SORT_NATURAL
 258:      * @see \Cake\Collection\CollectionIterface::sortBy()
 259:      * @return mixed The value of the top element in the collection
 260:      */
 261:     public function max($callback, $type = \SORT_NUMERIC);
 262: 
 263:     /**
 264:      * Returns the bottom element in this collection after being sorted by a property.
 265:      * Check the sortBy method for information on the callback and $type parameters
 266:      *
 267:      * ### Examples:
 268:      *
 269:      * ```
 270:      * // For a collection of employees
 271:      * $min = $collection->min('age');
 272:      * $min = $collection->min('user.salary');
 273:      * $min = $collection->min(function ($e) {
 274:      *  return $e->get('user')->get('salary');
 275:      * });
 276:      *
 277:      * // Display employee name
 278:      * echo $min->name;
 279:      * ```
 280:      *
 281:      * @param callable|string $callback the callback or column name to use for sorting
 282:      * @param int $type the type of comparison to perform, either SORT_STRING
 283:      * SORT_NUMERIC or SORT_NATURAL
 284:      * @see \Cake\Collection\CollectionInterface::sortBy()
 285:      * @return mixed The value of the bottom element in the collection
 286:      */
 287:     public function min($callback, $type = \SORT_NUMERIC);
 288: 
 289:     /**
 290:      * Returns the average of all the values extracted with $matcher
 291:      * or of this collection.
 292:      *
 293:      * ### Example:
 294:      *
 295:      * ```
 296:      * $items = [
 297:      *  ['invoice' => ['total' => 100]],
 298:      *  ['invoice' => ['total' => 200]]
 299:      * ];
 300:      *
 301:      * $total = (new Collection($items))->avg('invoice.total');
 302:      *
 303:      * // Total: 150
 304:      *
 305:      * $total = (new Collection([1, 2, 3]))->avg();
 306:      * // Total: 2
 307:      * ```
 308:      *
 309:      * @param string|callable|null $matcher The property name to sum or a function
 310:      * If no value is passed, an identity function will be used.
 311:      * that will return the value of the property to sum.
 312:      * @return float|int|null
 313:      */
 314:     public function avg($matcher = null);
 315: 
 316:     /**
 317:      * Returns the median of all the values extracted with $matcher
 318:      * or of this collection.
 319:      *
 320:      * ### Example:
 321:      *
 322:      * ```
 323:      * $items = [
 324:      *  ['invoice' => ['total' => 400]],
 325:      *  ['invoice' => ['total' => 500]]
 326:      *  ['invoice' => ['total' => 100]]
 327:      *  ['invoice' => ['total' => 333]]
 328:      *  ['invoice' => ['total' => 200]]
 329:      * ];
 330:      *
 331:      * $total = (new Collection($items))->median('invoice.total');
 332:      *
 333:      * // Total: 333
 334:      *
 335:      * $total = (new Collection([1, 2, 3, 4]))->median();
 336:      * // Total: 2.5
 337:      * ```
 338:      *
 339:      * @param string|callable|null $matcher The property name to sum or a function
 340:      * If no value is passed, an identity function will be used.
 341:      * that will return the value of the property to sum.
 342:      * @return float|int|null
 343:      */
 344:     public function median($matcher = null);
 345: 
 346:     /**
 347:      * Returns a sorted iterator out of the elements in this collection,
 348:      * ranked in ascending order by the results of running each value through a
 349:      * callback. $callback can also be a string representing the column or property
 350:      * name.
 351:      *
 352:      * The callback will receive as its first argument each of the elements in $items,
 353:      * the value returned by the callback will be used as the value for sorting such
 354:      * element. Please note that the callback function could be called more than once
 355:      * per element.
 356:      *
 357:      * ### Example:
 358:      *
 359:      * ```
 360:      * $items = $collection->sortBy(function ($user) {
 361:      *  return $user->age;
 362:      * });
 363:      *
 364:      * // alternatively
 365:      * $items = $collection->sortBy('age');
 366:      *
 367:      * // or use a property path
 368:      * $items = $collection->sortBy('department.name');
 369:      *
 370:      * // output all user name order by their age in descending order
 371:      * foreach ($items as $user) {
 372:      *  echo $user->name;
 373:      * }
 374:      * ```
 375:      *
 376:      * @param callable|string $callback the callback or column name to use for sorting
 377:      * @param int $dir either SORT_DESC or SORT_ASC
 378:      * @param int $type the type of comparison to perform, either SORT_STRING
 379:      * SORT_NUMERIC or SORT_NATURAL
 380:      * @return \Cake\Collection\CollectionInterface
 381:      */
 382:     public function sortBy($callback, $dir = SORT_DESC, $type = \SORT_NUMERIC);
 383: 
 384:     /**
 385:      * Splits a collection into sets, grouped by the result of running each value
 386:      * through the callback. If $callback is a string instead of a callable,
 387:      * groups by the property named by $callback on each of the values.
 388:      *
 389:      * When $callback is a string it should be a property name to extract or
 390:      * a dot separated path of properties that should be followed to get the last
 391:      * one in the path.
 392:      *
 393:      * ### Example:
 394:      *
 395:      * ```
 396:      * $items = [
 397:      *  ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
 398:      *  ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
 399:      *  ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
 400:      * ];
 401:      *
 402:      * $group = (new Collection($items))->groupBy('parent_id');
 403:      *
 404:      * // Or
 405:      * $group = (new Collection($items))->groupBy(function ($e) {
 406:      *  return $e['parent_id'];
 407:      * });
 408:      *
 409:      * // Result will look like this when converted to array
 410:      * [
 411:      *  10 => [
 412:      *      ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
 413:      *      ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
 414:      *  ],
 415:      *  11 => [
 416:      *      ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
 417:      *  ]
 418:      * ];
 419:      * ```
 420:      *
 421:      * @param callable|string $callback the callback or column name to use for grouping
 422:      * or a function returning the grouping key out of the provided element
 423:      * @return \Cake\Collection\CollectionInterface
 424:      */
 425:     public function groupBy($callback);
 426: 
 427:     /**
 428:      * Given a list and a callback function that returns a key for each element
 429:      * in the list (or a property name), returns an object with an index of each item.
 430:      * Just like groupBy, but for when you know your keys are unique.
 431:      *
 432:      * When $callback is a string it should be a property name to extract or
 433:      * a dot separated path of properties that should be followed to get the last
 434:      * one in the path.
 435:      *
 436:      * ### Example:
 437:      *
 438:      * ```
 439:      * $items = [
 440:      *  ['id' => 1, 'name' => 'foo'],
 441:      *  ['id' => 2, 'name' => 'bar'],
 442:      *  ['id' => 3, 'name' => 'baz'],
 443:      * ];
 444:      *
 445:      * $indexed = (new Collection($items))->indexBy('id');
 446:      *
 447:      * // Or
 448:      * $indexed = (new Collection($items))->indexBy(function ($e) {
 449:      *  return $e['id'];
 450:      * });
 451:      *
 452:      * // Result will look like this when converted to array
 453:      * [
 454:      *  1 => ['id' => 1, 'name' => 'foo'],
 455:      *  3 => ['id' => 3, 'name' => 'baz'],
 456:      *  2 => ['id' => 2, 'name' => 'bar'],
 457:      * ];
 458:      * ```
 459:      *
 460:      * @param callable|string $callback the callback or column name to use for indexing
 461:      * or a function returning the indexing key out of the provided element
 462:      * @return \Cake\Collection\CollectionInterface
 463:      */
 464:     public function indexBy($callback);
 465: 
 466:     /**
 467:      * Sorts a list into groups and returns a count for the number of elements
 468:      * in each group. Similar to groupBy, but instead of returning a list of values,
 469:      * returns a count for the number of values in that group.
 470:      *
 471:      * When $callback is a string it should be a property name to extract or
 472:      * a dot separated path of properties that should be followed to get the last
 473:      * one in the path.
 474:      *
 475:      * ### Example:
 476:      *
 477:      * ```
 478:      * $items = [
 479:      *  ['id' => 1, 'name' => 'foo', 'parent_id' => 10],
 480:      *  ['id' => 2, 'name' => 'bar', 'parent_id' => 11],
 481:      *  ['id' => 3, 'name' => 'baz', 'parent_id' => 10],
 482:      * ];
 483:      *
 484:      * $group = (new Collection($items))->countBy('parent_id');
 485:      *
 486:      * // Or
 487:      * $group = (new Collection($items))->countBy(function ($e) {
 488:      *  return $e['parent_id'];
 489:      * });
 490:      *
 491:      * // Result will look like this when converted to array
 492:      * [
 493:      *  10 => 2,
 494:      *  11 => 1
 495:      * ];
 496:      * ```
 497:      *
 498:      * @param callable|string $callback the callback or column name to use for indexing
 499:      * or a function returning the indexing key out of the provided element
 500:      * @return \Cake\Collection\CollectionInterface
 501:      */
 502:     public function countBy($callback);
 503: 
 504:     /**
 505:      * Returns the total sum of all the values extracted with $matcher
 506:      * or of this collection.
 507:      *
 508:      * ### Example:
 509:      *
 510:      * ```
 511:      * $items = [
 512:      *  ['invoice' => ['total' => 100]],
 513:      *  ['invoice' => ['total' => 200]]
 514:      * ];
 515:      *
 516:      * $total = (new Collection($items))->sumOf('invoice.total');
 517:      *
 518:      * // Total: 300
 519:      *
 520:      * $total = (new Collection([1, 2, 3]))->sumOf();
 521:      * // Total: 6
 522:      * ```
 523:      *
 524:      * @param string|callable|null $matcher The property name to sum or a function
 525:      * If no value is passed, an identity function will be used.
 526:      * that will return the value of the property to sum.
 527:      * @return float|int
 528:      */
 529:     public function sumOf($matcher = null);
 530: 
 531:     /**
 532:      * Returns a new collection with the elements placed in a random order,
 533:      * this function does not preserve the original keys in the collection.
 534:      *
 535:      * @return \Cake\Collection\CollectionInterface
 536:      */
 537:     public function shuffle();
 538: 
 539:     /**
 540:      * Returns a new collection with maximum $size random elements
 541:      * from this collection
 542:      *
 543:      * @param int $size the maximum number of elements to randomly
 544:      * take from this collection
 545:      * @return \Cake\Collection\CollectionInterface
 546:      */
 547:     public function sample($size = 10);
 548: 
 549:     /**
 550:      * Returns a new collection with maximum $size elements in the internal
 551:      * order this collection was created. If a second parameter is passed, it
 552:      * will determine from what position to start taking elements.
 553:      *
 554:      * @param int $size the maximum number of elements to take from
 555:      * this collection
 556:      * @param int $from A positional offset from where to take the elements
 557:      * @return \Cake\Collection\CollectionInterface
 558:      */
 559:     public function take($size = 1, $from = 0);
 560: 
 561:     /**
 562:      * Returns the last N elements of a collection
 563:      *
 564:      * ### Example:
 565:      *
 566:      * ```
 567:      * $items = [1, 2, 3, 4, 5];
 568:      *
 569:      * $last = (new Collection($items))->takeLast(3);
 570:      *
 571:      * // Result will look like this when converted to array
 572:      * [3, 4, 5];
 573:      * ```
 574:      *
 575:      * @param int $howMany The number of elements at the end of the collection
 576:      * @return \Cake\Collection\CollectionInterface
 577:      */
 578:     public function takeLast($howMany);
 579: 
 580:     /**
 581:      * Returns a new collection that will skip the specified amount of elements
 582:      * at the beginning of the iteration.
 583:      *
 584:      * @param int $howMany The number of elements to skip.
 585:      * @return \Cake\Collection\CollectionInterface
 586:      */
 587:     public function skip($howMany);
 588: 
 589:     /**
 590:      * Looks through each value in the list, returning a Collection of all the
 591:      * values that contain all of the key-value pairs listed in $conditions.
 592:      *
 593:      * ### Example:
 594:      *
 595:      * ```
 596:      * $items = [
 597:      *  ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
 598:      *  ['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
 599:      * ];
 600:      *
 601:      * $extracted = (new Collection($items))->match(['user.name' => 'Renan']);
 602:      *
 603:      * // Result will look like this when converted to array
 604:      * [
 605:      *  ['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
 606:      * ]
 607:      * ```
 608:      *
 609:      * @param array $conditions a key-value list of conditions where
 610:      * the key is a property path as accepted by `Collection::extract,
 611:      * and the value the condition against with each element will be matched
 612:      * @return \Cake\Collection\CollectionInterface
 613:      */
 614:     public function match(array $conditions);
 615: 
 616:     /**
 617:      * Returns the first result matching all of the key-value pairs listed in
 618:      * conditions.
 619:      *
 620:      * @param array $conditions a key-value list of conditions where the key is
 621:      * a property path as accepted by `Collection::extract`, and the value the
 622:      * condition against with each element will be matched
 623:      * @see \Cake\Collection\CollectionInterface::match()
 624:      * @return mixed
 625:      */
 626:     public function firstMatch(array $conditions);
 627: 
 628:     /**
 629:      * Returns the first result in this collection
 630:      *
 631:      * @return mixed The first value in the collection will be returned.
 632:      */
 633:     public function first();
 634: 
 635:     /**
 636:      * Returns the last result in this collection
 637:      *
 638:      * @return mixed The last value in the collection will be returned.
 639:      */
 640:     public function last();
 641: 
 642:     /**
 643:      * Returns a new collection as the result of concatenating the list of elements
 644:      * in this collection with the passed list of elements
 645:      *
 646:      * @param array|\Traversable $items Items list.
 647:      * @return \Cake\Collection\CollectionInterface
 648:      */
 649:     public function append($items);
 650: 
 651:     /**
 652:      * Returns a new collection where the values extracted based on a value path
 653:      * and then indexed by a key path. Optionally this method can produce parent
 654:      * groups based on a group property path.
 655:      *
 656:      * ### Examples:
 657:      *
 658:      * ```
 659:      * $items = [
 660:      *  ['id' => 1, 'name' => 'foo', 'parent' => 'a'],
 661:      *  ['id' => 2, 'name' => 'bar', 'parent' => 'b'],
 662:      *  ['id' => 3, 'name' => 'baz', 'parent' => 'a'],
 663:      * ];
 664:      *
 665:      * $combined = (new Collection($items))->combine('id', 'name');
 666:      *
 667:      * // Result will look like this when converted to array
 668:      * [
 669:      *  1 => 'foo',
 670:      *  2 => 'bar',
 671:      *  3 => 'baz',
 672:      * ];
 673:      *
 674:      * $combined = (new Collection($items))->combine('id', 'name', 'parent');
 675:      *
 676:      * // Result will look like this when converted to array
 677:      * [
 678:      *  'a' => [1 => 'foo', 3 => 'baz'],
 679:      *  'b' => [2 => 'bar']
 680:      * ];
 681:      * ```
 682:      *
 683:      * @param callable|string $keyPath the column name path to use for indexing
 684:      * or a function returning the indexing key out of the provided element
 685:      * @param callable|string $valuePath the column name path to use as the array value
 686:      * or a function returning the value out of the provided element
 687:      * @param callable|string|null $groupPath the column name path to use as the parent
 688:      * grouping key or a function returning the key out of the provided element
 689:      * @return \Cake\Collection\CollectionInterface
 690:      */
 691:     public function combine($keyPath, $valuePath, $groupPath = null);
 692: 
 693:     /**
 694:      * Returns a new collection where the values are nested in a tree-like structure
 695:      * based on an id property path and a parent id property path.
 696:      *
 697:      * @param callable|string $idPath the column name path to use for determining
 698:      * whether an element is parent of another
 699:      * @param callable|string $parentPath the column name path to use for determining
 700:      * whether an element is child of another
 701:      * @param string $nestingKey The key name under which children are nested
 702:      * @return \Cake\Collection\CollectionInterface
 703:      */
 704:     public function nest($idPath, $parentPath, $nestingKey = 'children');
 705: 
 706:     /**
 707:      * Returns a new collection containing each of the elements found in `$values` as
 708:      * a property inside the corresponding elements in this collection. The property
 709:      * where the values will be inserted is described by the `$path` parameter.
 710:      *
 711:      * The $path can be a string with a property name or a dot separated path of
 712:      * properties that should be followed to get the last one in the path.
 713:      *
 714:      * If a column or property could not be found for a particular element in the
 715:      * collection as part of the path, the element will be kept unchanged.
 716:      *
 717:      * ### Example:
 718:      *
 719:      * Insert ages into a collection containing users:
 720:      *
 721:      * ```
 722:      * $items = [
 723:      *  ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
 724:      *  ['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
 725:      * ];
 726:      * $ages = [25, 28];
 727:      * $inserted = (new Collection($items))->insert('comment.user.age', $ages);
 728:      *
 729:      * // Result will look like this when converted to array
 730:      * [
 731:      *  ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
 732:      *  ['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
 733:      * ];
 734:      * ```
 735:      *
 736:      * @param string $path a dot separated string symbolizing the path to follow
 737:      * inside the hierarchy of each value so that the value can be inserted
 738:      * @param mixed $values The values to be inserted at the specified path,
 739:      * values are matched with the elements in this collection by its positional index.
 740:      * @return \Cake\Collection\CollectionInterface
 741:      */
 742:     public function insert($path, $values);
 743: 
 744:     /**
 745:      * Returns an array representation of the results
 746:      *
 747:      * @param bool $preserveKeys whether to use the keys returned by this
 748:      * collection as the array keys. Keep in mind that it is valid for iterators
 749:      * to return the same key for different elements, setting this value to false
 750:      * can help getting all items if keys are not important in the result.
 751:      * @return array
 752:      */
 753:     public function toArray($preserveKeys = true);
 754: 
 755:     /**
 756:      * Returns an numerically-indexed array representation of the results.
 757:      * This is equivalent to calling `toArray(false)`
 758:      *
 759:      * @return array
 760:      */
 761:     public function toList();
 762: 
 763:     /**
 764:      * Convert a result set into JSON.
 765:      *
 766:      * Part of JsonSerializable interface.
 767:      *
 768:      * @return array The data to convert to JSON
 769:      */
 770:     public function jsonSerialize();
 771: 
 772:     /**
 773:      * Iterates once all elements in this collection and executes all stacked
 774:      * operations of them, finally it returns a new collection with the result.
 775:      * This is useful for converting non-rewindable internal iterators into
 776:      * a collection that can be rewound and used multiple times.
 777:      *
 778:      * A common use case is to re-use the same variable for calculating different
 779:      * data. In those cases it may be helpful and more performant to first compile
 780:      * a collection and then apply more operations to it.
 781:      *
 782:      * ### Example:
 783:      *
 784:      * ```
 785:      * $collection->map($mapper)->sortBy('age')->extract('name');
 786:      * $compiled = $collection->compile();
 787:      * $isJohnHere = $compiled->some($johnMatcher);
 788:      * $allButJohn = $compiled->filter($johnMatcher);
 789:      * ```
 790:      *
 791:      * In the above example, had the collection not been compiled before, the
 792:      * iterations for `map`, `sortBy` and `extract` would've been executed twice:
 793:      * once for getting `$isJohnHere` and once for `$allButJohn`
 794:      *
 795:      * You can think of this method as a way to create save points for complex
 796:      * calculations in a collection.
 797:      *
 798:      * @param bool $preserveKeys whether to use the keys returned by this
 799:      * collection as the array keys. Keep in mind that it is valid for iterators
 800:      * to return the same key for different elements, setting this value to false
 801:      * can help getting all items if keys are not important in the result.
 802:      * @return \Cake\Collection\CollectionInterface
 803:      */
 804:     public function compile($preserveKeys = true);
 805: 
 806:     /**
 807:      * Returns a new collection where any operations chained after it are guaranteed
 808:      * to be run lazily. That is, elements will be yieleded one at a time.
 809:      *
 810:      * A lazy collection can only be iterated once. A second attempt results in an error.
 811:      *
 812:      * @return \Cake\Collection\CollectionInterface
 813:      */
 814:     public function lazy();
 815: 
 816:     /**
 817:      * Returns a new collection where the operations performed by this collection.
 818:      * No matter how many times the new collection is iterated, those operations will
 819:      * only be performed once.
 820:      *
 821:      * This can also be used to make any non-rewindable iterator rewindable.
 822:      *
 823:      * @return \Cake\Collection\CollectionInterface
 824:      */
 825:     public function buffered();
 826: 
 827:     /**
 828:      * Returns a new collection with each of the elements of this collection
 829:      * after flattening the tree structure. The tree structure is defined
 830:      * by nesting elements under a key with a known name. It is possible
 831:      * to specify such name by using the '$nestingKey' parameter.
 832:      *
 833:      * By default all elements in the tree following a Depth First Search
 834:      * will be returned, that is, elements from the top parent to the leaves
 835:      * for each branch.
 836:      *
 837:      * It is possible to return all elements from bottom to top using a Breadth First
 838:      * Search approach by passing the '$dir' parameter with 'asc'. That is, it will
 839:      * return all elements for the same tree depth first and from bottom to top.
 840:      *
 841:      * Finally, you can specify to only get a collection with the leaf nodes in the
 842:      * tree structure. You do so by passing 'leaves' in the first argument.
 843:      *
 844:      * The possible values for the first argument are aliases for the following
 845:      * constants and it is valid to pass those instead of the alias:
 846:      *
 847:      * - desc: TreeIterator::SELF_FIRST
 848:      * - asc: TreeIterator::CHILD_FIRST
 849:      * - leaves: TreeIterator::LEAVES_ONLY
 850:      *
 851:      * ### Example:
 852:      *
 853:      * ```
 854:      * $collection = new Collection([
 855:      *  ['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
 856:      *  ['id' => 4, 'children' => [['id' => 5]]]
 857:      * ]);
 858:      * $flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
 859:      * ```
 860:      *
 861:      * @param string|int $dir The direction in which to return the elements
 862:      * @param string|callable $nestingKey The key name under which children are nested
 863:      * or a callable function that will return the children list
 864:      * @return \Cake\Collection\CollectionInterface
 865:      */
 866:     public function listNested($dir = 'desc', $nestingKey = 'children');
 867: 
 868:     /**
 869:      * Creates a new collection that when iterated will stop yielding results if
 870:      * the provided condition evaluates to true.
 871:      *
 872:      * This is handy for dealing with infinite iterators or any generator that
 873:      * could start returning invalid elements at a certain point. For example,
 874:      * when reading lines from a file stream you may want to stop the iteration
 875:      * after a certain value is reached.
 876:      *
 877:      * ### Example:
 878:      *
 879:      * Get an array of lines in a CSV file until the timestamp column is less than a date
 880:      *
 881:      * ```
 882:      * $lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
 883:      *  return (new DateTime($value))->format('Y') < 2012;
 884:      * })
 885:      * ->toArray();
 886:      * ```
 887:      *
 888:      * Get elements until the first unapproved message is found:
 889:      *
 890:      * ```
 891:      * $comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
 892:      * ```
 893:      *
 894:      * @param callable $condition the method that will receive each of the elements and
 895:      * returns true when the iteration should be stopped.
 896:      * If an array, it will be interpreted as a key-value list of conditions where
 897:      * the key is a property path as accepted by `Collection::extract`,
 898:      * and the value the condition against with each element will be matched.
 899:      * @return \Cake\Collection\CollectionInterface
 900:      */
 901:     public function stopWhen($condition);
 902: 
 903:     /**
 904:      * Creates a new collection where the items are the
 905:      * concatenation of the lists of items generated by the transformer function
 906:      * applied to each item in the original collection.
 907:      *
 908:      * The transformer function will receive the value and the key for each of the
 909:      * items in the collection, in that order, and it must return an array or a
 910:      * Traversable object that can be concatenated to the final result.
 911:      *
 912:      * If no transformer function is passed, an "identity" function will be used.
 913:      * This is useful when each of the elements in the source collection are
 914:      * lists of items to be appended one after another.
 915:      *
 916:      * ### Example:
 917:      *
 918:      * ```
 919:      * $items [[1, 2, 3], [4, 5]];
 920:      * $unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
 921:      * ```
 922:      *
 923:      * Using a transformer
 924:      *
 925:      * ```
 926:      * $items [1, 2, 3];
 927:      * $allItems = (new Collection($items))->unfold(function ($page) {
 928:      *  return $service->fetchPage($page)->toArray();
 929:      * });
 930:      * ```
 931:      *
 932:      * @param callable|null $transformer A callable function that will receive each of
 933:      * the items in the collection and should return an array or Traversable object
 934:      * @return \Cake\Collection\CollectionInterface
 935:      */
 936:     public function unfold(callable $transformer = null);
 937: 
 938:     /**
 939:      * Passes this collection through a callable as its first argument.
 940:      * This is useful for decorating the full collection with another object.
 941:      *
 942:      * ### Example:
 943:      *
 944:      * ```
 945:      * $items = [1, 2, 3];
 946:      * $decorated = (new Collection($items))->through(function ($collection) {
 947:      *      return new MyCustomCollection($collection);
 948:      * });
 949:      * ```
 950:      *
 951:      * @param callable $handler A callable function that will receive
 952:      * this collection as first argument.
 953:      * @return \Cake\Collection\CollectionInterface
 954:      */
 955:     public function through(callable $handler);
 956: 
 957:     /**
 958:      * Combines the elements of this collection with each of the elements of the
 959:      * passed iterables, using their positional index as a reference.
 960:      *
 961:      * ### Example:
 962:      *
 963:      * ```
 964:      * $collection = new Collection([1, 2]);
 965:      * $collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
 966:      * ```
 967:      *
 968:      * @param array|\Traversable ...$items The collections to zip.
 969:      * @return \Cake\Collection\CollectionInterface
 970:      */
 971:     public function zip($items);
 972: 
 973:     /**
 974:      * Combines the elements of this collection with each of the elements of the
 975:      * passed iterables, using their positional index as a reference.
 976:      *
 977:      * The resulting element will be the return value of the $callable function.
 978:      *
 979:      * ### Example:
 980:      *
 981:      * ```
 982:      * $collection = new Collection([1, 2]);
 983:      * $zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
 984:      *   return array_sum($args);
 985:      * });
 986:      * $zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
 987:      * ```
 988:      *
 989:      * @param array|\Traversable ...$items The collections to zip.
 990:      * @param callable $callable The function to use for zipping the elements together.
 991:      * @return \Cake\Collection\CollectionInterface
 992:      */
 993:     public function zipWith($items, $callable);
 994: 
 995:     /**
 996:      * Breaks the collection into smaller arrays of the given size.
 997:      *
 998:      * ### Example:
 999:      *
1000:      * ```
1001:      * $items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
1002:      * $chunked = (new Collection($items))->chunk(3)->toList();
1003:      * // Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
1004:      * ```
1005:      *
1006:      * @param int $chunkSize The maximum size for each chunk
1007:      * @return \Cake\Collection\CollectionInterface
1008:      */
1009:     public function chunk($chunkSize);
1010: 
1011:     /**
1012:      * Breaks the collection into smaller arrays of the given size.
1013:      *
1014:      * ### Example:
1015:      *
1016:      * ```
1017:      * $items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
1018:      * $chunked = (new Collection($items))->chunkWithKeys(3)->toList();
1019:      * // Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
1020:      * ```
1021:      *
1022:      * @param int $chunkSize The maximum size for each chunk
1023:      * @param bool $preserveKeys If the keys of the array should be preserved
1024:      * @return \Cake\Collection\CollectionInterface
1025:      */
1026:     public function chunkWithKeys($chunkSize, $preserveKeys = true);
1027: 
1028:     /**
1029:      * Returns whether or not there are elements in this collection
1030:      *
1031:      * ### Example:
1032:      *
1033:      * ```
1034:      * $items [1, 2, 3];
1035:      * (new Collection($items))->isEmpty(); // false
1036:      * ```
1037:      *
1038:      * ```
1039:      * (new Collection([]))->isEmpty(); // true
1040:      * ```
1041:      *
1042:      * @return bool
1043:      */
1044:     public function isEmpty();
1045: 
1046:     /**
1047:      * Returns the closest nested iterator that can be safely traversed without
1048:      * losing any possible transformations. This is used mainly to remove empty
1049:      * IteratorIterator wrappers that can only slowdown the iteration process.
1050:      *
1051:      * @return \Traversable
1052:      */
1053:     public function unwrap();
1054: 
1055:     /**
1056:      * Transpose rows and columns into columns and rows
1057:      *
1058:      * ### Example:
1059:      *
1060:      * ```
1061:      * $items = [
1062:      *       ['Products', '2012', '2013', '2014'],
1063:      *       ['Product A', '200', '100', '50'],
1064:      *       ['Product B', '300', '200', '100'],
1065:      *       ['Product C', '400', '300', '200'],
1066:      * ]
1067:      *
1068:      * $transpose = (new Collection($items))->transpose()->toList();
1069:      *
1070:      * // Returns
1071:      * // [
1072:      * //     ['Products', 'Product A', 'Product B', 'Product C'],
1073:      * //     ['2012', '200', '300', '400'],
1074:      * //     ['2013', '100', '200', '300'],
1075:      * //     ['2014', '50', '100', '200'],
1076:      * // ]
1077:      * ```
1078:      *
1079:      * @return \Cake\Collection\CollectionInterface
1080:      */
1081:     public function transpose();
1082: 
1083:     /**
1084:      * Returns the amount of elements in the collection.
1085:      *
1086:      * ## WARNINGS:
1087:      *
1088:      * ### Consumes all elements for NoRewindIterator collections:
1089:      *
1090:      * On certain type of collections, calling this method may render unusable afterwards.
1091:      * That is, you may not be able to get elements out of it, or to iterate on it anymore.
1092:      *
1093:      * Specifically any collection wrapping a Generator (a function with a yield statement)
1094:      * or a unbuffered database cursor will not accept any other function calls after calling
1095:      * `count()` on it.
1096:      *
1097:      * Create a new collection with `buffered()` method to overcome this problem.
1098:      *
1099:      * ### Can report more elements than unique keys:
1100:      *
1101:      * Any collection constructed by appending collections together, or by having internal iterators
1102:      * returning duplicate keys, will report a larger amount of elements using this functions than
1103:      * the final amount of elements when converting the collections to a keyed array. This is because
1104:      * duplicate keys will be collapsed into a single one in the final array, whereas this count method
1105:      * is only concerned by the amount of elements after converting it to a plain list.
1106:      *
1107:      * If you need the count of elements after taking the keys in consideration
1108:      * (the count of unique keys), you can call `countKeys()`
1109:      *
1110:      * ### Will change the current position of the iterator:
1111:      *
1112:      * Calling this method at the same time that you are iterating this collections, for example in
1113:      * a foreach, will result in undefined behavior. Avoid doing this.
1114:      *
1115:      *
1116:      * @return int
1117:      */
1118:     public function count();
1119: 
1120:     /**
1121:      * Returns the number of unique keys in this iterator. This is, the number of
1122:      * elements the collection will contain after calling `toArray()`
1123:      *
1124:      * This method comes with a number of caveats. Please refer to `CollectionInterface::count()`
1125:      * for details.
1126:      *
1127:      * @see \Cake\Collection\CollectionInterface::count()
1128:      * @return int
1129:      */
1130:     public function countKeys();
1131: }
1132: 
Follow @CakePHP
#IRC
OpenHub
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Logos & Trademarks
  • Community
  • Team
  • Issues (Github)
  • YouTube Channel
  • Get Involved
  • Bakery
  • Featured Resources
  • Newsletter
  • Certification
  • My CakePHP
  • CakeFest
  • Facebook
  • Twitter
  • Help & Support
  • Forum
  • Stack Overflow
  • IRC
  • Slack
  • Paid Support

Generated using CakePHP API Docs