`Entity` теперь имплементирует `Arrayable` и `ArrayAccess` для совместимости с иммутабельными методами коллекций

pull/15/head
Anthony Axenov 2021-12-08 15:55:52 +08:00
parent b57acf8b05
commit 793549aaac
3 changed files with 56 additions and 5 deletions

View File

@ -87,6 +87,7 @@ abstract class EntityCollection extends Collection
*/
public function checkCount(array $items = []): void
{
//TODO проверять пустоту?
if (count($items) > static::MAX_COUNT || $this->count() === static::MAX_COUNT) {
throw new (static::EXCEPTION_CLASS)(static::MAX_COUNT);
}

View File

@ -11,14 +11,29 @@ declare(strict_types = 1);
namespace AtolOnline\Entities;
use ArrayAccess;
use Illuminate\Contracts\Support\Arrayable;
use JsonSerializable;
use Stringable;
/**
* Абстрактное описание любой сущности, представляемой как json
*/
abstract class Entity implements JsonSerializable, Stringable
abstract class Entity implements JsonSerializable, Stringable, Arrayable, ArrayAccess
{
/**
* @inheritDoc
*/
abstract public function jsonSerialize(): array;
/**
* @inheritDoc
*/
public function toArray()
{
return $this->jsonSerialize();
}
/**
* Возвращает строковое представление json-структуры объекта
*
@ -26,6 +41,42 @@ abstract class Entity implements JsonSerializable, Stringable
*/
public function __toString()
{
return json_encode($this->jsonSerialize(), JSON_UNESCAPED_UNICODE);
return json_encode($this->toArray(), JSON_UNESCAPED_UNICODE);
}
/**
* @inheritDoc
*/
public function offsetExists(mixed $offset): bool
{
return isset($this->toArray()[$offset]);
}
/**
* @inheritDoc
*/
public function offsetGet(mixed $offset): mixed
{
return $this->toArray()[$offset];
}
/**
* @inheritDoc
*/
public function offsetSet(mixed $offset, mixed $value)
{
throw new \BadMethodCallException(
'Объект ' . static::class . ' нельзя изменять как массив. Следует использовать сеттеры.'
);
}
/**
* @inheritDoc
*/
public function offsetUnset(mixed $offset): void
{
throw new \BadMethodCallException(
'Объект ' . static::class . ' нельзя изменять как массив. Следует использовать сеттеры.'
);
}
}

View File

@ -16,8 +16,7 @@ use AtolOnline\Exceptions\InvalidEnumValueException;
use AtolOnline\Helpers;
use JetBrains\PhpStorm\{
ArrayShape,
Pure
};
Pure};
/**
* Класс, описывающий ставку НДС
@ -97,7 +96,7 @@ final class Vat extends Entity
}
/**
* Возвращает sdрасчитанный итоговый размер ставки НДС в рублях
* Возвращает расчитанный итоговый размер ставки НДС в рублях
*
* @return float
* @see https://nalog-nalog.ru/nds/nalogovaya_baza_nds/kak-schitat-nds-pravilno-vychislyaem-20-ot-summy-primer-algoritm/