View source
<?php
namespace Drupal\schemata_json_schema\Normalizer\hal;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\schemata_json_schema\Normalizer\json\DataReferenceDefinitionNormalizer as JsonDataReferenceDefinitionNormalizer;
use Drupal\schemata\SchemaUrl;
use Drupal\hal\LinkManager\LinkManagerInterface;
class DataReferenceDefinitionNormalizer extends JsonDataReferenceDefinitionNormalizer {
protected $format = 'schema_json';
protected $describedFormat = 'hal_json';
protected $linkManager;
public function __construct(EntityTypeManagerInterface $entity_type_manager, LinkManagerInterface $link_manager) {
parent::__construct($entity_type_manager);
$this->linkManager = $link_manager;
}
public function normalize($entity, $format = NULL, array $context = []) {
if (!$this
->validateEntity($entity)) {
return [];
}
$parentProperty = $this
->extractPropertyData($context['parent'], $context);
$property = $this
->extractPropertyData($entity, $context);
$target_type = $entity
->getConstraint('EntityType');
$target_bundles = isset($context['settings']['handler_settings']['target_bundles']) ? $context['settings']['handler_settings']['target_bundles'] : [];
$field_uri = $this->linkManager
->getRelationUri($context['entityTypeId'], isset($context['bundleId']) ? $context['bundleId'] : $context['entityTypeId'], $context['name'], $context);
$normalized = [
'_links' => [
$field_uri => [
'$ref' => '#/definitions/linkArray',
],
],
'_embedded' => [
$field_uri => [
'type' => 'array',
'items' => [],
],
],
];
if (isset($parentProperty['title'])) {
$normalized['_links'][$field_uri]['title'] = $parentProperty['title'];
$normalized['_embedded'][$field_uri]['title'] = $parentProperty['title'];
}
if (isset($parentProperty['description'])) {
$normalized['_links'][$field_uri]['description'] = $parentProperty['description'];
}
$item =& $normalized['_embedded'][$field_uri]['items'];
if (empty($target_bundles)) {
$generated_url = SchemaUrl::fromOptions($this->format, $this->describedFormat, $target_type)
->toString(TRUE);
$item['$ref'] = $generated_url
->getGeneratedUrl();
}
elseif (count($target_bundles) == 1) {
$generated_url = SchemaUrl::fromOptions($this->format, $this->describedFormat, $target_type, reset($target_bundles))
->toString(TRUE);
$item['$ref'] = $generated_url
->getGeneratedUrl();
}
elseif (count($target_bundles) > 1) {
$refs = [];
foreach ($target_bundles as $bundle) {
$generated_url = SchemaUrl::fromOptions($this->format, $this->describedFormat, $target_type, $bundle)
->toString(TRUE);
$refs[] = [
'$ref' => $generated_url
->getGeneratedUrl(),
];
}
$item['anyOf'] = $refs;
}
return [
'properties' => $normalized,
];
}
}