Skip to content

Commit

Permalink
Move getEntityUri to separate utility class. (#58)
Browse files Browse the repository at this point in the history
  • Loading branch information
whikloj authored Sep 21, 2021
1 parent dfd99c4 commit 7f16912
Show file tree
Hide file tree
Showing 15 changed files with 278 additions and 134 deletions.
9 changes: 6 additions & 3 deletions .github/workflows/build-8.x-1.x.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ jobs:
echo "DRUPAL_VERSION=${{ matrix.drupal-version }}" >> $GITHUB_ENV
echo "SCRIPT_DIR=$GITHUB_WORKSPACE/islandora_ci" >> $GITHUB_ENV
echo "DRUPAL_DIR=/opt/drupal" >> $GITHUB_ENV
echo "PHPUNIT_FILE=$GITHUB_WORKSPACE/build_dir/phpunit.xml" >> $GITHUB_ENV
- name: Cache Composer dependencies
uses: actions/cache@v2
Expand Down Expand Up @@ -98,11 +99,13 @@ jobs:
cd $DRUPAL_DIR/web
drush --uri=127.0.0.1:8282 en -y user jsonld
- name: Copy PHPunit file
run: cp $PHPUNIT_FILE $DRUPAL_DIR/web/core/phpunit.xml

- name: Test scripts
run: $SCRIPT_DIR/travis_scripts.sh

- name: PHPUNIT tests
run: |
cd $DRUPAL_DIR/web
php core/scripts/run-tests.sh --suppress-deprecations --url http://127.0.0.1:8282 --verbose --php `which php` --module jsonld
cd $DRUPAL_DIR/web/core
$DRUPAL_DIR/vendor/bin/phpunit --verbose --debug
33 changes: 30 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,37 @@
"role": "Owner"
},
{
"name": "Diego Pino",
"email": "[email protected]",
"name": "Jared Whiklo",
"email": "[email protected]",
"role": "Maintainer"
}
],
"require": {}
"require-dev": {
"phpunit/phpunit": "^8",
"squizlabs/php_codesniffer": "^3",
"drupal/coder": "*",
"sebastian/phpcpd": "*"
},
"autoload": {
"psr-4": {
"Drupal\\jsonld\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Drupal\\Tests\\jsonld\\": "tests/src/"
}
},
"scripts": {
"post-install-cmd": [
"./vendor/bin/phpcs --config-set installed_paths ~/.composer/vendor/drupal/coder/coder_sniffer"
],
"post-update-cmd": [
"./vendor/bin/phpcs --config-set installed_paths ~/.composer/vendor/drupal/coder/coder_sniffer"
],
"check": [
"./vendor/bin/phpcs --standard=Drupal --ignore=*.md,vendor --extensions=php,module,inc,install,test,profile,theme,css,info .",
"./vendor/bin/phpcpd --names='*.module,*.inc,*.test,*.php' --exclude=vendor ."
]
}
}
18 changes: 0 additions & 18 deletions composer.lock

This file was deleted.

4 changes: 4 additions & 0 deletions jsonld.api.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
/**
* Hook to alter the jsonld normalized array before it is encoded to json.
*
* $context['utils'] contains an instance of
* \Drupal\jsonld\Utils\JsonldNormalizerUtils, this provides the getEntityUri()
* method to correctly generate a URI with/without the ?format=jsonld suffix.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity we are normalizing.
* @param array $normalized
Expand Down
7 changes: 5 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_type.manager', '@http_client', '@hal.link_manager', '@module_handler', '@file_system', '@config.factory', '@language_manager', '@router.route_provider']
arguments: ['@entity_type.manager', '@http_client', '@hal.link_manager', '@module_handler', '@file_system', '@jsonld.normalizer_utils']
serializer.normalizer.entity.jsonld:
class: Drupal\jsonld\Normalizer\ContentEntityNormalizer
arguments: ['@hal.link_manager', '@entity_type.manager', '@module_handler', '@config.factory', '@language_manager', '@router.route_provider']
arguments: ['@hal.link_manager', '@entity_type.manager', '@module_handler', '@jsonld.normalizer_utils']
tags:
- { name: normalizer, priority: 10 }
serializer.encoder.jsonld:
Expand All @@ -37,3 +37,6 @@ services:
jsonld.contextgenerator:
class: Drupal\jsonld\ContextGenerator\JsonldContextGenerator
arguments: ['@entity_field.manager','@entity_type.bundle.info','@entity_type.manager', '@cache.default', '@logger.channel.jsonld']
jsonld.normalizer_utils:
class: Drupal\jsonld\Utils\JsonldNormalizerUtils
arguments: ['@config.factory', '@language_manager', '@router.route_provider']
74 changes: 74 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- TODO set checkForUnintentionallyCoveredCode="true" once https://www.drupal.org/node/2626832 is resolved. -->
<!-- PHPUnit expects functional tests to be run with either a privileged user
or your current system user. See core/tests/README.md and
https://www.drupal.org/node/2116263 for details.
-->
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" bootstrap="tests/bootstrap.php" colors="true" beStrictAboutTestsThatDoNotTestAnything="true" beStrictAboutOutputDuringTests="true" beStrictAboutChangesToGlobalState="true" printerClass="\Drupal\Tests\Listeners\HtmlOutputPrinter" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<php>
<!-- Set error reporting to E_ALL. -->
<ini name="error_reporting" value="32767"/>
<!-- Do not limit the amount of memory tests take to run. -->
<ini name="memory_limit" value="-1"/>
<!-- Example SIMPLETEST_BASE_URL value: http://localhost -->
<env name="SIMPLETEST_BASE_URL" value="http://127.0.0.1:8282"/>
<!-- Example SIMPLETEST_DB value: mysql://username:password@localhost/databasename#table_prefix -->
<env name="SIMPLETEST_DB" value="mysql://drupal:[email protected]/drupal"/>
<!-- Example BROWSERTEST_OUTPUT_DIRECTORY value: /path/to/webroot/sites/simpletest/browser_output -->
<env name="BROWSERTEST_OUTPUT_DIRECTORY" value="../sites/simpletest/browser_output"/>
<!-- To have browsertest output use an alternative base URL. For example if
SIMPLETEST_BASE_URL is an internal DDEV URL, you can set this to the
external DDev URL so you can follow the links directly.
-->
<env name="BROWSERTEST_OUTPUT_BASE_URL" value=""/>
<!-- To disable deprecation testing completely uncomment the next line. -->
<env name="SYMFONY_DEPRECATIONS_HELPER" value="disabled"/>
<!-- Example for changing the driver class for mink tests MINK_DRIVER_CLASS value: 'Drupal\FunctionalJavascriptTests\DrupalSelenium2Driver' -->
<env name="MINK_DRIVER_CLASS" value=""/>
<!-- Example for changing the driver args to mink tests MINK_DRIVER_ARGS value: '["http://127.0.0.1:8510"]' -->
<env name="MINK_DRIVER_ARGS" value=""/>
<!-- Example for changing the driver args to phantomjs tests MINK_DRIVER_ARGS_PHANTOMJS value: '["http://127.0.0.1:8510"]' -->
<env name="MINK_DRIVER_ARGS_PHANTOMJS" value=""/>
<!-- Example for changing the driver args to webdriver tests MINK_DRIVER_ARGS_WEBDRIVER value: '["chrome", { "chromeOptions": { "w3c": false } }, "http://localhost:4444/wd/hub"]' For using the Firefox browser, replace "chrome" with "firefox" -->
<env name="MINK_DRIVER_ARGS_WEBDRIVER" value=""/>
</php>
<testsuites>
<testsuite name="unit">
</testsuite>
<testsuite name="kernel">
<directory>../modules/contrib/jsonld/tests/src/Kernel</directory>
</testsuite>
<testsuite name="functional">
<directory>../modules/contrib/jsonld/tests/src/Functional</directory>
</testsuite>
<testsuite name="functional-javascript">
</testsuite>
<testsuite name="build">
</testsuite>
</testsuites>
<listeners>
<listener class="\Drupal\Tests\Listeners\DrupalListener">
</listener>
<!-- The Symfony deprecation listener has to come after the Drupal listener -->
<listener class="Symfony\Bridge\PhpUnit\SymfonyTestsListener">
</listener>
</listeners>
<!-- Filter for coverage reports. -->
<filter>
<whitelist>
<directory>./includes</directory>
<directory>./lib</directory>
<directory>./modules</directory>
<directory>../modules</directory>
<directory>../sites</directory>
<exclude>
<directory>./modules/*/src/Tests</directory>
<directory>./modules/*/tests</directory>
<directory>../modules/*/src/Tests</directory>
<directory>../modules/*/tests</directory>
<directory>../modules/*/*/src/Tests</directory>
<directory>../modules/*/*/tests</directory>
</exclude>
</whitelist>
</filter>
</phpunit>
99 changes: 15 additions & 84 deletions src/Normalizer/ContentEntityNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,10 @@

namespace Drupal\jsonld\Normalizer;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Routing\RouteProviderInterface;
use Drupal\Core\Url;
use Drupal\hal\LinkManager\LinkManagerInterface;
use Drupal\jsonld\Form\JsonLdSettingsForm;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Drupal\jsonld\Utils\JsonldNormalizerUtilsInterface;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;

/**
Expand Down Expand Up @@ -50,25 +44,11 @@ class ContentEntityNormalizer extends NormalizerBase {
protected $moduleHandler;

/**
* The configuration.
* Json-ld normalizer utilities.
*
* @var \Drupal\Core\Config\ImmutableConfig
* @var \Drupal\Jsonld\Utils\JsonldNormalizerUtilsInterface
*/
protected $config;

/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface
*/
protected $languageManager;

/**
* The route provider.
*
* @var \Drupal\Core\Routing\RouteProviderInterface
*/
protected $routeProvider;
protected $utils;

/**
* Constructs an ContentEntityNormalizer object.
Expand All @@ -79,26 +59,18 @@ class ContentEntityNormalizer extends NormalizerBase {
* The entity manager.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The configuration factory.
* @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
* The language manager.
* @param \Drupal\Core\Routing\RouteProviderInterface $route_provider
* The route provider.
* @param \Drupal\Jsonld\Utils\JsonldNormalizerUtilsInterface $normalizer_utils
* The json-ld normalizer utilities.
*/
public function __construct(LinkManagerInterface $link_manager,
EntityTypeManagerInterface $entity_manager,
ModuleHandlerInterface $module_handler,
ConfigFactoryInterface $config_factory,
LanguageManagerInterface $language_manager,
RouteProviderInterface $route_provider) {
JsonldNormalizerUtilsInterface $normalizer_utils) {

$this->linkManager = $link_manager;
$this->entityManager = $entity_manager;
$this->moduleHandler = $module_handler;
$this->config = $config_factory->get(JsonLdSettingsForm::CONFIG_NAME);
$this->languageManager = $language_manager;
$this->routeProvider = $route_provider;
$this->utils = $normalizer_utils;
}

/**
Expand Down Expand Up @@ -151,8 +123,8 @@ public function normalize($entity, $format = NULL, array $context = []) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$normalized = $normalized + [
'@graph' => [
$this->getEntityUri($entity) => [
'@id' => $this->getEntityUri($entity),
$this->utils->getEntityUri($entity) => [
'@id' => $this->utils->getEntityUri($entity),
'@type' => $types,
],
],
Expand All @@ -172,7 +144,7 @@ public function normalize($entity, $format = NULL, array $context = []) {
$fields = $entity->getFields();
}

$context['current_entity_id'] = $this->getEntityUri($entity);
$context['current_entity_id'] = $this->utils->getEntityUri($entity);
$context['current_entity_rdf_mapping'] = $rdf_mappings;

foreach ($fields as $name => $field) {
Expand Down Expand Up @@ -201,6 +173,10 @@ public function normalize($entity, $format = NULL, array $context = []) {
}

if (isset($context['depth']) && $context['depth'] == 0) {
if (!isset($context['utils'])) {
// Pass the normalizer utils to the invoking methods.
$context['utils'] = $this->utils;
}
$this->moduleHandler->invokeAll(self::NORMALIZE_ALTER_HOOK,
[$entity, &$normalized, $context]
);
Expand Down Expand Up @@ -279,51 +255,6 @@ public function denormalize($data, $class, $format = NULL, array $context = [])
return $entity;
}

/**
* Constructs the entity URI.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity.
*
* @return string
* The entity URI.
*
* @throws \Drupal\Core\Entity\EntityMalformedException
* When $entity->toUrl() fails.
*/
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')) {
if ($entity->getEntityTypeId() == 'file') {
return $entity->createFileUrl(FALSE);
}
return "";
}

try {
$undefined = $this->languageManager->getLanguage('und');
$entity_type = $entity->getEntityTypeId();

// This throws the RouteNotFoundException if the route doesn't exist.
$this->routeProvider->getRouteByName("rest.entity.$entity_type.GET");

$url = Url::fromRoute(
"rest.entity.$entity_type.GET",
[$entity_type => $entity->id()],
['absolute' => TRUE, 'language' => $undefined]
);
}
catch (RouteNotFoundException $e) {
$url = $entity->toUrl('canonical', ['absolute' => TRUE]);
}
if (!$this->config->get(JsonLdSettingsForm::REMOVE_JSONLD_FORMAT)) {
$url->setRouteParameter('_format', 'jsonld');
}
return $url->toString();
}

/**
* Gets the typed data IDs for a type URI.
*
Expand Down
Loading

0 comments on commit 7f16912

Please sign in to comment.