33 Commits

Author SHA1 Message Date
ca32fe5923 Повсюду улучшена проверка длин строк 2020-05-28 22:56:26 +08:00
9ea1c81666 Скорректирован Document::jsonSerialize() - не выдаёт пустого кассира 2020-05-28 22:55:53 +08:00
12b98dcdac Document::fromRaw() теперь парсит входящий json как массив, а не объект 2020-05-28 22:55:27 +08:00
1fec446ce0 Фикс тестов НДС 2020-05-28 01:31:37 +08:00
6256c14522 Обновления в composer.lock 2020-05-28 01:25:27 +08:00
7dff642f0a Бейджик в readme + фикс composer.json 2020-05-28 01:14:53 +08:00
670f440620 Github actions только на мастере 2020-05-28 01:13:08 +08:00
3385420005 Merge branch 'dev'. Мнда, я забыл слить изменения... 2020-05-28 00:56:31 +08:00
ff42eebb8c [RELEASE] v0.2.1-b 2020-05-28 00:53:18 +08:00
9121d44a26 Merge branch 'master' into dev 2020-05-28 00:43:28 +08:00
600a505c83 Генерация объекта документа по сырой json-строке 2020-05-28 00:41:58 +08:00
4fccf7809d Небольшие правки по Item (улучшена проверка длины ед. изм.) 2020-05-28 00:41:01 +08:00
2d29ff3994 Фикс исключения некорректного UUID в методе Kkt::getDocumentStatus() 2020-05-28 00:39:42 +08:00
954843e3ad Фикс исключения превышения количества ставок НДС в массиве 2020-05-28 00:38:48 +08:00
a619b06a48 Исправлен расчёт НДС для документа 2020-05-28 00:38:16 +08:00
0bb194b1f8 Улучшены исключения
- добавлены теги ФФД для удобства
- тексты исключений переведены на англ. язык во избежание проблем с кодировками
- новые исключения TooMany и TooLong для удобства, подходящие по смыслу исключения унаследованы от них
2020-05-27 23:10:30 +08:00
6263be5f03 [RELEASE] v0.1.1-b 2020-04-17 21:36:15 +08:00
aee25a993b Исправил обратно неисправную проверку количеств в массивах, удалил лишние исключения. Это была плохая идея. 2020-04-17 21:33:02 +08:00
7aa0d1ebb0 Тест для схем документов 2020-04-17 21:12:33 +08:00
5277db62fd Метод json() для объектов схем 2020-04-17 21:11:21 +08:00
025351a8ae Улучшена валидация количества оплат + новый экспешн
Также мелкофиксы по другим массивам
2020-04-17 20:53:03 +08:00
c9ed0bf467 Переименован AtolEntity -> Entity 2020-04-17 20:10:50 +08:00
7da7d25823 Улучшена валидация количества ставок НДС + новый экспешн 2020-04-17 20:09:09 +08:00
dc20d3e08e В тестовом режиме установка логина и пароля теперь необязательна 2020-04-16 21:47:36 +08:00
b499d998e3 Улучшена и исправлена валидация количества предметов расчёта 2020-04-16 21:46:02 +08:00
8370266185 Игнор файла-песочницы 2020-04-15 21:40:15 +08:00
b0ee2cb802 Мелочи в Kkt.php 2020-04-15 21:39:48 +08:00
db4b777648 Проверка количества предметов расчёта в массиве в соотв. со схемой (не тестировалось) 2020-04-15 21:39:23 +08:00
f161dc59f7 Обновление зависимостей 2020-04-15 21:38:53 +08:00
1061e1d3a7 Новые классы для работы со схемами 2020-04-15 21:38:33 +08:00
9ce4997699 Скорректированы ссылки в документации 2020-01-11 18:08:49 +08:00
32e4bbabab Create FUNDING.yml 2020-01-11 17:51:10 +08:00
03a0e737eb Update README.md
Добавлена версия API
2020-01-11 15:57:39 +08:00
59 changed files with 906 additions and 464 deletions

3
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,3 @@
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
custom: ['https://money.yandex.ru/to/41001685237530']

View File

@@ -1,6 +1,9 @@
name: Composer and phpunit tests name: Build
on: [push] on:
push:
branches:
- master
jobs: jobs:
build: build:

3
.gitignore vendored
View File

@@ -3,4 +3,5 @@
/atol_log /atol_log
*.log *.log
/config.php /config.php
*cache* *cache*
/test.php

View File

@@ -1,7 +1,13 @@
# АТОЛ Онлайн # АТОЛ Онлайн
![Build](https://github.com/anthonyaxenov/atol-online/workflows/Build/badge.svg?branch=master)
Библиотека для фискализации чеков по 54-ФЗ через [облачную ККТ АТОЛ](https://online.atol.ru/). Библиотека для фискализации чеков по 54-ФЗ через [облачную ККТ АТОЛ](https://online.atol.ru/).
Текущая поддерживаемая версия API: **5.1**
**[Документация](/docs/readme.md)**
## Системные требования ## Системные требования
* PHP 7.2+ * PHP 7.2+
@@ -20,7 +26,7 @@
```php ```php
require($project_root.'/vendor/autoload.php'); require($project_root.'/vendor/autoload.php');
``` ```
где $project_root — абсолютный путь к корневой директории вашего проекта. где `$project_root` — абсолютный путь к корневой директории вашего проекта.
### Тестирование кода библиотеки ### Тестирование кода библиотеки

View File

@@ -3,9 +3,14 @@
"description": "Library to use cloud cash register in e-commerce according to Russian Federal Law #54", "description": "Library to use cloud cash register in e-commerce according to Russian Federal Law #54",
"license": "MIT", "license": "MIT",
"type": "library", "type": "library",
"version": "0.1.0-b",
"keywords": [ "keywords": [
"54-fz", "54-fz",
"kkt",
"e-commerce",
"cash",
"cash register",
"payment",
"payment system",
"atol", "atol",
"atol-online" "atol-online"
], ],
@@ -35,6 +40,7 @@
"autoload": { "autoload": {
"classmap": [ "classmap": [
"src/AtolOnline/Api/", "src/AtolOnline/Api/",
"src/AtolOnline/Api/Schemas/",
"src/AtolOnline/Exceptions/", "src/AtolOnline/Exceptions/",
"src/AtolOnline/Entities/", "src/AtolOnline/Entities/",
"src/AtolOnline/Traits/", "src/AtolOnline/Traits/",

335
composer.lock generated
View File

@@ -4,27 +4,28 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "dae801b00d2c80c28d290f676970945b", "content-hash": "20b642fe60192cf1e67c9aa8dca27440",
"packages": [ "packages": [
{ {
"name": "guzzlehttp/guzzle", "name": "guzzlehttp/guzzle",
"version": "6.5.2", "version": "6.5.4",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/guzzle/guzzle.git", "url": "https://github.com/guzzle/guzzle.git",
"reference": "43ece0e75098b7ecd8d13918293029e555a50f82" "reference": "a4a1b6930528a8f7ee03518e6442ec7a44155d9d"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/43ece0e75098b7ecd8d13918293029e555a50f82", "url": "https://api.github.com/repos/guzzle/guzzle/zipball/a4a1b6930528a8f7ee03518e6442ec7a44155d9d",
"reference": "43ece0e75098b7ecd8d13918293029e555a50f82", "reference": "a4a1b6930528a8f7ee03518e6442ec7a44155d9d",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"ext-json": "*", "ext-json": "*",
"guzzlehttp/promises": "^1.0", "guzzlehttp/promises": "^1.0",
"guzzlehttp/psr7": "^1.6.1", "guzzlehttp/psr7": "^1.6.1",
"php": ">=5.5" "php": ">=5.5",
"symfony/polyfill-intl-idn": "1.17.0"
}, },
"require-dev": { "require-dev": {
"ext-curl": "*", "ext-curl": "*",
@@ -32,7 +33,6 @@
"psr/log": "^1.1" "psr/log": "^1.1"
}, },
"suggest": { "suggest": {
"ext-intl": "Required for Internationalized Domain Name (IDN) support",
"psr/log": "Required for using the Log middleware" "psr/log": "Required for using the Log middleware"
}, },
"type": "library", "type": "library",
@@ -71,7 +71,7 @@
"rest", "rest",
"web service" "web service"
], ],
"time": "2019-12-23T11:57:10+00:00" "time": "2020-05-25T19:35:05+00:00"
}, },
{ {
"name": "guzzlehttp/promises", "name": "guzzlehttp/promises",
@@ -292,16 +292,16 @@
}, },
{ {
"name": "psr/log", "name": "psr/log",
"version": "1.1.2", "version": "1.1.3",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/php-fig/log.git", "url": "https://github.com/php-fig/log.git",
"reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801" "reference": "0f73288fd15629204f9d42b7055f72dacbe811fc"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/php-fig/log/zipball/446d54b4cb6bf489fc9d75f55843658e6f25d801", "url": "https://api.github.com/repos/php-fig/log/zipball/0f73288fd15629204f9d42b7055f72dacbe811fc",
"reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801", "reference": "0f73288fd15629204f9d42b7055f72dacbe811fc",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@@ -335,7 +335,7 @@
"psr", "psr",
"psr-3" "psr-3"
], ],
"time": "2019-11-01T11:05:21+00:00" "time": "2020-03-23T09:12:05+00:00"
}, },
{ {
"name": "ralouphie/getallheaders", "name": "ralouphie/getallheaders",
@@ -379,16 +379,16 @@
}, },
{ {
"name": "ramsey/uuid", "name": "ramsey/uuid",
"version": "3.9.2", "version": "3.9.3",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/ramsey/uuid.git", "url": "https://github.com/ramsey/uuid.git",
"reference": "7779489a47d443f845271badbdcedfe4df8e06fb" "reference": "7e1633a6964b48589b142d60542f9ed31bd37a92"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/ramsey/uuid/zipball/7779489a47d443f845271badbdcedfe4df8e06fb", "url": "https://api.github.com/repos/ramsey/uuid/zipball/7e1633a6964b48589b142d60542f9ed31bd37a92",
"reference": "7779489a47d443f845271badbdcedfe4df8e06fb", "reference": "7e1633a6964b48589b142d60542f9ed31bd37a92",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@@ -462,20 +462,20 @@
"identifier", "identifier",
"uuid" "uuid"
], ],
"time": "2019-12-17T08:18:51+00:00" "time": "2020-02-21T04:36:14+00:00"
}, },
{ {
"name": "symfony/polyfill-ctype", "name": "symfony/polyfill-ctype",
"version": "v1.13.1", "version": "v1.17.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/symfony/polyfill-ctype.git", "url": "https://github.com/symfony/polyfill-ctype.git",
"reference": "f8f0b461be3385e56d6de3dbb5a0df24c0c275e3" "reference": "e94c8b1bbe2bc77507a1056cdb06451c75b427f9"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/f8f0b461be3385e56d6de3dbb5a0df24c0c275e3", "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/e94c8b1bbe2bc77507a1056cdb06451c75b427f9",
"reference": "f8f0b461be3385e56d6de3dbb5a0df24c0c275e3", "reference": "e94c8b1bbe2bc77507a1056cdb06451c75b427f9",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@@ -487,7 +487,7 @@
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "1.13-dev" "dev-master": "1.17-dev"
} }
}, },
"autoload": { "autoload": {
@@ -520,7 +520,183 @@
"polyfill", "polyfill",
"portable" "portable"
], ],
"time": "2019-11-27T13:56:44+00:00" "time": "2020-05-12T16:14:59+00:00"
},
{
"name": "symfony/polyfill-intl-idn",
"version": "v1.17.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-intl-idn.git",
"reference": "3bff59ea7047e925be6b7f2059d60af31bb46d6a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-intl-idn/zipball/3bff59ea7047e925be6b7f2059d60af31bb46d6a",
"reference": "3bff59ea7047e925be6b7f2059d60af31bb46d6a",
"shasum": ""
},
"require": {
"php": ">=5.3.3",
"symfony/polyfill-mbstring": "^1.3",
"symfony/polyfill-php72": "^1.10"
},
"suggest": {
"ext-intl": "For best performance"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.17-dev"
}
},
"autoload": {
"psr-4": {
"Symfony\\Polyfill\\Intl\\Idn\\": ""
},
"files": [
"bootstrap.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Laurent Bassin",
"email": "laurent@bassin.info"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"idn",
"intl",
"polyfill",
"portable",
"shim"
],
"time": "2020-05-12T16:47:27+00:00"
},
{
"name": "symfony/polyfill-mbstring",
"version": "v1.17.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-mbstring.git",
"reference": "fa79b11539418b02fc5e1897267673ba2c19419c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/fa79b11539418b02fc5e1897267673ba2c19419c",
"reference": "fa79b11539418b02fc5e1897267673ba2c19419c",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"suggest": {
"ext-mbstring": "For best performance"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.17-dev"
}
},
"autoload": {
"psr-4": {
"Symfony\\Polyfill\\Mbstring\\": ""
},
"files": [
"bootstrap.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill for the Mbstring extension",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"mbstring",
"polyfill",
"portable",
"shim"
],
"time": "2020-05-12T16:47:27+00:00"
},
{
"name": "symfony/polyfill-php72",
"version": "v1.17.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/polyfill-php72.git",
"reference": "f048e612a3905f34931127360bdd2def19a5e582"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/f048e612a3905f34931127360bdd2def19a5e582",
"reference": "f048e612a3905f34931127360bdd2def19a5e582",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.17-dev"
}
},
"autoload": {
"psr-4": {
"Symfony\\Polyfill\\Php72\\": ""
},
"files": [
"bootstrap.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions",
"homepage": "https://symfony.com",
"keywords": [
"compatibility",
"polyfill",
"portable",
"shim"
],
"time": "2020-05-12T16:47:27+00:00"
} }
], ],
"packages-dev": [ "packages-dev": [
@@ -582,16 +758,16 @@
}, },
{ {
"name": "myclabs/deep-copy", "name": "myclabs/deep-copy",
"version": "1.9.4", "version": "1.9.5",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/myclabs/DeepCopy.git", "url": "https://github.com/myclabs/DeepCopy.git",
"reference": "579bb7356d91f9456ccd505f24ca8b667966a0a7" "reference": "b2c28789e80a97badd14145fda39b545d83ca3ef"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/579bb7356d91f9456ccd505f24ca8b667966a0a7", "url": "https://api.github.com/repos/myclabs/DeepCopy/zipball/b2c28789e80a97badd14145fda39b545d83ca3ef",
"reference": "579bb7356d91f9456ccd505f24ca8b667966a0a7", "reference": "b2c28789e80a97badd14145fda39b545d83ca3ef",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@@ -626,7 +802,7 @@
"object", "object",
"object graph" "object graph"
], ],
"time": "2019-12-15T19:12:40+00:00" "time": "2020-01-17T21:11:47+00:00"
}, },
{ {
"name": "phar-io/manifest", "name": "phar-io/manifest",
@@ -732,24 +908,21 @@
}, },
{ {
"name": "phpdocumentor/reflection-common", "name": "phpdocumentor/reflection-common",
"version": "2.0.0", "version": "2.1.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/phpDocumentor/ReflectionCommon.git", "url": "https://github.com/phpDocumentor/ReflectionCommon.git",
"reference": "63a995caa1ca9e5590304cd845c15ad6d482a62a" "reference": "6568f4687e5b41b054365f9ae03fcb1ed5f2069b"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/63a995caa1ca9e5590304cd845c15ad6d482a62a", "url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/6568f4687e5b41b054365f9ae03fcb1ed5f2069b",
"reference": "63a995caa1ca9e5590304cd845c15ad6d482a62a", "reference": "6568f4687e5b41b054365f9ae03fcb1ed5f2069b",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": ">=7.1" "php": ">=7.1"
}, },
"require-dev": {
"phpunit/phpunit": "~6"
},
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
@@ -780,45 +953,42 @@
"reflection", "reflection",
"static analysis" "static analysis"
], ],
"time": "2018-08-07T13:53:10+00:00" "time": "2020-04-27T09:25:28+00:00"
}, },
{ {
"name": "phpdocumentor/reflection-docblock", "name": "phpdocumentor/reflection-docblock",
"version": "4.3.4", "version": "5.1.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/phpDocumentor/ReflectionDocBlock.git", "url": "https://github.com/phpDocumentor/ReflectionDocBlock.git",
"reference": "da3fd972d6bafd628114f7e7e036f45944b62e9c" "reference": "cd72d394ca794d3466a3b2fc09d5a6c1dc86b47e"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/da3fd972d6bafd628114f7e7e036f45944b62e9c", "url": "https://api.github.com/repos/phpDocumentor/ReflectionDocBlock/zipball/cd72d394ca794d3466a3b2fc09d5a6c1dc86b47e",
"reference": "da3fd972d6bafd628114f7e7e036f45944b62e9c", "reference": "cd72d394ca794d3466a3b2fc09d5a6c1dc86b47e",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": "^7.0", "ext-filter": "^7.1",
"phpdocumentor/reflection-common": "^1.0.0 || ^2.0.0", "php": "^7.2",
"phpdocumentor/type-resolver": "~0.4 || ^1.0.0", "phpdocumentor/reflection-common": "^2.0",
"webmozart/assert": "^1.0" "phpdocumentor/type-resolver": "^1.0",
"webmozart/assert": "^1"
}, },
"require-dev": { "require-dev": {
"doctrine/instantiator": "^1.0.5", "doctrine/instantiator": "^1",
"mockery/mockery": "^1.0", "mockery/mockery": "^1"
"phpdocumentor/type-resolver": "0.4.*",
"phpunit/phpunit": "^6.4"
}, },
"type": "library", "type": "library",
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "4.x-dev" "dev-master": "5.x-dev"
} }
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"phpDocumentor\\Reflection\\": [ "phpDocumentor\\Reflection\\": "src"
"src/"
]
} }
}, },
"notification-url": "https://packagist.org/downloads/", "notification-url": "https://packagist.org/downloads/",
@@ -829,33 +999,36 @@
{ {
"name": "Mike van Riel", "name": "Mike van Riel",
"email": "me@mikevanriel.com" "email": "me@mikevanriel.com"
},
{
"name": "Jaap van Otterdijk",
"email": "account@ijaap.nl"
} }
], ],
"description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.", "description": "With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.",
"time": "2019-12-28T18:55:12+00:00" "time": "2020-02-22T12:28:44+00:00"
}, },
{ {
"name": "phpdocumentor/type-resolver", "name": "phpdocumentor/type-resolver",
"version": "1.0.1", "version": "1.1.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/phpDocumentor/TypeResolver.git", "url": "https://github.com/phpDocumentor/TypeResolver.git",
"reference": "2e32a6d48972b2c1976ed5d8967145b6cec4a4a9" "reference": "7462d5f123dfc080dfdf26897032a6513644fc95"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/2e32a6d48972b2c1976ed5d8967145b6cec4a4a9", "url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/7462d5f123dfc080dfdf26897032a6513644fc95",
"reference": "2e32a6d48972b2c1976ed5d8967145b6cec4a4a9", "reference": "7462d5f123dfc080dfdf26897032a6513644fc95",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"php": "^7.1", "php": "^7.2",
"phpdocumentor/reflection-common": "^2.0" "phpdocumentor/reflection-common": "^2.0"
}, },
"require-dev": { "require-dev": {
"ext-tokenizer": "^7.1", "ext-tokenizer": "^7.2",
"mockery/mockery": "~1", "mockery/mockery": "~1"
"phpunit/phpunit": "^7.0"
}, },
"type": "library", "type": "library",
"extra": { "extra": {
@@ -879,28 +1052,28 @@
} }
], ],
"description": "A PSR-5 based resolver of Class names, Types and Structural Element Names", "description": "A PSR-5 based resolver of Class names, Types and Structural Element Names",
"time": "2019-08-22T18:11:29+00:00" "time": "2020-02-18T18:59:58+00:00"
}, },
{ {
"name": "phpspec/prophecy", "name": "phpspec/prophecy",
"version": "1.10.1", "version": "v1.10.3",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/phpspec/prophecy.git", "url": "https://github.com/phpspec/prophecy.git",
"reference": "cbe1df668b3fe136bcc909126a0f529a78d4cbbc" "reference": "451c3cd1418cf640de218914901e51b064abb093"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/phpspec/prophecy/zipball/cbe1df668b3fe136bcc909126a0f529a78d4cbbc", "url": "https://api.github.com/repos/phpspec/prophecy/zipball/451c3cd1418cf640de218914901e51b064abb093",
"reference": "cbe1df668b3fe136bcc909126a0f529a78d4cbbc", "reference": "451c3cd1418cf640de218914901e51b064abb093",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
"doctrine/instantiator": "^1.0.2", "doctrine/instantiator": "^1.0.2",
"php": "^5.3|^7.0", "php": "^5.3|^7.0",
"phpdocumentor/reflection-docblock": "^2.0|^3.0.2|^4.0|^5.0", "phpdocumentor/reflection-docblock": "^2.0|^3.0.2|^4.0|^5.0",
"sebastian/comparator": "^1.2.3|^2.0|^3.0", "sebastian/comparator": "^1.2.3|^2.0|^3.0|^4.0",
"sebastian/recursion-context": "^1.0|^2.0|^3.0" "sebastian/recursion-context": "^1.0|^2.0|^3.0|^4.0"
}, },
"require-dev": { "require-dev": {
"phpspec/phpspec": "^2.5 || ^3.2", "phpspec/phpspec": "^2.5 || ^3.2",
@@ -942,7 +1115,7 @@
"spy", "spy",
"stub" "stub"
], ],
"time": "2019-12-22T21:05:45+00:00" "time": "2020-03-05T15:02:03+00:00"
}, },
{ {
"name": "phpunit/php-code-coverage", "name": "phpunit/php-code-coverage",
@@ -1198,16 +1371,16 @@
}, },
{ {
"name": "phpunit/phpunit", "name": "phpunit/phpunit",
"version": "8.5.1", "version": "8.5.5",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git", "url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "7870c78da3c5e4883eaef36ae47853ebb3cb86f2" "reference": "63dda3b212a0025d380a745f91bdb4d8c985adb7"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/7870c78da3c5e4883eaef36ae47853ebb3cb86f2", "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/63dda3b212a0025d380a745f91bdb4d8c985adb7",
"reference": "7870c78da3c5e4883eaef36ae47853ebb3cb86f2", "reference": "63dda3b212a0025d380a745f91bdb4d8c985adb7",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@@ -1277,7 +1450,7 @@
"testing", "testing",
"xunit" "xunit"
], ],
"time": "2019-12-25T14:49:39+00:00" "time": "2020-05-22T13:51:52+00:00"
}, },
{ {
"name": "sebastian/code-unit-reverse-lookup", "name": "sebastian/code-unit-reverse-lookup",
@@ -1936,16 +2109,16 @@
}, },
{ {
"name": "webmozart/assert", "name": "webmozart/assert",
"version": "1.6.0", "version": "1.8.0",
"source": { "source": {
"type": "git", "type": "git",
"url": "https://github.com/webmozart/assert.git", "url": "https://github.com/webmozart/assert.git",
"reference": "573381c0a64f155a0d9a23f4b0c797194805b925" "reference": "ab2cb0b3b559010b75981b1bdce728da3ee90ad6"
}, },
"dist": { "dist": {
"type": "zip", "type": "zip",
"url": "https://api.github.com/repos/webmozart/assert/zipball/573381c0a64f155a0d9a23f4b0c797194805b925", "url": "https://api.github.com/repos/webmozart/assert/zipball/ab2cb0b3b559010b75981b1bdce728da3ee90ad6",
"reference": "573381c0a64f155a0d9a23f4b0c797194805b925", "reference": "ab2cb0b3b559010b75981b1bdce728da3ee90ad6",
"shasum": "" "shasum": ""
}, },
"require": { "require": {
@@ -1953,7 +2126,7 @@
"symfony/polyfill-ctype": "^1.8" "symfony/polyfill-ctype": "^1.8"
}, },
"conflict": { "conflict": {
"vimeo/psalm": "<3.6.0" "vimeo/psalm": "<3.9.1"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^4.8.36 || ^7.5.13" "phpunit/phpunit": "^4.8.36 || ^7.5.13"
@@ -1980,7 +2153,7 @@
"check", "check",
"validate" "validate"
], ],
"time": "2019-11-24T13:36:37+00:00" "time": "2020-04-18T12:12:48+00:00"
} }
], ],
"aliases": [], "aliases": [],

View File

@@ -1,5 +1,9 @@
# Работа с клиентами (покупателями) # Работа с клиентами (покупателями)
[Вернуться к содержанию](readme.md)
---
Объект покупателя инициализируется следующим образом: Объект покупателя инициализируется следующим образом:
```php ```php
@@ -73,3 +77,7 @@ $json_string = (string)$customer;
```php ```php
$json_array = $customer->jsonSerialize(); $json_array = $customer->jsonSerialize();
``` ```
---
[Вернуться к содержанию](readme.md)

View File

@@ -1,5 +1,9 @@
# Работа с компанией (продавцом) # Работа с компанией (продавцом)
[Вернуться к содержанию](readme.md)
---
Объект компании инициализируется следующим образом: Объект компании инициализируется следующим образом:
```php ```php
@@ -70,3 +74,7 @@ $json_string = (string)$company;
```php ```php
$json_array = $company->jsonSerialize(); $json_array = $company->jsonSerialize();
``` ```
---
[Вернуться к содержанию](readme.md)

View File

@@ -1,5 +1,9 @@
# Работа с данными коррекции # Работа с данными коррекции
[Вернуться к содержанию](readme.md)
---
Объект для данных коррекции инициализируется следующим образом: Объект для данных коррекции инициализируется следующим образом:
```php ```php
@@ -57,9 +61,6 @@ $json_string = (string)$customer;
$json_array = $customer->jsonSerialize(); $json_array = $customer->jsonSerialize();
``` ```
---
[Вернуться к содержанию](readme.md)

View File

@@ -1,5 +1,9 @@
# Работа с документами # Работа с документами
[Вернуться к содержанию](readme.md)
---
Объект документа инициализируется следующим образом: Объект документа инициализируется следующим образом:
```php ```php
@@ -157,3 +161,7 @@ $json_string = (string)$doc;
```php ```php
$json_array = $doc->jsonSerialize(); $json_array = $doc->jsonSerialize();
``` ```
---
[Вернуться к содержанию](readme.md)

View File

@@ -1,5 +1,9 @@
# Работа с предметами расчёта # Работа с предметами расчёта
[Вернуться к содержанию](readme.md)
---
## Один объект ## Один объект
Объект предмета расчёта инициализируется следующим образом: Объект предмета расчёта инициализируется следующим образом:
@@ -192,3 +196,7 @@ $json_string = (string)$item_array;
```php ```php
$json_array = $item_array->jsonSerialize(); $json_array = $item_array->jsonSerialize();
``` ```
---
[Вернуться к содержанию](readme.md)

View File

@@ -1,5 +1,9 @@
# Работа с ККТ # Работа с ККТ
[Вернуться к содержанию](readme.md)
---
Объект ККТ инициализируется следующим образом: Объект ККТ инициализируется следующим образом:
```php ```php
@@ -215,3 +219,7 @@ $json_string = (string)$item;
```php ```php
$json_array = $item->jsonSerialize(); $json_array = $item->jsonSerialize();
``` ```
---
[Вернуться к содержанию](readme.md)

View File

@@ -1,5 +1,9 @@
# Работа с оплатами # Работа с оплатами
[Вернуться к содержанию](readme.md)
---
## Один объект ## Один объект
Объект оплаты инициализируется следующим образом: Объект оплаты инициализируется следующим образом:
@@ -124,3 +128,7 @@ $json_string = (string)$payment_array;
```php ```php
$json_array = $payment_array->jsonSerialize(); $json_array = $payment_array->jsonSerialize();
``` ```
---
[Вернуться к содержанию](readme.md)

View File

@@ -6,8 +6,9 @@
3. [Работа с оплатами](payments.md) 3. [Работа с оплатами](payments.md)
4. [Работа со ставками НДС](vats.md) 4. [Работа со ставками НДС](vats.md)
5. [Работа с предметами расчёта](items.md) 5. [Работа с предметами расчёта](items.md)
6. [Работа с документами](documents.md) 6. [Работа с данными коррекции](correction_info.md)
7. [Работа с ККТ](kkt.md) 7. [Работа с документами](documents.md)
8. [Работа с ККТ](kkt.md)
--- ---

View File

@@ -1,5 +1,9 @@
# Работа со ставками НДС # Работа со ставками НДС
[Вернуться к содержанию](readme.md)
---
## Один объект ## Один объект
Объект ставки НДС инициализируется следующим образом: Объект ставки НДС инициализируется следующим образом:
@@ -184,3 +188,7 @@ $json_string = (string)$vat_array;
```php ```php
$json_array = $vat_array->jsonSerialize(); $json_array = $vat_array->jsonSerialize();
``` ```
---
[Вернуться к содержанию](readme.md)

View File

@@ -11,10 +11,10 @@ namespace AtolOnline\Api;
use AtolOnline\{Entities\Document, use AtolOnline\{Entities\Document,
Exceptions\AtolCorrectionInfoException, Exceptions\AtolCorrectionInfoException,
Exceptions\AtolInvalidUuidException,
Exceptions\AtolKktLoginEmptyException, Exceptions\AtolKktLoginEmptyException,
Exceptions\AtolKktLoginTooLongException, Exceptions\AtolKktLoginTooLongException,
Exceptions\AtolKktPasswordEmptyException, Exceptions\AtolKktPasswordEmptyException,
Exceptions\AtolUuidValidateException,
Exceptions\AtolWrongDocumentTypeException Exceptions\AtolWrongDocumentTypeException
}; };
use GuzzleHttp\Client; use GuzzleHttp\Client;
@@ -115,10 +115,12 @@ class Kkt extends Client
*/ */
public function setLogin(string $login) public function setLogin(string $login)
{ {
if (empty($login)) { if (!$this->isTestMode()) {
throw new AtolKktLoginEmptyException(); if (empty($login)) {
} elseif (strlen($login) > 100) { throw new AtolKktLoginEmptyException();
throw new AtolKktLoginTooLongException($login, 100); } elseif ((function_exists('mb_strlen') ? mb_strlen($login) : strlen($login)) > 100) {
throw new AtolKktLoginTooLongException($login, 100);
}
} }
$this->kkt_config['prod']['login'] = $login; $this->kkt_config['prod']['login'] = $login;
return $this; return $this;
@@ -143,8 +145,10 @@ class Kkt extends Client
*/ */
public function setPassword(string $password) public function setPassword(string $password)
{ {
if (empty($password)) { if (!$this->isTestMode()) {
throw new AtolKktPasswordEmptyException(); if (empty($password)) {
throw new AtolKktPasswordEmptyException();
}
} }
$this->kkt_config['prod']['pass'] = $password; $this->kkt_config['prod']['pass'] = $password;
return $this; return $this;
@@ -225,7 +229,7 @@ class Kkt extends Client
public function sell(Document $document) public function sell(Document $document)
{ {
if ($document->getCorrectionInfo()) { if ($document->getCorrectionInfo()) {
throw new AtolCorrectionInfoException('В документе есть данные коррекции'); throw new AtolCorrectionInfoException('Некорректная операция над документом коррекции');
} }
return $this->registerDocument('sell', 'receipt', $document); return $this->registerDocument('sell', 'receipt', $document);
} }
@@ -243,7 +247,7 @@ class Kkt extends Client
public function sellRefund(Document $document) public function sellRefund(Document $document)
{ {
if ($document->getCorrectionInfo()) { if ($document->getCorrectionInfo()) {
throw new AtolCorrectionInfoException('В документе есть данные коррекции'); throw new AtolCorrectionInfoException('Некорректная операция над документом коррекции');
} }
return $this->registerDocument('sell_refund', 'receipt', $document->clearVats()); return $this->registerDocument('sell_refund', 'receipt', $document->clearVats());
} }
@@ -277,7 +281,7 @@ class Kkt extends Client
public function buy(Document $document) public function buy(Document $document)
{ {
if ($document->getCorrectionInfo()) { if ($document->getCorrectionInfo()) {
throw new AtolCorrectionInfoException('В документе есть данные коррекции'); throw new AtolCorrectionInfoException('Некорректная операция над документом коррекции');
} }
return $this->registerDocument('buy', 'receipt', $document); return $this->registerDocument('buy', 'receipt', $document);
} }
@@ -295,7 +299,7 @@ class Kkt extends Client
public function buyRefund(Document $document) public function buyRefund(Document $document)
{ {
if ($document->getCorrectionInfo()) { if ($document->getCorrectionInfo()) {
throw new AtolCorrectionInfoException('В документе есть данные коррекции'); throw new AtolCorrectionInfoException('Некорректная операция над документом коррекции');
} }
return $this->registerDocument('buy_refund', 'receipt', $document->clearVats()); return $this->registerDocument('buy_refund', 'receipt', $document->clearVats());
} }
@@ -323,13 +327,13 @@ class Kkt extends Client
* *
* @param string $uuid UUID регистрации * @param string $uuid UUID регистрации
* @return \AtolOnline\Api\KktResponse * @return \AtolOnline\Api\KktResponse
* @throws \AtolOnline\Exceptions\AtolUuidValidateException Некорректный UUID документа * @throws \AtolOnline\Exceptions\AtolInvalidUuidException Некорректный UUID документа
*/ */
public function getDocumentStatus(string $uuid) public function getDocumentStatus(string $uuid)
{ {
$uuid = trim($uuid); $uuid = trim($uuid);
if (!Uuid::isValid($uuid)) { if (!Uuid::isValid($uuid)) {
throw new AtolUuidValidateException($uuid); throw new AtolInvalidUuidException($uuid);
} }
$this->auth(); $this->auth();
return $this->sendAtolRequest('GET', 'report/'.$uuid); return $this->sendAtolRequest('GET', 'report/'.$uuid);
@@ -370,7 +374,6 @@ class Kkt extends Client
$this->kkt_config['prod']['pass'] = ''; $this->kkt_config['prod']['pass'] = '';
$this->kkt_config['prod']['url'] = 'https://online.atol.ru/possystem/v4'; $this->kkt_config['prod']['url'] = 'https://online.atol.ru/possystem/v4';
$this->kkt_config['prod']['callback_url'] = ''; $this->kkt_config['prod']['callback_url'] = '';
$this->kkt_config['test']['group'] = 'v4-online-atol-ru_4179'; $this->kkt_config['test']['group'] = 'v4-online-atol-ru_4179';
$this->kkt_config['test']['login'] = 'v4-online-atol-ru'; $this->kkt_config['test']['login'] = 'v4-online-atol-ru';
$this->kkt_config['test']['pass'] = 'iGFFuihss'; $this->kkt_config['test']['pass'] = 'iGFFuihss';

View File

@@ -0,0 +1,23 @@
<?php
namespace AtolOnline\Api;
abstract class AtolSchema
{
/**
* @return mixed
*/
public static function get()
{
return static::$json
?? static::$json = json_decode(file_get_contents(static::$URL));
}
/**
* @return false|string
*/
public static function json()
{
return json_encode(static::get());
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace AtolOnline\Api;
class CorrectionSchema extends AtolSchema
{
/**
* @var
*/
protected static $json;
/**
* Адрес схемы
*/
protected static $URL = 'https://online.atol.ru/possystem/v4/schema/correction';
}

View File

@@ -0,0 +1,17 @@
<?php
namespace AtolOnline\Api;
class SellSchema extends AtolSchema
{
/**
* @var
*/
protected static $json;
/**
* Адрес схемы
*/
protected static $URL = 'https://online.atol.ru/possystem/v4/schema/sell';
}

View File

@@ -16,7 +16,7 @@ use AtolOnline\{Exceptions\AtolNameTooLongException, Exceptions\AtolPhoneTooLong
* *
* @package AtolOnline\Entities * @package AtolOnline\Entities
*/ */
class Client extends AtolEntity class Client extends Entity
{ {
use use
/** /**
@@ -89,7 +89,7 @@ class Client extends AtolEntity
public function setName(string $name) public function setName(string $name)
{ {
$name = trim($name); $name = trim($name);
if (strlen($name) > 256) { if ((function_exists('mb_strlen') ? mb_strlen($name) : strlen($name)) > 256) {
throw new AtolNameTooLongException($name, 256); throw new AtolNameTooLongException($name, 256);
} }
$this->name = $name; $this->name = $name;
@@ -119,7 +119,7 @@ class Client extends AtolEntity
public function setPhone(string $phone) public function setPhone(string $phone)
{ {
$phone = preg_replace("/[^0-9+]/", '', $phone); $phone = preg_replace("/[^0-9+]/", '', $phone);
if (strlen($phone) > 64) { if ((function_exists('mb_strlen') ? mb_strlen($phone) : strlen($phone)) > 64) {
throw new AtolPhoneTooLongException($phone, 64); throw new AtolPhoneTooLongException($phone, 64);
} }
$this->phone = $phone; $this->phone = $phone;

View File

@@ -22,7 +22,7 @@ use AtolOnline\{Exceptions\AtolEmailTooLongException,
* *
* @package AtolOnline\Entities * @package AtolOnline\Entities
*/ */
class Company extends AtolEntity class Company extends Entity
{ {
use use
/** /**
@@ -115,7 +115,7 @@ class Company extends AtolEntity
public function setPaymentAddress(string $payment_address) public function setPaymentAddress(string $payment_address)
{ {
$payment_address = trim($payment_address); $payment_address = trim($payment_address);
if (strlen($payment_address) > 256) { if ((function_exists('mb_strlen') ? mb_strlen($payment_address) : strlen($payment_address)) > 256) {
throw new AtolPaymentAddressTooLongException($payment_address, 256); throw new AtolPaymentAddressTooLongException($payment_address, 256);
} }
$this->payment_address = $payment_address; $this->payment_address = $payment_address;

View File

@@ -14,7 +14,7 @@ namespace AtolOnline\Entities;
* *
* @package AtolOnline\Entities * @package AtolOnline\Entities
*/ */
class CorrectionInfo extends AtolEntity class CorrectionInfo extends Entity
{ {
/** /**
* @var int Тип коррекции. Тег ФФД - 1173. * @var int Тип коррекции. Тег ФФД - 1173.

View File

@@ -10,13 +10,15 @@
namespace AtolOnline\Entities; namespace AtolOnline\Entities;
use AtolOnline\Exceptions\AtolCashierTooLongException; use AtolOnline\Exceptions\AtolCashierTooLongException;
use AtolOnline\Exceptions\AtolException;
use AtolOnline\Exceptions\AtolInvalidJsonException;
/** /**
* Класс, описывающий документ * Класс, описывающий документ
* *
* @package AtolOnline\Entities * @package AtolOnline\Entities
*/ */
class Document extends AtolEntity class Document extends Entity
{ {
/** /**
* @var \AtolOnline\Entities\ItemArray Массив предметов расчёта * @var \AtolOnline\Entities\ItemArray Массив предметов расчёта
@@ -60,10 +62,6 @@ class Document extends AtolEntity
/** /**
* Document constructor. * Document constructor.
*
* @throws \AtolOnline\Exceptions\AtolTooManyItemsException Слишком много предметов расчёта
* @throws \AtolOnline\Exceptions\AtolTooManyPaymentsException Слишком много оплат
* @throws \AtolOnline\Exceptions\AtolTooManyVatsException Слишком много ставок НДС
*/ */
public function __construct() public function __construct()
{ {
@@ -82,10 +80,6 @@ class Document extends AtolEntity
public function clearVats() public function clearVats()
{ {
$this->setVats([]); $this->setVats([]);
foreach ($this->getItems() as &$item) {
$item->setVatType(null);
}
$this->calcTotal();
return $this; return $this;
} }
@@ -98,11 +92,7 @@ class Document extends AtolEntity
*/ */
public function addVat(Vat $vat) public function addVat(Vat $vat)
{ {
if (count($this->getVats()) == 0 && !$vat->getSum()) {
$vat->setSum($this->calcTotal());
}
$this->vats->add($vat); $this->vats->add($vat);
$this->calcTotal();
return $this; return $this;
} }
@@ -127,7 +117,6 @@ class Document extends AtolEntity
public function setVats(array $vats) public function setVats(array $vats)
{ {
$this->vats->set($vats); $this->vats->set($vats);
$this->calcTotal();
return $this; return $this;
} }
@@ -271,8 +260,8 @@ class Document extends AtolEntity
public function setCashier(?string $cashier) public function setCashier(?string $cashier)
{ {
$cashier = trim($cashier); $cashier = trim($cashier);
if (strlen($cashier) > 64) { if ((function_exists('mb_strlen') ? mb_strlen($cashier) : strlen($cashier)) > 64) {
throw new AtolCashierTooLongException($cashier); throw new AtolCashierTooLongException($cashier, 64);
} }
$this->cashier = $cashier; $this->cashier = $cashier;
return $this; return $this;
@@ -309,11 +298,10 @@ class Document extends AtolEntity
public function calcTotal() public function calcTotal()
{ {
$sum = 0; $sum = 0;
$this->clearVats();
foreach ($this->items->get() as $item) { foreach ($this->items->get() as $item) {
$sum += $item->calcSum(); $sum += $item->calcSum();
} $this->addVat(new Vat($item->getVat()->getType(), $item->getSum()));
foreach ($this->vats->get() as $vat) {
$vat->setSum($sum);
} }
return $this->total = round($sum, 2); return $this->total = round($sum, 2);
} }
@@ -329,16 +317,95 @@ class Document extends AtolEntity
} }
/** /**
* @inheritDoc * Собирает объект документа из сырой json-строки
*
* @param string $json
* @return \AtolOnline\Entities\Document
* @throws \AtolOnline\Exceptions\AtolEmailTooLongException
* @throws \AtolOnline\Exceptions\AtolEmailValidateException
* @throws \AtolOnline\Exceptions\AtolException
* @throws \AtolOnline\Exceptions\AtolInnWrongLengthException
* @throws \AtolOnline\Exceptions\AtolInvalidJsonException
* @throws \AtolOnline\Exceptions\AtolNameTooLongException
* @throws \AtolOnline\Exceptions\AtolPaymentAddressTooLongException
* @throws \AtolOnline\Exceptions\AtolPhoneTooLongException
* @throws \AtolOnline\Exceptions\AtolPriceTooHighException
* @throws \AtolOnline\Exceptions\AtolTooManyException
* @throws \AtolOnline\Exceptions\AtolTooManyItemsException
* @throws \AtolOnline\Exceptions\AtolTooManyPaymentsException
* @throws \AtolOnline\Exceptions\AtolUnitTooLongException
* @throws \AtolOnline\Exceptions\AtolUserdataTooLongException
*/
public static function fromRaw(string $json)
{
$array = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new AtolInvalidJsonException();
}
$doc = new self();
if (isset($array['company'])) {
$doc->setCompany(new Company(
$array['company']['sno'] ?? null,
$array['company']['inn'] ?? null,
$array['company']['payment_address'] ?? null,
$array['company']['email'] ?? null
));
}
if (isset($array['client'])) {
$doc->setClient(new Client(
$array['client']['name'] ?? null,
$array['client']['phone'] ?? null,
$array['client']['email'] ?? null,
$array['client']['inn'] ?? null
));
}
if (isset($array['items'])) {
foreach ($array['items'] as $ar_item) {
$item = new Item(
$ar_item['name'] ?? null,
$ar_item['price'] ?? null,
$ar_item['quantity'] ?? null,
$ar_item['measurement_unit'] ?? null,
$ar_item['vat']['type'] ?? null,
$ar_item['payment_object'] ?? null,
$ar_item['payment_method'] ?? null
);
if (!empty($ar_item['user_data'])) {
$item->setUserData($ar_item['user_data'] ?? null);
}
$doc->addItem($item);
}
}
if (isset($array['payments'])) {
foreach ($array['payments'] as $ar_payment) {
$payment = new Payment();
if (isset($ar_payment['type'])) {
$payment->setType($ar_payment['type']);
}
if (isset($ar_payment['sum'])) {
$payment->setSum($ar_payment['sum']);
}
$doc->payments->add($payment);
}
}
if ($array['total'] != $doc->calcTotal()) {
throw new AtolException('Real total sum not equals to provided in JSON one');
}
return $doc;
}
/**
* Возвращает массив для кодирования в json
*
* @throws \Exception * @throws \Exception
*/ */
public function jsonSerialize() public function jsonSerialize()
{ {
$json = [ $json['company'] = $this->getCompany()->jsonSerialize();// обязательно
'company' => $this->getCompany()->jsonSerialize(), // обязательно $json['payments'] = $this->payments->jsonSerialize(); // обязательно
'payments' => $this->payments->jsonSerialize(), // обязательно if ($this->getCashier()) {
'cashier' => $this->getCashier() ?? '', $json['cashier'] = $this->getCashier();
]; }
if ($this->getCorrectionInfo()) { if ($this->getCorrectionInfo()) {
$json['correction_info'] = $this->getCorrectionInfo()->jsonSerialize(); // обязательно для коррекционных $json['correction_info'] = $this->getCorrectionInfo()->jsonSerialize(); // обязательно для коррекционных
} else { } else {

View File

@@ -16,7 +16,7 @@ use JsonSerializable;
* *
* @package AtolOnline\Entities * @package AtolOnline\Entities
*/ */
abstract class AtolEntity implements JsonSerializable abstract class Entity implements JsonSerializable
{ {
/** /**
* @inheritDoc * @inheritDoc

View File

@@ -11,18 +11,17 @@ namespace AtolOnline\Entities;
use AtolOnline\{Exceptions\AtolNameTooLongException, use AtolOnline\{Exceptions\AtolNameTooLongException,
Exceptions\AtolPriceTooHighException, Exceptions\AtolPriceTooHighException,
Exceptions\AtolQuantityTooHighException, Exceptions\AtolTooManyException,
Exceptions\AtolUnitTooLongException, Exceptions\AtolUnitTooLongException,
Exceptions\AtolUserdataTooLongException, Exceptions\AtolUserdataTooLongException,
Traits\RublesKopeksConverter Traits\RublesKopeksConverter};
};
/** /**
* Предмет расчёта (товар, услуга) * Предмет расчёта (товар, услуга)
* *
* @package AtolOnline\Entities * @package AtolOnline\Entities
*/ */
class Item extends AtolEntity class Item extends Entity
{ {
use RublesKopeksConverter; use RublesKopeksConverter;
@@ -83,7 +82,7 @@ class Item extends AtolEntity
* @param string|null $payment_method Способ расчёта * @param string|null $payment_method Способ расчёта
* @throws AtolNameTooLongException Слишком длинное наименование * @throws AtolNameTooLongException Слишком длинное наименование
* @throws AtolPriceTooHighException Слишком высокая цена за одну единицу * @throws AtolPriceTooHighException Слишком высокая цена за одну единицу
* @throws AtolQuantityTooHighException Слишком большое количество * @throws AtolTooManyException Слишком большое количество
* @throws AtolUnitTooLongException Слишком длинное название единицы измерения * @throws AtolUnitTooLongException Слишком длинное название единицы измерения
*/ */
public function __construct( public function __construct(
@@ -101,17 +100,17 @@ class Item extends AtolEntity
if ($price) { if ($price) {
$this->setPrice($price); $this->setPrice($price);
} }
if ($payment_object) {
$this->setPaymentObject($payment_object);
}
if ($quantity) { if ($quantity) {
$this->setQuantity($quantity); $this->setQuantity($quantity);
} }
if ($measurement_unit) {
$this->setMeasurementUnit($measurement_unit);
}
if ($vat_type) { if ($vat_type) {
$this->setVatType($vat_type); $this->setVatType($vat_type);
} }
if ($measurement_unit) { if ($payment_object) {
$this->setMeasurementUnit($measurement_unit); $this->setPaymentObject($payment_object);
} }
if ($payment_method) { if ($payment_method) {
$this->setPaymentMethod($payment_method); $this->setPaymentMethod($payment_method);
@@ -138,7 +137,7 @@ class Item extends AtolEntity
public function setName(string $name) public function setName(string $name)
{ {
$name = trim($name); $name = trim($name);
if (strlen($name) > 128) { if ((function_exists('mb_strlen') ? mb_strlen($name) : strlen($name)) > 128) {
throw new AtolNameTooLongException($name, 128); throw new AtolNameTooLongException($name, 128);
} }
$this->name = $name; $this->name = $name;
@@ -188,7 +187,7 @@ class Item extends AtolEntity
* @param float $quantity Количество * @param float $quantity Количество
* @param string|null $measurement_unit Единица измерения количества * @param string|null $measurement_unit Единица измерения количества
* @return $this * @return $this
* @throws AtolQuantityTooHighException Слишком большое количество * @throws AtolTooManyException Слишком большое количество
* @throws AtolPriceTooHighException Слишком высокая общая стоимость * @throws AtolPriceTooHighException Слишком высокая общая стоимость
* @throws AtolUnitTooLongException Слишком длинное название единицы измерения * @throws AtolUnitTooLongException Слишком длинное название единицы измерения
*/ */
@@ -196,7 +195,7 @@ class Item extends AtolEntity
{ {
$quantity = round($quantity, 3); $quantity = round($quantity, 3);
if ($quantity > 99999.999) { if ($quantity > 99999.999) {
throw new AtolQuantityTooHighException($quantity, 99999.999); throw new AtolTooManyException($quantity, 99999.999);
} }
$this->quantity = $quantity; $this->quantity = $quantity;
$this->calcSum(); $this->calcSum();
@@ -226,7 +225,7 @@ class Item extends AtolEntity
public function setMeasurementUnit(string $measurement_unit) public function setMeasurementUnit(string $measurement_unit)
{ {
$measurement_unit = trim($measurement_unit); $measurement_unit = trim($measurement_unit);
if (strlen($measurement_unit) > 16) { if ((function_exists('mb_strlen') ? mb_strlen($measurement_unit) : strlen($measurement_unit)) > 16) {
throw new AtolUnitTooLongException($measurement_unit, 16); throw new AtolUnitTooLongException($measurement_unit, 16);
} }
$this->measurement_unit = $measurement_unit; $this->measurement_unit = $measurement_unit;
@@ -329,7 +328,7 @@ class Item extends AtolEntity
public function setUserData(string $user_data) public function setUserData(string $user_data)
{ {
$user_data = trim($user_data); $user_data = trim($user_data);
if (strlen($user_data) > 64) { if ((function_exists('mb_strlen') ? mb_strlen($user_data) : strlen($user_data)) > 64) {
throw new AtolUserdataTooLongException($user_data, 64); throw new AtolUserdataTooLongException($user_data, 64);
} }
$this->user_data = $user_data; $this->user_data = $user_data;

View File

@@ -16,25 +16,27 @@ use AtolOnline\Exceptions\AtolTooManyItemsException;
* *
* @package AtolOnline\Entities * @package AtolOnline\Entities
*/ */
class ItemArray extends AtolEntity class ItemArray extends Entity
{ {
/** /**
* Максимальное количество элементов в массиве * Максимальное количество элементов в массиве
* По документации ограничение по количеству предметов расчёта = от 1 до 100,
* однако в схеме sell не указан receipt.properties.items.maxItems
*/ */
const MAX_COUNT = 100; public const MAX_COUNT = 100;
/** /**
* @var \AtolOnline\Entities\Item[] Массив предметов расчёта * @var Item[] Массив предметов расчёта
*/ */
private $items = []; private $items = [];
/** /**
* ItemArray constructor. * ItemArray constructor.
* *
* @param \AtolOnline\Entities\Item[]|null $items Массив предметов расчёта * @param Item[]|null $items Массив предметов расчёта
* @throws \AtolOnline\Exceptions\AtolTooManyItemsException Слишком много предметов расчёта * @throws AtolTooManyItemsException Слишком много предметов расчёта
*/ */
public function __construct(array $items = null) public function __construct(?array $items = null)
{ {
if ($items) { if ($items) {
$this->set($items); $this->set($items);
@@ -44,9 +46,9 @@ class ItemArray extends AtolEntity
/** /**
* Устанавливает массив предметов расчёта * Устанавливает массив предметов расчёта
* *
* @param \AtolOnline\Entities\Item[] $items Массив предметов расчёта * @param Item[] $items Массив предметов расчёта
* @return $this * @return $this
* @throws \AtolOnline\Exceptions\AtolTooManyItemsException Слишком много предметов расчёта * @throws AtolTooManyItemsException Слишком много предметов расчёта
*/ */
public function set(array $items) public function set(array $items)
{ {
@@ -59,9 +61,9 @@ class ItemArray extends AtolEntity
/** /**
* Добавляет предмет расчёта в массив * Добавляет предмет расчёта в массив
* *
* @param \AtolOnline\Entities\Item $item Объект предмета расчёта * @param Item $item Объект предмета расчёта
* @return $this * @return $this
* @throws \AtolOnline\Exceptions\AtolTooManyItemsException Слишком много предметов расчёта * @throws AtolTooManyItemsException Слишком много предметов расчёта
*/ */
public function add(Item $item) public function add(Item $item)
{ {
@@ -74,7 +76,7 @@ class ItemArray extends AtolEntity
/** /**
* Возвращает массив предметов расчёта * Возвращает массив предметов расчёта
* *
* @return \AtolOnline\Entities\Item[] * @return Item[]
*/ */
public function get() public function get()
{ {
@@ -94,16 +96,16 @@ class ItemArray extends AtolEntity
} }
/** /**
* Проверяет количество элементов в массиве * Проверяет количество предметов расчёта
* *
* @param array|null $items Если передать массив, то проверит количество его элементов. * @param Item[]|null $items Если передать массив, то проверит количество его элементов.
* Иначе проверит количество уже присвоенных элементов. * Иначе проверит количество уже присвоенных элементов.
* @return bool * @return bool true если всё хорошо, иначе выбрасывает исключение
* @throws \AtolOnline\Exceptions\AtolTooManyItemsException Слишком много предметов расчёта * @throws AtolTooManyItemsException Слишком много предметов расчёта
*/ */
protected function validateCount(array $items = null) protected function validateCount(?array $items = null): bool
{ {
if (($items && is_array($items) && count($items) >= self::MAX_COUNT) || count($this->items) == self::MAX_COUNT) { if ((!empty($items) && count($items) >= self::MAX_COUNT) || count($this->items) >= self::MAX_COUNT) {
throw new AtolTooManyItemsException(self::MAX_COUNT); throw new AtolTooManyItemsException(self::MAX_COUNT);
} }
return true; return true;

View File

@@ -16,7 +16,7 @@ use AtolOnline\Constants\PaymentTypes;
* *
* @package AtolOnline\Entities * @package AtolOnline\Entities
*/ */
class Payment extends AtolEntity class Payment extends Entity
{ {
/** /**
* @var int Тип оплаты * @var int Тип оплаты

View File

@@ -9,6 +9,7 @@
namespace AtolOnline\Entities; namespace AtolOnline\Entities;
use AtolOnline\Api\SellSchema;
use AtolOnline\Exceptions\AtolTooManyPaymentsException; use AtolOnline\Exceptions\AtolTooManyPaymentsException;
/** /**
@@ -16,13 +17,8 @@ use AtolOnline\Exceptions\AtolTooManyPaymentsException;
* *
* @package AtolOnline\Entities * @package AtolOnline\Entities
*/ */
class PaymentArray extends AtolEntity class PaymentArray extends Entity
{ {
/**
* Максимальное количество элементов в массиве
*/
const MAX_COUNT = 10;
/** /**
* @var Payment[] Массив оплат * @var Payment[] Массив оплат
*/ */
@@ -34,7 +30,7 @@ class PaymentArray extends AtolEntity
* @param Payment[]|null $payments Массив оплат * @param Payment[]|null $payments Массив оплат
* @throws AtolTooManyPaymentsException Слишком много оплат * @throws AtolTooManyPaymentsException Слишком много оплат
*/ */
public function __construct(array $payments = null) public function __construct(?array $payments = null)
{ {
if ($payments) { if ($payments) {
$this->set($payments); $this->set($payments);
@@ -94,17 +90,18 @@ class PaymentArray extends AtolEntity
} }
/** /**
* Проверяет количество элементов в массиве * Проверяет количество налоговых ставок
* *
* @param Payment[]|null $payments Если передать массив, то проверит количество его элементов. * @param Payment[]|null $payments Если передать массив, то проверит количество его элементов.
* Иначе проверит количество уже присвоенных элементов. * Иначе проверит количество уже присвоенных элементов.
* @return bool * @return bool true если всё хорошо, иначе выбрасывает исключение
* @throws AtolTooManyPaymentsException Слишком много оплат * @throws AtolTooManyPaymentsException Слишком много оплат
*/ */
protected function validateCount(array $payments = null) protected function validateCount(?array $payments = null): bool
{ {
if (($payments && is_array($payments) && count($payments) >= self::MAX_COUNT) || count($this->payments) == self::MAX_COUNT) { $max_items = SellSchema::get()->properties->receipt->properties->payments->maxItems;
throw new AtolTooManyPaymentsException(self::MAX_COUNT); if ((!empty($payments) && count($payments) >= $max_items) || count($this->payments) >= $max_items) {
throw new AtolTooManyPaymentsException($max_items);
} }
return true; return true;
} }

View File

@@ -16,7 +16,7 @@ use AtolOnline\{Constants\VatTypes, Traits\RublesKopeksConverter};
* *
* @package AtolOnline\Entities * @package AtolOnline\Entities
*/ */
class Vat extends AtolEntity class Vat extends Entity
{ {
use RublesKopeksConverter; use RublesKopeksConverter;
@@ -26,12 +26,12 @@ class Vat extends AtolEntity
private $type; private $type;
/** /**
* @var int Сумма в копейках, от которой пересчитывается размер налога * @var int Сумма в копейках, от которой пересчитывается размер НДС
*/ */
private $sum_original = 0; private $sum_original = 0;
/** /**
* @var int Сумма налога в копейках * @var int Сумма НДС в копейках
*/ */
private $sum_final = 0; private $sum_final = 0;
@@ -66,18 +66,19 @@ class Vat extends AtolEntity
case VatTypes::VAT0: case VatTypes::VAT0:
return 0; return 0;
case VatTypes::VAT10: case VatTypes::VAT10:
return $kopeks * 10 / 100; //return $kopeks * 10 / 100;
case VatTypes::VAT110: case VatTypes::VAT110:
return $kopeks * 10 / 110; return $kopeks * 10 / 110;
case VatTypes::VAT18: case VatTypes::VAT18:
return $kopeks * 18 / 100; //return $kopeks * 18 / 100;
case VatTypes::VAT118: case VatTypes::VAT118:
return $kopeks * 18 / 118; return $kopeks * 18 / 118;
case VatTypes::VAT20: case VatTypes::VAT20:
return $kopeks * 20 / 100; //return $kopeks * 20 / 100;
case VatTypes::VAT120: case VatTypes::VAT120:
return $kopeks * 20 / 120; return $kopeks * 20 / 120;
} }
return 0;
} }
/** /**

View File

@@ -9,6 +9,7 @@
namespace AtolOnline\Entities; namespace AtolOnline\Entities;
use AtolOnline\Api\SellSchema;
use AtolOnline\Exceptions\AtolTooManyVatsException; use AtolOnline\Exceptions\AtolTooManyVatsException;
/** /**
@@ -16,13 +17,8 @@ use AtolOnline\Exceptions\AtolTooManyVatsException;
* *
* @package AtolOnline\Entities * @package AtolOnline\Entities
*/ */
class VatArray extends AtolEntity class VatArray extends Entity
{ {
/**
* Максимальное количество элементов в массиве
*/
public const MAX_COUNT = 6;
/** /**
* @var Vat[] Массив ставок НДС * @var Vat[] Массив ставок НДС
*/ */
@@ -34,7 +30,7 @@ class VatArray extends AtolEntity
* @param Vat[]|null $vats Массив ставок НДС * @param Vat[]|null $vats Массив ставок НДС
* @throws AtolTooManyVatsException Слишком много ставок НДС * @throws AtolTooManyVatsException Слишком много ставок НДС
*/ */
public function __construct(array $vats = null) public function __construct(?array $vats = null)
{ {
if ($vats) { if ($vats) {
$this->set($vats); $this->set($vats);
@@ -66,7 +62,11 @@ class VatArray extends AtolEntity
public function add(Vat $vat) public function add(Vat $vat)
{ {
if ($this->validateCount()) { if ($this->validateCount()) {
$this->vats[] = $vat; if (isset($this->vats[$vat->getType()])) {
$this->vats[$vat->getType()]->addSum($vat->getSum());
} else {
$this->vats[$vat->getType()] = $vat;
}
} }
return $this; return $this;
} }
@@ -94,17 +94,18 @@ class VatArray extends AtolEntity
} }
/** /**
* Проверяет количество элементов в массиве * Проверяет количество налоговых ставок
* *
* @param array|null $vats Если передать массив, то проверит количество его элементов. * @param Vat[]|null $vats Если передать массив, то проверит количество его элементов.
* Иначе проверит количество уже присвоенных элементов. * Иначе проверит количество уже присвоенных элементов.
* @return bool * @return bool true если всё хорошо, иначе выбрасывает исключение
* @throws AtolTooManyVatsException Слишком много ставок НДС * @throws AtolTooManyVatsException Слишком много ставок НДС
*/ */
protected function validateCount(array $vats = null) protected function validateCount(?array $vats = null): bool
{ {
if (($vats && is_array($vats) && count($vats) >= self::MAX_COUNT) || count($this->vats) == self::MAX_COUNT) { $max_items = SellSchema::get()->properties->receipt->properties->vats->maxItems;
throw new AtolTooManyVatsException(self::MAX_COUNT); if ((!empty($vats) && count($vats) >= $max_items) || count($this->vats) >= $max_items) {
throw new AtolTooManyVatsException(count($vats), $max_items);
} }
return true; return true;
} }

View File

@@ -9,26 +9,22 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке указать слишком длинное имя кассира * Исключение, возникающее при попытке указать слишком длинное имя кассира
* *
* @package AtolOnline\Exceptions * @package AtolOnline\Exceptions
*/ */
class AtolCashierTooLongException extends AtolException class AtolCashierTooLongException extends AtolTooLongException
{ {
/** /**
* AtolCashierTooLongException constructor. * @inheritDoc
*
* @param $name
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($name, $message = "", $code = 0, Throwable $previous = null) protected $ffd_tags = [
{ 1021,
$message = $message ?: 'Слишком длинное имя кассира (макс. длина 64, фактически '.strlen($name).'): '.$name; ];
parent::__construct($message, $code, $previous);
} /**
* @var string Сообщение об ошибке
*/
protected $message = 'Cashier name is too long';
} }

View File

@@ -9,8 +9,6 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке зарегистрировать документ без данных коррекции * Исключение, возникающее при попытке зарегистрировать документ без данных коррекции
* *
@@ -19,15 +17,7 @@ use Throwable;
class AtolCorrectionInfoException extends AtolException class AtolCorrectionInfoException extends AtolException
{ {
/** /**
* AtolNoCorrectionInfoException constructor. * @var string Сообщение об ошибке
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($message = "", $code = 0, Throwable $previous = null) protected $message = 'Document must have correction info';
{
$message = $message ?: 'В документе отсутствуют данные коррекции';
parent::__construct($message, $code, $previous);
}
} }

View File

@@ -9,8 +9,6 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке указать пустой email * Исключение, возникающее при попытке указать пустой email
* *
@@ -19,15 +17,15 @@ use Throwable;
class AtolEmailEmptyException extends AtolException class AtolEmailEmptyException extends AtolException
{ {
/** /**
* AtolEmailEmptyException constructor. * @inheritDoc
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($message = "", $code = 0, Throwable $previous = null) protected $ffd_tags = [
{ 1008,
$message = $message ?: 'Email не может быть пустым'; 1117,
parent::__construct($message, $code, $previous); ];
}
/**
* @var string Сообщение об ошибке
*/
protected $message = 'Email cannot be empty';
} }

View File

@@ -9,27 +9,23 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке указать слишком длинный email * Исключение, возникающее при попытке указать слишком длинный email
* *
* @package AtolOnline\Exceptions * @package AtolOnline\Exceptions
*/ */
class AtolEmailTooLongException extends AtolException class AtolEmailTooLongException extends AtolTooLongException
{ {
/** /**
* AtolEmailTooLongException constructor. * @inheritDoc
*
* @param $email
* @param $max
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($email, $max, $message = "", $code = 0, Throwable $previous = null) protected $ffd_tags = [
{ 1008,
$message = $message ?: 'Слишком длинный email (макс. длина '.$max.', фактически '.strlen($email).'): '.$email; 1117,
parent::__construct($message, $code, $previous); ];
}
/**
* @var string Сообщение об ошибке
*/
protected $message = 'Email is is too long';
} }

View File

@@ -18,6 +18,14 @@ use Throwable;
*/ */
class AtolEmailValidateException extends AtolException class AtolEmailValidateException extends AtolException
{ {
/**
* @inheritDoc
*/
protected $ffd_tags = [
1008,
1117,
];
/** /**
* AtolEmailValidateException constructor. * AtolEmailValidateException constructor.
* *
@@ -28,7 +36,6 @@ class AtolEmailValidateException extends AtolException
*/ */
public function __construct($email, $message = "", $code = 0, Throwable $previous = null) public function __construct($email, $message = "", $code = 0, Throwable $previous = null)
{ {
$message = $message ?: 'Некорректный email: '.$email; parent::__construct($message ?: 'Invalid email: '.$email, $code, $previous);
parent::__construct($message, $code, $previous);
} }
} }

View File

@@ -10,6 +10,7 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Exception; use Exception;
use Throwable;
/** /**
* Исключение, возникающее при работе с АТОЛ Онлайн * Исключение, возникающее при работе с АТОЛ Онлайн
@@ -18,5 +19,33 @@ use Exception;
*/ */
class AtolException extends Exception class AtolException extends Exception
{ {
/**
* @var int[] Теги ФФД
*/
protected $ffd_tags = null;
/**
* AtolException constructor.
*
* @param string $message
* @param int $code
* @param \Throwable|null $previous
*/
public function __construct($message = "", $code = 0, Throwable $previous = null)
{
if ($this->getFfdTags()) {
$message .= ' [FFD tags: '.implode(', ', $this->getFfdTags()).']';
}
parent::__construct($message, $code, $previous);
}
/**
* Возвращает теги ФФД, с которыми связано исключение
*
* @return array|null
*/
protected function getFfdTags(): ?array
{
return $this->ffd_tags;
}
} }

View File

@@ -18,6 +18,16 @@ use Throwable;
*/ */
class AtolInnWrongLengthException extends AtolException class AtolInnWrongLengthException extends AtolException
{ {
/**
* @inheritDoc
*/
protected $ffd_tags = [
1016,
1018,
1226,
1228,
];
/** /**
* AtolInnWrongLengthException constructor. * AtolInnWrongLengthException constructor.
* *
@@ -28,7 +38,7 @@ class AtolInnWrongLengthException extends AtolException
*/ */
public function __construct($inn, $message = "", $code = 0, Throwable $previous = null) public function __construct($inn, $message = "", $code = 0, Throwable $previous = null)
{ {
$message = $message ?: 'Длина ИНН должна быть 10 или 12 цифр, фактически '.strlen($inn).': '.$inn; parent::__construct($message ?: 'INN length must be 10 or 12 digits only, but actual is '.
parent::__construct($message, $code, $previous); (function_exists('mb_strlen') ? mb_strlen($inn) : strlen($inn)).')', $code, $previous);
} }
} }

View File

@@ -0,0 +1,32 @@
<?php
/**
* Copyright (c) Антон Аксенов (aka Anthony Axenov)
*
* This code is licensed under MIT.
* Этот код распространяется по лицензии MIT.
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
namespace AtolOnline\Exceptions;
use Throwable;
/**
* Исключение, возникающее при работе с невалидным JSON
*
* @package AtolOnline\Exceptions
*/
class AtolInvalidJsonException extends AtolException
{
/**
* AtolInnWrongLengthException constructor.
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($message = "", $code = 0, Throwable $previous = null)
{
parent::__construct($message ?: 'Invalid JSON: ['.json_last_error().'] '.json_last_error_msg(), $code, $previous);
}
}

View File

@@ -16,10 +16,10 @@ use Throwable;
* *
* @package AtolOnline\Exceptions * @package AtolOnline\Exceptions
*/ */
class AtolUuidValidateException extends AtolException class AtolInvalidUuidException extends AtolException
{ {
/** /**
* AtolUuidValidateException constructor. * AtolInvalidUuidException constructor.
* *
* @param $uuid * @param $uuid
* @param string $message * @param string $message
@@ -28,7 +28,6 @@ class AtolUuidValidateException extends AtolException
*/ */
public function __construct($uuid, $message = "", $code = 0, Throwable $previous = null) public function __construct($uuid, $message = "", $code = 0, Throwable $previous = null)
{ {
$message = $message ?: 'Некорректный UUID: '.$uuid; parent::__construct($message ?: 'Invalid UUID: '.$uuid, $code, $previous);
parent::__construct($message, $code, $previous);
} }
} }

View File

@@ -9,8 +9,6 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке указать пустой логин ККТ * Исключение, возникающее при попытке указать пустой логин ККТ
* *
@@ -19,15 +17,7 @@ use Throwable;
class AtolKktLoginEmptyException extends AtolException class AtolKktLoginEmptyException extends AtolException
{ {
/** /**
* AtolKktLoginEmptyException constructor. * @var string Сообщение об ошибке
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($message = "", $code = 0, Throwable $previous = null) protected $message = 'KKT login cannot be empty';
{
$message = $message ?: 'Логин ККТ не может быть пустым';
parent::__construct($message, $code, $previous);
}
} }

View File

@@ -9,27 +9,15 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке указать слишком длинный логин ККТ * Исключение, возникающее при попытке указать слишком длинный логин ККТ
* *
* @package AtolOnline\Exceptions * @package AtolOnline\Exceptions
*/ */
class AtolKktLoginTooLongException extends AtolException class AtolKktLoginTooLongException extends AtolTooLongException
{ {
/** /**
* AtolKktLoginTooLongException constructor. * @var string Сообщение об ошибке
*
* @param $login
* @param $max
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($login, $max, $message = "", $code = 0, Throwable $previous = null) protected $message = 'KKT login is too long';
{
$message = $message ?: 'Слишком длинный логин ККТ (макс. длина '.$max.', фактически '.strlen($login).'): '.$login;
parent::__construct($message, $code, $previous);
}
} }

View File

@@ -9,8 +9,6 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке указать пустой пароль ККТ * Исключение, возникающее при попытке указать пустой пароль ККТ
* *
@@ -19,15 +17,7 @@ use Throwable;
class AtolKktPasswordEmptyException extends AtolException class AtolKktPasswordEmptyException extends AtolException
{ {
/** /**
* AtolKktPasswordEmptyException constructor. * @var string Сообщение об ошибке
*
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($message = "", $code = 0, Throwable $previous = null) protected $message = 'KKT password cannot be empty';
{
$message = $message ?: 'Пароль ККТ не может быть пустым';
parent::__construct($message, $code, $previous);
}
} }

View File

@@ -9,27 +9,26 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке указать слишком длинное имя * Исключение, возникающее при попытке указать слишком длинное имя
* *
* @package AtolOnline\Exceptions * @package AtolOnline\Exceptions
*/ */
class AtolNameTooLongException extends AtolException class AtolNameTooLongException extends AtolTooLongException
{ {
/** /**
* AtolNameTooLongException constructor. * @inheritDoc
*
* @param $name
* @param $max
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($name, $max, $message = "", $code = 0, Throwable $previous = null) protected $ffd_tags = [
{ 1026,
$message = $message ?: 'Слишком длинное имя/наименование (макс. длина '.$max.', фактически '.strlen($name).'): '.$name; 1030,
parent::__construct($message, $code, $previous); 1085,
} 1225,
1227,
];
/**
* @var string Сообщение об ошибке
*/
protected $message = 'Name is too long';
} }

View File

@@ -9,8 +9,6 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке указать слишком длинный платёжный адрес * Исключение, возникающее при попытке указать слишком длинный платёжный адрес
* *
@@ -19,17 +17,14 @@ use Throwable;
class AtolPaymentAddressTooLongException extends AtolException class AtolPaymentAddressTooLongException extends AtolException
{ {
/** /**
* AtolPaymentAddressTooLongException constructor. * @inheritDoc
*
* @param $address
* @param $max
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($address, $max, $message = "", $code = 0, Throwable $previous = null) protected $ffd_tags = [
{ 1187,
$message = $message ?: 'Слишком длинный адрес (макс. длина '.$max.', фактически '.strlen($address).'): '.$address; ];
parent::__construct($message, $code, $previous);
} /**
* @var string Сообщение об ошибке
*/
protected $message = 'Payment address is too long';
} }

View File

@@ -9,27 +9,26 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке указать слишком длинный телефон * Исключение, возникающее при попытке указать слишком длинный телефон
* *
* @package AtolOnline\Exceptions * @package AtolOnline\Exceptions
*/ */
class AtolPhoneTooLongException extends AtolException class AtolPhoneTooLongException extends AtolTooLongException
{ {
/** /**
* AtolPhoneTooLongException constructor. * @inheritDoc
*
* @param $phone
* @param $max
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($phone, $max, $message = "", $code = 0, Throwable $previous = null) protected $ffd_tags = [
{ 1008,
$message = $message ?: 'Слишком длинный телефон (макс. длина '.$max.', фактически '.strlen($phone).'): '.$phone; 1073,
parent::__construct($message, $code, $previous); 1074,
} 1075,
1171,
];
/**
* @var string Сообщение об ошибке
*/
protected $message = 'Phone is too long';
} }

View File

@@ -9,27 +9,22 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке указать слишком высокую цену (сумму) * Исключение, возникающее при попытке указать слишком высокую цену (сумму)
* *
* @package AtolOnline\Exceptions * @package AtolOnline\Exceptions
*/ */
class AtolPriceTooHighException extends AtolException class AtolPriceTooHighException extends AtolTooManyException
{ {
/** /**
* AtolPriceTooHighException constructor. * @inheritDoc
*
* @param $price
* @param $max
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($price, $max, $message = "", $code = 0, Throwable $previous = null) protected $ffd_tags = [
{ 1079,
$message = $message ?: 'Слишком большая сумма (макс. '.$max.'): '.$price; ];
parent::__construct($message, $code, $previous);
} /**
* @var string Сообщение об ошибке
*/
protected $message = 'Price is too high';
} }

View File

@@ -0,0 +1,40 @@
<?php
/**
* Copyright (c) Антон Аксенов (aka Anthony Axenov)
*
* This code is licensed under MIT.
* Этот код распространяется по лицензии MIT.
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/
namespace AtolOnline\Exceptions;
use Throwable;
/**
* Исключение, возникающее при попытке указать слишком длинное что-либо
*
* @package AtolOnline\Exceptions
*/
class AtolTooLongException extends AtolException
{
/**
* @var string Сообщение об ошибке
*/
protected $message = 'Parameter is too long';
/**
* AtolTooLongException constructor.
*
* @param $string
* @param $max
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/
public function __construct($string, $max, $message = "", $code = 0, Throwable $previous = null)
{
parent::__construct($message ?: $this->message.' (max length - '.$max.', actual length - '.
(function_exists('mb_strlen') ? mb_strlen($string) : strlen($string)).')', $code, $previous);
}
}

View File

@@ -12,14 +12,19 @@ namespace AtolOnline\Exceptions;
use Throwable; use Throwable;
/** /**
* Исключение, возникающее при попытке указать слишком большое количество * Исключение, возникающее при попытке указать слишком большое количество чего-либо
* *
* @package AtolOnline\Exceptions * @package AtolOnline\Exceptions
*/ */
class AtolQuantityTooHighException extends AtolException class AtolTooManyException extends AtolException
{ {
/** /**
* AtolQuantityTooHighException constructor. * @var string Сообщение об ошибке
*/
protected $message = 'Quantity is too high';
/**
* AtolTooManyException constructor.
* *
* @param $quantity * @param $quantity
* @param $max * @param $max
@@ -29,7 +34,7 @@ class AtolQuantityTooHighException extends AtolException
*/ */
public function __construct($quantity, $max, $message = "", $code = 0, Throwable $previous = null) public function __construct($quantity, $max, $message = "", $code = 0, Throwable $previous = null)
{ {
$message = $message ?: 'Слишком большое количество (макс. '.$max.'): '.$quantity; $message = $message ?: $this->message.' (max - '.$max.', actual - '.$quantity.')';
parent::__construct($message, $code, $previous); parent::__construct($message, $code, $previous);
} }
} }

View File

@@ -9,26 +9,15 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке добавить слишком много предметов расчёта в массив * Исключение, возникающее при попытке добавить слишком много предметов расчёта в массив
* *
* @package AtolOnline\Exceptions * @package AtolOnline\Exceptions
*/ */
class AtolTooManyItemsException extends AtolException class AtolTooManyItemsException extends AtolTooManyException
{ {
/** /**
* AtolTooManyItemsException constructor. * @var string Сообщение об ошибке
*
* @param int $max
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($max, $message = "", $code = 0, Throwable $previous = null) protected $message = 'Too many items';
{
$message = $message ?: 'Слишком много предметов расчёта (макс. '.$max.')';
parent::__construct($message, $code, $previous);
}
} }

View File

@@ -9,26 +9,25 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке добавить слишком много ставок НДС в массив * Исключение, возникающее при попытке добавить слишком много платежей в массив
* *
* @package AtolOnline\Exceptions * @package AtolOnline\Exceptions
*/ */
class AtolTooManyPaymentsException extends AtolException class AtolTooManyPaymentsException extends AtolTooManyException
{ {
/** /**
* AtolTooManyPaymentsException constructor. * @inheritDoc
*
* @param int $max
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($max, $message = "", $code = 0, Throwable $previous = null) protected $ffd_tags = [
{ 1031,
$message = $message ?: 'Слишком много платежей (макс. '.$max.')'; 1081,
parent::__construct($message, $code, $previous); 1215,
} 1217,
];
/**
* @var string Сообщение об ошибке
*/
protected $message = 'Too many payments';
} }

View File

@@ -9,26 +9,27 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке добавить слишком много ставок НДС в массив * Исключение, возникающее при попытке добавить слишком много ставок НДС в массив
* *
* @package AtolOnline\Exceptions * @package AtolOnline\Exceptions
*/ */
class AtolTooManyVatsException extends AtolException class AtolTooManyVatsException extends AtolTooManyException
{ {
/** /**
* AtolTooManyVatsException constructor. * @inheritDoc
*
* @param int $max
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($max, $message = "", $code = 0, Throwable $previous = null) protected $ffd_tags = [
{ 1102,
$message = $message ?: 'Слишком много ставок НДС (макс. '.$max.')'; 1103,
parent::__construct($message, $code, $previous); 1104,
} 1105,
1106,
1107,
];
/**
* @var string Сообщение об ошибке
*/
protected $message = 'Too many vats';
} }

View File

@@ -9,27 +9,22 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке указать слишком длинный телефон * Исключение, возникающее при попытке указать слишком длинный телефон
* *
* @package AtolOnline\Exceptions * @package AtolOnline\Exceptions
*/ */
class AtolUnitTooLongException extends AtolException class AtolUnitTooLongException extends AtolTooLongException
{ {
/** /**
* AtolUnitTooLongException constructor. * @inheritDoc
*
* @param $unit
* @param $max
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($unit, $max, $message = "", $code = 0, Throwable $previous = null) protected $ffd_tags = [
{ 1197,
$message = $message ?: 'Слишком длинное название единицы измерения (макс. длина '.$max.', фактически '.strlen($unit).'): '.$unit; ];
parent::__construct($message, $code, $previous);
} /**
* @var string Сообщение об ошибке
*/
protected $message = 'Measurement unit is too long';
} }

View File

@@ -9,27 +9,22 @@
namespace AtolOnline\Exceptions; namespace AtolOnline\Exceptions;
use Throwable;
/** /**
* Исключение, возникающее при попытке указать слишком длинный телефон * Исключение, возникающее при попытке указать слишком длинный дополнительный реквизит
* *
* @package AtolOnline\Exceptions * @package AtolOnline\Exceptions
*/ */
class AtolUserdataTooLongException extends AtolException class AtolUserdataTooLongException extends AtolTooLongException
{ {
/** /**
* AtolUserdataTooLongException constructor. * @inheritDoc
*
* @param $data
* @param $max
* @param string $message
* @param int $code
* @param Throwable|null $previous
*/ */
public function __construct($data, $max, $message = "", $code = 0, Throwable $previous = null) protected $ffd_tags = [
{ 1191,
$message = $message ?: 'Слишком длинный дополнительный реквизит (макс. длина '.$max.', фактически '.strlen($data).'): '.$data; ];
parent::__construct($message, $code, $previous);
} /**
* @var string Сообщение об ошибке
*/
protected $message = 'User data is too long';
} }

View File

@@ -28,7 +28,6 @@ class AtolWrongDocumentTypeException extends AtolException
*/ */
public function __construct($type, $message = "", $code = 0, Throwable $previous = null) public function __construct($type, $message = "", $code = 0, Throwable $previous = null)
{ {
$message = $message ?: 'Некорректный тип документа: ожидался \'receipt\' или \'correction\', указан \''.$type.'\''; parent::__construct($message ?: "Wrong document type: 'receipt' or 'correction' expected, but '$type' provided", $code, $previous);
parent::__construct($message, $code, $previous);
} }
} }

View File

@@ -44,7 +44,7 @@ trait HasEmail
public function setEmail(string $email) public function setEmail(string $email)
{ {
$email = trim($email); $email = trim($email);
if (strlen($email) > 64) { if ((function_exists('mb_strlen') ? mb_strlen($email) : strlen($email)) > 64) {
throw new AtolEmailTooLongException($email, 64); throw new AtolEmailTooLongException($email, 64);
} }
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

View File

@@ -7,7 +7,7 @@
* https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE * https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE
*/ */
use AtolOnline\Entities\AtolEntity; use AtolOnline\Entities\Entity;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
/** /**
@@ -28,10 +28,10 @@ class BasicTestCase extends TestCase
} }
/** /**
* @param AtolOnline\Entities\AtolEntity $entity * @param Entity $entity
* @return $this * @return $this
*/ */
public function checkAtolEntity(AtolEntity $entity) public function checkAtolEntity(Entity $entity)
{ {
$this->assertJson((string)$entity); $this->assertJson((string)$entity);
return $this; return $this;

View File

@@ -13,10 +13,9 @@ use AtolOnline\{Constants\PaymentMethods,
Entities\Item, Entities\Item,
Exceptions\AtolNameTooLongException, Exceptions\AtolNameTooLongException,
Exceptions\AtolPriceTooHighException, Exceptions\AtolPriceTooHighException,
Exceptions\AtolQuantityTooHighException, Exceptions\AtolTooManyException,
Exceptions\AtolUnitTooLongException, Exceptions\AtolUnitTooLongException,
Exceptions\AtolUserdataTooLongException Exceptions\AtolUserdataTooLongException};
};
/** /**
* Class ItemTest * Class ItemTest
@@ -28,7 +27,7 @@ class ItemTest extends BasicTestCase
* *
* @throws AtolOnline\Exceptions\AtolNameTooLongException * @throws AtolOnline\Exceptions\AtolNameTooLongException
* @throws AtolOnline\Exceptions\AtolPriceTooHighException * @throws AtolOnline\Exceptions\AtolPriceTooHighException
* @throws AtolOnline\Exceptions\AtolQuantityTooHighException * @throws AtolOnline\Exceptions\AtolTooManyException
* @throws AtolOnline\Exceptions\AtolUnitTooLongException * @throws AtolOnline\Exceptions\AtolUnitTooLongException
*/ */
public function testConstructor() public function testConstructor()
@@ -57,7 +56,7 @@ class ItemTest extends BasicTestCase
* *
* @throws AtolOnline\Exceptions\AtolNameTooLongException * @throws AtolOnline\Exceptions\AtolNameTooLongException
* @throws AtolOnline\Exceptions\AtolPriceTooHighException * @throws AtolOnline\Exceptions\AtolPriceTooHighException
* @throws AtolOnline\Exceptions\AtolQuantityTooHighException * @throws AtolOnline\Exceptions\AtolTooManyException
* @throws AtolOnline\Exceptions\AtolUnitTooLongException * @throws AtolOnline\Exceptions\AtolUnitTooLongException
* @throws AtolOnline\Exceptions\AtolUserdataTooLongException * @throws AtolOnline\Exceptions\AtolUserdataTooLongException
*/ */
@@ -88,7 +87,7 @@ class ItemTest extends BasicTestCase
* *
* @throws AtolOnline\Exceptions\AtolNameTooLongException * @throws AtolOnline\Exceptions\AtolNameTooLongException
* @throws AtolOnline\Exceptions\AtolPriceTooHighException * @throws AtolOnline\Exceptions\AtolPriceTooHighException
* @throws AtolOnline\Exceptions\AtolQuantityTooHighException * @throws AtolOnline\Exceptions\AtolTooManyException
* @throws AtolOnline\Exceptions\AtolUnitTooLongException * @throws AtolOnline\Exceptions\AtolUnitTooLongException
*/ */
public function testSetVat() public function testSetVat()
@@ -105,7 +104,7 @@ class ItemTest extends BasicTestCase
* *
* @throws AtolOnline\Exceptions\AtolNameTooLongException * @throws AtolOnline\Exceptions\AtolNameTooLongException
* @throws AtolOnline\Exceptions\AtolPriceTooHighException * @throws AtolOnline\Exceptions\AtolPriceTooHighException
* @throws AtolOnline\Exceptions\AtolQuantityTooHighException * @throws AtolOnline\Exceptions\AtolTooManyException
* @throws AtolOnline\Exceptions\AtolUnitTooLongException * @throws AtolOnline\Exceptions\AtolUnitTooLongException
*/ */
public function testAtolNameTooLongException() public function testAtolNameTooLongException()
@@ -119,14 +118,14 @@ class ItemTest extends BasicTestCase
* Тестирует исключение о слишком высоком количестве * Тестирует исключение о слишком высоком количестве
* *
* @throws AtolOnline\Exceptions\AtolNameTooLongException * @throws AtolOnline\Exceptions\AtolNameTooLongException
* @throws AtolOnline\Exceptions\AtolQuantityTooHighException * @throws AtolOnline\Exceptions\AtolTooManyException
* @throws AtolOnline\Exceptions\AtolPriceTooHighException * @throws AtolOnline\Exceptions\AtolPriceTooHighException
* @throws AtolOnline\Exceptions\AtolUnitTooLongException * @throws AtolOnline\Exceptions\AtolUnitTooLongException
*/ */
public function testAtolQuantityTooHighException() public function testAtolQuantityTooHighException()
{ {
$item = new Item(); $item = new Item();
$this->expectException(AtolQuantityTooHighException::class); $this->expectException(AtolTooManyException::class);
$item->setQuantity(100000.1); $item->setQuantity(100000.1);
} }
@@ -135,7 +134,7 @@ class ItemTest extends BasicTestCase
* *
* @throws AtolOnline\Exceptions\AtolPriceTooHighException * @throws AtolOnline\Exceptions\AtolPriceTooHighException
* @throws AtolOnline\Exceptions\AtolNameTooLongException * @throws AtolOnline\Exceptions\AtolNameTooLongException
* @throws AtolOnline\Exceptions\AtolQuantityTooHighException * @throws AtolOnline\Exceptions\AtolTooManyException
* @throws AtolOnline\Exceptions\AtolUnitTooLongException * @throws AtolOnline\Exceptions\AtolUnitTooLongException
*/ */
public function testAtolPriceTooHighException() public function testAtolPriceTooHighException()
@@ -151,7 +150,7 @@ class ItemTest extends BasicTestCase
* @throws AtolOnline\Exceptions\AtolUserdataTooLongException * @throws AtolOnline\Exceptions\AtolUserdataTooLongException
* @throws AtolOnline\Exceptions\AtolPriceTooHighException * @throws AtolOnline\Exceptions\AtolPriceTooHighException
* @throws AtolOnline\Exceptions\AtolNameTooLongException * @throws AtolOnline\Exceptions\AtolNameTooLongException
* @throws AtolOnline\Exceptions\AtolQuantityTooHighException * @throws AtolOnline\Exceptions\AtolTooManyException
* @throws AtolOnline\Exceptions\AtolUnitTooLongException * @throws AtolOnline\Exceptions\AtolUnitTooLongException
*/ */
public function testAtolUserdataTooLongException() public function testAtolUserdataTooLongException()
@@ -166,7 +165,7 @@ class ItemTest extends BasicTestCase
* *
* @throws AtolOnline\Exceptions\AtolNameTooLongException * @throws AtolOnline\Exceptions\AtolNameTooLongException
* @throws AtolOnline\Exceptions\AtolPriceTooHighException * @throws AtolOnline\Exceptions\AtolPriceTooHighException
* @throws AtolOnline\Exceptions\AtolQuantityTooHighException * @throws AtolOnline\Exceptions\AtolTooManyException
* @throws AtolOnline\Exceptions\AtolUnitTooLongException * @throws AtolOnline\Exceptions\AtolUnitTooLongException
*/ */
public function testAtolUnitTooLongException() public function testAtolUnitTooLongException()

30
tests/Unit/SchemaTest.php Normal file
View File

@@ -0,0 +1,30 @@
<?php
namespace Unit;
use AtolOnline\Api\CorrectionSchema;
use AtolOnline\Api\SellSchema;
use PHPUnit\Framework\TestCase;
class SchemaTest extends TestCase
{
/**
* Тестирует корректность работы объекта схемы документа
* прихода, возврата прихода, расхода, возврата расхода
*/
public function testSellSchema()
{
$this->assertIsObject(SellSchema::get());
$this->assertJson(SellSchema::json());
}
/**
* Тестирует корректность работы объекта схемы документа
* коррекции прихода, коррекции расхода
*/
public function testCorrectionSchema()
{
$this->assertIsObject(CorrectionSchema::get());
$this->assertJson(CorrectionSchema::json());
}
}

View File

@@ -44,8 +44,8 @@ class VatTest extends BasicTestCase
return [ return [
[VatTypes::NONE, 100, 0, 0], [VatTypes::NONE, 100, 0, 0],
[VatTypes::VAT0, 100, 0, 0], [VatTypes::VAT0, 100, 0, 0],
[VatTypes::VAT10, 100, 10, 12], [VatTypes::VAT10, 100, 9.09, 10.9],
[VatTypes::VAT18, 100, 18, 21.6], [VatTypes::VAT18, 100, 15.25, 18.3],
]; ];
} }
} }