Skip to content

Instantly share code, notes, and snippets.

@theotherdy theotherdy/Orcid.php
Created Jul 31, 2018

Embed
What would you like to do?
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Orcid implements Rule
{
/**
* Create a new rule instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* @param string $attribute
* @param mixed $value
* @return bool
*/
public function passes($attribute, $value)
{
$urlParts = explode("/",$value);
// get last digit
$lastDigit = substr($urlParts[count($urlParts) - 1],-1);
// let's get numbers from last part (removing any hyphens, etc)
$orcidDigits = preg_replace('/\D/', '', $urlParts[count($urlParts) - 1]);
// strip last digit
$baseDigits = substr($orcidDigits, 0, -1);
// get check digit - 0-9 or X
$generatedCheckDigit = $this->generateCheckDigit($baseDigits);
return $generatedCheckDigit === $lastDigit;
}
/**
* Get the validation error message.
*
* @return string
*/
public function message()
{
return 'The 16-digit number in the ORCID ID must have the correct checksum - please check it carefully';
}
/**
* Generates check digit as per ISO 7064 11,2 - see https://support.orcid.org/knowledgebase/articles/116780-structure-of-the-orcid-identifier
*
*/
private function generateCheckDigit($baseDigits) {
$total = 0;
for ($i = 0; $i < strlen($baseDigits); $i++) {
$digit = intval(substr($baseDigits,$i,1));
$total = ($total + $digit) * 2;
}
$remainder = $total % 11;
$result = (12 - $remainder) % 11;
if($result == 10) {
return "X";
} else {
return strval($result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.