Миграция на php8.1

* enum-ы теперь enum-ы, а не говно -- теперь всё переведено на них, где это было возможно
* некоторые свойства классов объявлены в конструкторе
* некоторые классы перемещены в корневой неймспейс
* исправлен код-стайл, вычищен некоторый мусор, выправлены тесты... работы над этим продолжаются
This commit is contained in:
2022-12-15 00:19:55 +08:00
parent 692ae43f9f
commit 4157ab68f5
120 changed files with 1098 additions and 1401 deletions

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -7,21 +8,19 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
declare(strict_types = 1);
declare(strict_types=1);
namespace AtolOnline\Entities;
use AtolOnline\Constants\Constraints;
use AtolOnline\Constraints;
use AtolOnline\Exceptions\{
EmptyAddUserPropNameException,
EmptyAddUserPropValueException,
TooLongAddUserPropNameException,
TooLongAddUserPropValueException
};
TooLongAddUserPropValueException};
use JetBrains\PhpStorm\{
ArrayShape,
Pure
};
Pure};
/**
* Класс, описывающий дополнительный реквизит пользователя
@@ -30,16 +29,6 @@ use JetBrains\PhpStorm\{
*/
final class AdditionalUserProps extends Entity
{
/**
* @var string Наименование (1085)
*/
protected string $name;
/**
* @var string Значение (1086)
*/
protected string $value;
/**
* Конструктор объекта покупателя
*
@@ -50,8 +39,10 @@ final class AdditionalUserProps extends Entity
* @throws TooLongAddUserPropNameException
* @throws TooLongAddUserPropValueException
*/
public function __construct(string $name, string $value)
{
public function __construct(
protected string $name,
protected string $value,
) {
$this->setName($name)->setValue($value);
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -7,12 +8,11 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
declare(strict_types = 1);
declare(strict_types=1);
namespace AtolOnline\Entities;
use AtolOnline\Enums\AgentTypes;
use AtolOnline\Exceptions\InvalidEnumValueException;
use AtolOnline\Enums\AgentType;
/**
* Класс, описывающий данные агента
@@ -21,53 +21,29 @@ use AtolOnline\Exceptions\InvalidEnumValueException;
*/
final class AgentInfo extends Entity
{
/**
* @var string|null Признак агента (1057)
*/
protected ?string $type = null;
/**
* @var PayingAgent|null Платёжный агент
*/
protected ?PayingAgent $paying_agent = null;
/**
* @var ReceivePaymentsOperator|null Оператор по приёму платежей
*/
protected ?ReceivePaymentsOperator $receive_payments_operator = null;
/**
* @var MoneyTransferOperator|null Оператор перевода
*/
protected ?MoneyTransferOperator $money_transfer_operator = null;
/**
* Конструктор
*
* @param string|null $type Признак агента (1057)
* @param PayingAgent|null $pagent Платёжный агент
* @param ReceivePaymentsOperator|null $rp_operator Оператор по приёму платежей
* @param MoneyTransferOperator|null $mt_operator Оператор перевода
* @throws InvalidEnumValueException
* @param AgentType|null $type Признак агента (1057)
* @param PayingAgent|null $payingAgent Платёжный агент
* @param ReceivePaymentsOperator|null $receivePaymentsOperator Оператор по приёму платежей
* @param MoneyTransferOperator|null $moneyTransferOperator Оператор перевода
*/
public function __construct(
?string $type = null,
?PayingAgent $pagent = null,
?ReceivePaymentsOperator $rp_operator = null,
?MoneyTransferOperator $mt_operator = null,
protected ?AgentType $type = null,
protected ?PayingAgent $payingAgent = null,
protected ?ReceivePaymentsOperator $receivePaymentsOperator = null,
protected ?MoneyTransferOperator $moneyTransferOperator = null,
) {
!is_null($type) && $this->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;
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -7,11 +8,11 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
declare(strict_types = 1);
declare(strict_types=1);
namespace AtolOnline\Entities;
use AtolOnline\Constants\Constraints;
use AtolOnline\Constraints;
use AtolOnline\Exceptions\{
InvalidEmailException,
InvalidInnLengthException,
@@ -30,17 +31,8 @@ use JetBrains\PhpStorm\Pure;
*/
final class Client extends Entity
{
use HasEmail, HasInn;
/**
* @var string|null Наименование (1227)
*/
protected ?string $name = null;
/**
* @var string|null Телефон (1008)
*/
protected ?string $phone = null;
use HasEmail;
use HasInn;
/**
* Конструктор объекта покупателя
@@ -56,9 +48,9 @@ final class Client extends Entity
* @throws TooLongEmailException
*/
public function __construct(
?string $name = null,
protected ?string $name = null,
protected ?string $phone = null,
?string $email = null,
?string $phone = null,
?string $inn = null
) {
!is_null($name) && $this->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;
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -7,24 +8,21 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
declare(strict_types = 1);
declare(strict_types=1);
namespace AtolOnline\Entities;
use AtolOnline\{
Constants\Constraints,
Enums\SnoTypes,
Constraints,
Enums\SnoType,
Traits\HasEmail,
Traits\HasInn
};
Traits\HasInn};
use AtolOnline\Exceptions\{
InvalidEmailException,
InvalidEnumValueException,
InvalidInnLengthException,
InvalidPaymentAddressException,
TooLongEmailException,
TooLongPaymentAddressException
};
TooLongPaymentAddressException};
use JetBrains\PhpStorm\ArrayShape;
/**
@@ -34,47 +32,39 @@ use JetBrains\PhpStorm\ArrayShape;
*/
final class Company extends Entity
{
use HasEmail, HasInn;
/**
* @var string|null Система налогообложения продавца (1055)
*/
protected ?string $sno;
/**
* @var string|null Место расчётов (адрес интернет-магазина) (1187)
*/
protected ?string $payment_address;
use HasEmail;
use HasInn;
/**
* Конструктор
*
* @param string $sno Система налогообложения продавца (1055)
* @param string $inn ИНН (1018)
* @param string $payment_address Место расчётов (адрес интернет-магазина) (1187)
* @param SnoType $sno Система налогообложения продавца (1055)
* @param string $paymentAddress Место расчётов (адрес интернет-магазина) (1187)
* @param string $email Почта (1117)
* @throws InvalidEmailException
* @throws InvalidInnLengthException
* @throws InvalidPaymentAddressException
* @throws InvalidEnumValueException
* @throws TooLongEmailException
* @throws TooLongPaymentAddressException
*/
public function __construct(
string $email, //TODO сделать необязательным здесь
string $sno, //TODO сделать необязательным здесь
string $inn,
string $payment_address,
protected SnoType $sno,
protected string $paymentAddress,
string $email,
) {
$this->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(),
];
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -14,7 +15,7 @@ use AtolOnline\{
Api\Fiscalizer,
Collections\Payments,
Collections\Vats,
Constants\Constraints};
Constraints};
use AtolOnline\Exceptions\{
AuthFailedException,
EmptyLoginException,
@@ -40,49 +41,29 @@ final class Correction extends Entity
*/
public const DOC_TYPE = 'correction';
/**
* @var Company Продавец
*/
protected Company $company;
/**
* @todo вынести в трейт?
* @var string|null ФИО кассира
*/
protected ?string $cashier = null;
/**
* @var CorrectionInfo Данные коррекции
*/
protected CorrectionInfo $correction_info;
/**
* @var Payments Коллекция оплат
*/
protected Payments $payments;
/**
* @var Vats Коллекция ставок НДС
*/
protected Vats $vats;
/**
* Конструктор
*
* @param Company $company
* @param CorrectionInfo $correction_info
* @param Payments $payments
* @param Vats $vats
* @param Company $company Продавец
* @param CorrectionInfo $correctionInfo Данные коррекции
* @param Payments $payments Коллекция оплат
* @param Vats $vats Коллекция ставок НДС
* @throws InvalidEntityInCollectionException
* @throws Exception
*/
public function __construct(
Company $company,
CorrectionInfo $correction_info,
Payments $payments,
Vats $vats,
protected Company $company,
protected CorrectionInfo $correctionInfo,
protected Payments $payments,
protected Vats $vats,
) {
$this->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;
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -7,21 +8,21 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
declare(strict_types = 1);
declare(strict_types=1);
namespace AtolOnline\Entities;
use AtolOnline\Constants\Constraints;
use AtolOnline\Enums\CorrectionTypes;
use AtolOnline\Constraints;
use AtolOnline\Enums\CorrectionType;
use AtolOnline\Exceptions\{
EmptyCorrectionNumberException,
InvalidCorrectionDateException,
InvalidEnumValueException};
InvalidCorrectionDateException,};
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use Exception;
use JetBrains\PhpStorm\{
ArrayShape,
Pure};
ArrayShape};
/**
* Класс, описывающий данные коррекции
@@ -31,41 +32,35 @@ use JetBrains\PhpStorm\{
final class CorrectionInfo extends Entity
{
/**
* @var string|null Тип коррекции (1173)
* @var DateTimeImmutable Дата документа основания для коррекции (1178)
*/
protected ?string $type = null;
/**
* @var string|null Дата документа основания для коррекции (1178)
*/
protected ?string $date = null;
/**
* @var string|null Номер документа основания для коррекции (1179)
*/
protected ?string $number = null;
protected DateTimeImmutable $date;
/**
* Конструктор
*
* @param string $type Тип коррекции
* @param string $date Дата документа
* @param string $number Номер документа
* @throws InvalidEnumValueException
* @param CorrectionType $type Тип коррекции (1173)
* @param DateTimeInterface|string $date Дата документа основания для коррекции (1178)
* @param string $number Номер документа основания для коррекции (1179)
* @throws InvalidCorrectionDateException
* @throws EmptyCorrectionNumberException
*/
public function __construct(string $type, string $date, string $number)
{
$this->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(),
];
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -9,7 +10,7 @@
/** @noinspection PhpMultipleClassDeclarationsInspection */
declare(strict_types = 1);
declare(strict_types=1);
namespace AtolOnline\Entities;
@@ -74,7 +75,7 @@ abstract class Entity implements JsonSerializable, Stringable, Arrayable, ArrayA
/**
* @inheritDoc
*/
public function offsetSet(mixed $offset, mixed $value)
public function offsetSet(mixed $offset, mixed $value): void
{
throw new BadMethodCallException(
'Объект ' . static::class . ' нельзя изменять как массив. Следует использовать сеттеры.'

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -7,20 +8,18 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
declare(strict_types = 1);
declare(strict_types=1);
namespace AtolOnline\Entities;
use AtolOnline\Constants\Constraints;
use AtolOnline\Constraints;
use AtolOnline\Enums\{
PaymentMethods,
PaymentObjects,
VatTypes
};
PaymentMethod,
PaymentObject,
VatType};
use AtolOnline\Exceptions\{
EmptyItemNameException,
InvalidDeclarationNumberException,
InvalidEnumValueException,
InvalidOKSMCodeException,
NegativeItemExciseException,
NegativeItemPriceException,
@@ -32,8 +31,7 @@ use AtolOnline\Exceptions\{
TooLongItemNameException,
TooLongMeasurementUnitException,
TooLongUserdataException,
TooManyException
};
TooManyException};
/**
* Предмет расчёта (товар, услуга)
@@ -42,21 +40,6 @@ use AtolOnline\Exceptions\{
*/
final class Item extends Entity
{
/**
* @var string Наименование (1030)
*/
protected string $name;
/**
* @var float Цена в рублях (с учётом скидок и наценок) (1079)
*/
protected float $price;
/**
* @var float Количество/вес (1023)
*/
protected float $quantity;
/**
* @var string|null Единица измерения (1197)
*/
@@ -70,22 +53,22 @@ final class Item extends Entity
/**
* @var string|null Код товара (1162) в форматированной шестнадцатиричной форме
*/
protected ?string $code_hex = null;
protected ?string $codeHex = null;
/**
* @var string|null Признак способа расчёта (1214)
* @var PaymentMethod|null Признак способа расчёта (1214)
*/
protected ?string $payment_method = null;
protected ?PaymentMethod $paymentMethod = null;
/**
* @var string|null Признак предмета расчёта (1212)
* @var PaymentObject|null Признак предмета расчёта (1212)
*/
protected ?string $payment_object = null;
protected ?PaymentObject $paymentObject = null;
/**
* @var string|null Номер таможенной декларации (1321)
*/
protected ?string $declaration_number = null;
protected ?string $declarationNumber = null;
/**
* @var Vat|null Ставка НДС
@@ -95,7 +78,7 @@ final class Item extends Entity
/**
* @var AgentInfo|null Атрибуты агента
*/
protected ?AgentInfo $agent_info = null;
protected ?AgentInfo $agentInfo = null;
/**
* @var Supplier|null Атрибуты поставшика
@@ -105,7 +88,7 @@ final class Item extends Entity
/**
* @var string|null Дополнительный реквизит (1191)
*/
protected ?string $user_data = null;
protected ?string $userData = null;
/**
* @var float|null Сумма акциза, включенная в стоимость (1229)
@@ -115,14 +98,14 @@ final class Item extends Entity
/**
* @var string|null Цифровой код страны происхождения товара (1230)
*/
protected ?string $country_code = null;
protected ?string $countryCode = null;
/**
* Конструктор
*
* @param string|null $name Наименование
* @param float|null $price Цена за одну единицу
* @param float|null $quantity Количество
* @param string|null $name Наименование (1030)
* @param float|null $price Цена в рублях (с учётом скидок и наценок) (1079)
* @param float|null $quantity Количество/вес (1023)
* @throws TooLongItemNameException
* @throws TooHighItemPriceException
* @throws TooManyException
@@ -131,9 +114,9 @@ final class Item extends Entity
* @throws NegativeItemQuantityException
*/
public function __construct(
string $name = null,
float $price = null,
float $quantity = null,
protected ?string $name = null,
protected ?float $price = null,
protected ?float $quantity = null,
) {
!is_null($name) && $this->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;
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -7,7 +8,7 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
declare(strict_types = 1);
declare(strict_types=1);
namespace AtolOnline\Entities;

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -7,18 +8,16 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
declare(strict_types = 1);
declare(strict_types=1);
namespace AtolOnline\Entities;
use AtolOnline\Exceptions\{
InvalidInnLengthException,
InvalidPhoneException
};
InvalidPhoneException};
use AtolOnline\Traits\{
HasInn,
HasPhones
};
HasPhones};
use Illuminate\Support\Collection;
/**
@@ -28,7 +27,8 @@ use Illuminate\Support\Collection;
*/
final class MoneyTransferOperator extends Entity
{
use HasInn, HasPhones;
use HasInn;
use HasPhones;
/**
* @var string|null Наименование (1026)
@@ -64,7 +64,7 @@ final class MoneyTransferOperator extends Entity
?string $name = null,
?string $inn = null,
?string $address = null,
array|Collection|null $phones = null,
array | Collection | null $phones = null,
) {
$this->setName($name);
$this->setInn($inn);

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -7,11 +8,11 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
declare(strict_types = 1);
declare(strict_types=1);
namespace AtolOnline\Entities;
use AtolOnline\Constants\Constraints;
use AtolOnline\Constraints;
use AtolOnline\Exceptions\{
InvalidPhoneException,
TooLongPayingAgentOperationException};
@@ -42,7 +43,7 @@ final class PayingAgent extends Entity
*/
public function __construct(
?string $operation = null,
array|Collection|null $phones = null,
array | Collection | null $phones = null,
) {
!is_null($operation) && $this->setOperation($operation);
$this->setPhones($phones);

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -7,23 +8,19 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
declare(strict_types = 1);
declare(strict_types=1);
namespace AtolOnline\Entities;
use AtolOnline\{
Constants\Constraints,
Enums\PaymentTypes,
};
Constraints,
Enums\PaymentType,};
use AtolOnline\Exceptions\{
InvalidEnumValueException,
NegativePaymentSumException,
TooHighPaymentSumException,
};
TooHighPaymentSumException,};
use JetBrains\PhpStorm\{
ArrayShape,
Pure
};
Pure};
/**
* Класс, описывающий оплату
@@ -32,36 +29,27 @@ use JetBrains\PhpStorm\{
*/
final class Payment extends Entity
{
/**
* @var int Тип оплаты
*/
protected int $type;
/**
* @var float Сумма оплаты (1031, 1081, 1215, 1216, 1217)
*/
protected float $sum;
/**
* Конструктор
*
* @param int $type Тип оплаты
* @param float $sum Сумма оплаты
* @param PaymentType $type Тип оплаты
* @param float $sum Сумма оплаты (1031, 1081, 1215, 1216, 1217)
* @throws NegativePaymentSumException
* @throws TooHighPaymentSumException
* @throws InvalidEnumValueException
*/
public function __construct(int $type, float $sum)
{
public function __construct(
protected PaymentType $type,
protected float $sum,
) {
$this->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;
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -7,7 +8,7 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
declare(strict_types = 1);
declare(strict_types=1);
namespace AtolOnline\Entities;
@@ -16,7 +17,7 @@ use AtolOnline\Api\Fiscalizer;
use AtolOnline\Collections\Items;
use AtolOnline\Collections\Payments;
use AtolOnline\Collections\Vats;
use AtolOnline\Constants\Constraints;
use AtolOnline\Constraints;
use AtolOnline\Exceptions\AuthFailedException;
use AtolOnline\Exceptions\EmptyItemsException;
use AtolOnline\Exceptions\EmptyLoginException;
@@ -227,7 +228,7 @@ final class Receipt extends Entity
$items->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;
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -7,7 +8,7 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
declare(strict_types = 1);
declare(strict_types=1);
namespace AtolOnline\Entities;
@@ -30,7 +31,7 @@ final 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);
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -7,18 +8,16 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
declare(strict_types = 1);
declare(strict_types=1);
namespace AtolOnline\Entities;
use AtolOnline\Exceptions\{
InvalidInnLengthException,
InvalidPhoneException
};
InvalidPhoneException};
use AtolOnline\Traits\{
HasInn,
HasPhones
};
HasPhones};
use Illuminate\Support\Collection;
/**
@@ -28,7 +27,8 @@ use Illuminate\Support\Collection;
*/
final class Supplier extends Entity
{
use HasPhones, HasInn;
use HasPhones;
use HasInn;
/**
* @var string|null Наименование (1225)
@@ -47,7 +47,7 @@ final class Supplier extends Entity
public function __construct(
?string $name = null,
?string $inn = null,
array|Collection|null $phones = null,
array | Collection | null $phones = null,
) {
!is_null($name) && $this->setName($name);
!is_null($inn) && $this->setInn($inn);

View File

@@ -1,4 +1,5 @@
<?php
/*
* Copyright (c) 2020-2021 Антон Аксенов (Anthony Axenov)
*
@@ -7,12 +8,11 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
declare(strict_types = 1);
declare(strict_types=1);
namespace AtolOnline\Entities;
use AtolOnline\Enums\VatTypes;
use AtolOnline\Exceptions\InvalidEnumValueException;
use AtolOnline\Enums\VatType;
use AtolOnline\Helpers;
use JetBrains\PhpStorm\{
ArrayShape,
@@ -25,49 +25,38 @@ use JetBrains\PhpStorm\{
*/
final class Vat extends Entity
{
/**
* @var string Тип ставки НДС (1199, 1105, 1104, 1103, 1102, 1107, 1106)
*/
private string $type;
/**
* @var float Сумма в рублях, от которой пересчитывается размер НДС
*/
private float $sum;
/**
* Конструктор
*
* @param string $type Тип ставки НДС (1199, 1105, 1104, 1103, 1102, 1107, 1106)
* @param float $rubles Исходная сумма в рублях, от которой нужно расчитать размер НДС
* @throws InvalidEnumValueException
* @param VatType $type Тип ставки НДС (1199, 1105, 1104, 1103, 1102, 1107, 1106)
* @param float $sum Исходная сумма в рублях, от которой нужно расчитать размер НДС
*/
public function __construct(string $type, float $rubles)
{
$this->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,
}
);