ItemsContainer.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace AlexLcDee\RegistryContainer;
  3. class ItemsContainer
  4. {
  5. /**
  6. * @var RegistrableItem[]
  7. */
  8. private $data = [];
  9. private $attributesMap = [];
  10. private $type;
  11. private $current = 0;
  12. /**
  13. * ItemsContainer constructor.
  14. * @param string $type type name of items inside container
  15. */
  16. public function __construct($type)
  17. {
  18. $this->type = $type;
  19. }
  20. /**
  21. * @param RegistrableItem $item
  22. * @throws RegistryException
  23. */
  24. public function add(RegistrableItem $item)
  25. {
  26. if (!($item instanceof $this->type)) {
  27. throw new RegistryException(strtr('Item must be an instance of {class}', [
  28. '{class}' => $this->type
  29. ]));
  30. }
  31. $this->data[] = $item;
  32. $this->mapAttributes($item, $this->current);
  33. $this->current++;
  34. }
  35. /**
  36. * @param RegistrableItem $item
  37. * @param int $itemPosition
  38. */
  39. private function mapAttributes(RegistrableItem $item, int $itemPosition)
  40. {
  41. if (!count($this->attributesMap)) {
  42. foreach ($item->getAttributes() as $attributeName => $attribute) {
  43. if (is_scalar($attribute)) {
  44. $this->attributesMap[$attributeName] = [
  45. $attribute => $itemPosition
  46. ];
  47. }
  48. }
  49. } else {
  50. foreach ($item->getAttributes() as $attributeName => $attribute) {
  51. if (is_scalar($attribute)) {
  52. $this->attributesMap[$attributeName][$attribute] = $itemPosition;
  53. }
  54. }
  55. }
  56. }
  57. /**
  58. * @param string $attributeName
  59. * @return array
  60. */
  61. public function getListOf(string $attributeName)
  62. {
  63. if (isset($this->attributesMap[$attributeName])) {
  64. return array_keys($this->attributesMap[$attributeName]);
  65. }
  66. return [];
  67. }
  68. /**
  69. * @param string $attributeName
  70. * @param mixed $value
  71. * @return null|RegistrableItem
  72. */
  73. public function getItemBy(string $attributeName, $value)
  74. {
  75. if (isset($this->attributesMap[$attributeName]) && isset($this->attributesMap[$attributeName][$value])) {
  76. $item = clone $this->data[$this->attributesMap[$attributeName][$value]];
  77. return $item;
  78. }
  79. return null;
  80. }
  81. }