1: <?php
2:
3: namespace Chromabits\Nucleus\Data;
4:
5: use Chromabits\Nucleus\Control\Maybe;
6: use Chromabits\Nucleus\Data\Interfaces\LeftFoldableInterface;
7: use Chromabits\Nucleus\Data\Interfaces\ReadMapInterface;
8: use Chromabits\Nucleus\Exceptions\CoreException;
9: use Chromabits\Nucleus\Foundation\BaseObject;
10: use Chromabits\Nucleus\Support\Std;
11: use Closure;
12: use Traversable;
13:
14: /**
15: * Class TraversableMap
16: *
17: * A Map backed by a Traversable object.
18: *
19: * Warning: At the moment, ReadMap operations on this object are not optimal.
20: *
21: * @author Eduardo Trujillo <ed@chromabits.com>
22: * @package Chromabits\Nucleus\Data
23: */
24: class TraversableLeftFoldable extends BaseObject implements
25: LeftFoldableInterface, ReadMapInterface
26: {
27: /**
28: * @var TraversableLeftFoldable
29: */
30: protected $value;
31:
32: /**
33: * Construct an instance of a TraversableLeftFoldable.
34: *
35: * @param Traversable $input
36: */
37: public function __construct(Traversable $input)
38: {
39: parent::__construct();
40:
41: $this->value = $input;
42: }
43:
44: /**
45: * Combine all the elements in the traversable using a combining operation.
46: *
47: * @param callable|Closure $closure
48: * @param mixed $initial
49: *
50: * @return mixed
51: */
52: public function foldl(callable $closure, $initial)
53: {
54: $accumulator = $initial;
55:
56: foreach ($this->value as $value) {
57: $accumulator = Std::call($closure, $accumulator, $value);
58: }
59:
60: return $accumulator;
61: }
62:
63: /**
64: * Combine all the elements in the traversable using a combining operation.
65: *
66: * @param callable|Closure $closure
67: * @param mixed $initial
68: *
69: * @return mixed
70: */
71: public function foldlWithKey(callable $closure, $initial)
72: {
73: $accumulator = $initial;
74:
75: foreach ($this->value as $key => $value) {
76: $accumulator = Std::call($closure, $accumulator, $value, $key);
77: }
78:
79: return $accumulator;
80: }
81:
82: /**
83: * Get the value of the provided key.
84: *
85: * @param string $key
86: *
87: * @return Maybe
88: * @throws CoreException
89: */
90: public function lookup($key)
91: {
92: foreach ($this->value as $innerKey => $value) {
93: if ($key === $innerKey) {
94: return Maybe::just($value);
95: }
96: }
97:
98: return Maybe::nothing();
99: }
100:
101: /**
102: * Return whether or not the map contains the specified key.
103: *
104: * @param string $key
105: *
106: * @return bool
107: */
108: public function member($key)
109: {
110: foreach ($this->value as $innerKey => $value) {
111: if ($key === $innerKey) {
112: return true;
113: }
114: }
115:
116: return false;
117: }
118: }
119: