| 1 | <?php |
||
| 17 | { |
||
| 18 | private array $bag = []; |
||
|
|
|||
| 19 | |||
| 20 | public function __construct(array $builders = []) |
||
| 21 | { |
||
| 22 | foreach ($builders as $builder) { |
||
| 23 | $this->add($builder); |
||
| 24 | } |
||
| 25 | } |
||
| 26 | |||
| 27 | public function add(BuilderInterface $builder): ?string |
||
| 28 | { |
||
| 29 | $name = bin2hex(random_bytes(30)); |
||
| 30 | |||
| 31 | if (method_exists($builder, 'getName')) { |
||
| 32 | $name = $builder->getName(); |
||
| 33 | } |
||
| 34 | |||
| 35 | $this->bag[$name] = $builder; |
||
| 36 | |||
| 37 | return $name; |
||
| 38 | } |
||
| 39 | |||
| 40 | public function has(string $name): bool |
||
| 41 | { |
||
| 42 | return isset($this->bag[$name]); |
||
| 43 | } |
||
| 44 | |||
| 45 | public function remove(string $name): void |
||
| 46 | { |
||
| 47 | unset($this->bag[$name]); |
||
| 48 | } |
||
| 49 | |||
| 50 | public function clear(): void |
||
| 51 | { |
||
| 52 | $this->bag = []; |
||
| 53 | } |
||
| 54 | |||
| 55 | public function get(string $name): BuilderInterface |
||
| 56 | { |
||
| 57 | return $this->bag[$name]; |
||
| 58 | } |
||
| 59 | |||
| 60 | public function all(?string $type = null): array |
||
| 61 | { |
||
| 62 | return array_filter( |
||
| 63 | $this->bag, |
||
| 64 | /** @var BuilderInterface $builder */ |
||
| 65 | function (BuilderInterface $builder) use ($type) { |
||
| 66 | return $type === null || $builder->getType() == $type; |
||
| 67 | } |
||
| 68 | ); |
||
| 69 | } |
||
| 70 | |||
| 71 | public function toArray(): array |
||
| 72 | { |
||
| 73 | $output = []; |
||
| 74 | foreach ($this->all() as $builder) { |
||
| 75 | $output = array_merge($output, $builder->toArray()); |
||
| 76 | } |
||
| 77 | |||
| 78 | return $output; |
||
| 79 | } |
||
| 80 | } |
||
| 81 |