1<?php 2 3/** 4 * This file is part of the ramsey/uuid library 5 * 6 * For the full copyright and license information, please view the LICENSE 7 * file that was distributed with this source code. 8 * 9 * @copyright Copyright (c) Ben Ramsey <ben@benramsey.com> 10 * @license http://opensource.org/licenses/MIT MIT 11 */ 12 13declare(strict_types=1); 14 15namespace Ramsey\Uuid\Type; 16 17use Ramsey\Uuid\Exception\InvalidArgumentException; 18 19use function ctype_xdigit; 20use function strpos; 21use function strtolower; 22use function substr; 23 24/** 25 * A value object representing a hexadecimal number 26 * 27 * This class exists for type-safety purposes, to ensure that hexadecimal numbers 28 * returned from ramsey/uuid methods as strings are truly hexadecimal and not some 29 * other kind of string. 30 * 31 * @psalm-immutable 32 */ 33final class Hexadecimal implements TypeInterface 34{ 35 /** 36 * @var string 37 */ 38 private $value; 39 40 /** 41 * @param string $value The hexadecimal value to store 42 */ 43 public function __construct(string $value) 44 { 45 $value = strtolower($value); 46 47 if (strpos($value, '0x') === 0) { 48 $value = substr($value, 2); 49 } 50 51 if (!ctype_xdigit($value)) { 52 throw new InvalidArgumentException( 53 'Value must be a hexadecimal number' 54 ); 55 } 56 57 $this->value = $value; 58 } 59 60 public function toString(): string 61 { 62 return $this->value; 63 } 64 65 public function __toString(): string 66 { 67 return $this->toString(); 68 } 69 70 public function jsonSerialize(): string 71 { 72 return $this->toString(); 73 } 74 75 public function serialize(): string 76 { 77 return $this->toString(); 78 } 79 80 /** 81 * Constructs the object from a serialized string representation 82 * 83 * @param string $serialized The serialized string representation of the object 84 * 85 * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint 86 */ 87 public function unserialize($serialized): void 88 { 89 $this->__construct($serialized); 90 } 91} 92