From 7f169128a638562dba8f7f9109a8e01c6a59e69c Mon Sep 17 00:00:00 2001 From: Jared Whiklo Date: Tue, 21 Sep 2021 09:54:18 -0500 Subject: [PATCH] Move getEntityUri to separate utility class. (#58) --- .github/workflows/build-8.x-1.x.yml | 9 +- composer.json | 33 ++++++- composer.lock | 18 ---- jsonld.api.php | 4 + jsonld.services.yml | 7 +- phpunit.xml | 74 ++++++++++++++ src/Normalizer/ContentEntityNormalizer.php | 99 +++---------------- src/Normalizer/FileEntityNormalizer.php | 20 ++-- src/Utils/JsonldNormalizerUtils.php | 97 ++++++++++++++++++ src/Utils/JsonldNormalizerUtilsInterface.php | 28 ++++++ .../Functional/JsonldContextGeneratorTest.php | 2 +- .../src/Kernel/JsonldContextGeneratorTest.php | 2 +- tests/src/Kernel/JsonldHookTest.php | 2 +- tests/src/Kernel/JsonldKernelTestBase.php | 7 +- ... => JsonldContentEntityNormalizerTest.php} | 10 +- 15 files changed, 278 insertions(+), 134 deletions(-) delete mode 100644 composer.lock create mode 100644 phpunit.xml create mode 100644 src/Utils/JsonldNormalizerUtils.php create mode 100644 src/Utils/JsonldNormalizerUtilsInterface.php rename tests/src/Kernel/Normalizer/{ContentEntityNormalizerTests.php => JsonldContentEntityNormalizerTest.php} (90%) diff --git a/.github/workflows/build-8.x-1.x.yml b/.github/workflows/build-8.x-1.x.yml index 8aa4aba..03c6344 100644 --- a/.github/workflows/build-8.x-1.x.yml +++ b/.github/workflows/build-8.x-1.x.yml @@ -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 @@ -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 diff --git a/composer.json b/composer.json index 9c71d8a..1efd6f4 100644 --- a/composer.json +++ b/composer.json @@ -14,10 +14,37 @@ "role": "Owner" }, { - "name": "Diego Pino", - "email": "dpino@metro.org", + "name": "Jared Whiklo", + "email": "jwhiklo@gmail.com", "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 ." + ] + } } diff --git a/composer.lock b/composer.lock deleted file mode 100644 index 64ccfba..0000000 --- a/composer.lock +++ /dev/null @@ -1,18 +0,0 @@ -{ - "_readme": [ - "This file locks the dependencies of your project to a known state", - "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", - "This file is @generated automatically" - ], - "content-hash": "10e2ac0726ff75523d5a41125a2045ca", - "packages": [], - "packages-dev": [], - "aliases": [], - "minimum-stability": "stable", - "stability-flags": [], - "prefer-stable": false, - "prefer-lowest": false, - "platform": [], - "platform-dev": [], - "plugin-api-version": "2.0.0" -} diff --git a/jsonld.api.php b/jsonld.api.php index f304522..6f65478 100644 --- a/jsonld.api.php +++ b/jsonld.api.php @@ -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 diff --git a/jsonld.services.yml b/jsonld.services.yml index 9f18315..50ad197 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_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: @@ -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'] diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..5debb88 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ../modules/contrib/jsonld/tests/src/Kernel + + + ../modules/contrib/jsonld/tests/src/Functional + + + + + + + + + + + + + + + + + ./includes + ./lib + ./modules + ../modules + ../sites + + ./modules/*/src/Tests + ./modules/*/tests + ../modules/*/src/Tests + ../modules/*/tests + ../modules/*/*/src/Tests + ../modules/*/*/tests + + + + \ No newline at end of file diff --git a/src/Normalizer/ContentEntityNormalizer.php b/src/Normalizer/ContentEntityNormalizer.php index eb13b46..79c55b9 100644 --- a/src/Normalizer/ContentEntityNormalizer.php +++ b/src/Normalizer/ContentEntityNormalizer.php @@ -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; /** @@ -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. @@ -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; } /** @@ -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, ], ], @@ -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) { @@ -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] ); @@ -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. * diff --git a/src/Normalizer/FileEntityNormalizer.php b/src/Normalizer/FileEntityNormalizer.php index 56ed6b6..356f169 100644 --- a/src/Normalizer/FileEntityNormalizer.php +++ b/src/Normalizer/FileEntityNormalizer.php @@ -2,13 +2,11 @@ namespace Drupal\jsonld\Normalizer; -use Drupal\Core\Config\ConfigFactoryInterface; use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Extension\ModuleHandlerInterface; use Drupal\Core\File\FileSystemInterface; -use Drupal\Core\Language\LanguageManagerInterface; -use Drupal\Core\Routing\RouteProviderInterface; use Drupal\hal\LinkManager\LinkManagerInterface; +use Drupal\jsonld\Utils\JsonldNormalizerUtilsInterface; use GuzzleHttp\ClientInterface; /** @@ -50,23 +48,17 @@ class FileEntityNormalizer extends ContentEntityNormalizer { * The module handler. * @param \Drupal\Core\File\FileSystemInterface $file_system * The file system 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 utils. */ public function __construct(EntityTypeManagerInterface $entity_manager, ClientInterface $http_client, LinkManagerInterface $link_manager, ModuleHandlerInterface $module_handler, FileSystemInterface $file_system, - ConfigFactoryInterface $config_factory, - LanguageManagerInterface $language_manager, - RouteProviderInterface $route_provider) { + JsonldNormalizerUtilsInterface $normalizer_utils) { - parent::__construct($link_manager, $entity_manager, $module_handler, $config_factory, $language_manager, $route_provider); + parent::__construct($link_manager, $entity_manager, $module_handler, $normalizer_utils); $this->httpClient = $http_client; $this->fileSystem = $file_system; @@ -79,7 +71,7 @@ public function normalize($entity, $format = NULL, array $context = []) { $data = parent::normalize($entity, $format, $context); // Replace the file url with a full url for the file. - $data['uri'][0]['value'] = $this->getEntityUri($entity); + $data['uri'][0]['value'] = $this->utils->getEntityUri($entity); return $data; } diff --git a/src/Utils/JsonldNormalizerUtils.php b/src/Utils/JsonldNormalizerUtils.php new file mode 100644 index 0000000..66b291f --- /dev/null +++ b/src/Utils/JsonldNormalizerUtils.php @@ -0,0 +1,97 @@ +config = $config_factory->get(JsonLdSettingsForm::CONFIG_NAME); + $this->languageManager = $language_manager; + $this->routeProvider = $route_provider; + } + + /** + * {@inheritdoc} + */ + public 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(); + } + +} diff --git a/src/Utils/JsonldNormalizerUtilsInterface.php b/src/Utils/JsonldNormalizerUtilsInterface.php new file mode 100644 index 0000000..f9ead8c --- /dev/null +++ b/src/Utils/JsonldNormalizerUtilsInterface.php @@ -0,0 +1,28 @@ +toUrl() fails. + */ + public function getEntityUri(EntityInterface $entity); + +} diff --git a/tests/src/Functional/JsonldContextGeneratorTest.php b/tests/src/Functional/JsonldContextGeneratorTest.php index 28cf9a5..649e4f3 100644 --- a/tests/src/Functional/JsonldContextGeneratorTest.php +++ b/tests/src/Functional/JsonldContextGeneratorTest.php @@ -36,7 +36,7 @@ class JsonldContextGeneratorTest extends BrowserTestBase { /** * Initial setup tasks that for every method method. */ - public function setUp() { + public function setUp() : void { parent::setUp(); // Create a test content type. diff --git a/tests/src/Kernel/JsonldContextGeneratorTest.php b/tests/src/Kernel/JsonldContextGeneratorTest.php index 127f584..9aeff21 100644 --- a/tests/src/Kernel/JsonldContextGeneratorTest.php +++ b/tests/src/Kernel/JsonldContextGeneratorTest.php @@ -52,7 +52,7 @@ class JsonldContextGeneratorTest extends JsonldKernelTestBase { /** * {@inheritdoc} */ - public function setUp() { + public function setUp() :void { parent::setUp(); $types = ['schema:Thing']; diff --git a/tests/src/Kernel/JsonldHookTest.php b/tests/src/Kernel/JsonldHookTest.php index d8609e4..3fa76ba 100644 --- a/tests/src/Kernel/JsonldHookTest.php +++ b/tests/src/Kernel/JsonldHookTest.php @@ -27,7 +27,7 @@ class JsonldHookTest extends JsonldKernelTestBase { /** * {@inheritdoc} */ - public function setUp() { + public function setUp() : void { parent::setUp(); \Drupal::service('router.builder')->rebuild(); } diff --git a/tests/src/Kernel/JsonldKernelTestBase.php b/tests/src/Kernel/JsonldKernelTestBase.php index 8e9df3f..e75f419 100644 --- a/tests/src/Kernel/JsonldKernelTestBase.php +++ b/tests/src/Kernel/JsonldKernelTestBase.php @@ -10,6 +10,7 @@ use Drupal\jsonld\Normalizer\EntityReferenceItemNormalizer; use Drupal\jsonld\Normalizer\FieldItemNormalizer; use Drupal\jsonld\Normalizer\FieldNormalizer; +use Drupal\jsonld\Utils\JsonldNormalizerUtils; use Drupal\KernelTests\KernelTestBase; use Drupal\serialization\EntityResolver\ChainEntityResolver; use Drupal\serialization\EntityResolver\TargetIdResolver; @@ -87,7 +88,7 @@ abstract class JsonldKernelTestBase extends KernelTestBase { /** * {@inheritdoc} */ - protected function setUp() { + protected function setUp() : void { parent::setUp(); $this->languageManager = \Drupal::service('language_manager'); @@ -182,9 +183,11 @@ protected function setUp() { $jsonld_context_generator = $this->container->get('jsonld.contextgenerator'); + $normalizer_utils = new JsonldNormalizerUtils(\Drupal::service('config.factory'), $this->languageManager, $this->routeProvider); + // Set up the mock serializer. $normalizers = [ - new ContentEntityNormalizer($link_manager, $entity_manager, \Drupal::moduleHandler(), \Drupal::service('config.factory'), $this->languageManager, $this->routeProvider), + new ContentEntityNormalizer($link_manager, $entity_manager, \Drupal::moduleHandler(), $normalizer_utils), new EntityReferenceItemNormalizer($link_manager, $chain_resolver, $jsonld_context_generator), new FieldItemNormalizer($jsonld_context_generator), new FieldNormalizer(), diff --git a/tests/src/Kernel/Normalizer/ContentEntityNormalizerTests.php b/tests/src/Kernel/Normalizer/JsonldContentEntityNormalizerTest.php similarity index 90% rename from tests/src/Kernel/Normalizer/ContentEntityNormalizerTests.php rename to tests/src/Kernel/Normalizer/JsonldContentEntityNormalizerTest.php index a5ba771..27c2d64 100644 --- a/tests/src/Kernel/Normalizer/ContentEntityNormalizerTests.php +++ b/tests/src/Kernel/Normalizer/JsonldContentEntityNormalizerTest.php @@ -5,16 +5,16 @@ use Drupal\Tests\jsonld\Kernel\JsonldKernelTestBase; /** - * Class ContentEntityTests. + * Tests the JSON-LD Normalizer. * * @group jsonld */ -class ContentEntityNormalizerTests extends JsonldKernelTestBase { +class JsonldContentEntityNormalizerTest extends JsonldKernelTestBase { /** * {@inheritdoc} */ - protected function setUp() { + protected function setUp() :void { parent::setUp(); \Drupal::service('router.builder')->rebuild(); @@ -24,11 +24,11 @@ protected function setUp() { * @covers \Drupal\jsonld\Normalizer\NormalizerBase::supportsNormalization * @covers \Drupal\jsonld\Normalizer\NormalizerBase::escapePrefix * @covers \Drupal\jsonld\Normalizer\ContentEntityNormalizer::normalize - * @covers \Drupal\jsonld\Normalizer\ContentEntityNormalizer::getEntityUri * @covers \Drupal\jsonld\Normalizer\FieldNormalizer::normalize * @covers \Drupal\jsonld\Normalizer\FieldNormalizer::normalizeFieldItems * @covers \Drupal\jsonld\Normalizer\FieldItemNormalizer::normalize * @covers \Drupal\jsonld\Normalizer\EntityReferenceItemNormalizer::normalize + * @covers \Drupal\jsonld\Utils\JsonldNormalizerUtils::getEntityUri */ public function testSimpleNormalizeJsonld() { @@ -43,11 +43,11 @@ public function testSimpleNormalizeJsonld() { * @covers \Drupal\jsonld\Normalizer\NormalizerBase::supportsNormalization * @covers \Drupal\jsonld\Normalizer\NormalizerBase::escapePrefix * @covers \Drupal\jsonld\Normalizer\ContentEntityNormalizer::normalize - * @covers \Drupal\jsonld\Normalizer\ContentEntityNormalizer::getEntityUri * @covers \Drupal\jsonld\Normalizer\FieldNormalizer::normalize * @covers \Drupal\jsonld\Normalizer\FieldNormalizer::normalizeFieldItems * @covers \Drupal\jsonld\Normalizer\FieldItemNormalizer::normalize * @covers \Drupal\jsonld\Normalizer\EntityReferenceItemNormalizer::normalize + * @covers \Drupal\jsonld\Utils\JsonldNormalizerUtils::getEntityUri */ public function testLocalizedNormalizeJsonld() {