RelationshipItemNormalizer.php in JSON:API 8        
                          
                  
                        
  
  
  
  
  
File
  src/Normalizer/RelationshipItemNormalizer.php
  
    View source  
  <?php
namespace Drupal\jsonapi\Normalizer;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityInterface;
use Drupal\jsonapi\Normalizer\Value\RelationshipItemNormalizerValue;
use Drupal\jsonapi\Resource\JsonApiDocumentTopLevel;
use Drupal\jsonapi\ResourceType\ResourceTypeRepositoryInterface;
use Drupal\jsonapi\Controller\EntityResource;
class RelationshipItemNormalizer extends FieldItemNormalizer {
  
  protected $supportedInterfaceOrClass = RelationshipItem::class;
  
  protected $resourceTypeRepository;
  
  public function __construct(ResourceTypeRepositoryInterface $resource_type_repository) {
    $this->resourceTypeRepository = $resource_type_repository;
  }
  
  public function normalize($relationship_item, $format = NULL, array $context = []) {
    
    
    $target_entity = $relationship_item
      ->getTargetEntity();
    $values = $relationship_item
      ->getValue();
    if (isset($context['langcode'])) {
      $values['lang'] = $context['langcode'];
    }
    $host_field_name = $relationship_item
      ->getParent()
      ->getPropertyName();
    if (!empty($context['include']) && in_array($host_field_name, $context['include']) && $target_entity !== NULL) {
      $context = $this
        ->buildSubContext($context, $target_entity, $host_field_name);
      $entity_and_access = EntityResource::getEntityAndAccess($target_entity);
      $included_normalizer_value = $this->serializer
        ->normalize(new JsonApiDocumentTopLevel($entity_and_access['entity']), $format, $context);
    }
    else {
      $included_normalizer_value = NULL;
    }
    return new RelationshipItemNormalizerValue($values, new CacheableMetadata(), $relationship_item
      ->getTargetResourceType(), $included_normalizer_value);
  }
  
  protected function buildSubContext(array $context, EntityInterface $entity, $host_field_name) {
    
    $context['resource_type'] = $this->resourceTypeRepository
      ->get($entity
      ->getEntityTypeId(), $entity
      ->bundle());
    
    $include_candidates = array_filter($context['include'], function ($include) use ($host_field_name) {
      return strpos($include, $host_field_name . '.') === 0;
    });
    $context['include'] = array_map(function ($include) use ($host_field_name) {
      return str_replace($host_field_name . '.', '', $include);
    }, $include_candidates);
    $context['is_include_normalization'] = TRUE;
    return $context;
  }
}