1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of Railt package. |
4
|
|
|
* |
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
6
|
|
|
* file that was distributed with this source code. |
7
|
|
|
*/ |
8
|
|
|
declare(strict_types=1); |
9
|
|
|
|
10
|
|
|
namespace Railt\SDL\Frontend\Deferred; |
11
|
|
|
|
12
|
|
|
use Railt\SDL\Frontend\Map; |
13
|
|
|
use Railt\SDL\IR\Type\TypeNameInterface; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Class Storage |
17
|
|
|
*/ |
18
|
|
|
class Storage implements \IteratorAggregate, \Countable |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* @var int |
22
|
|
|
*/ |
23
|
|
|
private $id = 0; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var Map<TypeNameInterface|int,DeferredInterface> |
27
|
|
|
*/ |
28
|
|
|
private $deferred; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Storage constructor. |
32
|
|
|
*/ |
33
|
|
|
public function __construct() |
34
|
|
|
{ |
35
|
|
|
$this->deferred = new Map(); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param DeferredInterface $deferred |
40
|
|
|
* @return DeferredInterface |
41
|
|
|
*/ |
42
|
|
|
public function add(DeferredInterface $deferred): DeferredInterface |
43
|
|
|
{ |
44
|
|
|
$id = $deferred instanceof Identifiable ? $deferred->getDefinition()->getName() : $this->id++; |
45
|
|
|
|
46
|
|
|
return $this->deferred[$id] = $deferred; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param TypeNameInterface $name |
51
|
|
|
* @return null|DeferredInterface |
52
|
|
|
*/ |
53
|
|
|
public function first(TypeNameInterface $name): ?DeferredInterface |
54
|
|
|
{ |
55
|
|
|
return $this->deferred[$name] ?? null; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param \Closure $filter |
60
|
|
|
* @return iterable |
61
|
|
|
*/ |
62
|
|
|
public function only(\Closure $filter): iterable |
63
|
|
|
{ |
64
|
|
|
foreach ($this->getIterator() as $key => $deferred) { |
65
|
|
|
if ($filter($deferred, $key)) { |
66
|
|
|
yield $key => $deferred; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* @param \Closure $filter |
73
|
|
|
* @return iterable|DeferredInterface[] |
74
|
|
|
*/ |
75
|
|
|
public function extract(\Closure $filter): iterable |
76
|
|
|
{ |
77
|
|
|
foreach ($this->only($filter) as $key => $deferred) { |
78
|
|
|
if ($filter($deferred, $key)) { |
79
|
|
|
$this->deferred->delete($key); |
80
|
|
|
|
81
|
|
|
yield $key => $deferred; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* @return iterable|DeferredInterface[] |
88
|
|
|
*/ |
89
|
|
|
public function getIterator(): iterable |
90
|
|
|
{ |
91
|
|
|
foreach ($this->deferred as $key => $deferred) { |
92
|
|
|
yield $key => $deferred; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|
96
|
|
|
/** |
97
|
|
|
* @return int |
98
|
|
|
*/ |
99
|
|
|
public function count(): int |
100
|
|
|
{ |
101
|
|
|
return \count($this->deferred); |
102
|
|
|
} |
103
|
|
|
} |
104
|
|
|
|