function LinkCollection::withLink

Same name in other branches
  1. 9 core/modules/jsonapi/src/JsonApiResource/LinkCollection.php \Drupal\jsonapi\JsonApiResource\LinkCollection::withLink()
  2. 8.9.x core/modules/jsonapi/src/JsonApiResource/LinkCollection.php \Drupal\jsonapi\JsonApiResource\LinkCollection::withLink()
  3. 11.x core/modules/jsonapi/src/JsonApiResource/LinkCollection.php \Drupal\jsonapi\JsonApiResource\LinkCollection::withLink()

Gets a new LinkCollection with the given link inserted.

Parameters

string $key: A key for the link. If the key already exists and the link shares an href, link relation type and attributes with an existing link with that key, those links will be merged together.

\Drupal\jsonapi\JsonApiResource\Link $new_link: The link to insert.

Return value

static A new LinkCollection with the given link inserted or merged with the current set of links.

File

core/modules/jsonapi/src/JsonApiResource/LinkCollection.php, line 85

Class

LinkCollection
Contains a set of JSON:API Link objects.

Namespace

Drupal\jsonapi\JsonApiResource

Code

public function withLink($key, Link $new_link) {
    assert(static::validKey($key));
    $merged = $this->links;
    if (isset($merged[$key])) {
        foreach ($merged[$key] as $index => $existing_link) {
            if (Link::compare($existing_link, $new_link) === 0) {
                $merged[$key][$index] = Link::merge($existing_link, $new_link);
                return new static($merged, $this->context);
            }
        }
    }
    $merged[$key][] = $new_link;
    return new static($merged, $this->context);
}

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