saveOnTerminate example

$fields = &$normalizer_values[ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_FIELDS];
    $non_cached_fields = array_diff_key($object->getFields()$fields);
    $non_cached_requested_fields = array_intersect_key($non_cached_fieldsarray_flip($field_names));
    foreach ($non_cached_requested_fields as $field_name => $field) {
      $fields[$field_name] = $this->serializeField($field$context$format);
    }
    // Add links if missing.     $base = &$normalizer_values[ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_BASE];
    $base['links'] = $base['links'] ?? $this->serializer->normalize($object->getLinks()$format$context)->omitIfEmpty();

    if (!empty($non_cached_requested_fields)) {
      $this->cacher->saveOnTerminate($object$normalizer_values);
    }

    return $normalizer_values;
  }

  /** * Builds the empty normalization structure for cache misses. * * @param \Drupal\jsonapi\JsonApiResource\ResourceObject $object * The resource object being normalized. * * @return array * The normalization structure as defined in ::getNormalization(). * * @see ::getNormalization() */
->normalize($resource_object->getLinks(), 'api_json')
      ->withCacheableDependency((new CacheableMetadata())->addCacheTags([$cache_tag_to_invalidate]));
    assert($normalized_links instanceof CacheableNormalization);
    $normalization_parts = [
      ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_BASE => [
        'type' => CacheableNormalization::permanent($resource_object->getTypeName()),
        'id' => CacheableNormalization::permanent($resource_object->getId()),
        'links' => $normalized_links,
      ],
      ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_FIELDS => [],
    ];
    $this->cacher->saveOnTerminate($resource_object$normalization_parts);

    $http_kernel = $this->prophesize(HttpKernelInterface::class);
    $request = $this->prophesize(Request::class);
    $response = $this->prophesize(Response::class);
    $event = new TerminateEvent($http_kernel->reveal()$request->reveal()$response->reveal());
    $this->cacher->onTerminate($event);
    $this->assertNotFalse((bool) $this->cacher->get($resource_object));
    Cache::invalidateTags([$cache_tag_to_invalidate]);
    $this->assertFalse((bool) $this->cacher->get($resource_object));
  }

}
Home | Imprint | This part of the site doesn't use cookies.