LinkCollection loses cacheability metadata when adding a link

Created on 26 June 2025, 1 day ago

Problem/Motivation

LinkCollection loses cacheability metadata when adding a link using \Drupal\jsonapi\JsonApiResource\LinkCollection::withLink()

Adding a new link actually creates a new collection. If we added any cacheability metadata to the collection, that will be lost on the returned new collection.

Steps to reproduce

pseudo code

$link1 = new Link(cache_tag_1)
$link2 = new Link(cache_tag_2)
$collection = new LinkCollection([cache_tag_1]);
$collection->addCacheTags([cache_tag_A, cache_tag_B]);
$collection = $collection->withLink($link2);

// $collection should have cache_tag_1, cache_tag_2, cache_tag_A, cache_tag_B but only keeps cache_tag_1, cache_tag_2

Proposed resolution

Similar to

  public function withLink(string $key, ResourceLink $new_link): ResourceLinkCollection {
    $merged = $this->links;
    if (isset($merged[$key])) {
      if (ResourceLink::compare($merged[$key], $new_link) === 0) {
        $merged[$key] = ResourceLink::merge($merged[$key], $new_link);
      }
    }
    else {
      $merged[$key] = $new_link;
    }
    $collection = new static($merged);
    // We need to keep existing cache metadata added to the collection object
    // for e.g. absent links.
    $collection->addCacheTags($this->getCacheTags())
      ->addCacheContexts($this->getCacheContexts())
      ->mergeCacheMaxAge($this->getCacheMaxAge());
    return $collection;
  }

Remaining tasks

MR + tests.

User interface changes

None.

Introduced terminology

None.

API changes

None.

Data model changes

None.

Release notes snippet

None.

🐛 Bug report
Status

Active

Version

11.0 🔥

Component

jsonapi.module

Created by

🇪🇸Spain penyaskito Seville 💃, Spain 🇪🇸, UTC+2 🇪🇺

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024