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