| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- <?php
- namespace AlexLcDee\RegistryContainer;
- class ItemsContainer
- {
- /**
- * @var RegistrableItem[]
- */
- private $data = [];
- private $attributesMap = [];
- private $type;
- private $current = 0;
- /**
- * ItemsContainer constructor.
- * @param string $type type name of items inside container
- */
- public function __construct($type)
- {
- $this->type = $type;
- }
- /**
- * @param RegistrableItem $item
- * @throws RegistryException
- */
- public function add(RegistrableItem $item)
- {
- if (!($item instanceof $this->type)) {
- throw new RegistryException(strtr('Item must be an instance of {class}', [
- '{class}' => $this->type
- ]));
- }
- $this->data[] = $item;
- $this->mapAttributes($item, $this->current);
- $this->current++;
- }
- /**
- * @param RegistrableItem $item
- * @param int $itemPosition
- */
- private function mapAttributes(RegistrableItem $item, int $itemPosition)
- {
- if (!count($this->attributesMap)) {
- foreach ($item->getAttributes() as $attributeName => $attribute) {
- if (is_scalar($attribute)) {
- $this->attributesMap[$attributeName] = [
- $attribute => $itemPosition
- ];
- }
- }
- } else {
- foreach ($item->getAttributes() as $attributeName => $attribute) {
- if (is_scalar($attribute)) {
- $this->attributesMap[$attributeName][$attribute] = $itemPosition;
- }
- }
- }
- }
- /**
- * @param string $attributeName
- * @return array
- */
- public function getListOf(string $attributeName)
- {
- if (isset($this->attributesMap[$attributeName])) {
- return array_keys($this->attributesMap[$attributeName]);
- }
- return [];
- }
- /**
- * @param string $attributeName
- * @param mixed $value
- * @return null|RegistrableItem
- */
- public function getItemBy(string $attributeName, $value)
- {
- if (isset($this->attributesMap[$attributeName]) && isset($this->attributesMap[$attributeName][$value])) {
- $item = clone $this->data[$this->attributesMap[$attributeName][$value]];
- return $item;
- }
- return null;
- }
- }
|