Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make a reaction to alter the JSON-LD #24

Merged
merged 6 commits into from
Mar 8, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions jsonld.api.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

/**
* @file
* Hooks and stuff.
*/

use Drupal\Core\Entity\EntityInterface;

/**
* Hook to alter the jsonld normalized array before it is encoded to json.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity we are normalizing.
* @param array $normalized
* The current normalized array.
* @param array $context
* The context for the normalization.
*/
function hook_jsonld_alter_normalized_array(EntityInterface $entity, array &$normalized, array $context) {
if ($entity->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',
];
}
}
}
4 changes: 2 additions & 2 deletions jsonld.services.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
26 changes: 20 additions & 6 deletions src/Normalizer/ContentEntityNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
namespace Drupal\jsonld\Normalizer;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\hal\LinkManager\LinkManagerInterface;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
Expand All @@ -13,6 +13,8 @@
*/
class ContentEntityNormalizer extends NormalizerBase {

const NORMALIZE_ALTER_HOOK = "jsonld_alter_normalized_array";

/**
* The interface or class that this Normalizer supports.
*
Expand Down Expand Up @@ -46,12 +48,12 @@ class ContentEntityNormalizer extends NormalizerBase {
*
* @param \Drupal\hal\LinkManager\LinkManagerInterface $link_manager
* The hypermedia link manager.
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
* The entity manager.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
*/
public function __construct(LinkManagerInterface $link_manager, EntityManagerInterface $entity_manager, ModuleHandlerInterface $module_handler) {
public function __construct(LinkManagerInterface $link_manager, EntityTypeManagerInterface $entity_manager, ModuleHandlerInterface $module_handler) {

$this->linkManager = $link_manager;
$this->entityManager = $entity_manager;
Expand All @@ -67,12 +69,17 @@ public function normalize($entity, $format = NULL, array $context = []) {
// @TODO check $format before going RDF crazy
$normalized = [];

if (isset($context['depth'])) {
$context['depth'] += 1;
}

$context += [
'account' => NULL,
'included_fields' => NULL,
'needs_jsonldcontext' => FALSE,
'embedded' => FALSE,
'namespaces' => rdf_get_namespaces(),
'depth' => 0,
];

if ($context['needs_jsonldcontext']) {
Expand All @@ -95,7 +102,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']);
}
}

Expand Down Expand Up @@ -126,6 +133,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
Expand All @@ -150,6 +158,12 @@ public function normalize($entity, $format = NULL, array $context = []) {
if (!$context['embedded']) {
$normalized['@graph'] = array_values($normalized['@graph']);
}

if (isset($context['depth']) && $context['depth'] == 0) {
$this->moduleHandler->invokeAll(self::NORMALIZE_ALTER_HOOK,
[$entity, &$normalized, $context]
);
}
return $normalized;
}

Expand Down Expand Up @@ -238,9 +252,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();
}

Expand Down
23 changes: 19 additions & 4 deletions src/Normalizer/FileEntityNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -26,23 +27,37 @@ 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.
* @param \Drupal\hal\LinkManager\LinkManagerInterface $link_manager
* 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;
}

/**
Expand All @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/Normalizer/NormalizerBase.php
Original file line number Diff line number Diff line change
Expand Up @@ -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]])) {
Expand Down
6 changes: 6 additions & 0 deletions tests/json_alter_normalize_hooks.info.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
name: 'Jsonld hook tests'
type: module
package: Testing
core: 8.x
dependencies:
- jsonld
25 changes: 25 additions & 0 deletions tests/json_alter_normalize_hooks.module
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

/**
* @file
* A test module to implement the hooks to be tested.
*/

use Drupal\Core\Entity\EntityInterface;

/**
* Implements hook_jsonld_alter_normalized_array().
*/
function json_alter_normalize_hooks_jsonld_alter_normalized_array(EntityInterface $entity, array &$normalized, array $context) {
if (isset($normalized['@graph'])) {
if (!is_array($normalized['@graph'])) {
$normalized['@graph'] = [
[$normalized['@graph']],
];
}
$normalized['@graph'][] = [
'@id' => 'json_alter_normalize_hooks',
'http://purl.org/dc/elements/1.1/title' => 'The hook is tested.',
];
}
}
1 change: 0 additions & 1 deletion tests/src/Kernel/JsonldContextGeneratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ class JsonldContextGeneratorTest extends KernelTestBase {
'rdf_test_namespaces',
'serialization',
'system',
'typed_data',
];


Expand Down
49 changes: 49 additions & 0 deletions tests/src/Kernel/JsonldHookTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

namespace Drupal\Tests\jsonld\Kernel;

/**
* Class JsonldHookTest.
*
* @package Drupal\Tests\jsonld\Kernel
* @group jsonld
*/
class JsonldHookTest extends JsonldKernelTestBase {

public static $modules = [
'entity',
'entity_test',
'hal',
'jsonld',
'rdf',
'rdf_test_namespaces',
'serialization',
'system',
'json_alter_normalize_hooks',
];

/**
* {@inheritdoc}
*/
public function setUp() {
parent::setUp();
\Drupal::service('router.builder')->rebuild();
}

/**
* Test hook alter.
*/
public function testAlterNormalizedJsonld() {

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);
$this->assertEquals($expected, $normalized, "Did not normalize and call hooks correctly.");

}

}
Loading