Skip to content

Commit

Permalink
downloadURL token for distributions. (#266)
Browse files Browse the repository at this point in the history
* DownloadURL token for distributions
* Unit tests for the new code
* Fix code style issues
  • Loading branch information
fmizzell authored and thierrydallacroce committed Dec 4, 2019
1 parent f7f1432 commit e4751f1
Show file tree
Hide file tree
Showing 9 changed files with 337 additions and 49 deletions.
15 changes: 14 additions & 1 deletion modules/custom/dkan_common/src/Tests/Mock/Chain.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,13 @@ public function add($objectClass, $method, $return, $storeId = NULL) {
return $this;
}

/**
* Get stored input.
*/
public function getStoredInput($id) {
return (isset($this->store[$id])) ? $this->store[$id] : NULL;
}

/**
* Get Mock.
*/
Expand Down Expand Up @@ -93,7 +100,13 @@ private function setupMethodReturns($objectClass, MockObject $mock, $method) {
*/
private function setStorageWithReturn(MockObject $mock, $method, $storeId, $return) {
$mock->method($method)->willReturnCallback(function ($input) use ($storeId, $return) {
$this->store[$storeId] = $input;
if (func_num_args() > 1) {
$this->store[$storeId] = func_get_args();
}
else {
$this->store[$storeId] = $input;
}

if (is_object($return)) {
if ($return instanceof \Exception) {
throw $return;
Expand Down
23 changes: 23 additions & 0 deletions modules/custom/dkan_common/src/UrlHostTokenResolver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace Drupal\dkan_common;

/**
* UrlHostTokenResolver.
*/
class UrlHostTokenResolver {
const TOKEN = "h-o.st";

/**
* Resolve.
*
* Replace a host's token in a string.
*/
public static function resolve($string) {
if (substr_count($string, self::TOKEN) > 0) {
$string = str_replace(self::TOKEN, \Drupal::request()->getHost(), $string);
}
return $string;
}

}
1 change: 0 additions & 1 deletion modules/custom/dkan_common/tests/src/Unit/.gitkeep

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

use Drupal\Core\DependencyInjection\Container;
use Drupal\dkan_common\Tests\Mock\Chain;
use Drupal\dkan_common\UrlHostTokenResolver;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;

/**
*
*/
class UrlHostTokenResolverTest extends TestCase {

/**
*
*/
public function test() {
$container = (new Chain($this))
->add(Container::class, "get", RequestStack::class)
->add(RequestStack::class, "getCurrentRequest", Request::class)
->add(Request::class, "getHost", "replacement")
->getMock();

\Drupal::setContainer($container);

$string = "blahj do bla da bla " . UrlHostTokenResolver::TOKEN . " after token.";
$newString = UrlHostTokenResolver::resolve($string);
$this->assertEquals("blahj do bla da bla replacement after token.", $newString);
}

}
57 changes: 13 additions & 44 deletions modules/custom/dkan_data/dkan_data.module
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\dkan_common\UrlHostTokenResolver;
use Drupal\dkan_data\DataNodeLifeCycle;
use Drupal\dkan_data\ValueReferencer;

/**
Expand All @@ -25,6 +27,13 @@ function dkan_data_node_load(array $entities) {
$metadata_obj = $referencer->dereference($metadata_obj, dereferencing_method());
$entity->set('field_json_metadata', json_encode($metadata_obj));
}

// @todo Decouple "resource" functionality from specific dataset properties.
if ($entity->bundle() == "data" && $entity->field_data_type->value == "distribution") {
$metadataString = $entity->get('field_json_metadata')->value;
$metadataString = UrlHostTokenResolver::resolve($metadataString);
$entity->set('field_json_metadata', $metadataString);
}
}

}
Expand Down Expand Up @@ -63,51 +72,11 @@ function dereferencing_method() : int {
* Implements hook_entity_presave().
*/
function dkan_data_entity_presave(EntityInterface $entity) {

if ($entity->bundle() != "data") {
return;
}

if (empty($entity->get('field_data_type')->value)) {
$entity->set('field_data_type', "dataset");
try {
(new DataNodeLifeCycle($entity))->presave();
}

if ($entity->get('field_data_type')->value != 'dataset') {
return;
}

$entityType = $entity->getEntityTypeId();

$metadata = json_decode($entity->get('field_json_metadata')->value);

$title = isset($metadata->title) ? $metadata->title : $metadata->name;
if ($entityType == 'node') {
$entity->setTitle($title);
if (empty($entity->field_data_type->value)) {
$entity->field_data_type->value = "dataset";
}
}

// If there is no uuid add one.
if (!isset($metadata->identifier)) {
$metadata->identifier = $entity->uuid();
}
// If one exists in the uuid it should be the same in the table.
else {
$entity->set('uuid', $metadata->identifier);
}

// Reference the dataset's values, and update our json metadata.
$referencer = Drupal::service("dkan_data.value_referencer");
$metadata = $referencer->reference($metadata);
$entity->set('field_json_metadata', json_encode($metadata));

// Check for possible orphan property references when updating a dataset.
if (isset($entity->original)) {
$referencer->processReferencesInUpdatedDataset(
json_decode($entity->referenced_metadata),
$metadata
);
catch (\Exception $e) {
// Nothing to do, this entity is not a data node.
}
}

Expand Down
167 changes: 167 additions & 0 deletions modules/custom/dkan_data/src/DataNodeLifeCycle.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
<?php

namespace Drupal\dkan_data;

use Drupal\Core\Entity\EntityInterface;
use Drupal\dkan_common\UrlHostTokenResolver;
use Drupal\node\Entity\Node;

/**
* DataNodeLifeCycle.
*/
class DataNodeLifeCycle {
private $node;

/**
* Constructor.
*/
public function __construct(EntityInterface $entity) {
$this->validate($entity);
$this->node = $entity;
}

/**
* Presave.
*
* Activities to move a data node through during presave.
*/
public function presave() {
/* @var $entity \Drupal\node\Entity\Node */
$entity = $this->node;

if (empty($entity->get('field_data_type')->value)) {
$entity->set('field_data_type', "dataset");
}

$dataType = $entity->get('field_data_type')->value;

switch ($dataType) {
case 'dataset':
$this->datasetPresave();
break;

case 'distribution':
$this->distributionPresave();
break;
}
}

/**
* Private.
*/
private function datasetPresave() {
/* @var $entity \Drupal\node\Entity\Node */
$entity = $this->node;

$metadata = $this->getMetaData();

$title = isset($metadata->title) ? $metadata->title : $metadata->name;

$entity->setTitle($title);
if (empty($entity->field_data_type->value)) {
$entity->field_data_type->value = "dataset";
}

// If there is no uuid add one.
if (!isset($metadata->identifier)) {
$metadata->identifier = $entity->uuid();
}
// If one exists in the uuid it should be the same in the table.
else {
$entity->set('uuid', $metadata->identifier);
}

// Reference the dataset's values, and update our json metadata.
$referencer = \Drupal::service("dkan_data.value_referencer");
$metadata = $referencer->reference($metadata);
$this->setMetadata($metadata);

// Check for possible orphan property references when updating a dataset.
if (isset($entity->original)) {
$referencer->processReferencesInUpdatedDataset(
json_decode($entity->referenced_metadata),
$metadata
);
}
}

/**
* Private.
*/
private function distributionPresave() {
$metadata = $this->getMetaData();
$host = \Drupal::request()->getSchemeAndHttpHost();
if (isset($metadata->data->downloadURL)) {
$newUrl = $metadata->data->downloadURL;
if (substr_count($newUrl, $host) > 0) {
$parsedUrl = parse_url($newUrl);
$parsedUrl['host'] = UrlHostTokenResolver::TOKEN;
$metadata->data->downloadURL = $this->unparseUrl($parsedUrl);
$this->setMetadata($metadata);
}
}

}

/**
* Private.
*/
private function getMetaData() {
/* @var $entity \Drupal\node\Entity\Node */
$entity = $this->node;
return json_decode($entity->get('field_json_metadata')->value);
}

/**
* Private.
*/
private function setMetadata($metadata) {
/* @var $entity \Drupal\node\Entity\Node */
$entity = $this->node;
$entity->set('field_json_metadata', json_encode($metadata));
}

/**
* Private.
*/
private function validate(EntityInterface $entity) {
if (!($entity instanceof Node)) {
throw new \Exception("We only work with nodes.");
}

if ($entity->bundle() != "data") {
throw new \Exception("We only work with data nodes.");
}
}

/**
* Private.
*/
private function unparseUrl($parsedUrl) {
$url = '';
$urlParts = [
'scheme',
'host',
'port',
'user',
'pass',
'path',
'query',
'fragment',
];

foreach ($urlParts as $part) {
if (!isset($parsedUrl[$part])) {
continue;
}
$url .= ($part == "port") ? ':' : '';
$url .= ($part == "query") ? '?' : '';
$url .= ($part == "fragment") ? '#' : '';
$url .= $parsedUrl[$part];
$url .= ($part == "scheme") ? '://' : '';
}

return $url;
}

}
Loading

0 comments on commit e4751f1

Please sign in to comment.