2011-10-18 20:25:47 +02:00
|
|
|
<?php
|
2015-06-08 16:47:14 +02:00
|
|
|
|
2015-06-08 17:09:25 +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.
|
|
|
|
*/
|
|
|
|
|
2017-11-19 19:01:31 +01:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
2011-10-18 20:25:47 +02:00
|
|
|
namespace Respect\Validation\Rules;
|
|
|
|
|
2013-01-14 22:55:03 +01:00
|
|
|
class Cnpj extends AbstractRule
|
2011-10-18 20:25:47 +02:00
|
|
|
{
|
2018-01-28 15:41:31 +01: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];
|
2013-01-14 22:55:03 +01:00
|
|
|
|
2016-06-22 16:50:34 +02:00
|
|
|
if ($cleanInput < 1) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2017-11-19 19:01:31 +01:00
|
|
|
if (14 != mb_strlen($cleanInput)) {
|
2012-04-08 02:37:37 +02:00
|
|
|
return false;
|
2013-01-14 22:55:03 +01:00
|
|
|
}
|
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]);
|
2013-01-14 22:55:03 +01:00
|
|
|
|
2016-06-22 16:50:34 +02:00
|
|
|
if ($cleanInput[12] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
|
2012-04-08 02:37:37 +02:00
|
|
|
return false;
|
2013-01-14 22:55:03 +01:00
|
|
|
}
|
|
|
|
|
2016-06-22 16:50:34 +02:00
|
|
|
for ($i = 0, $n = 0; $i <= 12; $n += $cleanInput[$i] * $b[$i++]);
|
2013-01-14 22:55:03 +01:00
|
|
|
|
2016-06-22 16:50:34 +02:00
|
|
|
if ($cleanInput[13] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
|
2012-04-08 02:37:37 +02:00
|
|
|
return false;
|
2013-01-14 22:55:03 +01:00
|
|
|
}
|
|
|
|
|
2011-10-20 00:57:25 +02:00
|
|
|
return true;
|
2011-10-18 20:25:47 +02:00
|
|
|
}
|
|
|
|
}
|