Skip to content

Commit

Permalink
Inn Validation
Browse files Browse the repository at this point in the history
  • Loading branch information
ruark committed Apr 16, 2024
1 parent 0f7cdd3 commit c8c92b3
Show file tree
Hide file tree
Showing 7 changed files with 239 additions and 15 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Yurii Lysyanskii

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
10 changes: 8 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
{
"name": "ruark/laravel-inn",
"description": "INN validation",
"keywords": [
"inn",
"validation",
"laravel"
],
"license": "MIT",
"authors": [
{
"name": "Yuriy Ruark",
"name": "Yuriy Lysyanskii",
"email": "[email protected]"
}
],
"require": {
"php": "^7.4"
"php": "^7.4.0",
"laravel/framework": "^5.8.0"
},
"autoload": {
"psr-4": {
Expand Down
14 changes: 14 additions & 0 deletions src/Exceptions/InnValidationException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Ruark\LaravelInn\Exceptions;

use Exception;
use Throwable;

class InnValidationException extends Exception
{
public function __construct($message = "", $code = 0, Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}
32 changes: 32 additions & 0 deletions src/InnServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace Ruark\LaravelInn;

use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Support\ServiceProvider;

class InnServiceProvider extends ServiceProvider
{
/**
* @return void
* @throws BindingResolutionException
*/
public function boot(): void
{
$this->publishes([
__DIR__ . '/config/inn.php' => config_path('inn.php'),
]);

$validator = $this->app->make('validator');
$validator->extend('inn', function ($attribute, $value, $parameters) {
return (new InnValidator)->validate($value, $parameters);
}, InnValidator::getMessageBag());
}

public function register(): void
{
$this->mergeConfigFrom(
__DIR__ . '/config/inn.php', 'inn'
);
}
}
154 changes: 154 additions & 0 deletions src/InnValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
<?php

namespace Ruark\LaravelInn;

use Ruark\LaravelInn\Exceptions\InnValidationException;

class InnValidator
{
private ?string $belonging = null;

/**
* @throws InnValidationException
*/
public function validate(?string $value, array $parameters): bool
{
// l - legal, i - individual, null - all
$spec = $parameters[0] ?? null;
if ($spec && !in_array($spec, ['i', 'l'])) {
throw new InnValidationException(('Invalid inn validation specification "' . $spec . '"'));
}
if (!$this->validateCommonInn($value)) {
return false;
}

if ($this->belonging === 'legal' && ($spec === 'l' || !$spec)) {
return $this->validateLegalInn($value);
}

if ($this->belonging === 'individual' && ($spec === 'i' || !$spec)) {
return $this->validateIndividualInn($value);
}

return false;
}

/**
* Сообщение при ошибке валидации
* @return string
*/
public static function getMessageBag(): string
{
$lang = __('validation.inn');
if (!$lang || $lang == 'validation.inn') {
return config('inn.default_validation_message');
}
return $lang;
}

/**
* Валидация общих признаков
* @param string|null $value
* @return bool
*/
protected function validateCommonInn(?string $value): bool
{
if (!$value || !is_numeric($value)) {
return false;
}
if (!$this->defineBelonging($value)) {
return false;
}
return true;
}

/**
* Проверка контрольной суммы для ИНН физического лица
* @param string $value
* @return bool
* @throws InnValidationException
*/
protected function validateIndividualInn(string $value): bool
{
if (strlen($value) !== 12) {
return false;
}

$weight_1 = $this->calcInnWeight($value, [7, 2, 4, 10, 3, 5, 9, 4, 6, 8, 0]);
$weight_1 = $weight_1 % 11;
if ($weight_1 > 9) {
$weight_1 = $weight_1 % 10;
}

$weight_2 = $this->calcInnWeight($value, [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8, 0]);
$weight_2 = $weight_2 % 11;
if ($weight_2 > 9) {
$weight_2 = $weight_2 % 10;
}

if ($weight_1 != $value[10] || $weight_2 != $value[11]) {
return false;
}

return true;
}

/**
* Проверка контрольной суммы для ИНН юридического лица
* @param string $value
* @return bool
* @throws InnValidationException
*/
protected function validateLegalInn(string $value): bool
{
if (strlen($value) !== 10) {
return false;
}

$weight = $this->calcInnWeight($value, [2, 4, 10, 3, 5, 9, 4, 6, 8, 0]);
$weight = $weight % 11;
if ($weight > 9) {
$weight = $weight % 10;
}

if ($weight != $value[9]) {
return false;
}
return true;
}

/**
* Расчет веса ИНН с учетом весового коэффициента
* @param string $value
* @param array $rule
* @return int
* @throws InnValidationException
*/
public function calcInnWeight(string $value, array $rule): int
{
if (count($rule) > strlen($value)) {
throw new InnValidationException('Invalid rule length for this value');
}

$result = 0;
foreach ($rule as $index => $w) {
$result += (int)$value[$index] * $w;
}
return $result;
}

/**
* @param string $value
* @return bool
*/
protected function defineBelonging(string $value): bool
{
$rules = config('inn.len_rules ');
$len = strlen($value);
if (array_key_exists($len, $rules)) {
$this->belonging = $rules[$len];
return true;
}
return false;
}
}
13 changes: 0 additions & 13 deletions src/InnValidatorServiceProvider.php

This file was deleted.

10 changes: 10 additions & 0 deletions src/config/inn.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

return [
'default_validation_message' => 'The :attribute has an invalid INN.',

'len_rules ' => [
10 => 'legal',
12 => 'individual',
]
];

0 comments on commit c8c92b3

Please sign in to comment.