Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. GuidStringCodec.php

class GuidStringCodec

GuidStringCodec encodes and decodes globally unique identifiers (GUID)

@psalm-immutable

Hierarchy

  • class \Ramsey\Uuid\Codec\StringCodec implements \Ramsey\Uuid\Codec\CodecInterface
    • class \Ramsey\Uuid\Codec\GuidStringCodec extends \Ramsey\Uuid\Codec\StringCodec

Expanded class hierarchy of GuidStringCodec

See also

Guid

1 file declares its use of GuidStringCodec
FeatureSet.php in vendor/ramsey/uuid/src/FeatureSet.php

File

vendor/ramsey/uuid/src/Codec/GuidStringCodec.php, line 31

Namespace

Ramsey\Uuid\Codec
View source
class GuidStringCodec extends StringCodec {
    public function encode(UuidInterface $uuid) : string {
        $hex = bin2hex($uuid->getFields()
            ->getBytes());
        
        /** @var non-empty-string */
        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));
    }
    public function decode(string $encodedUuid) : UuidInterface {
        $bytes = $this->getBytes($encodedUuid);
        return $this->getBuilder()
            ->build($this, $this->swapBytes($bytes));
    }
    public function decodeBytes(string $bytes) : UuidInterface {
        // Specifically call parent::decode to preserve correct byte order
        return parent::decode(bin2hex($bytes));
    }
    
    /**
     * Swaps bytes according to the GUID rules
     */
    private function swapBytes(string $bytes) : string {
        return $bytes[3] . $bytes[2] . $bytes[1] . $bytes[0] . $bytes[5] . $bytes[4] . $bytes[7] . $bytes[6] . substr($bytes, 8);
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
GuidStringCodec::decode public function @inheritDoc Overrides StringCodec::decode
GuidStringCodec::decodeBytes public function Returns a UuidInterface derived from a binary string representation Overrides StringCodec::decodeBytes
GuidStringCodec::encode public function Returns a hexadecimal string representation of a UuidInterface Overrides StringCodec::encode
GuidStringCodec::swapBytes private function Swaps bytes according to the GUID rules
StringCodec::encodeBinary public function @psalm-return non-empty-string
@psalm-suppress MoreSpecificReturnType we know that the retrieved `string` is never empty
@psalm-suppress LessSpecificReturnStatement we know that the retrieved `string` is never empty
Overrides CodecInterface::encodeBinary 2
StringCodec::getBuilder protected function Returns the UUID builder
StringCodec::getBytes protected function Returns a byte string of the UUID
StringCodec::__construct public function Constructs a StringCodec
RSS feed
Powered by Drupal