function LinkCollectionNormalizer::hashByHref

Same name and namespace in other branches
  1. 9 core/modules/jsonapi/src/Normalizer/LinkCollectionNormalizer.php \Drupal\jsonapi\Normalizer\LinkCollectionNormalizer::hashByHref()
  2. 8.9.x core/modules/jsonapi/src/Normalizer/LinkCollectionNormalizer.php \Drupal\jsonapi\Normalizer\LinkCollectionNormalizer::hashByHref()
  3. 10 core/modules/jsonapi/src/Normalizer/LinkCollectionNormalizer.php \Drupal\jsonapi\Normalizer\LinkCollectionNormalizer::hashByHref()

Hashes a link using its href and its target attributes, if any.

This method generates an unpredictable, but deterministic, 7 character alphanumeric hash for a given link.

The hash is unpredictable because a random hash salt will be used for every request. The hash is deterministic because, within a single request, links with the same href and target attributes (i.o.w. duplicates) will generate equivalent hash values.

Parameters

\Drupal\jsonapi\JsonApiResource\Link $link: A link to be hashed.

Return value

string A 7 character alphanumeric hash.

1 call to LinkCollectionNormalizer::hashByHref()
LinkCollectionNormalizer::normalize in core/modules/jsonapi/src/Normalizer/LinkCollectionNormalizer.php

File

core/modules/jsonapi/src/Normalizer/LinkCollectionNormalizer.php, line 128

Class

LinkCollectionNormalizer
Normalizes a LinkCollection object.

Namespace

Drupal\jsonapi\Normalizer

Code

protected function hashByHref(Link $link) {
    // Generate a salt unique to each instance of this class.
    if (!$this->hashSalt) {
        $this->hashSalt = Crypt::randomBytesBase64();
    }
    // Create a dictionary of link parameters.
    $link_parameters = [
        'href' => $link->getHref(),
    ] + $link->getTargetAttributes();
    // Serialize the dictionary into a string.
    foreach ($link_parameters as $name => $value) {
        $serialized_parameters[] = sprintf('%s="%s"', $name, implode(' ', (array) $value));
    }
    // Hash the string.
    $b64_hash = Crypt::hashBase64($this->hashSalt . implode('; ', $serialized_parameters));
    // Remove any dashes and underscores from the base64 hash and then return
    // the first 7 characters.
    return substr(str_replace([
        '-',
        '_',
    ], '', $b64_hash), 0, 7);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.