. */ declare(strict_types=1); namespace Fisharebest\Webtrees\Elements; use Fisharebest\Webtrees\Tree; use Ramsey\Uuid\Exception\RandomSourceException; use Ramsey\Uuid\Uuid; use function dechex; use function hexdec; use function strtoupper; use function strtr; use function substr; /** * _UID fields, as created by PAF and other applications */ class PafUid extends AbstractElement { protected const MAXIMUM_LENGTH = 34; /** * Create a default value for this element. * * @param Tree $tree * * @return string */ public function default(Tree $tree): string { try { $uid = strtr(Uuid::uuid4()->toString(), ['-' => '']); } catch (RandomSourceException $ex) { // uuid4() can fail if there is insufficient entropy in the system. return ''; } $checksum_a = 0; // a sum of the bytes $checksum_b = 0; // a sum of the incremental values of $checksum_a // Compute checksums for ($i = 0; $i < 32; $i += 2) { $checksum_a += hexdec(substr($uid, $i, 2)); $checksum_b += $checksum_a & 0xff; } $uid .= substr('0' . dechex($checksum_a), -2); $uid .= substr('0' . dechex($checksum_b), -2); return strtoupper($uid); } }