From 2260233e3ffdf2fef65d1ad247b453d462c4a5b0 Mon Sep 17 00:00:00 2001 From: AnthonyAxenov Date: Fri, 3 Dec 2021 18:23:00 +0800 Subject: [PATCH] =?UTF-8?q?=D0=9E=D0=B1=D1=89=D0=B8=D0=B5=20=D1=81=D0=B5?= =?UTF-8?q?=D1=82=D1=82=D0=B5=D1=80=D1=8B-=D0=B3=D0=B5=D1=82=D1=82=D0=B5?= =?UTF-8?q?=D1=80=D1=8B=20=D1=81=D1=83=D1=89=D0=BD=D0=BE=D1=81=D1=82=D0=B5?= =?UTF-8?q?=D0=B9=20=D0=B2=D1=8B=D0=BD=D0=B5=D1=81=D0=B5=D0=BD=D1=8B=20?= =?UTF-8?q?=D0=B2=20=D1=82=D1=80=D0=B5=D0=B9=D1=82=D1=8B=20`HasEmail`,=20`?= =?UTF-8?q?HasInn`,=20`HasPhones`?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Кодстайл и микрорефакторинг сущностей --- src/Entities/AgentInfo.php | 38 ++++----- src/Entities/Client.php | 103 +++++------------------ src/Entities/Company.php | 91 +++++--------------- src/Entities/Item.php | 70 ++++++--------- src/Entities/Kkt.php | 12 +-- src/Entities/MoneyTransferOperator.php | 76 +++-------------- src/Entities/PayingAgent.php | 48 ++--------- src/Entities/ReceivePaymentsOperator.php | 46 +--------- src/Entities/Supplier.php | 86 +++---------------- src/Entities/Vat.php | 21 +++-- src/Traits/HasEmail.php | 57 +++++++++++++ src/Traits/HasInn.php | 53 ++++++++++++ src/Traits/HasPhones.php | 57 +++++++++++++ 13 files changed, 305 insertions(+), 453 deletions(-) create mode 100644 src/Traits/HasEmail.php create mode 100644 src/Traits/HasInn.php create mode 100644 src/Traits/HasPhones.php diff --git a/src/Entities/AgentInfo.php b/src/Entities/AgentInfo.php index 346cd4a..6b4ddec 100644 --- a/src/Entities/AgentInfo.php +++ b/src/Entities/AgentInfo.php @@ -45,21 +45,21 @@ class AgentInfo extends Entity * Конструктор * * @param string|null $type Признак агента (1057) - * @param PayingAgent|null $paying_agent Платёжный агент - * @param ReceivePaymentsOperator|null $receive_payments_operator Оператор по приёму платежей - * @param MoneyTransferOperator|null $money_transfer_operator Оператор перевода + * @param PayingAgent|null $pagent Платёжный агент + * @param ReceivePaymentsOperator|null $rp_operator Оператор по приёму платежей + * @param MoneyTransferOperator|null $mt_operator Оператор перевода * @throws InvalidEnumValueException */ public function __construct( ?string $type = null, - ?PayingAgent $paying_agent = null, - ?ReceivePaymentsOperator $receive_payments_operator = null, - ?MoneyTransferOperator $money_transfer_operator = null, + ?PayingAgent $pagent = null, + ?ReceivePaymentsOperator $rp_operator = null, + ?MoneyTransferOperator $mt_operator = null, ) { !is_null($type) && $this->setType($type); - !is_null($paying_agent) && $this->setPayingAgent($paying_agent); - !is_null($receive_payments_operator) && $this->setReceivePaymentsOperator($receive_payments_operator); - !is_null($money_transfer_operator) && $this->setMoneyTransferOperator($money_transfer_operator); + !is_null($pagent) && $this->setPayingAgent($pagent); + !is_null($rp_operator) && $this->setReceivePaymentsOperator($rp_operator); + !is_null($mt_operator) && $this->setMoneyTransferOperator($mt_operator); } /** @@ -79,7 +79,7 @@ class AgentInfo extends Entity * @return AgentInfo * @throws InvalidEnumValueException */ - public function setType(?string $type): AgentInfo + public function setType(?string $type): self { AgentTypes::isValid($type) && $this->type = $type; return $this; @@ -98,12 +98,12 @@ class AgentInfo extends Entity /** * Устанавливает платёжного агента * - * @param PayingAgent|null $paying_agent + * @param PayingAgent|null $agent * @return AgentInfo */ - public function setPayingAgent(?PayingAgent $paying_agent): AgentInfo + public function setPayingAgent(?PayingAgent $agent): self { - $this->paying_agent = $paying_agent; + $this->paying_agent = $agent; return $this; } @@ -120,12 +120,12 @@ class AgentInfo extends Entity /** * Устанавливает оператора по приёму платежей * - * @param ReceivePaymentsOperator|null $receive_payments_operator + * @param ReceivePaymentsOperator|null $operator * @return AgentInfo */ - public function setReceivePaymentsOperator(?ReceivePaymentsOperator $receive_payments_operator): AgentInfo + public function setReceivePaymentsOperator(?ReceivePaymentsOperator $operator): self { - $this->receive_payments_operator = $receive_payments_operator; + $this->receive_payments_operator = $operator; return $this; } @@ -142,12 +142,12 @@ class AgentInfo extends Entity /** * Устанавливает оператора перевода * - * @param MoneyTransferOperator|null $money_transfer_operator + * @param MoneyTransferOperator|null $operator * @return AgentInfo */ - public function setMoneyTransferOperator(?MoneyTransferOperator $money_transfer_operator): AgentInfo + public function setMoneyTransferOperator(?MoneyTransferOperator $operator): self { - $this->money_transfer_operator = $money_transfer_operator; + $this->money_transfer_operator = $operator; return $this; } diff --git a/src/Entities/Client.php b/src/Entities/Client.php index e0672c1..4e54f37 100644 --- a/src/Entities/Client.php +++ b/src/Entities/Client.php @@ -11,14 +11,19 @@ declare(strict_types = 1); namespace AtolOnline\Entities; -use AtolOnline\{ - Constants\Constraints, - Exceptions\InvalidEmailException, - Exceptions\InvalidInnLengthException, - Exceptions\InvalidPhoneException, - Exceptions\TooLongClientContactException, - Exceptions\TooLongClientNameException, - Exceptions\TooLongEmailException}; +use AtolOnline\Constants\Constraints; +use AtolOnline\Exceptions\{ + InvalidEmailException, + InvalidInnLengthException, + InvalidPhoneException, + TooLongClientNameException, + TooLongEmailException +}; +use AtolOnline\Traits\{ + HasEmail, + HasInn +}; +use JetBrains\PhpStorm\Pure; /** * Класс, описывающий покупателя @@ -27,38 +32,30 @@ use AtolOnline\{ */ class Client extends Entity { + use HasEmail, HasInn; + /** * @var string|null Наименование (1227) */ protected ?string $name = null; - /** - * @var string|null Email (1008) - */ - protected ?string $email = null; - /** * @var string|null Телефон (1008) */ protected ?string $phone = null; - /** - * @var string|null ИНН (1228) - */ - protected ?string $inn = null; - /** * Конструктор объекта покупателя * * @param string|null $name Наименование (1227) - * @param string|null $phone Email (1008) * @param string|null $email Телефон (1008) + * @param string|null $phone Email (1008) * @param string|null $inn ИНН (1228) - * @throws TooLongClientNameException - * @throws TooLongClientContactException - * @throws TooLongEmailException * @throws InvalidEmailException * @throws InvalidInnLengthException + * @throws InvalidPhoneException + * @throws TooLongClientNameException + * @throws TooLongEmailException */ public function __construct( ?string $name = null, @@ -101,38 +98,6 @@ class Client extends Entity return $this; } - /** - * Возвращает установленный email - * - * @return string|null - */ - public function getEmail(): ?string - { - return $this->email; - } - - /** - * Устанавливает email - * - * @param string|null $email - * @return $this - * @throws TooLongEmailException Слишком длинный email - * @throws InvalidEmailException Невалидный email - */ - public function setEmail(?string $email): self - { - if (is_string($email)) { - $email = preg_replace('/[\n\r\t]/', '', trim($email)); - if (mb_strlen($email) > Constraints::MAX_LENGTH_EMAIL) { - throw new TooLongEmailException($email); - } elseif (filter_var($email, FILTER_VALIDATE_EMAIL) === false) { - throw new InvalidEmailException($email); - } - } - $this->email = empty($email) ? null : $email; - return $this; - } - /** * Возвращает установленный телефон * @@ -162,38 +127,10 @@ class Client extends Entity return $this; } - /** - * Возвращает установленный ИНН - * - * @return string|null - */ - public function getInn(): ?string - { - return $this->inn; - } - - /** - * Устанавливает ИНН - * - * @param string|null $inn - * @return $this - * @throws InvalidInnLengthException Некорректная длина ИНН - */ - public function setInn(?string $inn): self - { - if (is_string($inn)) { - $inn = preg_replace('/[^\d]/', '', trim($inn)); - if (preg_match_all(Constraints::PATTERN_INN, $inn) === 0) { - throw new InvalidInnLengthException($inn); - } - } - $this->inn = empty($inn) ? null : $inn; - return $this; - } - /** * @inheritDoc */ + #[Pure] public function jsonSerialize(): array { $json = []; diff --git a/src/Entities/Company.php b/src/Entities/Company.php index 73868d7..aeb556e 100644 --- a/src/Entities/Company.php +++ b/src/Entities/Company.php @@ -14,12 +14,18 @@ namespace AtolOnline\Entities; use AtolOnline\{ Constants\Constraints, Enums\SnoTypes, - Exceptions\InvalidEmailException, - Exceptions\InvalidEnumValueException, - Exceptions\InvalidInnLengthException, - Exceptions\InvalidPaymentAddressException, - Exceptions\TooLongEmailException, - Exceptions\TooLongPaymentAddressException}; + Traits\HasEmail, + Traits\HasInn +}; +use AtolOnline\Exceptions\{ + InvalidEmailException, + InvalidEnumValueException, + InvalidInnLengthException, + InvalidPaymentAddressException, + TooLongEmailException, + TooLongPaymentAddressException +}; +use JetBrains\PhpStorm\ArrayShape; /** * Класс, описывающий сущность компании-продавца @@ -28,21 +34,13 @@ use AtolOnline\{ */ class Company extends Entity { - /** - * @var string|null Почта (1117) - */ - protected ?string $email; + use HasEmail, HasInn; /** * @var string|null Система налогообложения продавца (1055) */ protected ?string $sno; - /** - * @var string|null ИНН (1018) - */ - protected ?string $inn; - /** * @var string|null Место расчётов (адрес интернет-магазина) (1187) */ @@ -74,36 +72,6 @@ class Company extends Entity $this->setPaymentAddress($payment_address); } - /** - * Возвращает установленный email - * - * @return string - */ - public function getEmail(): string - { - return $this->email; - } - - /** - * Устанавливает email - * - * @param string $email - * @return $this - * @throws TooLongEmailException Слишком длинный email - * @throws InvalidEmailException Невалидный email - */ - public function setEmail(string $email): self - { - $email = preg_replace('/[\n\r\t]/', '', trim($email)); - if (mb_strlen($email) > Constraints::MAX_LENGTH_EMAIL) { - throw new TooLongEmailException($email); - } elseif (empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) { - throw new InvalidEmailException($email); - } - $this->email = $email; - return $this; - } - /** * Возвращает установленный тип налогообложения * @@ -129,33 +97,6 @@ class Company extends Entity return $this; } - /** - * Возвращает установленный ИНН - * - * @return string - */ - public function getInn(): string - { - return $this->inn; - } - - /** - * Устанавливает ИНН - * - * @param string $inn - * @return $this - * @throws InvalidInnLengthException - */ - public function setInn(string $inn): self - { - $inn = preg_replace('/[^\d]/', '', trim($inn)); - if (empty($inn) || preg_match_all(Constraints::PATTERN_INN, $inn) === 0) { - throw new InvalidInnLengthException($inn); - } - $this->inn = $inn; - return $this; - } - /** * Возвращает установленный адрес места расчётов * @@ -193,6 +134,12 @@ class Company extends Entity * @throws InvalidInnLengthException * @throws InvalidPaymentAddressException */ + #[ArrayShape([ + 'email' => "string", + 'sno' => "string", + 'inn' => "string", + 'payment_address' => "string", + ])] public function jsonSerialize(): array { return [ diff --git a/src/Entities/Item.php b/src/Entities/Item.php index 9cb0fc1..7fcc45e 100644 --- a/src/Entities/Item.php +++ b/src/Entities/Item.php @@ -11,26 +11,28 @@ declare(strict_types = 1); namespace AtolOnline\Entities; -use AtolOnline\{ - Constants\Constraints, - Enums\PaymentMethods, - Enums\PaymentObjects, - Enums\VatTypes, - Exceptions\EmptyItemNameException, - Exceptions\InvalidDeclarationNumberException, - Exceptions\InvalidEnumValueException, - Exceptions\InvalidOKSMCodeException, - Exceptions\NegativeItemExciseException, - Exceptions\NegativeItemPriceException, - Exceptions\NegativeItemQuantityException, - Exceptions\TooHighItemQuantityException, - Exceptions\TooHighPriceException, - Exceptions\TooHighSumException, - Exceptions\TooLongItemCodeException, - Exceptions\TooLongItemNameException, - Exceptions\TooLongMeasurementUnitException, - Exceptions\TooLongUserdataException, - Exceptions\TooManyException +use AtolOnline\Constants\Constraints; +use AtolOnline\Enums\{ + PaymentMethods, + PaymentObjects, + VatTypes +}; +use AtolOnline\Exceptions\{ + EmptyItemNameException, + InvalidDeclarationNumberException, + InvalidEnumValueException, + InvalidOKSMCodeException, + NegativeItemExciseException, + NegativeItemPriceException, + NegativeItemQuantityException, + TooHighItemQuantityException, + TooHighPriceException, + TooHighSumException, + TooLongItemCodeException, + TooLongItemNameException, + TooLongMeasurementUnitException, + TooLongUserdataException, + TooManyException }; /** @@ -153,7 +155,7 @@ class Item extends Entity * * @param string $name Наименование * @return $this - * @throws TooLongItemNameException Слишком длинное имя/наименование + * @throws TooLongItemNameException * @throws EmptyItemNameException */ public function setName(string $name): self @@ -186,6 +188,7 @@ class Item extends Entity * @return $this * @throws NegativeItemPriceException * @throws TooHighPriceException + * @throws TooHighSumException */ public function setPrice(float $rubles): self { @@ -217,6 +220,7 @@ class Item extends Entity * @return $this * @throws TooHighItemQuantityException * @throws NegativeItemQuantityException + * @throws TooHighSumException */ public function setQuantity(float $quantity): self { @@ -457,7 +461,7 @@ class Item extends Entity * * @param string|null $user_data Дополнительный реквизит * @return $this - * @throws TooLongUserdataException Слишком длинный дополнительный реквизит + * @throws TooLongUserdataException */ public function setUserData(?string $user_data): self { @@ -485,8 +489,9 @@ class Item extends Entity * @param float|null $excise * @return Item * @throws NegativeItemExciseException + * @throws TooHighSumException */ - public function setExcise(?float $excise): Item + public function setExcise(?float $excise): self { if ($excise < 0) { throw new NegativeItemExciseException($this->getName(), $excise); @@ -558,25 +563,6 @@ class Item extends Entity return $this; } - /** - * Расчитывает стоимость и размер НДС на неё - * - * @return float - * @throws TooHighPriceException Слишком большая сумма - */ - //public function calcSum(): float - //{ - // $sum = $this->quantity * $this->price; - // if (rubles($sum) > 42949672.95) { - // throw new TooHighPriceException($sum, 42949672.95); - // } - // $this->sum = $sum; - // if ($this->vat) { - // $this->vat->setSum(rubles($sum)); - // } - // return $this->getSum(); - //} - /** * @inheritDoc * @throws TooHighSumException diff --git a/src/Entities/Kkt.php b/src/Entities/Kkt.php index 7203951..690c495 100644 --- a/src/Entities/Kkt.php +++ b/src/Entities/Kkt.php @@ -11,14 +11,17 @@ declare(strict_types = 1); namespace AtolOnline\Entities; -use AtolOnline\Exceptions\EmptyMonitorDataException; -use AtolOnline\Exceptions\NotEnoughMonitorDataException; +use AtolOnline\Exceptions\{ + EmptyMonitorDataException, + NotEnoughMonitorDataException +}; use DateTime; use Exception; /** * Класс сущности ККТ, получаемой от монитора * + * @see https://online.atol.ru/files/API_service_information.pdf Документация, стр 11 * @property string|null serialNumber Заводской номер ККТ * @property string|null registrationNumber Регистрационный номер машины (РНМ) * @property string|null deviceNumber Номер автоматического устройства (внутренний идентификатор устройства) @@ -38,14 +41,13 @@ use Exception; * @property DateTime|string|null firstUnsetDocTimestamp Дата первого неотправленного документа. Указывается, если * есть неотправленные документы. * @property int|null networkErrorCode Код ошибки сети - * @see https://online.atol.ru/files/API_service_information.pdf Документация, стр 11 */ final class Kkt extends Entity { /** * Сопоставление кодов сетевых ошибок ККТ с их описаниями */ - public const ERROR_CODES = [ + public const ERROR_CODES = [ 0 => 'Нет ошибок', 1 => 'Отсутствует физический канал связи', 2 => 'Ошибка сетевых настроек или нет соединения с сервером ОФД', @@ -97,7 +99,7 @@ final class Kkt extends Entity * @throws EmptyMonitorDataException * @throws NotEnoughMonitorDataException */ - public function __construct(protected \stdClass $data) + public function __construct(protected object $data) { if (empty((array)$data)) { throw new EmptyMonitorDataException(); diff --git a/src/Entities/MoneyTransferOperator.php b/src/Entities/MoneyTransferOperator.php index 198bab8..0047065 100644 --- a/src/Entities/MoneyTransferOperator.php +++ b/src/Entities/MoneyTransferOperator.php @@ -11,9 +11,14 @@ declare(strict_types = 1); namespace AtolOnline\Entities; -use AtolOnline\Constants\Constraints; -use AtolOnline\Exceptions\InvalidInnLengthException; -use AtolOnline\Exceptions\InvalidPhoneException; +use AtolOnline\Exceptions\{ + InvalidInnLengthException, + InvalidPhoneException +}; +use AtolOnline\Traits\{ + HasInn, + HasPhones +}; use Illuminate\Support\Collection; /** @@ -23,6 +28,8 @@ use Illuminate\Support\Collection; */ class MoneyTransferOperator extends Entity { + use HasInn, HasPhones; + /** * @var string|null Наименование (1026) */ @@ -111,69 +118,6 @@ class MoneyTransferOperator extends Entity return $this; } - /** - * Возвращает установленные номера телефонов - * - * @todo вытащить в трейт - * @return Collection - */ - public function getPhones(): Collection - { - return $this->phones; - } - - /** - * Устанавливает массив номеров телефонов - * - * @todo вытащить в трейт - * @param array|Collection|null $phones - * @return $this - * @throws InvalidPhoneException - */ - public function setPhones(array|Collection|null $phones): self - { - if (!is_null($phones)) { - $phones = is_array($phones) ? collect($phones) : $phones; - $phones->each(function ($phone) { - $phone = preg_replace('/[^\d]/', '', trim($phone)); - if (preg_match(Constraints::PATTERN_PHONE, $phone) != 1) { - throw new InvalidPhoneException($phone); - } - }); - } - $this->phones = $phones ?? collect(); - return $this; - } - - /** - * Возвращает установленный ИНН - * - * @return string|null - */ - public function getInn(): ?string - { - return $this->inn; - } - - /** - * Устанавливает ИНН - * - * @param string|null $inn - * @return $this - * @throws InvalidInnLengthException Некорректная длина ИНН - */ - public function setInn(?string $inn): self - { - if (is_string($inn)) { - $inn = preg_replace('/[^\d]/', '', trim($inn)); - if (preg_match_all(Constraints::PATTERN_INN, $inn) === 0) { - throw new InvalidInnLengthException($inn); - } - } - $this->inn = $inn ?: null; - return $this; - } - /** * @inheritDoc */ diff --git a/src/Entities/PayingAgent.php b/src/Entities/PayingAgent.php index 69636c7..a44aba7 100644 --- a/src/Entities/PayingAgent.php +++ b/src/Entities/PayingAgent.php @@ -12,8 +12,11 @@ declare(strict_types = 1); namespace AtolOnline\Entities; use AtolOnline\Constants\Constraints; -use AtolOnline\Exceptions\InvalidPhoneException; -use AtolOnline\Exceptions\TooLongPayingAgentOperationException; +use AtolOnline\Exceptions\{ + InvalidPhoneException, + TooLongPayingAgentOperationException +}; +use AtolOnline\Traits\HasPhones; use Illuminate\Support\Collection; /** @@ -23,16 +26,13 @@ use Illuminate\Support\Collection; */ class PayingAgent extends Entity { + use HasPhones; + /** * @var string|null Наименование операции (1044) */ protected ?string $operation = null; - /** - * @var Collection Телефоны платёжного агента (1073) - */ - protected Collection $phones; - /** * Конструктор * @@ -78,40 +78,6 @@ class PayingAgent extends Entity return $this->operation; } - /** - * Устанавливает массив номеров телефонов - * - * @todo вытащить в трейт - * @param array|Collection|null $phones - * @return $this - * @throws InvalidPhoneException - */ - public function setPhones(array|Collection|null $phones): self - { - if (!is_null($phones)) { - $phones = is_array($phones) ? collect($phones) : $phones; - $phones->each(function ($phone) { - $phone = preg_replace('/[^\d]/', '', trim($phone)); - if (preg_match(Constraints::PATTERN_PHONE, $phone) != 1) { - throw new InvalidPhoneException($phone); - } - }); - } - $this->phones = empty($phones) ? collect() : $phones; - return $this; - } - - /** - * Возвращает установленные номера телефонов - * - * @todo вытащить в трейт - * @return Collection - */ - public function getPhones(): Collection - { - return $this->phones; - } - /** * @inheritDoc */ diff --git a/src/Entities/ReceivePaymentsOperator.php b/src/Entities/ReceivePaymentsOperator.php index 06b0414..1bc5107 100644 --- a/src/Entities/ReceivePaymentsOperator.php +++ b/src/Entities/ReceivePaymentsOperator.php @@ -11,8 +11,8 @@ declare(strict_types = 1); namespace AtolOnline\Entities; -use AtolOnline\Constants\Constraints; use AtolOnline\Exceptions\InvalidPhoneException; +use AtolOnline\Traits\HasPhones; use Illuminate\Support\Collection; /** @@ -22,10 +22,7 @@ use Illuminate\Support\Collection; */ class ReceivePaymentsOperator extends Entity { - /** - * @var Collection Телефоны оператора по приёму платежей (1074) - */ - protected Collection $phones; + use HasPhones; /** * Конструктор @@ -33,46 +30,11 @@ class ReceivePaymentsOperator extends Entity * @param array|Collection|null $phones Телефоны оператора по приёму платежей (1074) * @throws InvalidPhoneException */ - public function __construct( - array|Collection|null $phones = null, - ) { + public function __construct(array|Collection|null $phones = null) + { $this->setPhones($phones); } - /** - * Возвращает установленные номера телефонов - * - * @todo вытащить в трейт - * @return Collection - */ - public function getPhones(): Collection - { - return $this->phones; - } - - /** - * Устанавливает массив номеров телефонов - * - * @todo вытащить в трейт - * @param array|Collection|null $phones - * @return $this - * @throws InvalidPhoneException - */ - public function setPhones(array|Collection|null $phones): self - { - if (!is_null($phones)) { - $phones = is_array($phones) ? collect($phones) : $phones; - $phones->each(function ($phone) { - $phone = preg_replace('/[^\d]/', '', trim($phone)); - if (preg_match(Constraints::PATTERN_PHONE, $phone) != 1) { - throw new InvalidPhoneException($phone); - } - }); - } - $this->phones = empty($phones) ? collect() : $phones; - return $this; - } - /** * @inheritDoc */ diff --git a/src/Entities/Supplier.php b/src/Entities/Supplier.php index 8ddcc40..81d8c28 100644 --- a/src/Entities/Supplier.php +++ b/src/Entities/Supplier.php @@ -11,9 +11,14 @@ declare(strict_types = 1); namespace AtolOnline\Entities; -use AtolOnline\Constants\Constraints; -use AtolOnline\Exceptions\InvalidInnLengthException; -use AtolOnline\Exceptions\InvalidPhoneException; +use AtolOnline\Exceptions\{ + InvalidInnLengthException, + InvalidPhoneException +}; +use AtolOnline\Traits\{ + HasInn, + HasPhones +}; use Illuminate\Support\Collection; /** @@ -23,21 +28,13 @@ use Illuminate\Support\Collection; */ class Supplier extends Entity { + use HasPhones, HasInn; + /** * @var string|null Наименование (1225) */ protected ?string $name = null; - /** - * @var string|null ИНН (1226) - */ - protected ?string $inn = null; - - /** - * @var Collection Телефоны (1171) - */ - protected Collection $phones; - /** * Конструктор * @@ -80,69 +77,6 @@ class Supplier extends Entity return $this; } - /** - * Возвращает установленные номера телефонов - * - * @todo вытащить в трейт - * @return Collection - */ - public function getPhones(): Collection - { - return $this->phones; - } - - /** - * Устанавливает массив номеров телефонов - * - * @todo вытащить в трейт - * @param array|Collection|null $phones - * @return $this - * @throws InvalidPhoneException - */ - public function setPhones(array|Collection|null $phones): self - { - if (!is_null($phones)) { - $phones = is_array($phones) ? collect($phones) : $phones; - $phones->each(function ($phone) { - $phone = preg_replace('/[^\d]/', '', trim($phone)); - if (preg_match(Constraints::PATTERN_PHONE, $phone) != 1) { - throw new InvalidPhoneException($phone); - } - }); - } - $this->phones = empty($phones) ? collect() : $phones; - return $this; - } - - /** - * Возвращает установленный ИНН - * - * @return string|null - */ - public function getInn(): ?string - { - return $this->inn; - } - - /** - * Устанавливает ИНН - * - * @param string|null $inn - * @return $this - * @throws InvalidInnLengthException Некорректная длина ИНН - */ - public function setInn(?string $inn): self - { - if (is_string($inn)) { - $inn = preg_replace('/[^\d]/', '', trim($inn)); - if (preg_match_all(Constraints::PATTERN_INN, $inn) === 0) { - throw new InvalidInnLengthException($inn); - } - } - $this->inn = empty($inn) ? null : $inn; - return $this; - } - /** * @inheritDoc */ diff --git a/src/Entities/Vat.php b/src/Entities/Vat.php index a4438db..f158a37 100644 --- a/src/Entities/Vat.php +++ b/src/Entities/Vat.php @@ -14,6 +14,10 @@ namespace AtolOnline\Entities; use AtolOnline\Enums\VatTypes; use AtolOnline\Exceptions\InvalidEnumValueException; use AtolOnline\Helpers; +use JetBrains\PhpStorm\{ + ArrayShape, + Pure +}; /** * Класс, описывающий ставку НДС @@ -37,6 +41,7 @@ class Vat extends Entity * * @param string $type Тип ставки НДС (1199, 1105, 1104, 1103, 1102, 1107, 1106) * @param float $rubles Исходная сумма в рублях, от которой нужно расчитать размер НДС + * @throws InvalidEnumValueException */ public function __construct(string $type, float $rubles) { @@ -99,16 +104,16 @@ class Vat extends Entity * @see https://glavkniga.ru/situations/k500734 * @see https://www.b-kontur.ru/nds-kalkuljator-online */ + #[Pure] public function getCalculated(): float { - $kopeks = Helpers::toKop($this->sum); return Helpers::toRub(match ($this->getType()) { - VatTypes::VAT10 => $kopeks * 10 / 100, - VatTypes::VAT18 => $kopeks * 18 / 100, - VatTypes::VAT20 => $kopeks * 20 / 100, - VatTypes::VAT110 => $kopeks * 10 / 110, - VatTypes::VAT118 => $kopeks * 18 / 118, - VatTypes::VAT120 => $kopeks * 20 / 120, + VatTypes::VAT10 => Helpers::toKop($this->sum) * 10 / 100, + VatTypes::VAT18 => Helpers::toKop($this->sum) * 18 / 100, + VatTypes::VAT20 => Helpers::toKop($this->sum) * 20 / 100, + VatTypes::VAT110 => Helpers::toKop($this->sum) * 10 / 110, + VatTypes::VAT118 => Helpers::toKop($this->sum) * 18 / 118, + VatTypes::VAT120 => Helpers::toKop($this->sum) * 20 / 120, default => 0, }); } @@ -128,6 +133,8 @@ class Vat extends Entity /** * @inheritDoc */ + #[Pure] + #[ArrayShape(['type' => 'string', 'sum' => 'float'])] public function jsonSerialize(): array { return [ diff --git a/src/Traits/HasEmail.php b/src/Traits/HasEmail.php new file mode 100644 index 0000000..e72b736 --- /dev/null +++ b/src/Traits/HasEmail.php @@ -0,0 +1,57 @@ + Constraints::MAX_LENGTH_EMAIL) { + throw new TooLongEmailException($email); + } elseif (filter_var($email, FILTER_VALIDATE_EMAIL) === false) { + throw new InvalidEmailException($email); + } + } + $this->email = empty($email) ? null : $email; + return $this; + } + + /** + * Возвращает установленный email + * + * @return string|null + */ + public function getEmail(): ?string + { + return $this->email; + } +} diff --git a/src/Traits/HasInn.php b/src/Traits/HasInn.php new file mode 100644 index 0000000..01ae7d3 --- /dev/null +++ b/src/Traits/HasInn.php @@ -0,0 +1,53 @@ +inn = empty($inn) ? null : $inn; + return $this; + } + + /** + * Возвращает установленный ИНН + * + * @return string|null + */ + public function getInn(): ?string + { + return $this->inn; + } +} diff --git a/src/Traits/HasPhones.php b/src/Traits/HasPhones.php new file mode 100644 index 0000000..a6eb5e9 --- /dev/null +++ b/src/Traits/HasPhones.php @@ -0,0 +1,57 @@ +each(function ($phone) { + $phone = preg_replace('/[^\d]/', '', trim($phone)); + if (preg_match(Constraints::PATTERN_PHONE, $phone) != 1) { + throw new InvalidPhoneException($phone); + } + }); + } + $this->phones = empty($phones) ? collect() : $phones; + return $this; + } + + /** + * Возвращает установленные номера телефонов + * + * @return Collection + */ + public function getPhones(): Collection + { + return $this->phones; + } +}