You are here

public static function Link::compare in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/jsonapi/src/JsonApiResource/Link.php \Drupal\jsonapi\JsonApiResource\Link::compare()
  2. 10 core/modules/jsonapi/src/JsonApiResource/Link.php \Drupal\jsonapi\JsonApiResource\Link::compare()

Compares two links.

Parameters

\Drupal\jsonapi\JsonApiResource\Link $a: The first link.

\Drupal\jsonapi\JsonApiResource\Link $b: The second link.

Return value

int 0 if the links can be considered identical, an integer greater than or less than 0 otherwise.

3 calls to Link::compare()
Link::merge in core/modules/jsonapi/src/JsonApiResource/Link.php
Merges two equivalent links into one link with the merged cacheability.
LinkCollection::withLink in core/modules/jsonapi/src/JsonApiResource/LinkCollection.php
Gets a new LinkCollection with the given link inserted.
LinkTest::testLinkComparison in core/modules/jsonapi/tests/src/Unit/JsonApiResource/LinkTest.php
@covers ::compare @dataProvider linkComparisonProvider

File

core/modules/jsonapi/src/JsonApiResource/Link.php, line 165

Class

Link
Represents an RFC8288 based link.

Namespace

Drupal\jsonapi\JsonApiResource

Code

public static function compare(Link $a, Link $b) {

  // @todo: Remove $rel_to_string function once rel property is a single
  //   string in https://www.drupal.org/project/drupal/issues/3080467.
  $rel_to_string = function (array $rel) {

    // Sort the link relation type array so that the order of link relation
    // types does not matter during link comparison.
    sort($rel);
    return implode(' ', $rel);
  };

  // Any string concatenation would work, but a Link header-like format makes
  // it clear what is being compared.
  $a_string = sprintf('<%s>;rel="%s"', $a
    ->getHref(), $rel_to_string($a->rel));
  $b_string = sprintf('<%s>;rel="%s"', $b
    ->getHref(), $rel_to_string($b->rel));
  $cmp = strcmp($a_string, $b_string);

  // If the `href` or `rel` of the links are not equivalent, it's not
  // necessary to compare target attributes.
  if ($cmp === 0) {
    return (int) (!empty(DiffArray::diffAssocRecursive($a
      ->getTargetAttributes(), $b
      ->getTargetAttributes())));
  }
  return $cmp;
}