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 ArrayIterator;
18: use InvalidArgumentException;
19: use IteratorIterator;
20: use Serializable;
21: use Traversable;
22:
23: /**
24: * A collection is an immutable list of elements with a handful of functions to
25: * iterate, group, transform and extract information from it.
26: */
27: class Collection extends IteratorIterator implements CollectionInterface, Serializable
28: {
29:
30: use CollectionTrait;
31:
32: /**
33: * Constructor. You can provide an array or any traversable object
34: *
35: * @param array|\Traversable $items Items.
36: * @throws \InvalidArgumentException If passed incorrect type for items.
37: */
38: public function __construct($items)
39: {
40: if (is_array($items)) {
41: $items = new ArrayIterator($items);
42: }
43:
44: if (!($items instanceof Traversable)) {
45: $msg = 'Only an array or \Traversable is allowed for Collection';
46: throw new InvalidArgumentException($msg);
47: }
48:
49: parent::__construct($items);
50: }
51:
52: /**
53: * Returns a string representation of this object that can be used
54: * to reconstruct it
55: *
56: * @return string
57: */
58: public function serialize()
59: {
60: return serialize($this->buffered());
61: }
62:
63: /**
64: * Unserializes the passed string and rebuilds the Collection instance
65: *
66: * @param string $collection The serialized collection
67: * @return void
68: */
69: public function unserialize($collection)
70: {
71: $this->__construct(unserialize($collection));
72: }
73:
74: /**
75: * {@inheritDoc}
76: *
77: * @return int
78: */
79: public function count()
80: {
81: $traversable = $this->optimizeUnwrap();
82:
83: if (is_array($traversable)) {
84: return count($traversable);
85: }
86:
87: return iterator_count($traversable);
88: }
89:
90: /**
91: * {@inheritDoc}
92: *
93: * @return int
94: */
95: public function countKeys()
96: {
97: return count($this->toArray());
98: }
99:
100: /**
101: * Returns an array that can be used to describe the internal state of this
102: * object.
103: *
104: * @return array
105: */
106: public function __debugInfo()
107: {
108: return [
109: 'count' => $this->count(),
110: ];
111: }
112: }
113: