From 4157ab68f55495ee6acaac34af47800605eb20bb Mon Sep 17 00:00:00 2001 From: AnthonyAxenov Date: Thu, 15 Dec 2022 00:19:55 +0800 Subject: [PATCH] =?UTF-8?q?=D0=9C=D0=B8=D0=B3=D1=80=D0=B0=D1=86=D0=B8?= =?UTF-8?q?=D1=8F=20=D0=BD=D0=B0=20php8.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * enum-ы теперь enum-ы, а не говно -- теперь всё переведено на них, где это было возможно * некоторые свойства классов объявлены в конструкторе * некоторые классы перемещены в корневой неймспейс * исправлен код-стайл, вычищен некоторый мусор, выправлены тесты... работы над этим продолжаются --- src/Api/AtolClient.php | 5 +- src/Api/AtolResponse.php | 8 +- src/Api/Fiscalizer.php | 7 +- src/Api/Monitor.php | 5 +- src/Collections/EntityCollection.php | 19 +- src/Collections/Items.php | 3 +- src/Collections/Payments.php | 3 +- src/Collections/Vats.php | 3 +- src/{Constants => }/Constraints.php | 65 +++--- src/Entities/AdditionalUserProps.php | 27 +-- src/Entities/AgentInfo.php | 92 ++++----- src/Entities/Client.php | 28 +-- src/Entities/Company.php | 92 ++++----- src/Entities/Correction.php | 59 ++---- src/Entities/CorrectionInfo.php | 83 ++++---- src/Entities/Entity.php | 5 +- src/Entities/Item.php | 185 +++++++---------- src/Entities/Kkt.php | 3 +- src/Entities/MoneyTransferOperator.php | 14 +- src/Entities/PayingAgent.php | 7 +- src/Entities/Payment.php | 55 ++--- src/Entities/Receipt.php | 9 +- src/Entities/ReceivePaymentsOperator.php | 5 +- src/Entities/Supplier.php | 14 +- src/Entities/Vat.php | 53 ++--- src/Enums/{AgentTypes.php => AgentType.php} | 29 +-- ...CorrectionTypes.php => CorrectionType.php} | 19 +- src/Enums/Enum.php | 36 ---- .../{PaymentMethods.php => PaymentMethod.php} | 29 +-- .../{PaymentObjects.php => PaymentObject.php} | 69 +++---- .../{PaymentTypes.php => PaymentType.php} | 41 ++-- ...tionTypes.php => ReceiptOperationType.php} | 19 +- src/Enums/{SnoTypes.php => SnoType.php} | 27 +-- src/Enums/VatType.php | 59 ++++++ src/Enums/VatTypes.php | 76 ------- src/Exceptions/AtolException.php | 3 +- src/Exceptions/AuthFailedException.php | 3 +- .../EmptyAddUserPropNameException.php | 5 +- .../EmptyAddUserPropValueException.php | 5 +- .../EmptyCorrectionInfoException.php | 3 +- .../EmptyCorrectionNumberException.php | 5 +- src/Exceptions/EmptyEmailException.php | 5 +- src/Exceptions/EmptyGroupException.php | 3 +- src/Exceptions/EmptyItemNameException.php | 5 +- src/Exceptions/EmptyItemsException.php | 3 +- src/Exceptions/EmptyLoginException.php | 3 +- src/Exceptions/EmptyMonitorDataException.php | 3 +- src/Exceptions/EmptyPasswordException.php | 3 +- src/Exceptions/EmptyPaymentsException.php | 3 +- src/Exceptions/EmptyVatsException.php | 3 +- .../InvalidCallbackUrlException.php | 3 +- .../InvalidCorrectionDateException.php | 5 +- .../InvalidDeclarationNumberException.php | 5 +- src/Exceptions/InvalidEmailException.php | 5 +- .../InvalidEntityInCollectionException.php | 6 +- src/Exceptions/InvalidEnumValueException.php | 17 +- src/Exceptions/InvalidInnLengthException.php | 5 +- src/Exceptions/InvalidJsonException.php | 3 +- src/Exceptions/InvalidOKSMCodeException.php | 5 +- .../InvalidPaymentAddressException.php | 5 +- src/Exceptions/InvalidPhoneException.php | 5 +- src/Exceptions/InvalidUuidException.php | 3 +- .../NegativeItemExciseException.php | 5 +- src/Exceptions/NegativeItemPriceException.php | 5 +- .../NegativeItemQuantityException.php | 5 +- .../NegativePaymentSumException.php | 5 +- .../NotEnoughMonitorDataException.php | 3 +- src/Exceptions/TooHighItemPriceException.php | 7 +- .../TooHighItemQuantityException.php | 7 +- src/Exceptions/TooHighItemSumException.php | 7 +- src/Exceptions/TooHighPaymentSumException.php | 7 +- .../TooLongAddCheckPropException.php | 8 +- .../TooLongAddUserPropNameException.php | 8 +- .../TooLongAddUserPropValueException.php | 8 +- .../TooLongCallbackUrlException.php | 5 +- src/Exceptions/TooLongCashierException.php | 7 +- .../TooLongClientContactException.php | 7 +- src/Exceptions/TooLongClientNameException.php | 7 +- src/Exceptions/TooLongEmailException.php | 7 +- src/Exceptions/TooLongException.php | 3 +- src/Exceptions/TooLongItemCodeException.php | 9 +- src/Exceptions/TooLongItemNameException.php | 9 +- src/Exceptions/TooLongLoginException.php | 5 +- .../TooLongMeasurementUnitException.php | 7 +- src/Exceptions/TooLongPasswordException.php | 5 +- .../TooLongPayingAgentOperationException.php | 9 +- .../TooLongPaymentAddressException.php | 7 +- src/Exceptions/TooLongUserdataException.php | 7 +- src/Exceptions/TooManyException.php | 3 +- src/Exceptions/TooManyItemsException.php | 5 +- src/Exceptions/TooManyPaymentsException.php | 5 +- src/Exceptions/TooManyVatsException.php | 5 +- src/{Constants => }/Ffd105Tags.php | 95 ++++----- src/Helpers.php | 1 + src/TestEnvParams.php | 3 +- src/Traits/HasEmail.php | 3 +- src/Traits/HasInn.php | 5 +- src/Traits/HasPhones.php | 5 +- tests/AtolOnline/Tests/Api/FiscalizerTest.php | 31 +-- tests/AtolOnline/Tests/Api/MonitorTest.php | 19 +- tests/AtolOnline/Tests/BasicTestCase.php | 75 ++++--- .../Tests/Collections/ItemsTest.php | 3 +- .../Tests/Collections/PaymentsTest.php | 5 +- .../AtolOnline/Tests/Collections/VatsTest.php | 10 +- .../Entities/AdditionalUserPropsTest.php | 3 +- .../Tests/Entities/AgentInfoTest.php | 105 +++++----- .../AtolOnline/Tests/Entities/ClientTest.php | 30 +-- .../AtolOnline/Tests/Entities/CompanyTest.php | 55 ++--- .../Tests/Entities/CorrectionInfoTest.php | 57 +++--- .../Tests/Entities/CorrectionTest.php | 5 +- tests/AtolOnline/Tests/Entities/ItemTest.php | 192 +++++------------- .../Tests/Entities/KktEntityTest.php | 13 +- .../Entities/MoneyTransferOperatorTest.php | 37 ++-- .../Tests/Entities/PayingAgentTest.php | 20 +- .../AtolOnline/Tests/Entities/PaymentTest.php | 36 +--- .../AtolOnline/Tests/Entities/ReceiptTest.php | 39 ++-- .../Entities/ReceivePaymentsOperatorTest.php | 3 +- .../Tests/Entities/SupplierTest.php | 28 +-- tests/AtolOnline/Tests/Entities/VatTest.php | 52 +++-- tests/AtolOnline/Tests/HelpersTest.php | 7 +- 120 files changed, 1098 insertions(+), 1401 deletions(-) rename src/{Constants => }/Constraints.php (82%) rename src/Enums/{AgentTypes.php => AgentType.php} (62%) rename src/Enums/{CorrectionTypes.php => CorrectionType.php} (66%) delete mode 100644 src/Enums/Enum.php rename src/Enums/{PaymentMethods.php => PaymentMethod.php} (70%) rename src/Enums/{PaymentObjects.php => PaymentObject.php} (66%) rename src/Enums/{PaymentTypes.php => PaymentType.php} (74%) rename src/Enums/{ReceiptOperationTypes.php => ReceiptOperationType.php} (75%) rename src/Enums/{SnoTypes.php => SnoType.php} (68%) create mode 100644 src/Enums/VatType.php delete mode 100644 src/Enums/VatTypes.php rename src/{Constants => }/Ffd105Tags.php (70%) diff --git a/src/Api/AtolClient.php b/src/Api/AtolClient.php index 08caa92..c4558a2 100644 --- a/src/Api/AtolClient.php +++ b/src/Api/AtolClient.php @@ -1,4 +1,5 @@ 'int', 'headers' => 'array|\string[][]', 'body' => 'mixed', diff --git a/src/Api/Fiscalizer.php b/src/Api/Fiscalizer.php index 17c90b5..75547a8 100644 --- a/src/Api/Fiscalizer.php +++ b/src/Api/Fiscalizer.php @@ -1,4 +1,5 @@ isTestMode() && $document->getCompany() diff --git a/src/Api/Monitor.php b/src/Api/Monitor.php index 77ecaf8..3e4df05 100644 --- a/src/Api/Monitor.php +++ b/src/Api/Monitor.php @@ -1,4 +1,5 @@ fetchAll($limit, $offset)->getContent()); - return $collection->map(fn($data) => new Kkt($data)); + return $collection->map(fn ($data) => new Kkt($data)); } /** diff --git a/src/Collections/EntityCollection.php b/src/Collections/EntityCollection.php index 7c92f0d..8868c53 100644 --- a/src/Collections/EntityCollection.php +++ b/src/Collections/EntityCollection.php @@ -1,4 +1,5 @@ isEmpty() && throw new (static::EMPTY_EXCEPTION_CLASS)(); $this->count() > static::MAX_COUNT && throw new (static::TOO_MANY_EXCEPTION_CLASS)(static::MAX_COUNT); + return $this; } /** * Проверяет корректность класса элемента коллекции * * @param mixed $item - * @return void + * @return static * @throws InvalidEntityInCollectionException */ - public function checkItemClass(mixed $item): void + public function checkItemClass(mixed $item): static { if (!is_object($item) || $item::class !== static::ENTITY_CLASS) { throw new InvalidEntityInCollectionException(static::class, static::ENTITY_CLASS, $item); } + return $this; } /** * Проверяет корректность классов элементов коллекции * - * @return $this + * @return static * @throws InvalidEntityInCollectionException */ - public function checkItemsClasses(): self + public function checkItemsClasses(): static { - return $this->each(fn($item) => $this->checkItemClass($item)); + return $this->each(fn ($item) => $this->checkItemClass($item)); } } diff --git a/src/Collections/Items.php b/src/Collections/Items.php index 62a1d06..a891482 100644 --- a/src/Collections/Items.php +++ b/src/Collections/Items.php @@ -1,4 +1,5 @@ setName($name)->setValue($value); } diff --git a/src/Entities/AgentInfo.php b/src/Entities/AgentInfo.php index 4607734..f30bc93 100644 --- a/src/Entities/AgentInfo.php +++ b/src/Entities/AgentInfo.php @@ -1,4 +1,5 @@ setType($type); - !is_null($pagent) && $this->setPayingAgent($pagent); - !is_null($rp_operator) && $this->setReceivePaymentsOperator($rp_operator); - !is_null($mt_operator) && $this->setMoneyTransferOperator($mt_operator); + $this->setType($type); } /** * Возвращает установленный признак оператора * - * @return string|null + * @return AgentType|null */ - public function getType(): ?string + public function getType(): ?AgentType { return $this->type; } @@ -75,24 +51,23 @@ final class AgentInfo extends Entity /** * Устанавливает признак оператора * - * @param string|null $type + * @param AgentType|null $type * @return AgentInfo - * @throws InvalidEnumValueException */ - public function setType(?string $type): self + public function setType(?AgentType $type): self { - AgentTypes::isValid($type) && $this->type = $type; + $this->type = $type; return $this; } /** - * Взвращает установленного платёжного агента + * Возвращает установленного платёжного агента * * @return PayingAgent|null */ public function getPayingAgent(): ?PayingAgent { - return $this->paying_agent; + return $this->payingAgent; } /** @@ -103,7 +78,7 @@ final class AgentInfo extends Entity */ public function setPayingAgent(?PayingAgent $agent): self { - $this->paying_agent = $agent; + $this->payingAgent = $agent; return $this; } @@ -114,7 +89,7 @@ final class AgentInfo extends Entity */ public function getReceivePaymentsOperator(): ?ReceivePaymentsOperator { - return $this->receive_payments_operator; + return $this->receivePaymentsOperator; } /** @@ -125,7 +100,7 @@ final class AgentInfo extends Entity */ public function setReceivePaymentsOperator(?ReceivePaymentsOperator $operator): self { - $this->receive_payments_operator = $operator; + $this->receivePaymentsOperator = $operator; return $this; } @@ -136,7 +111,7 @@ final class AgentInfo extends Entity */ public function getMoneyTransferOperator(): ?MoneyTransferOperator { - return $this->money_transfer_operator; + return $this->moneyTransferOperator; } /** @@ -147,7 +122,7 @@ final class AgentInfo extends Entity */ public function setMoneyTransferOperator(?MoneyTransferOperator $operator): self { - $this->money_transfer_operator = $operator; + $this->moneyTransferOperator = $operator; return $this; } @@ -157,13 +132,18 @@ final class AgentInfo extends Entity public function jsonSerialize(): array { $json = []; - $this->getType() && $json['type'] = $this->getType(); - $this->getPayingAgent()?->jsonSerialize() && $json['paying_agent'] = $this - ->getPayingAgent()->jsonSerialize(); - $this->getReceivePaymentsOperator()?->jsonSerialize() && $json['receive_payments_operator'] = $this - ->getReceivePaymentsOperator()->jsonSerialize(); - $this->getMoneyTransferOperator()?->jsonSerialize() && $json['money_transfer_operator'] = $this - ->getMoneyTransferOperator()->jsonSerialize(); + if ($this?->type) { + $json['type'] = $this->getType(); + } + if ($this->payingAgent?->jsonSerialize()) { + $json['paying_agent'] = $this->payingAgent->jsonSerialize(); + } + if ($this->receivePaymentsOperator?->jsonSerialize()) { + $json['receive_payments_operator'] = $this->receivePaymentsOperator->jsonSerialize(); + } + if ($this->moneyTransferOperator?->jsonSerialize()) { + $json['money_transfer_operator'] = $this->moneyTransferOperator->jsonSerialize(); + } return $json; } } diff --git a/src/Entities/Client.php b/src/Entities/Client.php index 8011274..23f796f 100644 --- a/src/Entities/Client.php +++ b/src/Entities/Client.php @@ -1,4 +1,5 @@ setName($name); @@ -116,8 +108,8 @@ final class Client extends Entity public function setPhone(?string $phone): self { if (is_string($phone)) { - $phone = preg_replace('/[^\d]/', '', trim($phone)); - if (preg_match(Constraints::PATTERN_PHONE, $phone) != 1) { + $phone = preg_replace('/\D/', '', trim($phone)); + if (preg_match(Constraints::PATTERN_PHONE, $phone) !== 1) { throw new InvalidPhoneException($phone); } } @@ -133,8 +125,8 @@ final class Client extends Entity { $json = []; !is_null($this->getName()) && $json['name'] = $this->getName(); - !is_null($this->getEmail()) && $json['email'] = $this->getEmail(); !is_null($this->getPhone()) && $json['phone'] = $this->getPhone(); + !is_null($this->getEmail()) && $json['email'] = $this->getEmail(); !is_null($this->getInn()) && $json['inn'] = $this->getInn(); return $json; } diff --git a/src/Entities/Company.php b/src/Entities/Company.php index e5b4b59..5329049 100644 --- a/src/Entities/Company.php +++ b/src/Entities/Company.php @@ -1,4 +1,5 @@ setEmail($email)->setSno($sno)->setInn($inn)->setPaymentAddress($payment_address); + $this->setInn($inn) + ->setPaymentAddress($paymentAddress) + ->setEmail($email); } /** * Возвращает установленный тип налогообложения * - * @return string + * @return SnoType */ - public function getSno(): string + public function getSno(): SnoType { return $this->sno; } @@ -82,14 +72,12 @@ final class Company extends Entity /** * Устанавливает тип налогообложения * - * @param string $sno + * @param SnoType $sno * @return $this - * @throws InvalidEnumValueException */ - public function setSno(string $sno): self + public function setSno(SnoType $sno): self { - $sno = trim($sno); - SnoTypes::isValid($sno) && $this->sno = $sno; + $this->sno = $sno; return $this; } @@ -100,57 +88,45 @@ final class Company extends Entity */ public function getPaymentAddress(): string { - return $this->payment_address; + return $this->paymentAddress; } /** * Устанавливает адрес места расчётов * - * @param string $payment_address + * @param string $paymentAddress * @return $this * @throws TooLongPaymentAddressException * @throws InvalidPaymentAddressException */ - public function setPaymentAddress(string $payment_address): self + public function setPaymentAddress(string $paymentAddress): self { - $payment_address = trim($payment_address); - if (empty($payment_address)) { + $paymentAddress = trim($paymentAddress); + if (empty($paymentAddress)) { throw new InvalidPaymentAddressException(); - } elseif (mb_strlen($payment_address) > Constraints::MAX_LENGTH_PAYMENT_ADDRESS) { - throw new TooLongPaymentAddressException($payment_address); + } elseif (mb_strlen($paymentAddress) > Constraints::MAX_LENGTH_PAYMENT_ADDRESS) { + throw new TooLongPaymentAddressException($paymentAddress); } - $this->payment_address = $payment_address; + $this->paymentAddress = $paymentAddress; return $this; } /** * @inheritDoc - * @throws InvalidEmailException - * @throws InvalidEnumValueException - * @throws InvalidInnLengthException - * @throws InvalidPaymentAddressException */ #[ArrayShape([ - 'email' => 'string', 'sno' => 'string', + 'email' => 'string', 'inn' => 'string', 'payment_address' => 'string', ])] public function jsonSerialize(): array { return [ - 'email' => $this->email - ? $this->getEmail() - : throw new InvalidEmailException(), - 'sno' => $this->sno - ? $this->getSno() - : throw new InvalidEnumValueException(SnoTypes::class, 'null'), - 'inn' => $this->inn - ? $this->getInn() - : throw new InvalidInnLengthException(), - 'payment_address' => $this->payment_address - ? $this->getPaymentAddress() - : throw new InvalidPaymentAddressException(), + 'inn' => $this->getInn(), + 'sno' => $this->getSno(), + 'payment_address' => $this->getPaymentAddress(), + 'email' => $this->getEmail(), ]; } } diff --git a/src/Entities/Correction.php b/src/Entities/Correction.php index 3e8fade..7185e2a 100644 --- a/src/Entities/Correction.php +++ b/src/Entities/Correction.php @@ -1,4 +1,5 @@ setCompany($company)->setCorrectionInfo($correction_info)->setPayments($payments)->setVats($vats); + $this->setCompany($company)->setCorrectionInfo($correctionInfo)->setPayments($payments)->setVats($vats); } /** @@ -143,18 +124,18 @@ final class Correction extends Entity */ public function getCorrectionInfo(): CorrectionInfo { - return $this->correction_info; + return $this->correctionInfo; } /** * Устанавливает данные коррекции * - * @param CorrectionInfo $correction_info + * @param CorrectionInfo $correctionInfo * @return Correction */ - public function setCorrectionInfo(CorrectionInfo $correction_info): Correction + public function setCorrectionInfo(CorrectionInfo $correctionInfo): Correction { - $this->correction_info = $correction_info; + $this->correctionInfo = $correctionInfo; return $this; } @@ -177,8 +158,7 @@ final class Correction extends Entity */ public function setPayments(Payments $payments): self { - $payments->checkCount(); - $payments->checkItemsClasses(); + $payments->checkCount()->checkItemsClasses(); $this->payments = $payments; return $this; } @@ -186,7 +166,7 @@ final class Correction extends Entity /** * Возвращает установленную коллекцию ставок НДС * - * @return Vats|null + * @return Vats */ public function getVats(): Vats { @@ -196,14 +176,13 @@ final class Correction extends Entity /** * Устанаваливает коллекцию ставок НДС * - * @param Vats|null $vats + * @param Vats $vats * @return $this * @throws Exception */ public function setVats(Vats $vats): self { - $vats->checkCount(); - $vats->checkItemsClasses(); + $vats->checkCount()->checkItemsClasses(); $this->vats = $vats; return $this; } diff --git a/src/Entities/CorrectionInfo.php b/src/Entities/CorrectionInfo.php index 2402640..3ffa566 100644 --- a/src/Entities/CorrectionInfo.php +++ b/src/Entities/CorrectionInfo.php @@ -1,4 +1,5 @@ setType($type)->setDate($date)->setNumber($number); + public function __construct( + protected CorrectionType $type, + DateTimeInterface | string $date, + protected string $number, + ) { + $this->setType($type) + ->setDate($date) + ->setNumber($number); } /** * Возвращает тип коррекции * - * @return string|null + * @return CorrectionType|null */ - public function getType(): ?string + public function getType(): ?CorrectionType { return $this->type; } @@ -73,23 +68,21 @@ final class CorrectionInfo extends Entity /** * Устанавливает тип коррекции * - * @param string $type + * @param CorrectionType $type * @return $this - * @throws InvalidEnumValueException */ - public function setType(string $type): self + public function setType(CorrectionType $type): self { - $type = trim($type); - CorrectionTypes::isValid($type) && $this->type = $type; + $this->type = $type; return $this; } /** * Возвращает дату документа основания для коррекции * - * @return string|null + * @return DateTimeImmutable */ - public function getDate(): ?string + public function getDate(): DateTimeImmutable { return $this->date; } @@ -97,17 +90,20 @@ final class CorrectionInfo extends Entity /** * Устанавливает дату документа основания для коррекции * - * @param DateTime|string $date Строковая дата в формате d.m.Y либо объект DateTime с датой + * @param DateTimeInterface|string $date Строковая дата в формате d.m.Y либо объект DateTime с датой * @return $this * @throws InvalidCorrectionDateException */ - public function setDate(DateTime|string $date): self + public function setDate(DateTimeInterface | string $date): self { try { if (is_string($date)) { - $date = new DateTime(trim($date)); + $this->date = new DateTimeImmutable(trim($date)); + } elseif ($date instanceof DateTime) { + $this->date = DateTimeImmutable::createFromMutable($date); + } elseif ($date instanceof DateTimeImmutable) { + $this->date = $date; } - $this->date = $date->format(Constraints::CORRECTION_DATE_FORMAT); } catch (Exception $e) { throw new InvalidCorrectionDateException($date, $e->getMessage()); } @@ -142,13 +138,16 @@ final class CorrectionInfo extends Entity /** * @inheritDoc */ - #[Pure] - #[ArrayShape(['type' => 'string', 'base_date' => 'string', 'base_number' => 'string'])] + #[ArrayShape([ + 'type' => 'string', + 'base_date' => 'string', + 'base_number' => 'string', + ])] public function jsonSerialize(): array { return [ 'type' => $this->getType(), - 'base_date' => $this->getDate(), + 'base_date' => $this->getDate()->format(Constraints::CORRECTION_DATE_FORMAT), 'base_number' => $this->getNumber(), ]; } diff --git a/src/Entities/Entity.php b/src/Entities/Entity.php index 86a13c7..9bc8fca 100644 --- a/src/Entities/Entity.php +++ b/src/Entities/Entity.php @@ -1,4 +1,5 @@ setName($name); !is_null($price) && $this->setPrice($price); @@ -160,13 +143,10 @@ final class Item extends Entity */ public function setName(string $name): self { - $name = trim($name); - if (mb_strlen($name) > Constraints::MAX_LENGTH_ITEM_NAME) { + if (mb_strlen($name = trim($name)) > Constraints::MAX_LENGTH_ITEM_NAME) { throw new TooLongItemNameException($name); } - if (empty($name)) { - throw new EmptyItemNameException(); - } + empty($name) && throw new EmptyItemNameException(); $this->name = $name; return $this; } @@ -193,12 +173,8 @@ final class Item extends Entity public function setPrice(float $price): self { $price = round($price, 2); - if ($price > Constraints::MAX_COUNT_ITEM_PRICE) { - throw new TooHighItemPriceException($this->getName(), $price); - } - if ($price < 0) { - throw new NegativeItemPriceException($this->getName(), $price); - } + $price > Constraints::MAX_COUNT_ITEM_PRICE && throw new TooHighItemPriceException($this->getName(), $price); + $price < 0 && throw new NegativeItemPriceException($this->getName(), $price); $this->price = $price; $this->getVat()?->setSum($this->getSum()); return $this; @@ -229,9 +205,7 @@ final class Item extends Entity if ($quantity > Constraints::MAX_COUNT_ITEM_QUANTITY) { throw new TooHighItemQuantityException($this->getName(), $quantity); } - if ($quantity < 0) { - throw new NegativeItemQuantityException($this->getName(), $quantity); - } + $quantity < 0 && throw new NegativeItemQuantityException($this->getName(), $quantity); $this->quantity = $quantity; $this->getVat()?->setSum($this->getSum()); return $this; @@ -296,7 +270,7 @@ final class Item extends Entity */ public function getCodeHex(): ?string { - return $this->code_hex; + return $this->codeHex; } /** @@ -318,57 +292,51 @@ final class Item extends Entity $hex_string = trim(preg_replace('/([\dA-Fa-f]{2})/', '$1 ', $hex)); } $this->code = $code ?: null; - $this->code_hex = $hex_string ?: null; + $this->codeHex = $hex_string ?: null; return $this; } /** * Возвращает признак способа оплаты * - * @return string|null + * @return PaymentMethod|null */ - public function getPaymentMethod(): ?string + public function getPaymentMethod(): ?PaymentMethod { - return $this->payment_method; + return $this->paymentMethod; } /** * Устанавливает признак способа оплаты * - * @param string|null $payment_method Признак способа оплаты + * @param PaymentMethod|null $paymentMethod Признак способа оплаты * @return $this - * @throws InvalidEnumValueException */ - public function setPaymentMethod(?string $payment_method): self + public function setPaymentMethod(?PaymentMethod $paymentMethod): self { - $payment_method = trim((string)$payment_method); - PaymentMethods::isValid($payment_method); - $this->payment_method = $payment_method ?: null; + $this->paymentMethod = $paymentMethod; return $this; } /** * Возвращает признак предмета расчёта * - * @return string|null + * @return PaymentObject|null */ - public function getPaymentObject(): ?string + public function getPaymentObject(): ?PaymentObject { - return $this->payment_object; + return $this->paymentObject; } /** * Устанавливает признак предмета расчёта * - * @param string|null $payment_object Признак предмета расчёта + * @param PaymentObject|null $paymentObject Признак предмета расчёта * @return $this - * @throws InvalidEnumValueException */ - public function setPaymentObject(?string $payment_object): self + public function setPaymentObject(?PaymentObject $paymentObject): self { - $payment_object = trim((string)$payment_object); - PaymentObjects::isValid($payment_object); - $this->payment_object = $payment_object ?: null; + $this->paymentObject = $paymentObject; return $this; } @@ -385,21 +353,19 @@ final class Item extends Entity /** * Устанавливает ставку НДС * - * @param Vat|string|null $vat Объект ставки, одно из значений VatTypes или null для удаления ставки + * @param Vat | VatType | null $vat Объект ставки, одно из значений VatTypes или null для удаления ставки * @return $this * @throws TooHighItemSumException - * @throws InvalidEnumValueException */ - public function setVat(Vat|string|null $vat): self + public function setVat(Vat | VatType | null $vat): self { - if (is_string($vat)) { - $vat = trim($vat); - empty($vat) - ? $this->vat = null - : VatTypes::isValid($vat) && $this->vat = new Vat($vat, $this->getSum()); + if (is_null($vat)) { + $this->vat = null; } elseif ($vat instanceof Vat) { $vat->setSum($this->getSum()); $this->vat = $vat; + } else { + $this->vat = new Vat($vat, $this->getSum()); } return $this; } @@ -411,18 +377,18 @@ final class Item extends Entity */ public function getAgentInfo(): ?AgentInfo { - return $this->agent_info; + return $this->agentInfo; } /** * Устанавливает атрибуты агента * - * @param AgentInfo|null $agent_info + * @param AgentInfo|null $agentInfo * @return Item */ - public function setAgentInfo(?AgentInfo $agent_info): self + public function setAgentInfo(?AgentInfo $agentInfo): self { - $this->agent_info = $agent_info; + $this->agentInfo = $agentInfo; return $this; } @@ -455,23 +421,23 @@ final class Item extends Entity */ public function getUserData(): ?string { - return $this->user_data; + return $this->userData; } /** * Устанавливает дополнительный реквизит * - * @param string|null $user_data Дополнительный реквизит + * @param string|null $userData Дополнительный реквизит * @return $this * @throws TooLongUserdataException */ - public function setUserData(?string $user_data): self + public function setUserData(?string $userData): self { - $user_data = trim((string)$user_data); - if (mb_strlen($user_data) > Constraints::MAX_LENGTH_USER_DATA) { - throw new TooLongUserdataException($user_data); + $userData = trim((string)$userData); + if (mb_strlen($userData) > Constraints::MAX_LENGTH_USER_DATA) { + throw new TooLongUserdataException($userData); } - $this->user_data = $user_data ?: null; + $this->userData = $userData ?: null; return $this; } @@ -512,25 +478,25 @@ final class Item extends Entity */ public function getCountryCode(): ?string { - return $this->country_code; + return $this->countryCode; } /** * Устанавливает код страны происхождения товара * - * @param string|null $country_code + * @param string|null $countryCode * @return Item * @throws InvalidOKSMCodeException * @see https://classifikators.ru/oksm * @see https://ru.wikipedia.org/wiki/Общероссийский_классификатор_стран_мира */ - public function setCountryCode(?string $country_code): self + public function setCountryCode(?string $countryCode): self { - $country_code = trim((string)$country_code); - if (preg_match(Constraints::PATTERN_OKSM_CODE, $country_code) != 1) { - throw new InvalidOKSMCodeException($country_code); + $countryCode = trim((string)$countryCode); + if (preg_match(Constraints::PATTERN_OKSM_CODE, $countryCode) != 1) { + throw new InvalidOKSMCodeException($countryCode); } - $this->country_code = $country_code ?: null; + $this->countryCode = $countryCode ?: null; return $this; } @@ -541,28 +507,27 @@ final class Item extends Entity */ public function getDeclarationNumber(): ?string { - return $this->declaration_number; + return $this->declarationNumber; } /** * Устанавливает код таможенной декларации * - * @param string|null $declaration_number + * @param string|null $declarationNumber * @return Item * @throws InvalidDeclarationNumberException */ - public function setDeclarationNumber(?string $declaration_number): self + public function setDeclarationNumber(?string $declarationNumber): self { - if (is_string($declaration_number)) { - $declaration_number = trim($declaration_number); - if ( - mb_strlen($declaration_number) < Constraints::MIN_LENGTH_DECLARATION_NUMBER - || mb_strlen($declaration_number) > Constraints::MAX_LENGTH_DECLARATION_NUMBER - ) { - throw new InvalidDeclarationNumberException($declaration_number); + if (is_string($declarationNumber)) { + $declarationNumber = trim($declarationNumber); + $is_short = mb_strlen($declarationNumber) < Constraints::MIN_LENGTH_DECLARATION_NUMBER; + $is_long = mb_strlen($declarationNumber) > Constraints::MAX_LENGTH_DECLARATION_NUMBER; + if ($is_short || $is_long) { + throw new InvalidDeclarationNumberException($declarationNumber); } } - $this->declaration_number = $declaration_number; + $this->declarationNumber = $declarationNumber; return $this; } diff --git a/src/Entities/Kkt.php b/src/Entities/Kkt.php index ba33358..0fca078 100644 --- a/src/Entities/Kkt.php +++ b/src/Entities/Kkt.php @@ -1,4 +1,5 @@ setName($name); $this->setInn($inn); diff --git a/src/Entities/PayingAgent.php b/src/Entities/PayingAgent.php index 7620382..7dca1b5 100644 --- a/src/Entities/PayingAgent.php +++ b/src/Entities/PayingAgent.php @@ -1,4 +1,5 @@ setOperation($operation); $this->setPhones($phones); diff --git a/src/Entities/Payment.php b/src/Entities/Payment.php index e4e57b4..c3aa3a0 100644 --- a/src/Entities/Payment.php +++ b/src/Entities/Payment.php @@ -1,4 +1,5 @@ setType($type)->setSum($sum); } /** * Возвращает установленный тип оплаты * - * @return int + * @return PaymentType */ - public function getType(): int + public function getType(): PaymentType { return $this->type; } @@ -69,13 +57,12 @@ final class Payment extends Entity /** * Устанавливает тип оплаты * - * @param int $type + * @param PaymentType $type * @return $this - * @throws InvalidEnumValueException */ - public function setType(int $type): self + public function setType(PaymentType $type): self { - PaymentTypes::isValid($type) && $this->type = $type; + $this->type = $type; return $this; } @@ -100,12 +87,8 @@ final class Payment extends Entity public function setSum(float $sum): self { $sum = round($sum, 2); - if ($sum > Constraints::MAX_COUNT_PAYMENT_SUM) { - throw new TooHighPaymentSumException($sum); - } - if ($sum < 0) { - throw new NegativePaymentSumException($sum); - } + $sum > Constraints::MAX_COUNT_PAYMENT_SUM && throw new TooHighPaymentSumException($sum); + $sum < 0 && throw new NegativePaymentSumException($sum); $this->sum = $sum; return $this; } diff --git a/src/Entities/Receipt.php b/src/Entities/Receipt.php index 67c7e59..c638bc3 100644 --- a/src/Entities/Receipt.php +++ b/src/Entities/Receipt.php @@ -1,4 +1,5 @@ checkCount(); $items->checkItemsClasses(); $this->items = $items; - $this->getItems()->each(fn($item) => $this->total += $item->getSum()); + $this->getItems()->each(fn ($item) => $this->total += $item->getSum()); $this->total = round($this->total, 2); return $this; } @@ -280,7 +281,7 @@ final class Receipt extends Entity $vats->checkItemsClasses(); $this->vats = $vats; /** @var Vat $vat */ - $this->getVats()->each(fn($vat) => $vat->setSum($this->getTotal())); + $this->getVats()->each(fn ($vat) => $vat->setSum($this->getTotal())); return $this; } diff --git a/src/Entities/ReceivePaymentsOperator.php b/src/Entities/ReceivePaymentsOperator.php index 83b52a3..92740b1 100644 --- a/src/Entities/ReceivePaymentsOperator.php +++ b/src/Entities/ReceivePaymentsOperator.php @@ -1,4 +1,5 @@ setPhones($phones); } diff --git a/src/Entities/Supplier.php b/src/Entities/Supplier.php index 579e241..65e18a5 100644 --- a/src/Entities/Supplier.php +++ b/src/Entities/Supplier.php @@ -1,4 +1,5 @@ setName($name); !is_null($inn) && $this->setInn($inn); diff --git a/src/Entities/Vat.php b/src/Entities/Vat.php index e65e829..51848ca 100644 --- a/src/Entities/Vat.php +++ b/src/Entities/Vat.php @@ -1,4 +1,5 @@ setType($type)->setSum($rubles); + public function __construct( + protected VatType $type, + protected float $sum, + ) { + $this->setType($type)->setSum($sum); } /** * Устанавливает тип ставки НДС * Автоматически пересчитывает итоговый размер НДС от исходной суммы. * - * @param string $type Тип ставки НДС + * @param VatType $type Тип ставки НДС * @return $this - * @throws InvalidEnumValueException */ - public function setType(string $type): self + public function setType(VatType $type): self { - $type = trim($type); - VatTypes::isValid($type) && $this->type = $type; + $this->type = $type; return $this; } /** * Возвращает тип ставки НДС * - * @return string + * @return VatType */ - public function getType(): string + public function getType(): VatType { return $this->type; } @@ -108,12 +97,12 @@ final class Vat extends Entity { return Helpers::toRub( match ($this->getType()) { - 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, + VatType::VAT10 => Helpers::toKop($this->sum) * 10 / 100, + VatType::VAT18 => Helpers::toKop($this->sum) * 18 / 100, + VatType::VAT20 => Helpers::toKop($this->sum) * 20 / 100, + VatType::VAT110 => Helpers::toKop($this->sum) * 10 / 110, + VatType::VAT118 => Helpers::toKop($this->sum) * 18 / 118, + VatType::VAT120 => Helpers::toKop($this->sum) * 20 / 120, default => 0, } ); diff --git a/src/Enums/AgentTypes.php b/src/Enums/AgentType.php similarity index 62% rename from src/Enums/AgentTypes.php rename to src/Enums/AgentType.php index 8d906dc..05c3166 100644 --- a/src/Enums/AgentTypes.php +++ b/src/Enums/AgentType.php @@ -1,4 +1,5 @@ assertEquals( + $this->assertSame( TestEnvParams::FFD105()['group'], (new Fiscalizer(group: 'group'))->getGroup() ); // prod mode - $this->assertEquals('group', (new Fiscalizer(false, group: 'group'))->getGroup()); + $this->assertSame('group', (new Fiscalizer(false, group: 'group'))->getGroup()); $this->assertNull((new Fiscalizer(false))->getGroup()); } @@ -164,7 +165,6 @@ class FiscalizerTest extends BasicTestCase * @throws EmptyLoginException * @throws EmptyPasswordException * @throws InvalidEntityInCollectionException - * @throws InvalidEnumValueException * @throws InvalidInnLengthException * @throws InvalidPaymentAddressException * @throws NegativeItemPriceException @@ -176,12 +176,13 @@ class FiscalizerTest extends BasicTestCase * @throws TooLongPaymentAddressException * @throws TooManyException * @throws GuzzleException + * @throws InvalidEnumValueException */ public function testSell(): void { $fisc_result = $this->newReceipt()->sell(new Fiscalizer()); $this->assertTrue($fisc_result->isSuccessful()); - $this->assertEquals('wait', $fisc_result->getContent()->status); + $this->assertSame('wait', $fisc_result->getContent()->status); self::$registered_uuids[] = $fisc_result->getContent()->uuid; } @@ -201,7 +202,6 @@ class FiscalizerTest extends BasicTestCase * @throws EmptyLoginException * @throws EmptyPasswordException * @throws InvalidEntityInCollectionException - * @throws InvalidEnumValueException * @throws InvalidInnLengthException * @throws InvalidPaymentAddressException * @throws NegativeItemPriceException @@ -213,12 +213,13 @@ class FiscalizerTest extends BasicTestCase * @throws TooLongPaymentAddressException * @throws TooManyException * @throws GuzzleException + * @throws InvalidEnumValueException */ public function testSellRefund(): void { $fisc_result = $this->newReceipt()->sellRefund(new Fiscalizer()); $this->assertTrue($fisc_result->isSuccessful()); - $this->assertEquals('wait', $fisc_result->getContent()->status); + $this->assertSame('wait', $fisc_result->getContent()->status); self::$registered_uuids[] = $fisc_result->getContent()->uuid; } @@ -237,7 +238,6 @@ class FiscalizerTest extends BasicTestCase * @throws EmptyPasswordException * @throws GuzzleException * @throws InvalidEntityInCollectionException - * @throws InvalidEnumValueException * @throws InvalidInnLengthException * @throws InvalidPaymentAddressException * @throws NegativePaymentSumException @@ -245,12 +245,13 @@ class FiscalizerTest extends BasicTestCase * @throws TooLongPaymentAddressException * @throws EmptyCorrectionNumberException * @throws InvalidCorrectionDateException + * @throws InvalidEnumValueException */ public function testSellCorrect(): void { $fisc_result = $this->newCorrection()->sellCorrect(new Fiscalizer()); $this->assertTrue($fisc_result->isSuccessful()); - $this->assertEquals('wait', $fisc_result->getContent()->status); + $this->assertSame('wait', $fisc_result->getContent()->status); //self::$registered_uuids[] = $fisc_result->getContent()->uuid; } @@ -270,7 +271,6 @@ class FiscalizerTest extends BasicTestCase * @throws EmptyLoginException * @throws EmptyPasswordException * @throws InvalidEntityInCollectionException - * @throws InvalidEnumValueException * @throws InvalidInnLengthException * @throws InvalidPaymentAddressException * @throws NegativeItemPriceException @@ -282,12 +282,13 @@ class FiscalizerTest extends BasicTestCase * @throws TooLongPaymentAddressException * @throws TooManyException * @throws GuzzleException + * @throws InvalidEnumValueException */ public function testBuy(): void { $fisc_result = $this->newReceipt()->buy(new Fiscalizer()); $this->assertTrue($fisc_result->isSuccessful()); - $this->assertEquals('wait', $fisc_result->getContent()->status); + $this->assertSame('wait', $fisc_result->getContent()->status); //self::$registered_uuids[] = $fisc_result->getContent()->uuid; } @@ -307,7 +308,6 @@ class FiscalizerTest extends BasicTestCase * @throws EmptyLoginException * @throws EmptyPasswordException * @throws InvalidEntityInCollectionException - * @throws InvalidEnumValueException * @throws InvalidInnLengthException * @throws InvalidPaymentAddressException * @throws NegativeItemPriceException @@ -319,12 +319,13 @@ class FiscalizerTest extends BasicTestCase * @throws TooLongPaymentAddressException * @throws TooManyException * @throws GuzzleException + * @throws InvalidEnumValueException */ public function testBuyRefund(): void { $fisc_result = $this->newReceipt()->buyRefund(new Fiscalizer()); $this->assertTrue($fisc_result->isSuccessful()); - $this->assertEquals('wait', $fisc_result->getContent()->status); + $this->assertSame('wait', $fisc_result->getContent()->status); //self::$registered_uuids[] = $fisc_result->getContent()->uuid; } @@ -356,7 +357,7 @@ class FiscalizerTest extends BasicTestCase { $fisc_result = $this->newCorrection()->buyCorrect(new Fiscalizer()); $this->assertTrue($fisc_result->isSuccessful()); - $this->assertEquals('wait', $fisc_result->getContent()->status); + $this->assertSame('wait', $fisc_result->getContent()->status); //self::$registered_uuids[] = $fisc_result->getContent()->uuid; } @@ -395,6 +396,6 @@ class FiscalizerTest extends BasicTestCase { $fisc_status = (new Fiscalizer())->pollDocumentStatus(array_shift(self::$registered_uuids)); //$this->assertTrue($fisc_status->isSuccessful()); - $this->assertEquals('done', $fisc_status->getContent()->status); + $this->assertSame('done', $fisc_status->getContent()->status); } } diff --git a/tests/AtolOnline/Tests/Api/MonitorTest.php b/tests/AtolOnline/Tests/Api/MonitorTest.php index bebe25c..76a6248 100644 --- a/tests/AtolOnline/Tests/Api/MonitorTest.php +++ b/tests/AtolOnline/Tests/Api/MonitorTest.php @@ -1,4 +1,5 @@ assertEquals('login', $client->getLogin()); + $this->assertSame('login', $client->getLogin()); $client = new Monitor(); - $this->assertEquals(TestEnvParams::FFD105()['login'], $client->getLogin()); + $this->assertSame(TestEnvParams::FFD105()['login'], $client->getLogin()); $client->setLogin('login'); - $this->assertEquals(TestEnvParams::FFD105()['login'], $client->getLogin()); + $this->assertSame(TestEnvParams::FFD105()['login'], $client->getLogin()); } /** @@ -145,13 +146,13 @@ class MonitorTest extends BasicTestCase public function testPassword(): void { $client = new Monitor(false, password: 'password'); - $this->assertEquals('password', $client->getPassword()); + $this->assertSame('password', $client->getPassword()); $client = new Monitor(); - $this->assertEquals(TestEnvParams::FFD105()['password'], $client->getPassword()); + $this->assertSame(TestEnvParams::FFD105()['password'], $client->getPassword()); $client->setPassword('password'); - $this->assertEquals(TestEnvParams::FFD105()['password'], $client->getPassword()); + $this->assertSame(TestEnvParams::FFD105()['password'], $client->getPassword()); } /** @@ -204,9 +205,6 @@ class MonitorTest extends BasicTestCase $client = (new Monitor())->setTestMode(); $this->assertTrue($client->isTestMode()); - $client = (new Monitor())->setTestMode(true); - $this->assertTrue($client->isTestMode()); - $client = (new Monitor())->setTestMode(false); $this->assertFalse($client->isTestMode()); } @@ -302,7 +300,6 @@ class MonitorTest extends BasicTestCase $client = $this->newTestClient(); $client->auth(); $kkts = $client->getAll(); - $sss = $kkts->where('deviceNumber', 'KKT014034'); $this->assertNotEmpty($client->getLastResponse()->getContent()); $this->assertIsCollection($kkts); $this->assertTrue($kkts->count() > 0); @@ -342,6 +339,6 @@ class MonitorTest extends BasicTestCase $this->assertIsSameClass(Kkt::class, $kkt); $this->assertIsAtolable($kkt); $this->assertNotNull($kkt->serialNumber); - $this->assertEquals($serial_number, $kkt->serialNumber); + $this->assertSame($serial_number, $kkt->serialNumber); } } diff --git a/tests/AtolOnline/Tests/BasicTestCase.php b/tests/AtolOnline/Tests/BasicTestCase.php index 8f576d6..a1c5673 100644 --- a/tests/AtolOnline/Tests/BasicTestCase.php +++ b/tests/AtolOnline/Tests/BasicTestCase.php @@ -1,4 +1,5 @@ assertIsArray($entity->jsonSerialize()); $this->assertIsArray($entity->toArray()); - $this->assertEquals($entity->jsonSerialize(), $entity->toArray()); + $this->assertSame($entity->jsonSerialize(), $entity->toArray()); $this->assertIsString((string)$entity); $this->assertJson((string)$entity); - if (!is_null($json_structure)) { - $this->assertEquals(json_encode($json_structure), (string)$entity); + if (!empty($json_structure)) { + $this->assertSame(json_encode($json_structure), (string)$entity); } } @@ -134,7 +135,7 @@ class BasicTestCase extends TestCase * @param object|string $expected Ожидаемый класс * @param object|string $actual Фактический класс */ - public function assertIsSameClass(object|string $expected, object|string $actual): void + public function assertIsSameClass(object | string $expected, object | string $actual): void { $this->assertTrue($this->checkisSameClass($expected, $actual)); } @@ -146,7 +147,7 @@ class BasicTestCase extends TestCase * @param object|string $class2 * @return bool */ - private function checkisSameClass(object|string $class1, object|string $class2): bool + private function checkisSameClass(object | string $class1, object | string $class2): bool { return (is_object($class1) ? $class1::class : $class1) === (is_object($class2) ? $class2::class : $class2); @@ -158,7 +159,7 @@ class BasicTestCase extends TestCase * @param array $expected Массив ожидаемых имён классов-родителей * @param object|string $actual Объект или имя класса для проверки */ - public function assertExtendsClasses(array $expected, object|string $actual): void + public function assertExtendsClasses(array $expected, object | string $actual): void { $this->assertTrue($this->checkExtendsClasses($expected, $actual)); } @@ -169,7 +170,7 @@ class BasicTestCase extends TestCase * @param string[] $parents Имена классов-родителей * @param object|string $class Объект или имя класса для проверки */ - private function checkExtendsClasses(array $parents, object|string $class): bool + private function checkExtendsClasses(array $parents, object | string $class): bool { return !empty(array_intersect($parents, is_object($class) ? class_parents($class) : [$class])); } @@ -180,7 +181,7 @@ class BasicTestCase extends TestCase * @param string[] $expected Массив ожидаемых имён интерфейсов * @param object|string $actual Объект или имя класса для проверки */ - public function assertImplementsInterfaces(array $expected, object|string $actual): void + public function assertImplementsInterfaces(array $expected, object | string $actual): void { $this->assertTrue($this->checkImplementsInterfaces($expected, $actual)); } @@ -192,7 +193,7 @@ class BasicTestCase extends TestCase * @param object|string $class Объект или имя класса для проверки * @see https://www.php.net/manual/ru/function.class-implements.php */ - private function checkImplementsInterfaces(array $interfaces, object|string $class): bool + private function checkImplementsInterfaces(array $interfaces, object | string $class): bool { return !empty(array_intersect($interfaces, is_object($class) ? class_implements($class) : [$class])); } @@ -203,7 +204,7 @@ class BasicTestCase extends TestCase * @param string[] $expected Массив ожидаемых имён трейтов * @param object|string $actual Объект или имя класса для проверки */ - public function assertUsesTraits(array $expected, object|string $actual): void + public function assertUsesTraits(array $expected, object | string $actual): void { $this->assertTrue($this->checkUsesTraits($expected, $actual)); } @@ -216,15 +217,15 @@ class BasicTestCase extends TestCase * @return bool * @see https://www.php.net/manual/ru/function.class-uses.php#110752 */ - private function checkUsesTraits(array $traits, object|string $class): bool + private function checkUsesTraits(array $traits, object | string $class): bool { $found_traits = []; $check_class = is_object($class) ? $class::class : $class; do { - $found_traits = array_merge(class_uses($check_class, true), $found_traits); + $found_traits = array_merge(class_uses($check_class), $found_traits); } while ($check_class = get_parent_class($check_class)); foreach ($found_traits as $trait => $same) { - $found_traits = array_merge(class_uses($trait, true), $found_traits); + $found_traits = array_merge(class_uses($trait), $found_traits); } return !empty(array_intersect(array_unique($found_traits), $traits)); } @@ -349,13 +350,11 @@ class BasicTestCase extends TestCase * @throws TooManyException * @throws Exception */ - protected function generateItemObjects(int $count = 1): array + protected function generateItemObjects(int $count = 1): iterable { - $result = []; for ($i = 0; $i < abs($count); ++$i) { - $result[] = new Item(Helpers::randomStr(), random_int(1, 100), random_int(1, 10)); + yield new Item(Helpers::randomStr(), random_int(1, 100), random_int(1, 10)); } - return $result; } /** @@ -363,22 +362,19 @@ class BasicTestCase extends TestCase * * @param int $count * @return Payment[] - * @throws InvalidEnumValueException * @throws NegativePaymentSumException * @throws TooHighPaymentSumException * @throws Exception */ - protected function generatePaymentObjects(int $count = 1): array + protected function generatePaymentObjects(int $count = 1): iterable { - $types = PaymentTypes::toArray(); - $result = []; + $types = PaymentType::cases(); for ($i = 0; $i < abs($count); ++$i) { - $result[] = new Payment( - array_values($types)[random_int(min($types), max($types))], + yield new Payment( + $types[random_int(0, count($types) - 1)], random_int(1, 100) * 2 / 3 ); } - return $result; } /** @@ -389,17 +385,15 @@ class BasicTestCase extends TestCase * @throws InvalidEnumValueException * @throws Exception */ - protected function generateVatObjects(int $count = 1): array + protected function generateVatObjects(int $count = 1): iterable { - $types = VatTypes::toArray(); - $result = []; + $types = VatType::cases(); for ($i = 0; $i < abs($count); ++$i) { - $result[] = new Vat( - array_values($types)[random_int(0, count($types) - 1)], + yield new Vat( + $types[random_int(0, count($types) - 1)], random_int(1, 100) * 2 / 3 ); } - return $result; } /** @@ -409,7 +403,6 @@ class BasicTestCase extends TestCase * @throws EmptyItemNameException * @throws EmptyItemsException * @throws InvalidEntityInCollectionException - * @throws InvalidEnumValueException * @throws NegativeItemPriceException * @throws NegativeItemQuantityException * @throws NegativePaymentSumException @@ -421,8 +414,8 @@ class BasicTestCase extends TestCase protected function newReceipt(): Receipt { return new Receipt( - new Client('John Doe', 'john@example.com', '+79501234567', '1234567890'), - new Company('company@example.com', SnoTypes::OSN, '1234567890', 'https://example.com'), + new Client('John Doe', '+79501234567', 'john@example.com', '1234567890'), + new Company('1234567890', SnoType::OSN, 'https://example.com', 'company@example.com'), new Items($this->generateItemObjects(2)), new Payments($this->generatePaymentObjects()) ); @@ -442,8 +435,8 @@ class BasicTestCase extends TestCase protected function newCorrection(): Correction { return new Correction( - new Company('company@example.com', SnoTypes::OSN, '1234567890', 'https://example.com'), - new CorrectionInfo(CorrectionTypes::SELF, '01.01.2021', Helpers::randomStr()), + new Company('1234567890', SnoType::OSN, 'https://example.com', 'company@example.com'), + new CorrectionInfo(CorrectionType::SELF, '01.01.2021', Helpers::randomStr()), new Payments($this->generatePaymentObjects(2)), new Vats($this->generateVatObjects(2)), ); diff --git a/tests/AtolOnline/Tests/Collections/ItemsTest.php b/tests/AtolOnline/Tests/Collections/ItemsTest.php index 6cc9ace..cdf146f 100644 --- a/tests/AtolOnline/Tests/Collections/ItemsTest.php +++ b/tests/AtolOnline/Tests/Collections/ItemsTest.php @@ -1,4 +1,5 @@ generateVatObjects(3)); $this->assertIsCollection($vats); - $this->assertEquals(3, $vats->count()); + $this->assertSame(3, $vats->count()); $this->assertIsAtolable($vats); } @@ -89,6 +90,7 @@ class VatsTest extends BasicTestCase * @covers \AtolOnline\Exceptions\InvalidEntityInCollectionException * @throws InvalidEnumValueException * @throws Exception + * @noinspection PhpParamsInspection */ public function testInvalidCollectionItemExceptionScalar(): void { @@ -115,7 +117,7 @@ class VatsTest extends BasicTestCase $this->expectException(InvalidEntityInCollectionException::class); $this->expectExceptionMessage(Payment::class); (new Vats($this->generateVatObjects())) - ->merge([new Payment(PaymentTypes::PREPAID, 1)]) + ->merge([new Payment(PaymentType::PREPAID, 1)]) ->jsonSerialize(); } } diff --git a/tests/AtolOnline/Tests/Entities/AdditionalUserPropsTest.php b/tests/AtolOnline/Tests/Entities/AdditionalUserPropsTest.php index 8ee0f58..476c1e8 100644 --- a/tests/AtolOnline/Tests/Entities/AdditionalUserPropsTest.php +++ b/tests/AtolOnline/Tests/Entities/AdditionalUserPropsTest.php @@ -1,4 +1,5 @@ assertIsAtolable(new AgentInfo(), []); + $this->assertIsAtolable(new AgentInfo()); } /** @@ -58,63 +58,64 @@ class AgentInfoTest extends BasicTestCase * @throws InvalidPhoneException * @throws TooLongPayingAgentOperationException * @throws InvalidInnLengthException - * @throws InvalidEnumValueException * @throws Exception */ public function testConstructorWithArgs(): void { - $this->assertIsAtolable(new AgentInfo(null), []); - $this->assertIsAtolable(new AgentInfo(AgentTypes::ANOTHER), ['type' => AgentTypes::ANOTHER]); - $this->assertIsAtolable(new AgentInfo(pagent: new PayingAgent()), []); - $this->assertIsAtolable(new AgentInfo(mt_operator: new MoneyTransferOperator()), []); - $this->assertIsAtolable(new AgentInfo(rp_operator: new ReceivePaymentsOperator()), []); + $this->assertIsAtolable(new AgentInfo(null)); + $this->assertIsAtolable( + new AgentInfo(AgentType::ANOTHER), + ['type' => AgentType::ANOTHER] + ); + $this->assertIsAtolable( + new AgentInfo(payingAgent: new PayingAgent()) + ); + $this->assertIsAtolable( + new AgentInfo(moneyTransferOperator: new MoneyTransferOperator()) + ); + $this->assertIsAtolable( + new AgentInfo(receivePaymentsOperator: new ReceivePaymentsOperator()) + ); - $this->assertIsAtolable(new AgentInfo( - AgentTypes::ANOTHER, - new PayingAgent(), - new ReceivePaymentsOperator(), - new MoneyTransferOperator(), - ), ['type' => AgentTypes::ANOTHER]); + $this->assertIsAtolable( + new AgentInfo( + AgentType::ANOTHER, + new PayingAgent(), + new ReceivePaymentsOperator(), + new MoneyTransferOperator(), + ), + ['type' => AgentType::ANOTHER] + ); - $this->assertIsAtolable(new AgentInfo( - AgentTypes::ANOTHER, - new PayingAgent('test', ['+79518888888']), - new ReceivePaymentsOperator(['+79519999999']), - new MoneyTransferOperator('MTO Name', '9876543210', 'London', ['+79517777777']), - ), [ - 'type' => AgentTypes::ANOTHER, - 'paying_agent' => [ - 'operation' => 'test', - 'phones' => [ - '+79518888888', + $this->assertIsAtolable( + new AgentInfo( + AgentType::ANOTHER, + new PayingAgent('test', ['+79518888888']), + new ReceivePaymentsOperator(['+79519999999']), + new MoneyTransferOperator('MTO Name', '9876543210', 'London', ['+79517777777']), + ), + [ + 'type' => AgentType::ANOTHER, + 'paying_agent' => [ + 'operation' => 'test', + 'phones' => [ + '+79518888888', + ], ], - ], - 'receive_payments_operator' => [ - 'phones' => [ - '+79519999999', + 'receive_payments_operator' => [ + 'phones' => [ + '+79519999999', + ], ], - ], - 'money_transfer_operator' => [ - 'name' => 'MTO Name', - 'inn' => '9876543210', - 'address' => 'London', - 'phones' => [ - "+79517777777", + 'money_transfer_operator' => [ + 'name' => 'MTO Name', + 'inn' => '9876543210', + 'address' => 'London', + 'phones' => [ + '+79517777777', + ], ], - ], - ]); - } - - /** - * Тестирует исключение при некорректном типе - * - * @covers \AtolOnline\Entities\AgentInfo - * @covers \AtolOnline\Enums\AgentTypes::isValid - * @covers \AtolOnline\Exceptions\InvalidEnumValueException - */ - public function testInvalidEnumValueException(): void - { - $this->expectException(InvalidEnumValueException::class); - new AgentInfo('qwerty'); + ] + ); } } diff --git a/tests/AtolOnline/Tests/Entities/ClientTest.php b/tests/AtolOnline/Tests/Entities/ClientTest.php index b68c8c3..102f57a 100644 --- a/tests/AtolOnline/Tests/Entities/ClientTest.php +++ b/tests/AtolOnline/Tests/Entities/ClientTest.php @@ -1,4 +1,5 @@ assertIsAtolable(new Client(), []); + $this->assertIsAtolable(new Client()); } /** @@ -56,19 +57,20 @@ class ClientTest extends BasicTestCase public function testConstructorWithArgs(): void { $this->assertIsAtolable(new Client('John Doe'), ['name' => 'John Doe']); - $this->assertIsAtolable(new Client(email: 'john@example.com'), ['email' => 'john@example.com']); $this->assertIsAtolable(new Client(phone: '+1/22/99*73s dsdas654 5s6'), ['phone' => '+122997365456']); + $this->assertIsAtolable(new Client(email: 'john@example.com'), ['email' => 'john@example.com']); $this->assertIsAtolable(new Client(inn: '+fasd3\qe3fs_=nac99013928czc'), ['inn' => '3399013928']); $this->assertIsAtolable( new Client( 'John Doe', - 'john@example.com', '+1/22/99*73s dsdas654 5s6', // +122997365456 + 'john@example.com', '+fasd3\qe3fs_=nac99013928czc' // 3399013928 - ), [ + ), + [ 'name' => 'John Doe', - 'email' => 'john@example.com', 'phone' => '+122997365456', + 'email' => 'john@example.com', 'inn' => '3399013928', ] ); @@ -100,7 +102,7 @@ class ClientTest extends BasicTestCase public function testValidName(): void { $name = Helpers::randomStr(); - $this->assertEquals($name, (new Client())->setName($name)->getName()); + $this->assertSame($name, (new Client())->setName($name)->getName()); } /** @@ -143,7 +145,7 @@ class ClientTest extends BasicTestCase */ public function testValidPhone(string $input, string $output): void { - $this->assertEquals($output, (new Client())->setPhone($input)->getPhone()); + $this->assertSame($output, (new Client())->setPhone($input)->getPhone()); } /** @@ -174,7 +176,7 @@ class ClientTest extends BasicTestCase */ public function testValidEmails(mixed $email): void { - $this->assertEquals($email, (new Client())->setEmail($email)->getEmail()); + $this->assertSame($email, (new Client())->setEmail($email)->getEmail()); } /** @@ -219,8 +221,8 @@ class ClientTest extends BasicTestCase */ public function testValidInn(): void { - $this->assertEquals('1234567890', (new Client())->setInn('1234567890')->getInn()); - $this->assertEquals('123456789012', (new Client())->setInn('123456789012')->getInn()); + $this->assertSame('1234567890', (new Client())->setInn('1234567890')->getInn()); + $this->assertSame('123456789012', (new Client())->setInn('123456789012')->getInn()); } /** @@ -261,7 +263,7 @@ class ClientTest extends BasicTestCase public function testOffsetGetExists(): void { $client = new Client('John Doe'); - $this->assertEquals('John Doe', $client['name']); + $this->assertSame('John Doe', $client['name']); $this->assertTrue(isset($client['name'])); $this->assertFalse(isset($client['qwerty'])); } diff --git a/tests/AtolOnline/Tests/Entities/CompanyTest.php b/tests/AtolOnline/Tests/Entities/CompanyTest.php index 862c68e..5d0fc47 100644 --- a/tests/AtolOnline/Tests/Entities/CompanyTest.php +++ b/tests/AtolOnline/Tests/Entities/CompanyTest.php @@ -1,4 +1,5 @@ assertIsAtolable(new Company( - $email = 'company@example.com', - $sno = SnoTypes::OSN, - $inn = '1234567890', - $payment_address = 'https://example.com', - ), [ - 'email' => $email, - 'sno' => $sno, - 'inn' => $inn, - 'payment_address' => $payment_address, - ]); + $this->assertIsAtolable( + new Company( + $inn = '1234567890', + $sno = SnoType::OSN, + $paymentAddress = 'https://example.com', + $email = 'company@example.com', + ), + [ + 'inn' => $inn, + 'sno' => $sno, + 'payment_address' => $paymentAddress, + 'email' => $email, + ] + ); } /** @@ -64,7 +67,6 @@ class CompanyTest extends BasicTestCase * @covers \AtolOnline\Entities\Company::setEmail * @covers \AtolOnline\Exceptions\TooLongEmailException * @throws InvalidEmailException - * @throws InvalidEnumValueException * @throws InvalidInnLengthException * @throws InvalidPaymentAddressException * @throws TooLongEmailException @@ -73,7 +75,7 @@ class CompanyTest extends BasicTestCase public function testEmailTooLongException() { $this->expectException(TooLongEmailException::class); - new Company(Helpers::randomStr(65), SnoTypes::OSN, '1234567890', 'https://example.com'); + new Company('1234567890', SnoType::OSN, 'https://example.com', Helpers::randomStr(65)); } /** @@ -86,20 +88,7 @@ class CompanyTest extends BasicTestCase public function testInvalidEmailException() { $this->expectException(InvalidEmailException::class); - new Company('company@examas%^*.com', SnoTypes::OSN, '1234567890', 'https://example.com'); - } - - /** - * Тестирует исключение о слишком длинном платёжном адресе - * - * @covers \AtolOnline\Entities\Company - * @covers \AtolOnline\Entities\Company::setSno - * @covers \AtolOnline\Exceptions\InvalidEnumValueException - */ - public function testInvalidSnoException() - { - $this->expectException(InvalidEnumValueException::class); - new Company('company@example.com', 'test', '1234567890', 'https://example.com'); + new Company('1234567890', SnoType::OSN, 'https://example.com', 'company@examas%^*.com'); } /** @@ -109,7 +98,6 @@ class CompanyTest extends BasicTestCase * @covers \AtolOnline\Entities\Company::setInn * @covers \AtolOnline\Exceptions\InvalidInnLengthException * @throws InvalidEmailException - * @throws InvalidEnumValueException * @throws InvalidInnLengthException * @throws InvalidPaymentAddressException * @throws TooLongEmailException @@ -118,7 +106,7 @@ class CompanyTest extends BasicTestCase public function testInvalidInnLengthException() { $this->expectException(InvalidInnLengthException::class); - new Company('company@example.com', SnoTypes::OSN, Helpers::randomStr(13), 'https://example.com'); + new Company(Helpers::randomStr(13), SnoType::OSN, 'https://example.com', 'company@example.com'); } /** @@ -128,7 +116,6 @@ class CompanyTest extends BasicTestCase * @covers \AtolOnline\Entities\Company::setPaymentAddress * @covers \AtolOnline\Exceptions\TooLongPaymentAddressException * @throws InvalidEmailException - * @throws InvalidEnumValueException * @throws InvalidInnLengthException * @throws InvalidPaymentAddressException * @throws TooLongEmailException @@ -137,7 +124,7 @@ class CompanyTest extends BasicTestCase public function testTooLongPaymentAddressException() { $this->expectException(TooLongPaymentAddressException::class); - new Company('company@example.com', SnoTypes::OSN, '1234567890', Helpers::randomStr(257)); + new Company('1234567890', SnoType::OSN, Helpers::randomStr(257), 'company@example.com'); } /** @@ -150,6 +137,6 @@ class CompanyTest extends BasicTestCase public function testInvalidPaymentAddressException() { $this->expectException(InvalidPaymentAddressException::class); - new Company('company@example.com', SnoTypes::OSN, '1234567890', ''); + new Company('1234567890', SnoType::OSN, '', 'company@example.com'); } } diff --git a/tests/AtolOnline/Tests/Entities/CorrectionInfoTest.php b/tests/AtolOnline/Tests/Entities/CorrectionInfoTest.php index 3cf7e8d..cdf3e13 100644 --- a/tests/AtolOnline/Tests/Entities/CorrectionInfoTest.php +++ b/tests/AtolOnline/Tests/Entities/CorrectionInfoTest.php @@ -1,4 +1,5 @@ assertIsAtolable( - new CorrectionInfo(CorrectionTypes::SELF, '01.01.2021', $number = Helpers::randomStr()), + new CorrectionInfo(CorrectionType::SELF, '01.01.2021', $number = Helpers::randomStr()), [ - 'type' => CorrectionTypes::SELF, + 'type' => CorrectionType::SELF, 'base_date' => '01.01.2021', 'base_number' => $number, ] ); - } - /** - * Тестирует исключение при некорректном типе - * - * @covers \AtolOnline\Entities\CorrectionInfo - * @covers \AtolOnline\Entities\CorrectionInfo::setType - * @covers \AtolOnline\Enums\CorrectionTypes::isValid - * @covers \AtolOnline\Exceptions\InvalidEnumValueException - * @return void - * @throws EmptyCorrectionNumberException - * @throws InvalidCorrectionDateException - * @throws InvalidEnumValueException - */ - public function testInvalidEnumValueException(): void - { - $this->expectException(InvalidEnumValueException::class); - $this->expectExceptionMessage('Некорректное значение AtolOnline\Enums\CorrectionTypes::wrong_value'); - new CorrectionInfo('wrong_value', '01.01.2021', Helpers::randomStr()); + $this->assertIsAtolable( + new CorrectionInfo(CorrectionType::SELF, new DateTime('02.02.2022'), $number = Helpers::randomStr()), + [ + 'type' => CorrectionType::SELF, + 'base_date' => '02.02.2022', + 'base_number' => $number, + ] + ); + + $this->assertIsAtolable( + new CorrectionInfo( + CorrectionType::SELF, + new DateTimeImmutable('03.03.2023'), + $number = Helpers::randomStr() + ), + [ + 'type' => CorrectionType::SELF, + 'base_date' => '03.03.2023', + 'base_number' => $number, + ] + ); } /** @@ -77,17 +81,15 @@ class CorrectionInfoTest extends BasicTestCase * * @covers \AtolOnline\Entities\CorrectionInfo * @covers \AtolOnline\Entities\CorrectionInfo::setDate - * @covers \AtolOnline\Enums\CorrectionTypes::isValid * @covers \AtolOnline\Exceptions\InvalidCorrectionDateException * @return void * @throws EmptyCorrectionNumberException * @throws InvalidCorrectionDateException - * @throws InvalidEnumValueException */ public function testInvalidCorrectionDateException(): void { $this->expectException(InvalidCorrectionDateException::class); - new CorrectionInfo(CorrectionTypes::SELF, Helpers::randomStr(), Helpers::randomStr()); + new CorrectionInfo(CorrectionType::SELF, Helpers::randomStr(), Helpers::randomStr()); } /** @@ -95,13 +97,12 @@ class CorrectionInfoTest extends BasicTestCase * * @covers \AtolOnline\Entities\CorrectionInfo * @covers \AtolOnline\Entities\CorrectionInfo::setNumber - * @covers \AtolOnline\Enums\CorrectionTypes::isValid * @covers \AtolOnline\Exceptions\EmptyCorrectionNumberException * @return void */ public function testEmptyCorrectionNumberException(): void { $this->expectException(EmptyCorrectionNumberException::class); - new CorrectionInfo(CorrectionTypes::SELF, '01.01.2021', "\n\r\t\0"); + new CorrectionInfo(CorrectionType::SELF, '01.01.2021', "\n\r\t\0"); } } diff --git a/tests/AtolOnline/Tests/Entities/CorrectionTest.php b/tests/AtolOnline/Tests/Entities/CorrectionTest.php index 7cef2b2..398568b 100644 --- a/tests/AtolOnline/Tests/Entities/CorrectionTest.php +++ b/tests/AtolOnline/Tests/Entities/CorrectionTest.php @@ -1,4 +1,5 @@ newCorrection()->setCashier(Helpers::randomStr()); $this->assertArrayHasKey('cashier', $correction->jsonSerialize()); - $this->assertEquals($correction->getCashier(), $correction->jsonSerialize()['cashier']); + $this->assertSame($correction->getCashier(), $correction->jsonSerialize()['cashier']); } /** diff --git a/tests/AtolOnline/Tests/Entities/ItemTest.php b/tests/AtolOnline/Tests/Entities/ItemTest.php index 3be1b50..9950f83 100644 --- a/tests/AtolOnline/Tests/Entities/ItemTest.php +++ b/tests/AtolOnline/Tests/Entities/ItemTest.php @@ -1,4 +1,5 @@ assertEquals( - PaymentMethods::ADVANCE, - $item->setPaymentMethod(PaymentMethods::ADVANCE)->getPaymentMethod() + $this->assertSame( + PaymentMethod::ADVANCE, + $item->setPaymentMethod(PaymentMethod::ADVANCE)->getPaymentMethod() ); - $this->assertEquals( - PaymentObjects::COMMODITY, - $item->setPaymentObject(PaymentObjects::COMMODITY)->getPaymentObject() + $this->assertSame( + PaymentObject::COMMODITY, + $item->setPaymentObject(PaymentObject::COMMODITY)->getPaymentObject() ); $this->assertIsAtolable($item, [ 'name' => 'test item', @@ -287,80 +289,6 @@ class ItemTest extends BasicTestCase ]); } - /** - * Тестирует установку невалидного способа оплаты - * - * @covers \AtolOnline\Entities\Item::setPaymentMethod - * @covers \AtolOnline\Exceptions\InvalidEnumValueException - * @throws EmptyItemNameException - * @throws InvalidEnumValueException - * @throws TooManyException - * @throws NegativeItemPriceException - * @throws TooHighItemPriceException - * @throws NegativeItemQuantityException - * @throws TooLongItemNameException - */ - public function testInvalidPaymentMethod(): void - { - $this->expectException(InvalidEnumValueException::class); - $this->expectExceptionMessage('Некорректное значение AtolOnline\Enums\PaymentMethods::wrong_value'); - (new Item('test item', 2, 3))->setPaymentMethod('wrong_value'); - } - - /** - * Тестирует установку невалидного предмета расчёта - * - * @covers \AtolOnline\Entities\Item::setPaymentObject - * @covers \AtolOnline\Exceptions\InvalidEnumValueException - * @throws EmptyItemNameException - * @throws InvalidEnumValueException - * @throws TooManyException - * @throws NegativeItemPriceException - * @throws TooHighItemPriceException - * @throws NegativeItemQuantityException - * @throws TooLongItemNameException - */ - public function testInvalidPaymentObject(): void - { - $this->expectException(InvalidEnumValueException::class); - $this->expectExceptionMessage('Некорректное значение AtolOnline\Enums\PaymentObjects::wrong_value'); - (new Item('test item', 2, 3))->setPaymentObject('wrong_value'); - } - - /** - * Тестирует установку ставки НДС по строковой константе типа ставки - * - * @covers \AtolOnline\Entities\Item::setVat - * @covers \AtolOnline\Entities\Item::getVat - * @covers \AtolOnline\Entities\Item::jsonSerialize - * @throws EmptyItemNameException - * @throws InvalidEnumValueException - * @throws NegativeItemPriceException - * @throws NegativeItemQuantityException - * @throws TooHighItemPriceException - * @throws TooHighItemSumException - * @throws TooLongItemNameException - * @throws TooManyException - * @throws Exception - */ - public function testValidVatByString(): void - { - $item = (new Item('test item', 2, 3))->setVat(VatTypes::VAT20); - $this->assertIsSameClass(Vat::class, $item->getVat()); - $this->assertEquals(VatTypes::VAT20, $item->getVat()->getType()); - $this->assertEquals($item->getSum(), $item->getVat()->getSum()); - $this->assertIsAtolable($item, [ - 'name' => 'test item', - 'price' => 2, - 'quantity' => 3, - 'sum' => 6, - 'vat' => [ - 'type' => 'vat20', - 'sum' => 1.2, - ], - ]); - } - /** * Тестирует установку ставки НДС объектом * @@ -368,7 +296,6 @@ class ItemTest extends BasicTestCase * @covers \AtolOnline\Entities\Item::getVat * @covers \AtolOnline\Entities\Item::jsonSerialize * @throws EmptyItemNameException - * @throws InvalidEnumValueException * @throws NegativeItemPriceException * @throws NegativeItemQuantityException * @throws TooHighItemPriceException @@ -379,11 +306,11 @@ class ItemTest extends BasicTestCase */ public function testValidVatByObject(): void { - $vat = new Vat(VatTypes::VAT20, 4000); + $vat = new Vat(VatType::VAT20, 4000); $item = (new Item('test item', 2, 3))->setVat($vat); $this->assertIsSameClass(Vat::class, $item->getVat()); - $this->assertEquals(VatTypes::VAT20, $item->getVat()->getType()); - $this->assertEquals($item->getSum(), $item->getVat()->getSum()); + $this->assertSame(VatType::VAT20, $item->getVat()->getType()); + $this->assertSame($item->getSum(), $item->getVat()->getSum()); $this->assertIsAtolable($item, [ 'name' => 'test item', 'price' => 2, @@ -396,28 +323,6 @@ class ItemTest extends BasicTestCase ]); } - /** - * Тестирует обнуление ставки НДС - * - * @param mixed $vat - * @dataProvider providerNullableStrings - * @covers \AtolOnline\Entities\Item::setVat - * @covers \AtolOnline\Entities\Item::getVat - * @covers \AtolOnline\Entities\Item::jsonSerialize - * @throws EmptyItemNameException - * @throws NegativeItemPriceException - * @throws NegativeItemQuantityException - * @throws TooHighItemPriceException - * @throws TooLongItemNameException - * @throws TooManyException - * @throws InvalidEnumValueException - */ - public function testNullableVatByString(mixed $vat): void - { - $item = (new Item('test item', 2, 3))->setVat($vat); - $this->assertNull($item->getVat()); - } - /** * Тестирует установку атрибутов агента * @@ -425,7 +330,6 @@ class ItemTest extends BasicTestCase * @covers \AtolOnline\Entities\Item::getAgentInfo * @covers \AtolOnline\Entities\Item::jsonSerialize * @throws EmptyItemNameException - * @throws InvalidEnumValueException * @throws InvalidInnLengthException * @throws InvalidPhoneException * @throws NegativeItemPriceException @@ -438,13 +342,13 @@ class ItemTest extends BasicTestCase public function testAgentInfo(): void { $agent_info = new AgentInfo( - AgentTypes::ANOTHER, + AgentType::ANOTHER, new PayingAgent('test', ['+79518888888']), new ReceivePaymentsOperator(['+79519999999']), new MoneyTransferOperator('MTO Name', '9876543210', 'London', ['+79517777777']), ); $item = (new Item('test item', 2, 3))->setAgentInfo($agent_info); - $this->assertEquals($agent_info, $item->getAgentInfo()); + $this->assertSame($agent_info, $item->getAgentInfo()); } /** @@ -471,7 +375,7 @@ class ItemTest extends BasicTestCase ['+122997365456'], ); $item = (new Item('test item', 2, 3))->setSupplier($supplier); - $this->assertEquals($supplier, $item->getSupplier()); + $this->assertSame($supplier, $item->getSupplier()); $this->assertIsAtolable($item, [ 'name' => 'test item', 'price' => 2, @@ -744,11 +648,11 @@ class ItemTest extends BasicTestCase $encoded = trim(preg_replace('/([\dA-Fa-f]{2})/', '$1 ', bin2hex($code))); $item = (new Item('test item', 2, 3))->setCode($code); - $this->assertEquals($code, $item->getCode()); - $this->assertEquals($encoded, $item->getCodeHex()); + $this->assertSame($code, $item->getCode()); + $this->assertSame($encoded, $item->getCodeHex()); $decoded = hex2bin(str_replace(' ', '', $item->getCodeHex())); - $this->assertEquals($decoded, $item->getCode()); + $this->assertSame($decoded, $item->getCode()); $this->assertIsAtolable($item, [ 'name' => 'test item', diff --git a/tests/AtolOnline/Tests/Entities/KktEntityTest.php b/tests/AtolOnline/Tests/Entities/KktEntityTest.php index f27758e..a6b88d3 100644 --- a/tests/AtolOnline/Tests/Entities/KktEntityTest.php +++ b/tests/AtolOnline/Tests/Entities/KktEntityTest.php @@ -1,4 +1,5 @@ expectException(NotEnoughMonitorDataException::class); - new Kkt((object)[ - 'fiscalizationDate' => '2021-11-20T10:21:00+00:00', - ]); + new Kkt( + (object)[ + 'fiscalizationDate' => '2021-11-20T10:21:00+00:00', + ] + ); } /** @@ -104,7 +107,7 @@ class KktEntityTest extends BasicTestCase // string $this->assertNotNull($kkt->serialNumber); $this->assertIsString($kkt->serialNumber); - $this->assertEquals($this->sample_data['serialNumber'], $kkt->serialNumber); + $this->assertSame($this->sample_data['serialNumber'], $kkt->serialNumber); // int $this->assertNotNull($kkt->signedDocuments); diff --git a/tests/AtolOnline/Tests/Entities/MoneyTransferOperatorTest.php b/tests/AtolOnline/Tests/Entities/MoneyTransferOperatorTest.php index f077466..31ebdc1 100644 --- a/tests/AtolOnline/Tests/Entities/MoneyTransferOperatorTest.php +++ b/tests/AtolOnline/Tests/Entities/MoneyTransferOperatorTest.php @@ -1,4 +1,5 @@ assertEquals('[]', (string)(new MoneyTransferOperator())); + $this->assertSame('[]', (string)(new MoneyTransferOperator())); } /** @@ -52,20 +53,26 @@ class MoneyTransferOperatorTest extends BasicTestCase public function testConstructorWithArgs(): void { $this->assertIsAtolable(new MoneyTransferOperator('some name'), ['name' => 'some name']); - $this->assertIsAtolable(new MoneyTransferOperator(inn: '+fasd3\qe3fs_=nac99013928czc'), ['inn' => '3399013928']); + $this->assertIsAtolable( + new MoneyTransferOperator(inn: '+fasd3\qe3fs_=nac99013928czc'), + ['inn' => '3399013928'] + ); $this->assertIsAtolable(new MoneyTransferOperator(address: 'London'), ['address' => 'London']); $this->assertIsAtolable(new MoneyTransferOperator(phones: ['+122997365456']), ['phones' => ['+122997365456']]); - $this->assertIsAtolable(new MoneyTransferOperator( - 'some name', - '+fasd3\qe3fs_=nac99013928czc', - 'London', - ['+122997365456'], - ), [ - 'name' => 'some name', - 'inn' => '3399013928', - 'address' => 'London', - 'phones' => ['+122997365456'], - ]); + $this->assertIsAtolable( + new MoneyTransferOperator( + 'some name', + '+fasd3\qe3fs_=nac99013928czc', + 'London', + ['+122997365456'], + ), + [ + 'name' => 'some name', + 'inn' => '3399013928', + 'address' => 'London', + 'phones' => ['+122997365456'], + ] + ); } /** @@ -145,8 +152,8 @@ class MoneyTransferOperatorTest extends BasicTestCase */ public function testValidInn(): void { - $this->assertEquals('1234567890', (new MoneyTransferOperator())->setInn('1234567890')->getInn()); - $this->assertEquals('123456789012', (new MoneyTransferOperator())->setInn('123456789012')->getInn()); + $this->assertSame('1234567890', (new MoneyTransferOperator())->setInn('1234567890')->getInn()); + $this->assertSame('123456789012', (new MoneyTransferOperator())->setInn('123456789012')->getInn()); } /** diff --git a/tests/AtolOnline/Tests/Entities/PayingAgentTest.php b/tests/AtolOnline/Tests/Entities/PayingAgentTest.php index 62ed0a4..7f2fe6a 100644 --- a/tests/AtolOnline/Tests/Entities/PayingAgentTest.php +++ b/tests/AtolOnline/Tests/Entities/PayingAgentTest.php @@ -1,4 +1,5 @@ assertEquals('[]', (string)(new PayingAgent())); + $this->assertSame('[]', (string)(new PayingAgent())); } /** @@ -49,13 +50,16 @@ class PayingAgentTest extends BasicTestCase public function testConstructorWithArgs(): void { $operation = Helpers::randomStr(); - $this->assertIsAtolable(new PayingAgent( - $operation, - ['+122997365456'], - ), [ - 'operation' => $operation, - 'phones' => ['+122997365456'], - ]); + $this->assertIsAtolable( + new PayingAgent( + $operation, + ['+122997365456'], + ), + [ + 'operation' => $operation, + 'phones' => ['+122997365456'], + ] + ); $this->assertIsAtolable( new PayingAgent($operation), ['operation' => $operation] diff --git a/tests/AtolOnline/Tests/Entities/PaymentTest.php b/tests/AtolOnline/Tests/Entities/PaymentTest.php index da58d5a..d441518 100644 --- a/tests/AtolOnline/Tests/Entities/PaymentTest.php +++ b/tests/AtolOnline/Tests/Entities/PaymentTest.php @@ -1,4 +1,5 @@ assertIsAtolable( - new Payment(PaymentTypes::ELECTRON, 123.456789), + new Payment(PaymentType::ELECTRON, 123.456789), [ - 'type' => PaymentTypes::ELECTRON, + 'type' => PaymentType::ELECTRON, 'sum' => 123.46, ] ); } - /** - * Тестирует исключение при некорректном типе - * - * @covers \AtolOnline\Entities\Payment - * @covers \AtolOnline\Entities\Payment::setType - * @covers \AtolOnline\Enums\PaymentTypes::isValid - * @covers \AtolOnline\Exceptions\InvalidEnumValueException - * @return void - * @throws InvalidEnumValueException - * @throws NegativePaymentSumException - * @throws TooHighPaymentSumException - */ - public function testInvalidEnumValueException(): void - { - $this->expectException(InvalidEnumValueException::class); - $this->expectExceptionMessage('Некорректное значение AtolOnline\Enums\PaymentTypes::123'); - new Payment(123, 123.456789); - } - /** * Тестирует исключение при слишком большой сумме * @@ -77,13 +57,12 @@ class PaymentTest extends BasicTestCase * @covers \AtolOnline\Entities\Payment::setSum * @covers \AtolOnline\Exceptions\TooHighPaymentSumException * @return void - * @throws InvalidEnumValueException * @throws NegativePaymentSumException */ public function testTooHighPaymentSumException(): void { $this->expectException(TooHighPaymentSumException::class); - new Payment(PaymentTypes::ELECTRON, Constraints::MAX_COUNT_PAYMENT_SUM + 1); + new Payment(PaymentType::ELECTRON, Constraints::MAX_COUNT_PAYMENT_SUM + 1); } /** @@ -93,13 +72,12 @@ class PaymentTest extends BasicTestCase * @covers \AtolOnline\Entities\Payment::setSum * @covers \AtolOnline\Exceptions\NegativePaymentSumException * @return void - * @throws InvalidEnumValueException * @throws NegativePaymentSumException * @throws TooHighPaymentSumException */ public function testNegativePaymentSumException(): void { $this->expectException(NegativePaymentSumException::class); - new Payment(PaymentTypes::ELECTRON, -1); + new Payment(PaymentType::ELECTRON, -1); } } diff --git a/tests/AtolOnline/Tests/Entities/ReceiptTest.php b/tests/AtolOnline/Tests/Entities/ReceiptTest.php index ce3151b..403243b 100644 --- a/tests/AtolOnline/Tests/Entities/ReceiptTest.php +++ b/tests/AtolOnline/Tests/Entities/ReceiptTest.php @@ -1,4 +1,5 @@ newReceipt()->setAgentInfo($agent_info); $this->assertArrayHasKey('agent_info', $receipt->jsonSerialize()); - $this->assertEquals($receipt->getAgentInfo()->jsonSerialize(), $receipt->jsonSerialize()['agent_info']); + $this->assertSame($receipt->getAgentInfo()->jsonSerialize(), $receipt->jsonSerialize()['agent_info']); $this->assertArrayNotHasKey('agent_info', $receipt->setAgentInfo(null)->jsonSerialize()); } @@ -159,7 +160,7 @@ class ReceiptTest extends BasicTestCase $supplier = new Supplier('some name', '+fasd3\qe3fs_=nac99013928czc', ['+122997365456']); $receipt = $this->newReceipt()->setSupplier($supplier); $this->assertArrayHasKey('supplier_info', $receipt->jsonSerialize()); - $this->assertEquals($receipt->getSupplier()->jsonSerialize(), $receipt->jsonSerialize()['supplier_info']); + $this->assertSame($receipt->getSupplier()->jsonSerialize(), $receipt->jsonSerialize()['supplier_info']); $this->assertArrayNotHasKey('supplier_info', $receipt->setSupplier(null)->jsonSerialize()); } @@ -181,8 +182,8 @@ class ReceiptTest extends BasicTestCase { $this->expectException(EmptyItemsException::class); new Receipt( - new Client('John Doe', 'john@example.com', '+1/22/99*73s dsdas654 5s6', '+fasd3\qe3fs_=nac99013928czc'), - new Company('company@example.com', SnoTypes::OSN, '1234567890', 'https://example.com'), + new Client('John Doe', '+1/22/99*73s dsdas654 5s6', 'john@example.com', '+fasd3\qe3fs_=nac99013928czc'), + new Company('1234567890', SnoType::OSN, 'https://example.com', 'company@example.com'), new Items([]), new Payments($this->generatePaymentObjects()) ); @@ -211,8 +212,8 @@ class ReceiptTest extends BasicTestCase 'Коллекция AtolOnline\Collections\Items должна содержать объекты AtolOnline\Entities\Item' ); new Receipt( - new Client('John Doe', 'john@example.com', '+1/22/99*73s dsdas654 5s6', '+fasd3\qe3fs_=nac99013928czc'), - new Company('company@example.com', SnoTypes::OSN, '1234567890', 'https://example.com'), + new Client('John Doe', '+1/22/99*73s dsdas654 5s6', 'john@example.com', '+fasd3\qe3fs_=nac99013928czc'), + new Company('1234567890', SnoType::OSN, 'https://example.com', 'company@example.com'), new Items(['qwerty']), new Payments($this->generatePaymentObjects()) ); @@ -240,8 +241,8 @@ class ReceiptTest extends BasicTestCase { $this->expectException(EmptyPaymentsException::class); new Receipt( - new Client('John Doe', 'john@example.com', '+1/22/99*73s dsdas654 5s6', '+fasd3\qe3fs_=nac99013928czc'), - new Company('company@example.com', SnoTypes::OSN, '1234567890', 'https://example.com'), + new Client('John Doe', '+1/22/99*73s dsdas654 5s6', 'john@example.com', '+fasd3\qe3fs_=nac99013928czc'), + new Company('1234567890', SnoType::OSN, 'https://example.com', 'company@example.com'), new Items([new Item('test item', 2, 3)]), new Payments([]) ); @@ -273,8 +274,8 @@ class ReceiptTest extends BasicTestCase 'Коллекция AtolOnline\Collections\Payments должна содержать объекты AtolOnline\Entities\Payment' ); (string)new Receipt( - new Client('John Doe', 'john@example.com', '+1/22/99*73s dsdas654 5s6', '+fasd3\qe3fs_=nac99013928czc'), - new Company('company@example.com', SnoTypes::OSN, '1234567890', 'https://example.com'), + new Client('John Doe', '+1/22/99*73s dsdas654 5s6', 'john@example.com', '+fasd3\qe3fs_=nac99013928czc'), + new Company('1234567890', SnoType::OSN, 'https://example.com', 'company@example.com'), new Items([new Item('test item', 2, 3)]), new Payments(['qwerty']) ); @@ -365,11 +366,11 @@ class ReceiptTest extends BasicTestCase { $receipt = $this->newReceipt(); $items_total = $receipt->getItems()->pluck('sum')->sum(); - $this->assertEquals($items_total, $receipt->getTotal()); + $this->assertSame($items_total, $receipt->getTotal()); /** @var Vat $vat */ $receipt->setVats(new Vats($this->generateVatObjects(2)))->getVats() - ->each(fn($vat) => $this->assertEquals($items_total, $vat->getSum())); + ->each(fn ($vat) => $this->assertSame($items_total, $vat->getSum())); } /** @@ -398,7 +399,7 @@ class ReceiptTest extends BasicTestCase { $receipt = $this->newReceipt()->setCashier(Helpers::randomStr()); $this->assertArrayHasKey('cashier', $receipt->jsonSerialize()); - $this->assertEquals($receipt->getCashier(), $receipt->jsonSerialize()['cashier']); + $this->assertSame($receipt->getCashier(), $receipt->jsonSerialize()['cashier']); } /** @@ -480,7 +481,7 @@ class ReceiptTest extends BasicTestCase { $receipt = $this->newReceipt()->setAddCheckProps(Helpers::randomStr()); $this->assertArrayHasKey('additional_check_props', $receipt->jsonSerialize()); - $this->assertEquals($receipt->getAddCheckProps(), $receipt->jsonSerialize()['additional_check_props']); + $this->assertSame($receipt->getAddCheckProps(), $receipt->jsonSerialize()['additional_check_props']); } /** @@ -562,7 +563,7 @@ class ReceiptTest extends BasicTestCase $aup = new AdditionalUserProps('name', 'value'); $receipt = $this->newReceipt()->setAddUserProps($aup); $this->assertArrayHasKey('additional_user_props', $receipt->jsonSerialize()); - $this->assertEquals( + $this->assertSame( $receipt->getAddUserProps()->jsonSerialize(), $receipt->jsonSerialize()['additional_user_props'] ); diff --git a/tests/AtolOnline/Tests/Entities/ReceivePaymentsOperatorTest.php b/tests/AtolOnline/Tests/Entities/ReceivePaymentsOperatorTest.php index 8ed134d..b0f897a 100644 --- a/tests/AtolOnline/Tests/Entities/ReceivePaymentsOperatorTest.php +++ b/tests/AtolOnline/Tests/Entities/ReceivePaymentsOperatorTest.php @@ -1,4 +1,5 @@ assertEquals('[]', (string)(new ReceivePaymentsOperator())); + $this->assertSame('[]', (string)(new ReceivePaymentsOperator())); } /** diff --git a/tests/AtolOnline/Tests/Entities/SupplierTest.php b/tests/AtolOnline/Tests/Entities/SupplierTest.php index c14720c..5d775ae 100644 --- a/tests/AtolOnline/Tests/Entities/SupplierTest.php +++ b/tests/AtolOnline/Tests/Entities/SupplierTest.php @@ -1,4 +1,5 @@ assertEquals('[]', (string)(new Supplier())); + $this->assertSame('[]', (string)(new Supplier())); } /** @@ -52,15 +53,18 @@ class SupplierTest extends BasicTestCase $this->assertIsAtolable(new Supplier('some name'), ['name' => 'some name']); $this->assertIsAtolable(new Supplier(inn: '+fasd3\qe3fs_=nac99013928czc'), ['inn' => '3399013928']); $this->assertIsAtolable(new Supplier(phones: ['+122997365456']), ['phones' => ['+122997365456']]); - $this->assertIsAtolable(new Supplier( - 'some name', - '+fasd3\qe3fs_=nac99013928czc', - ['+122997365456'], - ), [ - 'name' => 'some name', - 'inn' => '3399013928', - 'phones' => ['+122997365456'], - ]); + $this->assertIsAtolable( + new Supplier( + 'some name', + '+fasd3\qe3fs_=nac99013928czc', + ['+122997365456'], + ), + [ + 'name' => 'some name', + 'inn' => '3399013928', + 'phones' => ['+122997365456'], + ] + ); } /** @@ -140,8 +144,8 @@ class SupplierTest extends BasicTestCase */ public function testValidInn(): void { - $this->assertEquals('1234567890', (new Supplier())->setInn('1234567890')->getInn()); - $this->assertEquals('123456789012', (new Supplier())->setInn('123456789012')->getInn()); + $this->assertSame('1234567890', (new Supplier())->setInn('1234567890')->getInn()); + $this->assertSame('123456789012', (new Supplier())->setInn('123456789012')->getInn()); } /** diff --git a/tests/AtolOnline/Tests/Entities/VatTest.php b/tests/AtolOnline/Tests/Entities/VatTest.php index 33d39cd..6012cc5 100644 --- a/tests/AtolOnline/Tests/Entities/VatTest.php +++ b/tests/AtolOnline/Tests/Entities/VatTest.php @@ -1,4 +1,5 @@ assertIsAtolable($vat, [ 'type' => $vat->getType(), 'sum' => $vat->getCalculated(), ]); - $this->assertEquals($type, $vat->getType()); - $this->assertEquals($sum, $vat->getSum()); + $this->assertSame($type, $vat->getType()); + $this->assertSame($sum, $vat->getSum()); } /** * Тестирует расчёт суммы НДС от суммы 100+20р и 100-20р * * @dataProvider providerVatsAdd - * @param string $type Тип НДС + * @param VatType $type Тип НДС * @param float $after_plus Результат после +20р * @param float $after_minus Результат после -20р * @covers \AtolOnline\Entities\Vat::addSum * @covers \AtolOnline\Entities\Vat::getCalculated - * @throws InvalidEnumValueException */ - public function testVatAdd(string $type, float $after_plus, float $after_minus) + public function testVatAdd(VatType $type, float $after_plus, float $after_minus) { $vat = (new Vat($type, 100))->addSum(20); // 120р - $this->assertEquals($after_plus, $vat->getCalculated()); + $this->assertSame($after_plus, $vat->getCalculated()); $vat->addSum(-20); // 100р - $this->assertEquals($after_minus, $vat->getCalculated()); + $this->assertSame($after_minus, $vat->getCalculated()); } } diff --git a/tests/AtolOnline/Tests/HelpersTest.php b/tests/AtolOnline/Tests/HelpersTest.php index 79e90c9..c66064f 100644 --- a/tests/AtolOnline/Tests/HelpersTest.php +++ b/tests/AtolOnline/Tests/HelpersTest.php @@ -1,4 +1,5 @@ assertIsFloat($result); - $this->assertEquals($result, $rubles); + $this->assertSame($result, $rubles); } /** @@ -103,7 +104,7 @@ class HelpersTest extends BasicTestCase { $result = Helpers::toKop($rubles); $this->assertIsInt($result); - $this->assertEquals($result, $kopeks); + $this->assertSame($result, $kopeks); } /** @@ -117,7 +118,7 @@ class HelpersTest extends BasicTestCase { $result = Helpers::randomStr($input); $this->assertIsString($result); - $this->assertEquals($output, strlen($result)); + $this->assertSame($output, strlen($result)); // тестировать на наличие цифр быссмысленно } }