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\Iterator;
16:
17: use ArrayIterator;
18: use Cake\Collection\Collection;
19: use Cake\Collection\CollectionInterface;
20:
21: /**
22: * Creates an iterator from another iterator that extract the requested column
23: * or property based on a path
24: */
25: class ExtractIterator extends Collection
26: {
27:
28: /**
29: * A callable responsible for extracting a single value for each
30: * item in the collection.
31: *
32: * @var callable
33: */
34: protected $_extractor;
35:
36: /**
37: * Creates the iterator that will return the requested property for each value
38: * in the collection expressed in $path
39: *
40: * ### Example:
41: *
42: * Extract the user name for all comments in the array:
43: *
44: * ```
45: * $items = [
46: * ['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
47: * ['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
48: * ];
49: * $extractor = new ExtractIterator($items, 'comment.user.name'');
50: * ```
51: *
52: * @param array|\Traversable $items The list of values to iterate
53: * @param string $path a dot separated string symbolizing the path to follow
54: * inside the hierarchy of each value so that the column can be extracted.
55: */
56: public function __construct($items, $path)
57: {
58: $this->_extractor = $this->_propertyExtractor($path);
59: parent::__construct($items);
60: }
61:
62: /**
63: * Returns the column value defined in $path or null if the path could not be
64: * followed
65: *
66: * @return mixed
67: */
68: public function current()
69: {
70: $extractor = $this->_extractor;
71:
72: return $extractor(parent::current());
73: }
74:
75: /**
76: * {@inheritDoc}
77: *
78: * We perform here some strictness analysis so that the
79: * iterator logic is bypassed entirely.
80: *
81: * @return \Iterator
82: */
83: public function unwrap()
84: {
85: $iterator = $this->getInnerIterator();
86:
87: if ($iterator instanceof CollectionInterface) {
88: $iterator = $iterator->unwrap();
89: }
90:
91: if (get_class($iterator) !== ArrayIterator::class) {
92: return $this;
93: }
94:
95: // ArrayIterator can be traversed strictly.
96: // Let's do that for performance gains
97:
98: $callback = $this->_extractor;
99: $res = [];
100:
101: foreach ($iterator->getArrayCopy() as $k => $v) {
102: $res[$k] = $callback($v);
103: }
104:
105: return new ArrayIterator($res);
106: }
107: }
108: