You are here

protected function LinkCollectionNormalizer::hashByHref in Drupal 9

Same name and namespace in other branches
  1. 8 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 137

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);
}