From 3d3eba5b4ed8c77d716bde0ca574d05b33432736 Mon Sep 17 00:00:00 2001 From: AnthonyAxenov Date: Mon, 6 Dec 2021 14:16:34 +0800 Subject: [PATCH] =?UTF-8?q?=D0=91=D0=B0=D0=B7=D0=BE=D0=B2=D1=8B=D0=B9=20?= =?UTF-8?q?=D0=BA=D0=BB=D0=B0=D1=81=D1=81=20=D0=BA=D0=BE=D0=BB=D0=BB=D0=B5?= =?UTF-8?q?=D0=BA=D1=86=D0=B8=D0=B8=20=D0=BE=D0=B1=D1=8A=D0=B5=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D0=B2=20`EntityCollection`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Entities/EntityCollection.php | 119 ++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 src/Entities/EntityCollection.php diff --git a/src/Entities/EntityCollection.php b/src/Entities/EntityCollection.php new file mode 100644 index 0000000..e74557f --- /dev/null +++ b/src/Entities/EntityCollection.php @@ -0,0 +1,119 @@ +checkCount($items); + parent::__construct($items); + } + + /** + * @inheritDoc + */ + public function prepend($value, $key = null): self + { + $this->checkCount(); + return parent::prepend($value, $key); + } + + /** + * @inheritDoc + */ + public function add($item): self + { + $this->checkCount(); + return parent::add($item); + } + + /** + * @inheritDoc + */ + public function push(...$values): self + { + $this->checkCount(); + return parent::push(...$values); + } + + /** + * @inheritDoc + */ + public function merge($items): self + { + $this->checkCount(); + return parent::merge($items); + } + + /** + * @inheritDoc + * @throws \Exception + */ + public function jsonSerialize(): array + { + return array_map(function ($value) { + $this->checkEntityClass($value); + if ($value instanceof \JsonSerializable) { + return $value->jsonSerialize(); + } elseif ($value instanceof Jsonable) { + return json_decode($value->toJson(), true); + } elseif ($value instanceof Arrayable) { + return $value->toArray(); + } + return $value; + }, $this->all()); + } + + /** + * Проверяет количество ставок + * + * @param array $items Массив элементов, если пустой - проверит содержимое коллекции + * @return void + */ + private function checkCount(array $items = []): void + { + if ( + count($items) > static::MAX_COUNT || + $this->count() === static::MAX_COUNT + ) { + $exception = static::EXCEPTION_CLASS; + throw new $exception(static::MAX_COUNT); + } + } + + /** + * @throws \Exception + */ + private function checkEntityClass(mixed $item): void + { + if (!is_object($item) || $item::class !== static::ENTITY_CLASS) { + //TODO proper exception + throw new \Exception( + 'Коллекция должна содержать только объекты класса ' . + static::ENTITY_CLASS . ', найден ' . $item::class + ); + } + } +}