2012-11-26 01:22:59 +01: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>
|
|
|
|
*
|
2019-05-23 16:21:34 +02:00
|
|
|
* For the full copyright and license information, please view the LICENSE file
|
|
|
|
* that was distributed with this source code.
|
2015-06-08 17:09:25 +02:00
|
|
|
*/
|
|
|
|
|
2017-11-19 19:01:31 +01:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
2012-11-26 01:22:59 +01:00
|
|
|
namespace Respect\Validation\Rules;
|
|
|
|
|
2018-06-10 18:48:03 +02:00
|
|
|
use function is_scalar;
|
|
|
|
use function mb_strlen;
|
|
|
|
use function preg_replace;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Validates a Brazilian driver's license.
|
|
|
|
*
|
|
|
|
* @author Gabriel Pedro <gpedro@users.noreply.github.com>
|
|
|
|
* @author Henrique Moody <henriquemoody@gmail.com>
|
|
|
|
* @author Kinn Coelho Julião <kinncj@gmail.com>
|
|
|
|
* @author William Espindola <oi@williamespindola.com.br>
|
|
|
|
*/
|
|
|
|
final class Cnh extends AbstractRule
|
2012-11-26 01:22:59 +01:00
|
|
|
{
|
2018-06-10 18:48:03 +02:00
|
|
|
/**
|
2019-04-05 14:33:00 +02:00
|
|
|
* {@inheritDoc}
|
2018-06-10 18:48:03 +02:00
|
|
|
*/
|
2018-01-28 15:41:31 +01:00
|
|
|
public function validate($input): bool
|
2012-11-26 01:22:59 +01:00
|
|
|
{
|
2016-05-13 16:20:11 +02:00
|
|
|
if (!is_scalar($input)) {
|
|
|
|
return false;
|
2012-11-26 01:22:59 +01:00
|
|
|
}
|
2013-01-14 22:55:03 +01:00
|
|
|
|
2016-05-13 16:20:11 +02:00
|
|
|
// Canonicalize input
|
2020-07-22 14:02:39 +02:00
|
|
|
$input = (string) preg_replace('{\D}', '', (string) $input);
|
2016-05-13 16:20:11 +02:00
|
|
|
|
|
|
|
// Validate length and invalid numbers
|
2019-02-09 13:28:08 +01:00
|
|
|
if (mb_strlen($input) != 11 || ((int) $input === 0)) {
|
2016-05-13 16:20:11 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Validate check digits using a modulus 11 algorithm
|
|
|
|
for ($c = $s1 = $s2 = 0, $p = 9; $c < 9; $c++, $p--) {
|
2018-06-10 18:48:03 +02:00
|
|
|
$s1 += (int) $input[$c] * $p;
|
|
|
|
$s2 += (int) $input[$c] * (10 - $p);
|
2016-05-13 16:20:11 +02:00
|
|
|
}
|
|
|
|
|
2019-02-09 12:15:13 +01:00
|
|
|
$dv1 = $s1 % 11;
|
|
|
|
if ($input[9] != ($dv1 > 9) ? 0 : $dv1) {
|
2016-05-13 16:20:11 +02:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2019-02-09 12:45:53 +01:00
|
|
|
$dv2 = $s2 % 11 - ($dv1 > 9 ? 2 : 0);
|
2020-04-04 22:13:44 +02:00
|
|
|
$check = $dv2 < 0 ? $dv2 + 11 : ($dv2 > 9 ? 0 : $dv2);
|
2016-05-13 16:20:11 +02:00
|
|
|
|
2019-02-09 14:00:53 +01:00
|
|
|
return $input[10] == $check;
|
2012-11-26 01:22:59 +01:00
|
|
|
}
|
2013-01-14 22:55:03 +01:00
|
|
|
}
|