From c79d94f3d16c152bab5190d3e654dd5e8d0d6ff2 Mon Sep 17 00:00:00 2001 From: Jared Whiklo Date: Tue, 13 Feb 2018 16:48:41 -0600 Subject: [PATCH 1/6] Make a reaction to alter the JSON-LD --- src/ContextProvider/JsonldContextProvider.php | 54 +++++++++++++++++++ .../NormalizerAlterReaction.php | 29 ++++++++++ src/Normalizer/ContentEntityNormalizer.php | 51 ++++++++++++++++-- src/Normalizer/NormalizerBase.php | 2 +- 4 files changed, 132 insertions(+), 4 deletions(-) create mode 100644 src/ContextProvider/JsonldContextProvider.php create mode 100644 src/ContextReaction/NormalizerAlterReaction.php diff --git a/src/ContextProvider/JsonldContextProvider.php b/src/ContextProvider/JsonldContextProvider.php new file mode 100644 index 0000000..47fddbe --- /dev/null +++ b/src/ContextProvider/JsonldContextProvider.php @@ -0,0 +1,54 @@ +entity = $entity; + } + + /** + * {@inheritdoc} + */ + public function getRuntimeContexts(array $unqualified_context_ids) { + $context_definition = new ContextDefinition('any', $this->t('runtime context normalized array from jsonld'), FALSE); + $context = new Context($context_definition, $this->entity); + return ['@jsonld.jsonld_normalized_context_provider:array' => $context]; + } + + /** + * {@inheritdoc} + */ + public function getAvailableContexts() { + $context = new Context(new ContextDefinition('any', $this->t('normalized array from jsonld'))); + return ['@jsonld.jsonld_normalized_context_provider:array' => $context]; + } + +} diff --git a/src/ContextReaction/NormalizerAlterReaction.php b/src/ContextReaction/NormalizerAlterReaction.php new file mode 100644 index 0000000..f656400 --- /dev/null +++ b/src/ContextReaction/NormalizerAlterReaction.php @@ -0,0 +1,29 @@ + NULL, 'included_fields' => NULL, 'needs_jsonldcontext' => FALSE, 'embedded' => FALSE, 'namespaces' => rdf_get_namespaces(), + 'depth' => 0, ]; if ($context['needs_jsonldcontext']) { @@ -95,7 +101,7 @@ public function normalize($entity, $format = NULL, array $context = []) { // not shortened ones. So we replace them in place. if ($context['needs_jsonldcontext'] === FALSE && is_array($types)) { for ($i = 0; $i < count($types); $i++) { - $types[$i] = $this->escapePrefix($types[$i], $context['namespaces']); + $types[$i] = ContentEntityNormalizer::escapePrefix($types[$i], $context['namespaces']); } } @@ -126,6 +132,7 @@ public function normalize($entity, $format = NULL, array $context = []) { $context['current_entity_id'] = $this->getEntityUri($entity); $context['current_entity_rdf_mapping'] = $rdf_mappings; + foreach ($fields as $name => $field) { // Just process fields that have rdf mappings defined. // We could also pass as not contextualized keys the others @@ -150,9 +157,47 @@ public function normalize($entity, $format = NULL, array $context = []) { if (!$context['embedded']) { $normalized['@graph'] = array_values($normalized['@graph']); } + + if (isset($context['depth']) && $context['depth'] == 0) { + self::executeContextReactions($entity, $normalized, $context); + } return $normalized; } + /** + * Executes any context reactions. + * + * @param \Drupal\Core\Entity\EntityInterface $entity + * The current entity. + * @param array|null $normalized + * The array of normalized json-ld. + * @param array|null $context + * The context used by the normalizer. + */ + private static function executeContextReactions(EntityInterface $entity, array &$normalized = NULL, array $context = NULL) { + switch ($entity->getEntityType()->id()) { + case "node": + case "media": + case "file": + $provider = new JsonldContextProvider($entity); + break; + + default: + $provider = NULL; + break; + } + + if ($provider) { + $context_manager = \Drupal::service('context.manager'); + $provided = $provider->getRuntimeContexts([]); + $context_manager->evaluateContexts($provided); + + foreach ($context_manager->getActiveReactions('\Drupal\jsonld\ContextReaction\NormalizerAlterReaction') as $reaction) { + $reaction->execute($entity, $normalized, $context); + } + } + } + /** * {@inheritdoc} */ @@ -238,9 +283,9 @@ protected function getEntityUri(EntityInterface $entity) { // Some entity types don't provide a canonical link template, at least call // out to ->url(). if ($entity->isNew() || !$entity->hasLinkTemplate('canonical')) { - return $entity->url('canonical', []); + return $entity->toUrl('canonical', []); } - $url = $entity->urlInfo('canonical', ['absolute' => TRUE]); + $url = $entity->toUrl('canonical', ['absolute' => TRUE]); return $url->setRouteParameter('_format', 'jsonld')->toString(); } diff --git a/src/Normalizer/NormalizerBase.php b/src/Normalizer/NormalizerBase.php index a3e1468..cb66c76 100644 --- a/src/Normalizer/NormalizerBase.php +++ b/src/Normalizer/NormalizerBase.php @@ -55,7 +55,7 @@ public function supportsDenormalization($data, $type, $format = NULL) { * @return string * The predicate with escaped namespace prefix. */ - protected function escapePrefix($predicate, array $namespaces) { + public static function escapePrefix($predicate, array $namespaces) { $exploded = explode(":", $predicate); if (!isset($namespaces[$exploded[0]])) { From f0214ffd303dae9f3772dadab0e31fa32ee518e7 Mon Sep 17 00:00:00 2001 From: Jared Whiklo Date: Fri, 16 Feb 2018 08:46:08 -0600 Subject: [PATCH 2/6] Switch Reaction back to hook Fix deprecated use of drupal_basename --- jsonld.api.php | 32 +++++++++++ jsonld.services.yml | 4 +- src/ContextProvider/JsonldContextProvider.php | 54 ------------------- .../NormalizerAlterReaction.php | 29 ---------- src/Normalizer/ContentEntityNormalizer.php | 47 +++------------- src/Normalizer/FileEntityNormalizer.php | 23 ++++++-- 6 files changed, 61 insertions(+), 128 deletions(-) create mode 100644 jsonld.api.php delete mode 100644 src/ContextProvider/JsonldContextProvider.php delete mode 100644 src/ContextReaction/NormalizerAlterReaction.php diff --git a/jsonld.api.php b/jsonld.api.php new file mode 100644 index 0000000..7066ac1 --- /dev/null +++ b/jsonld.api.php @@ -0,0 +1,32 @@ +getEntityTypeId() == 'node') { + if (isset($normalized['@graph'])) { + if (!is_array($normalized["@graph"])) { + $normalized['@graph'] = [$normalized['@graph']]; + } + $normalized['@graph'][] = [ + '@id' => 'http://example.org/first/name', + '@type' => 'schemaOrg:Person', + ]; + } + } +} diff --git a/jsonld.services.yml b/jsonld.services.yml index fb07de3..0cfaf15 100644 --- a/jsonld.services.yml +++ b/jsonld.services.yml @@ -17,10 +17,10 @@ services: class: Drupal\jsonld\Normalizer\FileEntityNormalizer tags: - { name: normalizer, priority: 20 } - arguments: ['@entity.manager', '@http_client', '@hal.link_manager', '@module_handler'] + arguments: ['@entity_type.manager', '@http_client', '@hal.link_manager', '@module_handler', '@file_system'] serializer.normalizer.entity.jsonld: class: Drupal\jsonld\Normalizer\ContentEntityNormalizer - arguments: ['@hal.link_manager', '@entity.manager', '@module_handler'] + arguments: ['@hal.link_manager', '@entity_type.manager', '@module_handler'] tags: - { name: normalizer, priority: 10 } serializer.encoder.jsonld: diff --git a/src/ContextProvider/JsonldContextProvider.php b/src/ContextProvider/JsonldContextProvider.php deleted file mode 100644 index 47fddbe..0000000 --- a/src/ContextProvider/JsonldContextProvider.php +++ /dev/null @@ -1,54 +0,0 @@ -entity = $entity; - } - - /** - * {@inheritdoc} - */ - public function getRuntimeContexts(array $unqualified_context_ids) { - $context_definition = new ContextDefinition('any', $this->t('runtime context normalized array from jsonld'), FALSE); - $context = new Context($context_definition, $this->entity); - return ['@jsonld.jsonld_normalized_context_provider:array' => $context]; - } - - /** - * {@inheritdoc} - */ - public function getAvailableContexts() { - $context = new Context(new ContextDefinition('any', $this->t('normalized array from jsonld'))); - return ['@jsonld.jsonld_normalized_context_provider:array' => $context]; - } - -} diff --git a/src/ContextReaction/NormalizerAlterReaction.php b/src/ContextReaction/NormalizerAlterReaction.php deleted file mode 100644 index f656400..0000000 --- a/src/ContextReaction/NormalizerAlterReaction.php +++ /dev/null @@ -1,29 +0,0 @@ -linkManager = $link_manager; $this->entityManager = $entity_manager; @@ -159,45 +160,13 @@ public function normalize($entity, $format = NULL, array $context = []) { } if (isset($context['depth']) && $context['depth'] == 0) { - self::executeContextReactions($entity, $normalized, $context); + $this->moduleHandler->invokeAll(self::NORMALIZE_ALTER_HOOK, + [$entity, &$normalized, $context] + ); } return $normalized; } - /** - * Executes any context reactions. - * - * @param \Drupal\Core\Entity\EntityInterface $entity - * The current entity. - * @param array|null $normalized - * The array of normalized json-ld. - * @param array|null $context - * The context used by the normalizer. - */ - private static function executeContextReactions(EntityInterface $entity, array &$normalized = NULL, array $context = NULL) { - switch ($entity->getEntityType()->id()) { - case "node": - case "media": - case "file": - $provider = new JsonldContextProvider($entity); - break; - - default: - $provider = NULL; - break; - } - - if ($provider) { - $context_manager = \Drupal::service('context.manager'); - $provided = $provider->getRuntimeContexts([]); - $context_manager->evaluateContexts($provided); - - foreach ($context_manager->getActiveReactions('\Drupal\jsonld\ContextReaction\NormalizerAlterReaction') as $reaction) { - $reaction->execute($entity, $normalized, $context); - } - } - } - /** * {@inheritdoc} */ diff --git a/src/Normalizer/FileEntityNormalizer.php b/src/Normalizer/FileEntityNormalizer.php index 6a3e9a8..0fe5198 100644 --- a/src/Normalizer/FileEntityNormalizer.php +++ b/src/Normalizer/FileEntityNormalizer.php @@ -2,8 +2,9 @@ namespace Drupal\jsonld\Normalizer; -use Drupal\Core\Entity\EntityManagerInterface; +use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Extension\ModuleHandlerInterface; +use Drupal\Core\File\FileSystemInterface; use Drupal\hal\LinkManager\LinkManagerInterface; use GuzzleHttp\ClientInterface; @@ -26,10 +27,17 @@ class FileEntityNormalizer extends ContentEntityNormalizer { */ protected $httpClient; + /** + * The Drupal file system. + * + * @var \Drupal\Core\File\FileSystemInterface + */ + protected $fileSystem; + /** * Constructs a FileEntityNormalizer object. * - * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager + * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager * The entity manager. * @param \GuzzleHttp\ClientInterface $http_client * The HTTP Client. @@ -37,12 +45,19 @@ class FileEntityNormalizer extends ContentEntityNormalizer { * The hypermedia link manager. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler * The module handler. + * @param \Drupal\Core\File\FileSystemInterface $file_system + * The file system handler. */ - public function __construct(EntityManagerInterface $entity_manager, ClientInterface $http_client, LinkManagerInterface $link_manager, ModuleHandlerInterface $module_handler) { + public function __construct(EntityTypeManagerInterface $entity_manager, + ClientInterface $http_client, + LinkManagerInterface $link_manager, + ModuleHandlerInterface $module_handler, + FileSystemInterface $file_system) { parent::__construct($link_manager, $entity_manager, $module_handler); $this->httpClient = $http_client; + $this->fileSystem = $file_system; } /** @@ -64,7 +79,7 @@ public function denormalize($data, $class, $format = NULL, array $context = []) $file_data = (string) $this->httpClient->get($data['uri'][0]['value'])->getBody(); - $path = 'temporary://' . drupal_basename($data['uri'][0]['value']); + $path = 'temporary://' . $this->fileSystem->basename($data['uri'][0]['value']); $data['uri'] = file_unmanaged_save_data($file_data, $path); return $this->entityManager->getStorage('file')->create($data); From fda94c36d0bd54cf38c43030cc31c3f089fe7e4c Mon Sep 17 00:00:00 2001 From: Jared Whiklo Date: Fri, 16 Feb 2018 09:01:45 -0600 Subject: [PATCH 3/6] Require typed_data --- tests/src/Kernel/JsonldContextGeneratorTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/src/Kernel/JsonldContextGeneratorTest.php b/tests/src/Kernel/JsonldContextGeneratorTest.php index 881584b..82c2c38 100644 --- a/tests/src/Kernel/JsonldContextGeneratorTest.php +++ b/tests/src/Kernel/JsonldContextGeneratorTest.php @@ -12,6 +12,7 @@ * * @group jsonld * @coversDefaultClass \Drupal\jsonld\ContextGenerator\JsonldContextGenerator + * @requires module typed_data */ class JsonldContextGeneratorTest extends KernelTestBase { From a221500c5d3731daa114b74735eee7a3b39360a9 Mon Sep 17 00:00:00 2001 From: Jared Whiklo Date: Fri, 16 Feb 2018 09:29:36 -0600 Subject: [PATCH 4/6] Typed_data no longer required. --- tests/src/Kernel/JsonldContextGeneratorTest.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/src/Kernel/JsonldContextGeneratorTest.php b/tests/src/Kernel/JsonldContextGeneratorTest.php index 82c2c38..bc0a861 100644 --- a/tests/src/Kernel/JsonldContextGeneratorTest.php +++ b/tests/src/Kernel/JsonldContextGeneratorTest.php @@ -12,7 +12,6 @@ * * @group jsonld * @coversDefaultClass \Drupal\jsonld\ContextGenerator\JsonldContextGenerator - * @requires module typed_data */ class JsonldContextGeneratorTest extends KernelTestBase { @@ -25,7 +24,6 @@ class JsonldContextGeneratorTest extends KernelTestBase { 'rdf_test_namespaces', 'serialization', 'system', - 'typed_data', ]; From a31e0ae8478e33f6318b151b8f3e0b9e2d9e0ad7 Mon Sep 17 00:00:00 2001 From: Jared Whiklo Date: Fri, 16 Feb 2018 12:00:14 -0600 Subject: [PATCH 5/6] Add a hook test --- tests/json_alter_normalize_hooks.info.yml | 6 + tests/json_alter_normalize_hooks.module | 25 ++++ tests/src/Kernel/JsonldHookTest.php | 152 ++++++++++++++++++++++ 3 files changed, 183 insertions(+) create mode 100644 tests/json_alter_normalize_hooks.info.yml create mode 100644 tests/json_alter_normalize_hooks.module create mode 100644 tests/src/Kernel/JsonldHookTest.php diff --git a/tests/json_alter_normalize_hooks.info.yml b/tests/json_alter_normalize_hooks.info.yml new file mode 100644 index 0000000..105d1c9 --- /dev/null +++ b/tests/json_alter_normalize_hooks.info.yml @@ -0,0 +1,6 @@ +name: 'Jsonld hook tests' +type: module +package: Testing +core: 8.x +dependencies: + - jsonld diff --git a/tests/json_alter_normalize_hooks.module b/tests/json_alter_normalize_hooks.module new file mode 100644 index 0000000..8509a70 --- /dev/null +++ b/tests/json_alter_normalize_hooks.module @@ -0,0 +1,25 @@ + 'json_alter_normalize_hooks', + 'http://purl.org/dc/elements/1.1/title' => 'The hook is tested.', + ]; + } +} diff --git a/tests/src/Kernel/JsonldHookTest.php b/tests/src/Kernel/JsonldHookTest.php new file mode 100644 index 0000000..3881ceb --- /dev/null +++ b/tests/src/Kernel/JsonldHookTest.php @@ -0,0 +1,152 @@ +rebuild(); + } + + /** + * Test hook alter. + */ + public function testAlterNormalizedJsonld() { + + $target_entity = EntityTest::create([ + 'name' => $this->randomMachineName(), + 'langcode' => 'en', + 'field_test_entity_reference' => NULL, + ]); + $target_entity->save(); + + $target_user = User::create([ + 'name' => $this->randomMachineName(), + 'langcode' => 'en', + ]); + $target_user->save(); + + rdf_get_mapping('entity_test', 'entity_test')->setBundleMapping( + [ + 'types' => [ + "schema:ImageObject", + ], + ])->setFieldMapping('field_test_text', [ + 'properties' => ['dc:description'], + ])->setFieldMapping('user_id', [ + 'properties' => ['schema:author'], + ])->setFieldMapping('modified', [ + 'properties' => ['schema:dateModified'], + 'datatype' => 'xsd:dateTime', + ])->save(); + + $tz = new \DateTimeZone('UTC'); + $dt = new \DateTime(NULL, $tz); + $created = $dt->format("U"); + $created_iso = $dt->format(\DateTime::W3C); + // Create an entity. + $values = [ + 'langcode' => 'en', + 'name' => $this->randomMachineName(), + 'type' => 'entity_test', + 'bundle' => 'entity_test', + 'user_id' => $target_user->id(), + 'created' => [ + 'value' => $created, + ], + 'field_test_text' => [ + 'value' => $this->randomMachineName(), + 'format' => 'full_html', + ], + 'field_test_entity_reference' => [ + 'target_id' => $target_entity->id(), + ], + ]; + + $entity = EntityTest::create($values); + $entity->save(); + + $expected = [ + "@graph" => [ + [ + "@id" => $this->getEntityUri($entity), + "@type" => [ + 'http://schema.org/ImageObject', + ], + "http://purl.org/dc/terms/references" => [ + [ + "@id" => $this->getEntityUri($target_entity), + ], + ], + "http://purl.org/dc/terms/description" => [ + [ + "@type" => "http://www.w3.org/2001/XMLSchema#string", + "@value" => $values['field_test_text']['value'], + ], + ], + "http://purl.org/dc/terms/title" => [ + [ + "@type" => "http://www.w3.org/2001/XMLSchema#string", + "@value" => $values['name'], + ], + ], + "http://schema.org/author" => [ + [ + "@id" => $this->getEntityUri($target_user), + ], + ], + "http://schema.org/dateCreated" => [ + [ + "@type" => "http://www.w3.org/2001/XMLSchema#dateTime", + "@value" => $created_iso, + ], + ], + ], + [ + "@id" => $this->getEntityUri($target_user), + "@type" => "http://localhost/rest/type/user/user", + ], + [ + "@id" => $this->getEntityUri($target_entity), + "@type" => [ + "http://schema.org/ImageObject", + ], + ], + [ + "@id" => "json_alter_normalize_hooks", + "http://purl.org/dc/elements/1.1/title" => "The hook is tested.", + ], + ], + ]; + + $normalized = $this->serializer->normalize($entity, $this->format); + $this->assertEquals($expected, $normalized, "Did not normalize and call hooks correctly."); + + } + +} From e0bb8e881a76c4b77d47c445dc1f0817b204dc49 Mon Sep 17 00:00:00 2001 From: Jared Whiklo Date: Fri, 16 Feb 2018 12:27:37 -0600 Subject: [PATCH 6/6] De-duplicate entity creation --- tests/src/Kernel/JsonldHookTest.php | 111 +--------------- tests/src/Kernel/JsonldKernelTestBase.php | 118 +++++++++++++++++- .../ContentEntityNormalizerTests.php | 104 +-------------- 3 files changed, 121 insertions(+), 212 deletions(-) diff --git a/tests/src/Kernel/JsonldHookTest.php b/tests/src/Kernel/JsonldHookTest.php index 3881ceb..e98eb54 100644 --- a/tests/src/Kernel/JsonldHookTest.php +++ b/tests/src/Kernel/JsonldHookTest.php @@ -2,9 +2,6 @@ namespace Drupal\Tests\jsonld\Kernel; -use Drupal\entity_test\Entity\EntityTest; -use Drupal\user\Entity\User; - /** * Class JsonldHookTest. * @@ -38,110 +35,10 @@ public function setUp() { */ public function testAlterNormalizedJsonld() { - $target_entity = EntityTest::create([ - 'name' => $this->randomMachineName(), - 'langcode' => 'en', - 'field_test_entity_reference' => NULL, - ]); - $target_entity->save(); - - $target_user = User::create([ - 'name' => $this->randomMachineName(), - 'langcode' => 'en', - ]); - $target_user->save(); - - rdf_get_mapping('entity_test', 'entity_test')->setBundleMapping( - [ - 'types' => [ - "schema:ImageObject", - ], - ])->setFieldMapping('field_test_text', [ - 'properties' => ['dc:description'], - ])->setFieldMapping('user_id', [ - 'properties' => ['schema:author'], - ])->setFieldMapping('modified', [ - 'properties' => ['schema:dateModified'], - 'datatype' => 'xsd:dateTime', - ])->save(); - - $tz = new \DateTimeZone('UTC'); - $dt = new \DateTime(NULL, $tz); - $created = $dt->format("U"); - $created_iso = $dt->format(\DateTime::W3C); - // Create an entity. - $values = [ - 'langcode' => 'en', - 'name' => $this->randomMachineName(), - 'type' => 'entity_test', - 'bundle' => 'entity_test', - 'user_id' => $target_user->id(), - 'created' => [ - 'value' => $created, - ], - 'field_test_text' => [ - 'value' => $this->randomMachineName(), - 'format' => 'full_html', - ], - 'field_test_entity_reference' => [ - 'target_id' => $target_entity->id(), - ], - ]; - - $entity = EntityTest::create($values); - $entity->save(); - - $expected = [ - "@graph" => [ - [ - "@id" => $this->getEntityUri($entity), - "@type" => [ - 'http://schema.org/ImageObject', - ], - "http://purl.org/dc/terms/references" => [ - [ - "@id" => $this->getEntityUri($target_entity), - ], - ], - "http://purl.org/dc/terms/description" => [ - [ - "@type" => "http://www.w3.org/2001/XMLSchema#string", - "@value" => $values['field_test_text']['value'], - ], - ], - "http://purl.org/dc/terms/title" => [ - [ - "@type" => "http://www.w3.org/2001/XMLSchema#string", - "@value" => $values['name'], - ], - ], - "http://schema.org/author" => [ - [ - "@id" => $this->getEntityUri($target_user), - ], - ], - "http://schema.org/dateCreated" => [ - [ - "@type" => "http://www.w3.org/2001/XMLSchema#dateTime", - "@value" => $created_iso, - ], - ], - ], - [ - "@id" => $this->getEntityUri($target_user), - "@type" => "http://localhost/rest/type/user/user", - ], - [ - "@id" => $this->getEntityUri($target_entity), - "@type" => [ - "http://schema.org/ImageObject", - ], - ], - [ - "@id" => "json_alter_normalize_hooks", - "http://purl.org/dc/elements/1.1/title" => "The hook is tested.", - ], - ], + list($entity, $expected) = $this->generateTestEntity(); + $expected['@graph'][] = [ + "@id" => "json_alter_normalize_hooks", + "http://purl.org/dc/elements/1.1/title" => "The hook is tested.", ]; $normalized = $this->serializer->normalize($entity, $this->format); diff --git a/tests/src/Kernel/JsonldKernelTestBase.php b/tests/src/Kernel/JsonldKernelTestBase.php index 4f3d5bd..e4cadb3 100644 --- a/tests/src/Kernel/JsonldKernelTestBase.php +++ b/tests/src/Kernel/JsonldKernelTestBase.php @@ -4,6 +4,7 @@ use Drupal\Core\Cache\MemoryBackend; use Drupal\Core\Entity\EntityInterface; +use Drupal\entity_test\Entity\EntityTest; use Drupal\field\Entity\FieldConfig; use Drupal\field\Entity\FieldStorageConfig; use Drupal\jsonld\Encoder\JsonldEncoder; @@ -18,6 +19,7 @@ use Drupal\serialization\EntityResolver\ChainEntityResolver; use Drupal\serialization\EntityResolver\TargetIdResolver; use Drupal\serialization\EntityResolver\UuidResolver; +use Drupal\user\Entity\User; use Symfony\Component\Serializer\Serializer; /** @@ -181,10 +183,122 @@ protected function getEntityUri(EntityInterface $entity) { // Some entity types don't provide a canonical link template, at least call // out to ->url(). if ($entity->isNew() || !$entity->hasLinkTemplate('canonical')) { - return $entity->url('canonical', []); + return $entity->toUrl('canonical', []); } - $url = $entity->urlInfo('canonical', ['absolute' => TRUE]); + $url = $entity->toUrl('canonical', ['absolute' => TRUE]); return $url->setRouteParameter('_format', 'jsonld')->toString(); } + /** + * Generate a test entity and the expected normalized array. + * + * @return array + * with [ the entity, the normalized array ]. + */ + protected function generateTestEntity() { + $target_entity = EntityTest::create([ + 'name' => $this->randomMachineName(), + 'langcode' => 'en', + 'field_test_entity_reference' => NULL, + ]); + $target_entity->save(); + + $target_user = User::create([ + 'name' => $this->randomMachineName(), + 'langcode' => 'en', + ]); + $target_user->save(); + + rdf_get_mapping('entity_test', 'entity_test')->setBundleMapping( + [ + 'types' => [ + "schema:ImageObject", + ], + ])->setFieldMapping('field_test_text', [ + 'properties' => ['dc:description'], + ])->setFieldMapping('user_id', [ + 'properties' => ['schema:author'], + ])->setFieldMapping('modified', [ + 'properties' => ['schema:dateModified'], + 'datatype' => 'xsd:dateTime', + ])->save(); + + $tz = new \DateTimeZone('UTC'); + $dt = new \DateTime(NULL, $tz); + $created = $dt->format("U"); + $created_iso = $dt->format(\DateTime::W3C); + // Create an entity. + $values = [ + 'langcode' => 'en', + 'name' => $this->randomMachineName(), + 'type' => 'entity_test', + 'bundle' => 'entity_test', + 'user_id' => $target_user->id(), + 'created' => [ + 'value' => $created, + ], + 'field_test_text' => [ + 'value' => $this->randomMachineName(), + 'format' => 'full_html', + ], + 'field_test_entity_reference' => [ + 'target_id' => $target_entity->id(), + ], + ]; + + $entity = EntityTest::create($values); + $entity->save(); + + $expected = [ + "@graph" => [ + [ + "@id" => $this->getEntityUri($entity), + "@type" => [ + 'http://schema.org/ImageObject', + ], + "http://purl.org/dc/terms/references" => [ + [ + "@id" => $this->getEntityUri($target_entity), + ], + ], + "http://purl.org/dc/terms/description" => [ + [ + "@type" => "http://www.w3.org/2001/XMLSchema#string", + "@value" => $values['field_test_text']['value'], + ], + ], + "http://purl.org/dc/terms/title" => [ + [ + "@type" => "http://www.w3.org/2001/XMLSchema#string", + "@value" => $values['name'], + ], + ], + "http://schema.org/author" => [ + [ + "@id" => $this->getEntityUri($target_user), + ], + ], + "http://schema.org/dateCreated" => [ + [ + "@type" => "http://www.w3.org/2001/XMLSchema#dateTime", + "@value" => $created_iso, + ], + ], + ], + [ + "@id" => $this->getEntityUri($target_user), + "@type" => "http://localhost/rest/type/user/user", + ], + [ + "@id" => $this->getEntityUri($target_entity), + "@type" => [ + "http://schema.org/ImageObject", + ], + ], + ], + ]; + + return [$entity, $expected]; + } + } diff --git a/tests/src/Kernel/Normalizer/ContentEntityNormalizerTests.php b/tests/src/Kernel/Normalizer/ContentEntityNormalizerTests.php index 810b2e3..15908ec 100644 --- a/tests/src/Kernel/Normalizer/ContentEntityNormalizerTests.php +++ b/tests/src/Kernel/Normalizer/ContentEntityNormalizerTests.php @@ -2,9 +2,7 @@ namespace Drupal\Tests\jsonld\Kernel\Normalizer; -use Drupal\entity_test\Entity\EntityTest; use Drupal\Tests\jsonld\Kernel\JsonldKernelTestBase; -use Drupal\user\Entity\User; /** * Class ContentEntityTests. @@ -34,107 +32,7 @@ protected function setUp() { */ public function testSimpleNormalizeJsonld() { - $target_entity = EntityTest::create([ - 'name' => $this->randomMachineName(), - 'langcode' => 'en', - 'field_test_entity_reference' => NULL, - ]); - $target_entity->save(); - - $target_user = User::create([ - 'name' => $this->randomMachineName(), - 'langcode' => 'en', - ]); - $target_user->save(); - - rdf_get_mapping('entity_test', 'entity_test')->setBundleMapping( - [ - 'types' => [ - "schema:ImageObject", - ], - ])->setFieldMapping('field_test_text', [ - 'properties' => ['dc:description'], - ])->setFieldMapping('user_id', [ - 'properties' => ['schema:author'], - ])->setFieldMapping('modified', [ - 'properties' => ['schema:dateModified'], - 'datatype' => 'xsd:dateTime', - ])->save(); - - $tz = new \DateTimeZone('UTC'); - $dt = new \DateTime(NULL, $tz); - $created = $dt->format("U"); - $created_iso = $dt->format(\DateTime::W3C); - // Create an entity. - $values = [ - 'langcode' => 'en', - 'name' => $this->randomMachineName(), - 'type' => 'entity_test', - 'bundle' => 'entity_test', - 'user_id' => $target_user->id(), - 'created' => [ - 'value' => $created, - ], - 'field_test_text' => [ - 'value' => $this->randomMachineName(), - 'format' => 'full_html', - ], - 'field_test_entity_reference' => [ - 'target_id' => $target_entity->id(), - ], - ]; - - $entity = EntityTest::create($values); - $entity->save(); - - $expected = [ - "@graph" => [ - [ - "@id" => $this->getEntityUri($entity), - "@type" => [ - 'http://schema.org/ImageObject', - ], - "http://purl.org/dc/terms/references" => [ - [ - "@id" => $this->getEntityUri($target_entity), - ], - ], - "http://purl.org/dc/terms/description" => [ - [ - "@type" => "http://www.w3.org/2001/XMLSchema#string", - "@value" => $values['field_test_text']['value'], - ], - ], - "http://purl.org/dc/terms/title" => [ - [ - "@type" => "http://www.w3.org/2001/XMLSchema#string", - "@value" => $values['name'], - ], - ], - "http://schema.org/author" => [ - [ - "@id" => $this->getEntityUri($target_user), - ], - ], - "http://schema.org/dateCreated" => [ - [ - "@type" => "http://www.w3.org/2001/XMLSchema#dateTime", - "@value" => $created_iso, - ], - ], - ], - [ - "@id" => $this->getEntityUri($target_user), - "@type" => "http://localhost/rest/type/user/user", - ], - [ - "@id" => $this->getEntityUri($target_entity), - "@type" => [ - "http://schema.org/ImageObject", - ], - ], - ], - ]; + list($entity, $expected) = $this->generateTestEntity(); $normalized = $this->serializer->normalize($entity, $this->format); $this->assertEquals($expected, $normalized, "Did not normalize correctly.");