11
0
Fork 0
mirror of https://github.com/n3w/helpers-cli-input.git synced 2025-12-19 20:53:27 +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);
$index = null;
$type = null;
2019-05-20 15:08:41 +10:00
if (!$replace && null !== $this->find($input->name(), null, null, $index, $type)) {
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] = $argument;
} else {
$this->items[$class->getShortName()][] = $input;
}
2019-05-20 15:08:41 +10:00
return $this;
2019-05-20 15:08:41 +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
{
foreach($this->items as $type => $items) {
2019-05-20 15:08:41 +10:00
// Check if we're restricting to or excluding specific types
if(null !== $restrictToType && !in_array($type, $restrictToType)) {
continue;
} elseif(null !== $excludeType && in_array($type, $excludeType)) {
continue;
2019-05-20 15:08:41 +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;
return null;
}
public function getTypes(): array {
return array_keys($this->items);
2019-05-20 15:08:41 +10:00
}
public function getItems(): array {
return $this->items;
2019-05-20 15:08:41 +10:00
}
public function getItemsByType(string $type): array {
return $this->items[$type] ?? [];
2019-05-20 15:08:41 +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
{
$items = [];
2019-05-20 15:08:41 +10:00
foreach ($collections as $c) {
foreach($c->items() as $type => $items) {
foreach($items as $item) {
$items[] = $item;
}
}
2019-05-20 15:08:41 +10:00
}
$mergedCollection = new self();
foreach ($items 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;
}
}