You are here

public function LinkCollection::withLink in JSON:API 8.2

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 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

src/JsonApiResource/LinkCollection.php, line 83

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