Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 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
 
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
 * @psalm-immutable
30
 */
31
class GuidStringCodec extends StringCodec
32
{
33
    public function encode(UuidInterface $uuid): string
34
    {
35
        $hex = bin2hex($uuid->getFields()->getBytes());
36
 
37
        /** @var non-empty-string */
38
        return sprintf(
39
            '%02s%02s%02s%02s-%02s%02s-%02s%02s-%04s-%012s',
40
            substr($hex, 6, 2),
41
            substr($hex, 4, 2),
42
            substr($hex, 2, 2),
43
            substr($hex, 0, 2),
44
            substr($hex, 10, 2),
45
            substr($hex, 8, 2),
46
            substr($hex, 14, 2),
47
            substr($hex, 12, 2),
48
            substr($hex, 16, 4),
49
            substr($hex, 20),
50
        );
51
    }
52
 
53
    public function decode(string $encodedUuid): UuidInterface
54
    {
55
        $bytes = $this->getBytes($encodedUuid);
56
 
57
        return $this->getBuilder()->build($this, $this->swapBytes($bytes));
58
    }
59
 
60
    public function decodeBytes(string $bytes): UuidInterface
61
    {
62
        // Specifically call parent::decode to preserve correct byte order
63
        return parent::decode(bin2hex($bytes));
64
    }
65
 
66
    /**
67
     * Swaps bytes according to the GUID rules
68
     */
69
    private function swapBytes(string $bytes): string
70
    {
71
        return $bytes[3] . $bytes[2] . $bytes[1] . $bytes[0]
72
            . $bytes[5] . $bytes[4]
73
            . $bytes[7] . $bytes[6]
74
            . substr($bytes, 8);
75
    }
76
}