|
@@ -0,0 +1,94 @@
|
|
|
|
|
+<?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])) {
|
|
|
|
|
+ return $this->data[$this->attributesMap[$attributeName][$value]];
|
|
|
|
|
+ }
|
|
|
|
|
+ return null;
|
|
|
|
|
+ }
|
|
|
|
|
+}
|