From 42d194116f0470c8d11b5c0282ea3af2d67126e9 Mon Sep 17 00:00:00 2001 From: AnthonyAxenov Date: Wed, 24 Nov 2021 01:30:54 +0800 Subject: [PATCH] =?UTF-8?q?=D0=A2=D1=83=D1=87=D0=B0=20=D0=B4=D0=BE=D1=80?= =?UTF-8?q?=D0=B0=D0=B1=D0=BE=D1=82=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - класс `PayingAgent`, покрытый тестами - новые константы для тегов ФФД 1.05 `Ffd105Tags` - `Entity::jsonSerialize()` object -> array (again) - `TooManyException::$max` int -> float - тесты по psr-4, потому что почему бы и нет - некоторые провайдеры вынесены в `BasicTestCase` - улучшен тест покупателя --- composer.json | 6 +- docs/monitoring.md | 2 +- src/Constants/Constraints.php | 30 +++- src/Constants/Ffd105Tags.php | 86 +++++++++++ src/Entities/Client.php | 19 +-- src/Entities/Company.php | 6 +- src/Entities/CorrectionInfo.php | 12 +- src/Entities/Kkt.php | 4 +- src/Entities/PayingAgent.php | 123 +++++++++++++++ src/Exceptions/EmptyEmailException.php | 8 +- src/Exceptions/InvalidEmailException.php | 8 +- src/Exceptions/InvalidInnLengthException.php | 9 +- .../InvalidPaymentAddressException.php | 5 +- src/Exceptions/InvalidPhoneException.php | 35 +++++ src/Exceptions/TooHighPriceException.php | 19 +-- .../TooLongCallbackUrlException.php | 2 +- src/Exceptions/TooLongCashierException.php | 5 +- .../TooLongClientContactException.php | 5 +- src/Exceptions/TooLongClientNameException.php | 5 +- src/Exceptions/TooLongEmailException.php | 8 +- src/Exceptions/TooLongException.php | 4 +- src/Exceptions/TooLongItemNameException.php | 9 +- src/Exceptions/TooLongLoginException.php | 2 +- src/Exceptions/TooLongPasswordException.php | 2 +- .../TooLongPayingAgentOperationException.php | 9 +- .../TooLongPaymentAddressException.php | 5 +- src/Exceptions/TooLongUnitException.php | 5 +- src/Exceptions/TooLongUserdataException.php | 5 +- src/Exceptions/TooManyException.php | 4 +- src/Exceptions/TooManyItemsException.php | 2 +- src/Exceptions/TooManyPaymentsException.php | 2 +- src/Exceptions/TooManyVatsException.php | 2 +- src/Helpers.php | 4 +- .../Tests/Api}/KktMonitorTest.php | 3 +- .../{ => AtolOnline/Tests}/BasicTestCase.php | 62 +++++++- .../Tests/Entities}/ClientTest.php | 137 +++++------------ .../Tests/Entities}/CompanyTest.php | 8 +- .../Tests/Entities}/KktEntityTest.php | 3 +- .../Tests/Entities/PayingAgentTest.php | 145 ++++++++++++++++++ tests/{ => AtolOnline/Tests}/HelpersTest.php | 4 +- 40 files changed, 622 insertions(+), 192 deletions(-) create mode 100644 src/Constants/Ffd105Tags.php create mode 100644 src/Entities/PayingAgent.php create mode 100644 src/Exceptions/InvalidPhoneException.php rename tests/{ => AtolOnline/Tests/Api}/KktMonitorTest.php (99%) rename tests/{ => AtolOnline/Tests}/BasicTestCase.php (77%) rename tests/{ => AtolOnline/Tests/Entities}/ClientTest.php (67%) rename tests/{ => AtolOnline/Tests/Entities}/CompanyTest.php (98%) rename tests/{ => AtolOnline/Tests/Entities}/KktEntityTest.php (98%) create mode 100644 tests/AtolOnline/Tests/Entities/PayingAgentTest.php rename tests/{ => AtolOnline/Tests}/HelpersTest.php (99%) diff --git a/composer.json b/composer.json index be3ec00..12a1f8e 100644 --- a/composer.json +++ b/composer.json @@ -57,9 +57,9 @@ } }, "autoload-dev": { - "psr-4": { - "AtolOnlineTests\\": "tests/" - } + "classmap": [ + "tests/" + ] }, "scripts": { "test": "vendor/bin/phpunit --colors=always", diff --git a/docs/monitoring.md b/docs/monitoring.md index 6fafe5f..c3dcf2f 100644 --- a/docs/monitoring.md +++ b/docs/monitoring.md @@ -113,4 +113,4 @@ $kkt = $monitor->getOne($kkts->first()->serialNumber); --- -[Вернуться к содержанию](readme.md) \ No newline at end of file +[Вернуться к содержанию](readme.md) diff --git a/src/Constants/Constraints.php b/src/Constants/Constraints.php index 44ad74a..2c17544 100644 --- a/src/Constants/Constraints.php +++ b/src/Constants/Constraints.php @@ -25,17 +25,17 @@ final class Constraints * Максимальная длина email */ const MAX_LENGTH_EMAIL = 64; - + /** * Максимальная длина логина ККТ */ const MAX_LENGTH_LOGIN = 100; - + /** * Максимальная длина пароля ККТ */ const MAX_LENGTH_PASSWORD = 100; - + /** * Максимальная длина адреса места расчётов */ @@ -116,17 +116,31 @@ final class Constraints /** * Максимальная длина имени кассира (1021) + * * @see https://online.atol.ru/files/API_atol_online_v4.pdf Документация, стр 32 */ const MAX_LENGTH_CASHIER_NAME = 64; - + /** * Регулярное выражание для валидации строки ИНН + * + * @see https://online.atol.ru/possystem/v4/schema/sell Схема "#/receipt/client/inn" */ - const PATTERN_INN = "/(^[0-9]{10}$)|(^[0-9]{12}$)/"; - + const PATTERN_INN = /* @lang PhpRegExp */ + '/(^[\d]{10}$)|(^[\d]{12}$)/'; + + /** + * Регулярное выражение для валидации номера телефона + * + * @see https://online.atol.ru/possystem/v4/schema/sell Схема "#/definitions/phone_number" + */ + const PATTERN_PHONE = /* @lang PhpRegExp */ + '/^([^\s\\\]{0,17}|\+[^\s\\\]{1,18})$/'; + /** * Регулярное выражание для валидации строки Callback URL */ - const PATTERN_CALLBACK_URL = "/^http(s?)\:\/\/[0-9a-zA-Zа-яА-Я]([-.\w]*[0-9a-zA-Zа-яА-Я])*(:(0-9)*)*(\/?)([a-zAZ0-9а-яА-Я\-\.\?\,\'\/\\\+&=%\$#_]*)?$/"; -} \ No newline at end of file + const PATTERN_CALLBACK_URL = /* @lang PhpRegExp */ + '/^http(s?)\:\/\/[0-9a-zA-Zа-яА-Я]' . + '([-.\w]*[0-9a-zA-Zа-яА-Я])*(:(0-9)*)*(\/?)([a-zAZ0-9а-яА-Я\-\.\?\,\'\/\\\+&=%\$#_]*)?$/'; +} diff --git a/src/Constants/Ffd105Tags.php b/src/Constants/Ffd105Tags.php new file mode 100644 index 0000000..f2b4003 --- /dev/null +++ b/src/Constants/Ffd105Tags.php @@ -0,0 +1,86 @@ +getName() && $json['name'] = $this->getName(); $this->getEmail() && $json['email'] = $this->getEmail(); $this->getPhone() && $json['phone'] = $this->getPhone(); $this->getInn() && $json['inn'] = $this->getInn(); - return (object)$json; + return $json; } } diff --git a/src/Entities/Company.php b/src/Entities/Company.php index df3f8f2..c0259a4 100644 --- a/src/Entities/Company.php +++ b/src/Entities/Company.php @@ -205,9 +205,9 @@ class Company extends Entity * @throws InvalidInnLengthException * @throws InvalidPaymentAddressException */ - public function jsonSerialize(): object + public function jsonSerialize(): array { - return (object)[ + return [ 'email' => $this->email ? $this->getEmail() : throw new InvalidEmailException(), @@ -222,4 +222,4 @@ class Company extends Entity : throw new InvalidPaymentAddressException(), ]; } -} \ No newline at end of file +} diff --git a/src/Entities/CorrectionInfo.php b/src/Entities/CorrectionInfo.php index 07f4122..6a06f82 100644 --- a/src/Entities/CorrectionInfo.php +++ b/src/Entities/CorrectionInfo.php @@ -123,12 +123,12 @@ class CorrectionInfo extends Entity /** * @inheritDoc */ - public function jsonSerialize(): object + public function jsonSerialize(): array { - return (object)[ - 'type' => $this->getType() ?? '', // обязателен - 'base_date' => $this->getDate() ?? '', // обязателен - 'base_number' => $this->getNumber() ?? '', // обязателен + return [ + 'type' => $this->getType() ?? '', + 'base_date' => $this->getDate() ?? '', + 'base_number' => $this->getNumber() ?? '', ]; } -} \ No newline at end of file +} diff --git a/src/Entities/Kkt.php b/src/Entities/Kkt.php index 3178188..fab9335 100644 --- a/src/Entities/Kkt.php +++ b/src/Entities/Kkt.php @@ -129,8 +129,8 @@ final class Kkt extends Entity /** * @inheritDoc */ - public function jsonSerialize() + public function jsonSerialize(): array { - return $this->data; + return (array)$this->data; } } diff --git a/src/Entities/PayingAgent.php b/src/Entities/PayingAgent.php new file mode 100644 index 0000000..606cfb3 --- /dev/null +++ b/src/Entities/PayingAgent.php @@ -0,0 +1,123 @@ +setOperation($operation); + $this->setPhones($phones); + } + + /** + * Устанавливает операцию + * + * @param string|null $operation + * @return $this + * @throws TooLongPayingAgentOperationException + */ + public function setOperation(?string $operation): self + { + if (!is_null($operation)) { + $operation = trim($operation); + if (mb_strlen($operation) > Constraints::MAX_LENGTH_PAYING_AGENT_OPERATION) { + throw new TooLongPayingAgentOperationException($operation); + } + } + $this->operation = empty($operation) ? null : $operation; + return $this; + } + + /** + * Вoзвращает установленную операцию + * + * @return string|null + */ + public function getOperation(): ?string + { + return $this->operation; + } + + /** + * Устанавливает массив номеров телефонов + * + * @param array|Collection|null $phones + * @return $this + * @throws InvalidPhoneException + */ + public function setPhones(array|Collection|null $phones): self + { + if (!is_null($phones)) { + $phones = is_array($phones) ? collect($phones) : $phones; + $phones->each(function ($phone) { + $phone = preg_replace('/[^\d]/', '', trim($phone)); + if (preg_match(Constraints::PATTERN_PHONE, $phone) != 1) { + throw new InvalidPhoneException($phone); + } + }); + } + $this->phones = empty($phones) ? collect() : $phones; + return $this; + } + + /** + * Возвращает установленные + * + * @return Collection + */ + public function getPhones(): Collection + { + return $this->phones; + } + + /** + * @inheritDoc + */ + public function jsonSerialize(): array + { + $json = []; + $this->getOperation() && $json['operation'] = $this->getOperation(); + !$this->getPhones()->isEmpty() && $json['phones'] = $this->getPhones()->toArray(); + return $json; + } +} diff --git a/src/Exceptions/EmptyEmailException.php b/src/Exceptions/EmptyEmailException.php index bb4200b..1993027 100644 --- a/src/Exceptions/EmptyEmailException.php +++ b/src/Exceptions/EmptyEmailException.php @@ -11,12 +11,18 @@ declare(strict_types = 1); namespace AtolOnline\Exceptions; +use AtolOnline\Constants\Ffd105Tags; + /** * Исключение, возникающее при попытке указать пустой email + * * @see https://online.atol.ru/files/API_atol_online_v4.pdf Документация, стр 17 */ class EmptyEmailException extends AtolException { protected $message = 'Email не может быть пустым'; - protected array $ffd_tags = [1008, 1117]; + protected array $ffd_tags = [ + Ffd105Tags::CLIENT_CONTACT, + Ffd105Tags::COMPANY_EMAIL, + ]; } diff --git a/src/Exceptions/InvalidEmailException.php b/src/Exceptions/InvalidEmailException.php index 148df7e..9b07ca9 100644 --- a/src/Exceptions/InvalidEmailException.php +++ b/src/Exceptions/InvalidEmailException.php @@ -11,13 +11,19 @@ declare(strict_types = 1); namespace AtolOnline\Exceptions; +use AtolOnline\Constants\Ffd105Tags; + /** * Исключение, возникающее при ошибке валидации email + * * @see https://online.atol.ru/files/API_atol_online_v4.pdf Документация, стр 17 */ class InvalidEmailException extends AtolException { - protected array $ffd_tags = [1008, 1117]; + protected array $ffd_tags = [ + Ffd105Tags::CLIENT_CONTACT, + Ffd105Tags::COMPANY_EMAIL, + ]; /** * Конструктор diff --git a/src/Exceptions/InvalidInnLengthException.php b/src/Exceptions/InvalidInnLengthException.php index a385add..e304125 100644 --- a/src/Exceptions/InvalidInnLengthException.php +++ b/src/Exceptions/InvalidInnLengthException.php @@ -11,12 +11,19 @@ declare(strict_types = 1); namespace AtolOnline\Exceptions; +use AtolOnline\Constants\Ffd105Tags; + /** * Исключение, возникающее при попытке указать ИНН некорректной длины */ class InvalidInnLengthException extends AtolException { - protected array $ffd_tags = [1016, 1018, 1226, 1228]; + protected array $ffd_tags = [ + Ffd105Tags::MTO_INN, + Ffd105Tags::COMPANY_INN, + Ffd105Tags::SUPPLIER_INN, + Ffd105Tags::CLIENT_INN, + ]; /** * Конструктор diff --git a/src/Exceptions/InvalidPaymentAddressException.php b/src/Exceptions/InvalidPaymentAddressException.php index e390da3..59a0bef 100644 --- a/src/Exceptions/InvalidPaymentAddressException.php +++ b/src/Exceptions/InvalidPaymentAddressException.php @@ -11,13 +11,16 @@ declare(strict_types = 1); namespace AtolOnline\Exceptions; +use AtolOnline\Constants\Ffd105Tags; + /** * Исключение, возникающее при попытке указать некорректный адрес места расчётов + * * @see https://online.atol.ru/files/API_atol_online_v4.pdf Документация, стр 35 */ class InvalidPaymentAddressException extends AtolException { - protected array $ffd_tags = [1187]; + protected array $ffd_tags = [Ffd105Tags::COMPANY_PADDRESS]; /** * Конструктор diff --git a/src/Exceptions/InvalidPhoneException.php b/src/Exceptions/InvalidPhoneException.php new file mode 100644 index 0000000..3e0ac61 --- /dev/null +++ b/src/Exceptions/InvalidPhoneException.php @@ -0,0 +1,35 @@ +assertIsObject($entity); - $this->assertIsObject($entity->jsonSerialize()); + $this->assertIsArray($entity->jsonSerialize()); $this->assertIsString((string)$entity); $this->assertJson((string)$entity); if ($json_structure) { @@ -138,6 +137,23 @@ class BasicTestCase extends TestCase $this->assertIsSameClass($expected, Collection::class); } + //------------------------------------------------------------------------------------------------------------------ + + /** + * Провайдер строк, которые приводятся к null + * + * @return array> + */ + public function providerNullableStrings(): array + { + return [ + [''], + [' '], + [null], + ["\n\r\t"], + ]; + } + /** * Провайдер валидных телефонов * @@ -155,6 +171,22 @@ class BasicTestCase extends TestCase ]; } + /** + * Провайдер телефонов, которые приводятся к null + * + * @return array> + */ + public function providerNullablePhones(): array + { + return array_merge( + $this->providerNullableStrings(), + [ + [Helpers::randomStr(10, false)], + ["asdfgvs \n\rtt\t*/(*&%^*$%"], + ] + ); + } + /** * Провайдер валидных email-ов * @@ -170,4 +202,24 @@ class BasicTestCase extends TestCase ['abc.def@mail-archive.com'], ]; } -} \ No newline at end of file + + /** + * Провайдер невалидных email-ов + * + * @return array> + */ + public function providerInvalidEmails(): array + { + return [ + ['@example'], + [Helpers::randomStr(15)], + ['@example.com'], + ['abc.def@mail'], + ['.abc@mail.com'], + ['example@example'], + ['abc..def@mail.com'], + ['abc.def@mail..com'], + ['abc.def@mail#archive.com'], + ]; + } +} diff --git a/tests/ClientTest.php b/tests/AtolOnline/Tests/Entities/ClientTest.php similarity index 67% rename from tests/ClientTest.php rename to tests/AtolOnline/Tests/Entities/ClientTest.php index 0442646..52f05c9 100644 --- a/tests/ClientTest.php +++ b/tests/AtolOnline/Tests/Entities/ClientTest.php @@ -7,7 +7,7 @@ * https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE */ -namespace AtolOnlineTests; +namespace AtolOnline\Tests\Entities; use AtolOnline\{ Entities\Client, @@ -16,91 +16,28 @@ use AtolOnline\{ Exceptions\TooLongClientContactException, Exceptions\TooLongClientNameException, Exceptions\TooLongEmailException, - Exceptions\TooLongItemNameException, - Helpers}; + Helpers, + Tests\BasicTestCase +}; /** - * Набор тестов для проверки работы класс покупателя + * Набор тестов для проверки работы класса покупателя */ class ClientTest extends BasicTestCase { /** - * Провайдер строк, которые приводятся к null - * - * @return array> - */ - public function providerNullableStrings(): array - { - return [ - [''], - [' '], - [null], - ["\n\r\t"], - ]; - } - - /** - * Провайдер телефонов, которые приводятся к null - * - * @return array> - */ - public function providerNullablePhones(): array - { - return array_merge( - $this->providerNullableStrings(), - [ - [Helpers::randomStr(10, false)], - ["asdfgvs \n\rtt\t*/(*&%^*$%"], - ] - ); - } - - /** - * Провайдер невалидных email-ов - * - * @return array> - */ - public function providerInvalidEmails(): array - { - return [ - ['@example'], - [Helpers::randomStr(15)], - ['@example.com'], - ['abc.def@mail'], - ['.abc@mail.com'], - ['example@example'], - ['abc..def@mail.com'], - ['abc.def@mail..com'], - ['abc.def@mail#archive.com'], - ]; - } - - //------------------------------------------------------------------------------------------------------------------ - - /** - * Тестирует приведение покупателя к json - * - * @covers \AtolOnline\Entities\Client - * @covers \AtolOnline\Entities\Client::jsonSerialize - */ - public function testAtolable(): void - { - $this->assertAtolable(new Client()); - } - - /** - * Тестирует конструктор покупателя без передачи значений + * Тестирует конструктор без передачи значений и приведение к json * * @covers \AtolOnline\Entities\Client * @covers \AtolOnline\Entities\Client::jsonSerialize */ public function testConstructorWithoutArgs(): void { - $this->assertEquals('{}', (string)(new Client())); + $this->assertEquals('[]', (string)(new Client())); } /** - * Тестирует конструктор с передачей значений (внутри работают сеттеры) + * Тестирует конструктор с передачей значений и приведение к json * * @covers \AtolOnline\Entities\Client * @covers \AtolOnline\Entities\Client::jsonSerialize @@ -108,16 +45,23 @@ class ClientTest extends BasicTestCase * @covers \AtolOnline\Entities\Client::setPhone * @covers \AtolOnline\Entities\Client::setEmail * @covers \AtolOnline\Entities\Client::setInn + * @covers \AtolOnline\Entities\Client::getName + * @covers \AtolOnline\Entities\Client::getPhone + * @covers \AtolOnline\Entities\Client::getEmail + * @covers \AtolOnline\Entities\Client::getInn */ public function testConstructorWithArgs(): void { - $customer = new Client( + $this->assertAtolable(new Client('John Doe'), ['name' => 'John Doe']); + $this->assertAtolable(new Client(email: 'john@example.com'), ['email' => 'john@example.com']); + $this->assertAtolable(new Client(phone: '+1/22/99*73s dsdas654 5s6'), ['phone' => '+122997365456']); + $this->assertAtolable(new Client(inn: '+fasd3\qe3fs_=nac99013928czc'), ['inn' => '3399013928']); + $this->assertAtolable(new Client( 'John Doe', 'john@example.com', '+1/22/99*73s dsdas654 5s6', // +122997365456 '+fasd3\qe3fs_=nac99013928czc' // 3399013928 - ); - $this->assertAtolable($customer, [ + ), [ 'name' => 'John Doe', 'email' => 'john@example.com', 'phone' => '+122997365456', @@ -125,10 +69,8 @@ class ClientTest extends BasicTestCase ]); } - //------------------------------------------------------------------------------------------------------------------ - /** - * Тестирует установку имён покупателя, которые приводятся к null + * Тестирует установку имён, которые приводятся к null * * @param mixed $name * @dataProvider providerNullableStrings @@ -139,27 +81,25 @@ class ClientTest extends BasicTestCase */ public function testNullableNames(mixed $name): void { - $customer = (new Client())->setName($name); - $this->assertNull($customer->getName()); + $this->assertNull((new Client())->setName($name)->getName()); } /** - * Тестирует установку валидного имени покупателя + * Тестирует установку валидного имени * * @covers \AtolOnline\Entities\Client * @covers \AtolOnline\Entities\Client::setName * @covers \AtolOnline\Entities\Client::getName - * @throws TooLongItemNameException + * @throws TooLongClientNameException */ public function testValidName(): void { $name = Helpers::randomStr(); - $customer = (new Client())->setName($name); - $this->assertEquals($name, $customer->getName()); + $this->assertEquals($name, (new Client())->setName($name)->getName()); } /** - * Тестирует установку невалидного имени покупателя + * Тестирует установку невалидного имени * * @covers \AtolOnline\Entities\Client * @covers \AtolOnline\Entities\Client::setName @@ -174,7 +114,7 @@ class ClientTest extends BasicTestCase //------------------------------------------------------------------------------------------------------------------ /** - * Тестирует установку телефонов покупателя, которые приводятся к null + * Тестирует установку телефонов, которые приводятся к null * * @param mixed $phone * @dataProvider providerNullablePhones @@ -185,13 +125,13 @@ class ClientTest extends BasicTestCase */ public function testNullablePhones(mixed $phone): void { - $customer = (new Client())->setPhone($phone); - $this->assertNull($customer->getPhone()); + $this->assertNull((new Client())->setPhone($phone)->getPhone()); } /** - * Тестирует установку валидного телефона покупателя + * Тестирует установку валидного телефона * + * @todo актуализировать при доработатанной валидации * @dataProvider providerValidPhones * @covers \AtolOnline\Entities\Client * @covers \AtolOnline\Entities\Client::setPhone @@ -200,13 +140,13 @@ class ClientTest extends BasicTestCase */ public function testValidPhone(string $input, string $output): void { - $customer = (new Client())->setPhone($input); - $this->assertEquals($output, $customer->getPhone()); + $this->assertEquals($output, (new Client())->setPhone($input)->getPhone()); } /** - * Тестирует установку невалидного телефона покупателя + * Тестирует установку невалидного телефона * + * @todo актуализировать при доработатанной валидации * @covers \AtolOnline\Entities\Client * @covers \AtolOnline\Entities\Client::setPhone * @covers \AtolOnline\Exceptions\TooLongClientContactException @@ -221,7 +161,7 @@ class ClientTest extends BasicTestCase //------------------------------------------------------------------------------------------------------------------ /** - * Тестирует установку валидных email-ов покупателя + * Тестирует установку валидных email-ов * * @param mixed $email * @dataProvider providerValidEmails @@ -233,12 +173,11 @@ class ClientTest extends BasicTestCase */ public function testValidEmails(mixed $email): void { - $customer = (new Client())->setEmail($email); - $this->assertEquals($email, $customer->getEmail()); + $this->assertEquals($email, (new Client())->setEmail($email)->getEmail()); } /** - * Тестирует установку слишком длинного email покупателя + * Тестирует установку слишком длинного email * * @covers \AtolOnline\Entities\Client * @covers \AtolOnline\Entities\Client::setEmail @@ -253,7 +192,7 @@ class ClientTest extends BasicTestCase } /** - * Тестирует установку невалидного email покупателя + * Тестирует установку невалидного email * * @param mixed $email * @dataProvider providerInvalidEmails @@ -281,10 +220,8 @@ class ClientTest extends BasicTestCase */ public function testValidInn(): void { - $customer = (new Client())->setInn('1234567890'); - $this->assertEquals('1234567890', $customer->getInn()); - $customer = $customer->setInn('123456789012'); - $this->assertEquals('123456789012', $customer->getInn()); + $this->assertEquals('1234567890', (new Client())->setInn('1234567890')->getInn()); + $this->assertEquals('123456789012', (new Client())->setInn('123456789012')->getInn()); } /** diff --git a/tests/CompanyTest.php b/tests/AtolOnline/Tests/Entities/CompanyTest.php similarity index 98% rename from tests/CompanyTest.php rename to tests/AtolOnline/Tests/Entities/CompanyTest.php index 93fa09c..b392678 100644 --- a/tests/CompanyTest.php +++ b/tests/AtolOnline/Tests/Entities/CompanyTest.php @@ -7,7 +7,7 @@ * https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE */ -namespace AtolOnlineTests; +namespace AtolOnline\Tests\Entities; use AtolOnline\{ Entities\Company, @@ -18,7 +18,9 @@ use AtolOnline\{ Exceptions\InvalidPaymentAddressException, Exceptions\TooLongEmailException, Exceptions\TooLongPaymentAddressException, - Helpers}; + Helpers, + Tests\BasicTestCase +}; /** * Набор тестов для проверки работы класс продавца @@ -131,4 +133,4 @@ class CompanyTest extends BasicTestCase $this->expectException(InvalidPaymentAddressException::class); new Company('company@example.com', SnoTypes::OSN, '1234567890', ''); } -} \ No newline at end of file +} diff --git a/tests/KktEntityTest.php b/tests/AtolOnline/Tests/Entities/KktEntityTest.php similarity index 98% rename from tests/KktEntityTest.php rename to tests/AtolOnline/Tests/Entities/KktEntityTest.php index 6f2cfd7..6e6cbba 100644 --- a/tests/KktEntityTest.php +++ b/tests/AtolOnline/Tests/Entities/KktEntityTest.php @@ -9,11 +9,12 @@ declare(strict_types = 1); -namespace AtolOnlineTests; +namespace AtolOnline\Tests\Entities; use AtolOnline\Entities\Kkt; use AtolOnline\Exceptions\EmptyMonitorDataException; use AtolOnline\Exceptions\NotEnoughMonitorDataException; +use AtolOnline\Tests\BasicTestCase; use DateTime; use Exception; diff --git a/tests/AtolOnline/Tests/Entities/PayingAgentTest.php b/tests/AtolOnline/Tests/Entities/PayingAgentTest.php new file mode 100644 index 0000000..afadb13 --- /dev/null +++ b/tests/AtolOnline/Tests/Entities/PayingAgentTest.php @@ -0,0 +1,145 @@ +assertEquals('[]', (string)(new PayingAgent())); + } + + /** + * Тестирует конструктор с передачей значений и корректное приведение к json + * + * @covers \AtolOnline\Entities\PayingAgent + * @covers \AtolOnline\Entities\PayingAgent::jsonSerialize + * @covers \AtolOnline\Entities\PayingAgent::setOperation + * @covers \AtolOnline\Entities\PayingAgent::setPhones + * @covers \AtolOnline\Entities\PayingAgent::getOperation + * @covers \AtolOnline\Entities\PayingAgent::getPhones + * @throws InvalidPhoneException + * @throws TooLongPayingAgentOperationException + */ + public function testConstructorWithArgs(): void + { + $operation = Helpers::randomStr(); + $this->assertAtolable(new PayingAgent( + $operation, + ['+122997365456'], + ), [ + 'operation' => $operation, + 'phones' => ['+122997365456'], + ]); + $this->assertAtolable( + new PayingAgent($operation), + ['operation' => $operation] + ); + $this->assertAtolable( + new PayingAgent(phones: ['+122997365456']), + ['phones' => ['+122997365456']] + ); + } + + /** + * Тестирует установку операций, которые приводятся к null + * + * @param mixed $name + * @dataProvider providerNullableStrings + * @covers \AtolOnline\Entities\PayingAgent + * @covers \AtolOnline\Entities\PayingAgent::setOperation + * @covers \AtolOnline\Entities\PayingAgent::getOperation + * @throws TooLongPayingAgentOperationException + */ + public function testNullableOperations(mixed $name): void + { + $this->assertNull((new PayingAgent())->setOperation($name)->getOperation()); + } + + /** + * Тестирует установку невалидного имени покупателя + * + * @covers \AtolOnline\Entities\PayingAgent + * @covers \AtolOnline\Entities\PayingAgent::setOperation + * @covers \AtolOnline\Exceptions\TooLongPayingAgentOperationException + */ + public function testTooLongPayingAgentOperationException(): void + { + $this->expectException(TooLongPayingAgentOperationException::class); + (new PayingAgent())->setOperation(Helpers::randomStr(25)); + } + + /** + * Провайдер массивов телефонов, которые приводятся к null + * + * @return array> + */ + public function providerNullablePhonesArrays(): array + { + return [ + [[]], + [null], + [collect()], + ]; + } + + /** + * Тестирует установку пустых телефонов + * + * @dataProvider providerNullablePhonesArrays + * @covers \AtolOnline\Entities\PayingAgent + * @covers \AtolOnline\Entities\PayingAgent::setPhones + * @covers \AtolOnline\Entities\PayingAgent::getPhones + * @throws InvalidPhoneException + * @throws TooLongPayingAgentOperationException + */ + public function testNullablePhones(mixed $phones): void + { + $agent = new PayingAgent(phones: $phones); + $this->assertIsCollection($agent->getPhones()); + $this->assertTrue($agent->getPhones()->isEmpty()); + } + + /** + * Тестирует установку невалидных телефонов + * + * @covers \AtolOnline\Entities\PayingAgent + * @covers \AtolOnline\Entities\PayingAgent::setPhones + * @covers \AtolOnline\Exceptions\InvalidPhoneException + * @throws InvalidPhoneException + */ + public function testInvalidPhoneException(): void + { + $this->expectException(InvalidPhoneException::class); + (new PayingAgent())->setPhones([ + '12345678901234567', // good + '+123456789012345678', // good + '12345678901234567890', // bad + '+12345678901234567890', // bad + ]); + } +} diff --git a/tests/HelpersTest.php b/tests/AtolOnline/Tests/HelpersTest.php similarity index 99% rename from tests/HelpersTest.php rename to tests/AtolOnline/Tests/HelpersTest.php index 7715516..70f0140 100644 --- a/tests/HelpersTest.php +++ b/tests/AtolOnline/Tests/HelpersTest.php @@ -7,7 +7,7 @@ * https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE */ -namespace AtolOnlineTests; +namespace AtolOnline\Tests; use AtolOnline\Helpers; @@ -120,4 +120,4 @@ class HelpersTest extends BasicTestCase $this->assertEquals($output, strlen($result)); // тестировать на наличие цифр быссмысленно } -} \ No newline at end of file +}