respect-validation/library/Rules/Cnpj.php

51 lines
1.1 KiB
PHP
Raw Normal View History

2011-10-18 20:25:47 +02:00
<?php
2015-06-08 16:47:14 +02:00
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
declare(strict_types=1);
2011-10-18 20:25:47 +02:00
namespace Respect\Validation\Rules;
class Cnpj extends AbstractRule
2011-10-18 20:25:47 +02:00
{
public function validate($input): bool
2011-10-18 20:25:47 +02:00
{
2016-06-22 16:50:34 +02:00
if (!is_scalar($input)) {
return false;
}
// Code ported from jsfromhell.com
$cleanInput = preg_replace('/\D/', '', $input);
2015-10-18 03:44:47 +02:00
$b = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
2016-06-22 16:50:34 +02:00
if ($cleanInput < 1) {
return false;
}
if (14 != mb_strlen($cleanInput)) {
return false;
}
2013-01-22 20:25:34 +01:00
2016-06-22 16:50:34 +02:00
for ($i = 0, $n = 0; $i < 12; $n += $cleanInput[$i] * $b[++$i]);
2016-06-22 16:50:34 +02:00
if ($cleanInput[12] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
return false;
}
2016-06-22 16:50:34 +02:00
for ($i = 0, $n = 0; $i <= 12; $n += $cleanInput[$i] * $b[$i++]);
2016-06-22 16:50:34 +02:00
if ($cleanInput[13] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
return false;
}
2011-10-20 00:57:25 +02:00
return true;
2011-10-18 20:25:47 +02:00
}
}