getNormalization example


  public static function aggregate(array $cacheable_normalizations) {
    assert(Inspector::assertAllObjects($cacheable_normalizations, CacheableNormalization::class));
    return new static(
      array_reduce($cacheable_normalizationsfunction DCacheableMetadata $merged, CacheableNormalization $item) {
        return $merged->addCacheableDependency($item);
      }new CacheableMetadata()),
      array_reduce(array_keys($cacheable_normalizations)function D$merged$key) use ($cacheable_normalizations) {
        if (!$cacheable_normalizations[$key] instanceof CacheableOmission) {
          $merged[$key] = $cacheable_normalizations[$key]->getNormalization();
        }
        return $merged;
      }[])
    );
  }

  /** * Ensures that no nested values are instances of this class. * * @param array|\Traversable $array * The traversable object which may contain instance of this object. * * @return bool * Whether the given object or its children have CacheableNormalizations in * them. */
$resource_type_name = $resource_type->getTypeName();
    $fields = $object->getFields();
    // Get the bundle ID of the requested resource. This is used to determine if     // this is a bundle level resource or an entity level resource.     if (!empty($context['sparse_fieldset'][$resource_type_name])) {
      $field_names = $context['sparse_fieldset'][$resource_type_name];
    }
    else {
      $field_names = array_keys($fields);
    }

    $normalization_parts = $this->getNormalization($field_names$object$format$context);

    // Keep only the requested fields (the cached normalization gradually grows     // to the complete set of fields).     $fields = $normalization_parts[ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_FIELDS];
    $field_normalizations = array_intersect_key($fieldsarray_flip($field_names));

    $relationship_field_names = array_keys($resource_type->getRelatableResourceTypes());
    $attributes = array_diff_key($field_normalizationsarray_flip($relationship_field_names));
    $relationships = array_intersect_key($field_normalizationsarray_flip($relationship_field_names));
    $entity_normalization = array_filter(
      $normalization_parts[ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_BASE] + [
        

  public function testNormalizeFieldItemWithoutProperties(): void {
    $item = $this->prophesize(FieldItemInterface::class);
    $item->getProperties(TRUE)->willReturn([]);
    $item->getValue()->willReturn('Direct call to getValue');

    $result = $this->normalizer->normalize($item->reveal(), 'api_json');
    assert($result instanceof CacheableNormalization);
    $this->assertSame('Direct call to getValue', $result->getNormalization());
  }

  /** * Tests normalizing field item. */
  public function testNormalizeFieldItem(): void {
    $entity = EntityTest::create([
      'name' => 'Test entity',
      'links' => [
        [
          'uri' => 'https://www.drupal.org',
          

  protected function normalize(EntityInterface $entity, Url $url) {
    // Don't use cached normalizations in tests.     $this->container->get('cache.jsonapi_normalizations')->deleteAll();

    $self_link = new Link(new CacheableMetadata()$url, 'self');
    $resource_type = $this->container->get('jsonapi.resource_type.repository')->getByTypeName(static::$resourceTypeName);
    $doc = new JsonApiDocumentTopLevel(new ResourceObjectData([ResourceObject::createFromEntity($resource_type$entity)], 1)new NullIncludedData()new LinkCollection(['self' => $self_link]));
    return $this->serializer->normalize($doc, 'api_json', [
      'resource_type' => $resource_type,
      'account' => $this->account,
    ])->getNormalization();
  }

  /** * Creates the entity to be tested. * * @return \Drupal\Core\Entity\EntityInterface * The entity to be tested. */
  abstract protected function createEntity();

  /** * Creates another entity to be tested. * * @param mixed $key * A unique key to be used for the ID and/or label of the duplicated entity. * * @return \Drupal\Core\Entity\EntityInterface * Another entity based on $this->entity. * * @throws \Drupal\Core\Entity\EntityStorageException */
return $value;
    }
    if (is_array($value)) {
      $output = [];
      foreach ($value as $key => $item) {
        $output[$key] = static::rasterizeValueRecursive($item);
      }

      return $output;
    }
    if ($value instanceof CacheableNormalization) {
      return $value->getNormalization();
    }
    // If the object can be turned into a string it's better than nothing.     if (method_exists($value, '__toString')) {
      return $value->__toString();
    }

    // We give up, since we do not know how to rasterize this.     return NULL;
  }

  /** * {@inheritdoc} */
if ($data instanceof ErrorCollection) {
      $document['errors'] = $this->normalizeErrorDocument($object$format$context);
    }
    else {
      // Add data.       $document['data'] = $this->serializer->normalize($data$format$context);
      // Add includes.       $document['included'] = $this->serializer->normalize($object->getIncludes()$format$context)->omitIfEmpty();
      // Add omissions and metadata.       $normalized_omissions = $this->normalizeOmissionsLinks($object->getOmissions()$format$context);
      $meta = !$normalized_omissions instanceof CacheableOmission
        ? array_merge($object->getMeta()['omitted' => $normalized_omissions->getNormalization()])
        : $object->getMeta();
      $document['meta'] = (new CacheableNormalization($normalized_omissions$meta))->omitIfEmpty();
    }
    // Add document links.     $document['links'] = $this->serializer->normalize($object->getLinks()$format$context)->omitIfEmpty();
    // Every JSON:API document contains absolute URLs.     return CacheableNormalization::aggregate($document)->withCacheableDependency((new CacheableMetadata())->addCacheContexts(['url.site']));
  }

  /** * Normalizes an error collection. * * @param \Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel $document * The document to normalize. * @param string $format * The normalization format. * @param array $context * The normalization context. * * @return \Drupal\jsonapi\Normalizer\Value\CacheableNormalization * The normalized document. * * @todo: refactor this to use CacheableNormalization::aggregate in https://www.drupal.org/project/drupal/issues/3036284. */
$config = $this->prophesize(ImmutableConfig::class);
    $config->get('error_level')->willReturn(ERROR_REPORTING_DISPLAY_VERBOSE);
    $config_factory = $this->prophesize(ConfigFactory::class);
    $config_factory->get('system.logging')->willReturn($config->reveal());
    $container->get('config.factory')->willReturn($config_factory->reveal());
    \Drupal::setContainer($container->reveal());
    $exception = new AccessDeniedHttpException('lorem', NULL, 13);
    $current_user = $this->prophesize(AccountInterface::class);
    $current_user->hasPermission('access site reports')->willReturn(TRUE);
    $normalizer = new HttpExceptionNormalizer($current_user->reveal());
    $normalized = $normalizer->normalize($exception, 'api_json');
    $normalized = $normalized->getNormalization();
    $error = $normalized[0];
    $this->assertNotEmpty($error['meta']);
    $this->assertNotEmpty($error['source']);
    $this->assertSame('13', $error['code']);
    $this->assertSame('403', $error['status']);
    $this->assertEquals('Forbidden', $error['title']);
    $this->assertEquals('lorem', $error['detail']);
    $this->assertArrayHasKey('trace', $error['meta']);
    $this->assertNotEmpty($error['meta']['trace']);

    $current_user = $this->prophesize(AccountInterface::class);
    

    $normalized_items = CacheableNormalization::aggregate($this->serializer->normalize($resource_identifiers$format$context));
    assert($context['resource_object'] instanceof ResourceObject);
    $resource_relationship = $context['resource_object']->getResourceType()->getFieldByInternalName($field->getName());
    assert($resource_relationship instanceof ResourceTypeRelationship);
    $link_cacheability = new CacheableMetadata();
    $links = array_map(function DUrl $link) use ($link_cacheability) {
      $href = $link->setAbsolute()->toString(TRUE);
      $link_cacheability->addCacheableDependency($href);
      return ['href' => $href->getGeneratedUrl()];
    }static::getRelationshipLinks($context['resource_object']$resource_relationship));
    $data_normalization = $normalized_items->getNormalization();
    $normalization = [
      // Empty 'to-one' relationships must be NULL.       // Empty 'to-many' relationships must be an empty array.       // @link http://jsonapi.org/format/#document-resource-object-linkage       'data' => $resource_relationship->hasOne() ? array_shift($data_normalization) : $data_normalization,
    ];
    if (!empty($links)) {
      $normalization['links'] = $links;
    }
    return (new CacheableNormalization($normalized_items$normalization))->withCacheableDependency($link_cacheability);
  }

  
      // @see \Drupal\jsonapi\EventSubscriber\DefaultExceptionSubscriber::isJsonApiExceptionEvent()       $context = !$response->isSuccessful() ? [] : static::generateContext($request);
      $jsonapi_doc_object = $serializer->normalize($data$format$context);
      // Having just normalized the data, we can associate its cacheability with       // the response object.       if ($response instanceof CacheableResponseInterface) {
        assert($jsonapi_doc_object instanceof CacheableNormalization);
        $response->addCacheableDependency($jsonapi_doc_object);
      }
      // Finally, encode the normalized data (JSON:API's encoder rasterizes it       // automatically).       $response->setContent($serializer->encode($jsonapi_doc_object->getNormalization()$format));
      $response->headers->set('Content-Type', $request->getMimeType($format));
    }
  }

  /** * Generates a top-level JSON:API normalization context. * * @param \Symfony\Component\HttpFoundation\Request $request * The request from which the context can be derived. * * @return array * The generated context. */
/** * Tests the link collection normalizer. */
  public function testNormalize() {
    $link_context = new ResourceObject(new CacheableMetadata()new ResourceType('n/a', 'n/a', 'n/a'), 'n/a', NULL, []new LinkCollection([]));
    $link_collection = (new LinkCollection([]))
      ->withLink('related', new Link(new CacheableMetadata(), Url::fromUri('http://example.com/post/42'), 'related', ['title' => 'Most viewed']))
      ->withLink('related', new Link(new CacheableMetadata(), Url::fromUri('http://example.com/post/42'), 'related', ['title' => 'Top rated']))
      ->withContext($link_context);
    // Create the SUT.     $normalized = $this->getNormalizer()->normalize($link_collection)->getNormalization();
    $this->assertIsArray($normalized);
    foreach (array_keys($normalized) as $key) {
      $this->assertStringStartsWith('related', $key);
    }
    $this->assertSame([
      [
        'href' => 'http://example.com/post/42',
        'meta' => [
          'title' => 'Most viewed',
        ],
      ],
      [
$value['title'] = 'My spirit animal 😍';
          break;
      }
      return $value;
    }$entity_property_names);
    $resource_object = ResourceObject::createFromEntity($this->referencingResourceType, $this->referencer);
    $relationship = Relationship::createFromEntityReferenceField($resource_object$resource_object->getField($field_name));
    // Normalize.     $actual = $this->normalizer->normalize($relationship, 'api_json');
    // Assert.     assert($actual instanceof CacheableNormalization);
    $this->assertEquals($expected$actual->getNormalization());
  }

  /** * Data provider for testNormalize. */
  public function normalizeProvider() {
    return [
      'single cardinality' => [
        ['user1'],
        'field_user',
        [
          
'user--user' => [
              'display_name',
            ],
          ],
          'include' => [
            'uid',
            'field_tags',
            'field_image',
          ],
        ]
      );
    $normalized = $jsonapi_doc_object->getNormalization();

    // @see http://jsonapi.org/format/#document-jsonapi-object     $this->assertEquals('1.0', $normalized['jsonapi']['version']);
    $this->assertEquals('http://jsonapi.org/format/1.0/', $normalized['jsonapi']['meta']['links']['self']['href']);

    $this->assertSame($normalized['data']['attributes']['title'], 'dummy_title');
    $this->assertEquals($normalized['data']['id']$this->node->uuid());
    $this->assertSame([
      'data' => [
        'type' => 'node_type--node_type',
        'id' => NodeType::load('article')->uuid(),
        
Home | Imprint | This part of the site doesn't use cookies.