1: <?php declare(strict_types=1);
2:
3: namespace Salient\Iterator\Concern;
4:
5: use Salient\Contract\Iterator\FluentIteratorInterface;
6:
7: /**
8: * Implements FluentIteratorInterface
9: *
10: * @see FluentIteratorInterface
11: *
12: * @api
13: *
14: * @template TKey of array-key
15: * @template TValue
16: *
17: * @phpstan-require-implements FluentIteratorInterface
18: */
19: trait FluentIteratorTrait
20: {
21: /**
22: * @inheritDoc
23: */
24: public function toArray(bool $preserveKeys = true): array
25: {
26: if ($preserveKeys) {
27: foreach ($this as $key => $value) {
28: $array[$key] = $value;
29: }
30: } else {
31: foreach ($this as $value) {
32: $array[] = $value;
33: }
34: }
35: return $array ?? [];
36: }
37:
38: /**
39: * @inheritDoc
40: */
41: public function forEach(callable $callback)
42: {
43: foreach ($this as $key => $value) {
44: $callback($value, $key);
45: }
46: return $this;
47: }
48:
49: /**
50: * @inheritDoc
51: */
52: public function nextWithValue($key, $value, bool $strict = false)
53: {
54: $found = null;
55: foreach ($this as $current) {
56: // Move forward-only iterators to the next element
57: if ($found) {
58: break;
59: }
60: if (is_array($current)) {
61: if (array_key_exists($key, $current)) {
62: $_value = $current[$key];
63: } else {
64: continue;
65: }
66: } elseif (is_object($current)) {
67: $_value = $current->$key;
68: } else {
69: continue;
70: }
71: if ($strict) {
72: if ($_value === $value) {
73: $found = $current;
74: }
75: } elseif ($_value == $value) {
76: $found = $current;
77: }
78: }
79: // @phpstan-ignore return.type
80: return $found;
81: }
82: }
83: