| 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 <[email protected]> |
| 10 |
* @license http://opensource.org/licenses/MIT MIT |
| 11 |
*/ |
| 12 |
|
| 13 |
declare(strict_types=1); |
| 14 |
|
| 15 |
namespace Ramsey\Uuid\Codec; |
| 16 |
|
| 17 |
use Ramsey\Uuid\Guid\Guid; |
| 18 |
use Ramsey\Uuid\UuidInterface; |
| 19 |
|
| 20 |
use function bin2hex; |
| 21 |
use function sprintf; |
| 22 |
use function substr; |
| 23 |
|
| 24 |
/** |
| 25 |
* GuidStringCodec encodes and decodes globally unique identifiers (GUID) |
| 26 |
* |
| 27 |
* @see Guid |
| 28 |
* |
| 29 |
* @immutable |
| 30 |
*/ |
| 31 |
class GuidStringCodec extends StringCodec |
| 32 |
{ |
| 33 |
public function encode(UuidInterface $uuid): string |
| 34 |
{ |
| 35 |
/** @phpstan-ignore possiblyImpure.methodCall */ |
| 36 |
$hex = bin2hex($uuid->getFields()->getBytes()); |
| 37 |
|
| 38 |
/** @var non-empty-string */ |
| 39 |
return sprintf( |
| 40 |
'%02s%02s%02s%02s-%02s%02s-%02s%02s-%04s-%012s', |
| 41 |
substr($hex, 6, 2), |
| 42 |
substr($hex, 4, 2), |
| 43 |
substr($hex, 2, 2), |
| 44 |
substr($hex, 0, 2), |
| 45 |
substr($hex, 10, 2), |
| 46 |
substr($hex, 8, 2), |
| 47 |
substr($hex, 14, 2), |
| 48 |
substr($hex, 12, 2), |
| 49 |
substr($hex, 16, 4), |
| 50 |
substr($hex, 20), |
| 51 |
); |
| 52 |
} |
| 53 |
|
| 54 |
public function decode(string $encodedUuid): UuidInterface |
| 55 |
{ |
| 56 |
/** @phpstan-ignore possiblyImpure.methodCall */ |
| 57 |
$bytes = $this->getBytes($encodedUuid); |
| 58 |
|
| 59 |
/** @phpstan-ignore possiblyImpure.methodCall, possiblyImpure.methodCall */ |
| 60 |
return $this->getBuilder()->build($this, $this->swapBytes($bytes)); |
| 61 |
} |
| 62 |
|
| 63 |
public function decodeBytes(string $bytes): UuidInterface |
| 64 |
{ |
| 65 |
// Call parent::decode() to preserve the correct byte order. |
| 66 |
return parent::decode(bin2hex($bytes)); |
| 67 |
} |
| 68 |
|
| 69 |
/** |
| 70 |
* Swaps bytes according to the GUID rules |
| 71 |
*/ |
| 72 |
private function swapBytes(string $bytes): string |
| 73 |
{ |
| 74 |
return $bytes[3] . $bytes[2] . $bytes[1] . $bytes[0] |
| 75 |
. $bytes[5] . $bytes[4] . $bytes[7] . $bytes[6] |
| 76 |
. substr($bytes, 8); |
| 77 |
} |
| 78 |
} |
| 79 |
|