11
0
Fork 0
mirror of https://github.com/n3w/helpers-cli-input.git synced 2025-12-19 12:43:23 +00:00
helpers-cli-input/src/Input/InputCollection.php

99 lines
2.6 KiB
PHP
Raw Normal View History

2019-05-20 15:08:41 +10:00
<?php
declare(strict_types=1);
namespace pointybeard\Helpers\Cli\Input;
class InputCollection
{
private $items = [];
2019-05-20 15:08:41 +10:00
// Prevents the class from being instanciated
public function __construct()
{
}
public function append(Interfaces\InputTypeInterface $input, bool $replace = false): self
{
$class = new \ReflectionClass($input);
if (null !== $this->find($input->name(), null, null, $type, $index) && !$replace) {
throw new \Exception("{$class->getShortName()} '{$input->name()}' already exists in this collection");
2019-05-20 15:08:41 +10:00
}
if (true == $replace && null !== $index) {
$this->items[$class->getShortName()][$index] = $input;
} else {
$this->items[$class->getShortName()][] = $input;
}
2019-05-20 15:08:41 +10:00
return $this;
2019-05-20 15:08:41 +10:00
}
2019-05-27 00:22:25 +10:00
public function find(string $name, array $restrictToType = null, array $excludeType = null, &$type = null, &$index = null): ?AbstractInputType
2019-05-20 15:08:41 +10:00
{
2019-05-27 00:22:25 +10:00
foreach ($this->items as $type => $items) {
// Check if we're restricting to or excluding specific types
2019-05-27 00:22:25 +10:00
if (null !== $restrictToType && !in_array($type, $restrictToType)) {
continue;
2019-05-27 00:22:25 +10:00
} elseif (null !== $excludeType && in_array($type, $excludeType)) {
continue;
2019-05-20 15:08:41 +10:00
}
2019-05-27 00:22:25 +10:00
foreach ($items as $index => $item) {
if ($item->respondsTo($name)) {
return $item;
}
}
}
$type = null;
2019-05-20 15:08:41 +10:00
$index = null;
2019-05-27 00:22:25 +10:00
2019-05-20 15:08:41 +10:00
return null;
}
2019-05-27 00:22:25 +10:00
public function getTypes(): array
{
return array_keys($this->items);
2019-05-20 15:08:41 +10:00
}
2019-05-27 00:22:25 +10:00
public function getItems(): array
{
return $this->items;
2019-05-20 15:08:41 +10:00
}
2019-05-27 00:22:25 +10:00
public function getItemsByType(string $type): array
{
return $this->items[$type] ?? [];
2019-05-20 15:08:41 +10:00
}
2019-05-27 00:22:25 +10:00
public function getItemByIndex(string $type, int $index): ?AbstractInputType
{
return $this->items[$type][$index] ?? null;
2019-05-20 15:08:41 +10:00
}
public static function merge(self ...$collections): self
{
$inputs = [];
2019-05-20 15:08:41 +10:00
foreach ($collections as $c) {
foreach ($c->getItems() as $type => $items) {
2019-05-27 00:22:25 +10:00
foreach ($items as $item) {
$inputs[] = $item;
}
}
2019-05-20 15:08:41 +10:00
}
$mergedCollection = new self();
foreach ($inputs as $input) {
2019-05-20 15:08:41 +10:00
try {
$mergedCollection->append($input, true);
} catch (\Exception $ex) {
// Already exists, so skip it.
}
}
return $mergedCollection;
}
}