From 8df5e4f5536cd8461ca7a964a40ec97d90813998 Mon Sep 17 00:00:00 2001 From: Paul Vidal Date: Thu, 28 Mar 2019 12:37:41 -0500 Subject: [PATCH] =?UTF-8?q?agregada=20funci=C3=B3n=20de=20validaci=C3=B3n?= =?UTF-8?q?=20de=20digito=20de=20verificaci=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/DNI.php | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/src/DNI.php b/src/DNI.php index e277850..573543d 100644 --- a/src/DNI.php +++ b/src/DNI.php @@ -51,6 +51,11 @@ public function get($dni, $asArray = false) } } + public function validateDigit($dni, $digit) + { + return $this->validate($dni) && $this->validateHash($dni, $digit); + } + protected function validate($value) { if (is_numeric($value)) { @@ -58,4 +63,48 @@ protected function validate($value) } return false; } + + protected function validateHash($v, $h) + { + $identificationDocument = $v . '0'; + $addition = 0; + $hash = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2 ]; + $identificationDocumentLength = strlen($identificationDocument); + + $identificationComponent = substr($identificationDocument, 0, $identificationDocumentLength - 1); + + $identificationComponentLength = strlen($identificationComponent); + + $diff = count($hash) - $identificationComponentLength; + + for ($i = $identificationComponentLength - 1; $i >= 0; $i--) + { + $addition += ($identificationComponent[$i] - '0') * $hash[$i + $diff]; + } + + $addition = 11 - ($addition % 11); + + if ($addition == 11) + { + $addition = 0; + } + + $last = $identificationDocument[$identificationDocumentLength - 1]; + + $hashValue = ''; + + if (ctype_alpha($last)) + { + $hashLetters = [ 'K', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' ]; + $hashValue = $hashLetters[$addition]; + } + + else if (is_numeric($last)) + { + $hashNumbers = [ '6', '7', '8', '9', '0', '1', '1', '2', '3', '4', '5' ]; + $hashValue = $hashNumbers[$addition]; + } + + return $h == $hashValue; + } }