first commit

This commit is contained in:
2020-06-08 23:57:36 +02:00
commit 6277454f7a
16057 changed files with 1715382 additions and 0 deletions
@@ -0,0 +1,8 @@
name: 'RDF module conflicting namespaces test'
type: module
description: 'Test conflicting namespace declaration.'
package: Testing
version: VERSION
core: 8.x
dependencies:
- drupal:rdf
@@ -0,0 +1,15 @@
<?php
/**
* @file
* Test the namespace registration functionality.
*/
/**
* Implements hook_rdf_namespaces().
*/
function rdf_conflicting_namespaces_rdf_namespaces() {
return [
'dc' => 'http://purl.org/conflicting/namespace',
];
}
@@ -0,0 +1,8 @@
name: 'RDF test module'
type: module
description: 'Test functionality for the RDF module.'
package: Testing
version: VERSION
core: 8.x
dependencies:
- rdf
@@ -0,0 +1,23 @@
<?php
namespace Drupal\rdf_test;
/**
* Contains methods for test data conversions.
*/
class TestDataConverter {
/**
* Converts data into a string for placement into a content attribute.
*
* @param array $data
* The data to be altered and placed in the content attribute.
*
* @return string
* Returns the data.
*/
public static function convertFoo($data) {
return 'foo' . $data['value'];
}
}
@@ -0,0 +1,8 @@
name: 'RDF module namespaces test'
type: module
description: 'Test namespace declaration.'
package: Testing
version: VERSION
core: 8.x
dependencies:
- drupal:rdf
@@ -0,0 +1,16 @@
<?php
/**
* @file
* Test the namespace registration functionality.
*/
/**
* Implements hook_rdf_namespaces().
*/
function rdf_test_namespaces_rdf_namespaces() {
return [
'foaf' => 'http://xmlns.com/foaf/0.1/',
'foaf1' => 'http://xmlns.com/foaf/0.1/',
];
}
@@ -0,0 +1,359 @@
<?php
namespace Drupal\Tests\rdf\Functional;
use Drupal\Core\Url;
use Drupal\comment\CommentInterface;
use Drupal\comment\CommentManagerInterface;
use Drupal\Tests\comment\Functional\CommentTestBase;
use Drupal\Tests\rdf\Traits\RdfParsingTrait;
use Drupal\user\RoleInterface;
use Drupal\comment\Entity\Comment;
/**
* Tests the RDFa markup of comments.
*
* @group rdf
*/
class CommentAttributesTest extends CommentTestBase {
use RdfParsingTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['views', 'node', 'comment', 'rdf'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* URI of the front page of the Drupal site.
*
* @var string
*/
protected $baseUri;
/**
* URI of the test node created by CommentTestBase::setUp().
*
* @var string
*/
protected $nodeUri;
protected function setUp() {
parent::setUp();
// Enables anonymous user comments.
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
'access comments' => TRUE,
'post comments' => TRUE,
'skip comment approval' => TRUE,
]);
// Allows anonymous to leave their contact information.
$this->setCommentAnonymous(CommentInterface::ANONYMOUS_MAY_CONTACT);
$this->setCommentPreview(DRUPAL_OPTIONAL);
$this->setCommentForm(TRUE);
$this->setCommentSubject(TRUE);
$this->setCommentSettings('comment_default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.');
// Prepares commonly used URIs.
$this->baseUri = Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString();
$this->nodeUri = $this->node->toUrl('canonical', ['absolute' => TRUE])->toString();
// Set relation between node and comment.
$article_mapping = rdf_get_mapping('node', 'article');
$comment_count_mapping = [
'properties' => ['sioc:num_replies'],
'datatype' => 'xsd:integer',
'datatype_callback' => ['callable' => 'Drupal\rdf\CommonDataConverter::rawValue'],
];
$article_mapping->setFieldMapping('comment_count', $comment_count_mapping)->save();
// Save user mapping.
$user_mapping = rdf_get_mapping('user', 'user');
$username_mapping = [
'properties' => ['foaf:name'],
];
$user_mapping->setFieldMapping('name', $username_mapping)->save();
$user_mapping->setFieldMapping('homepage', ['properties' => ['foaf:page'], 'mapping_type' => 'rel'])->save();
// Save comment mapping.
$mapping = rdf_get_mapping('comment', 'comment');
$mapping->setBundleMapping(['types' => ['sioc:Post', 'sioct:Comment']])->save();
$field_mappings = [
'subject' => [
'properties' => ['dc:title'],
],
'created' => [
'properties' => ['dc:date', 'dc:created'],
'datatype' => 'xsd:dateTime',
'datatype_callback' => ['callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value'],
],
'changed' => [
'properties' => ['dc:modified'],
'datatype' => 'xsd:dateTime',
'datatype_callback' => ['callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value'],
],
'comment_body' => [
'properties' => ['content:encoded'],
],
'pid' => [
'properties' => ['sioc:reply_of'],
'mapping_type' => 'rel',
],
'uid' => [
'properties' => ['sioc:has_creator'],
'mapping_type' => 'rel',
],
'name' => [
'properties' => ['foaf:name'],
],
];
// Iterate over shared field mappings and save.
foreach ($field_mappings as $field_name => $field_mapping) {
$mapping->setFieldMapping($field_name, $field_mapping)->save();
}
}
/**
* Tests the presence of the RDFa markup for the number of comments.
*/
public function testNumberOfCommentsRdfaMarkup() {
// Posts 2 comments on behalf of registered user.
$this->saveComment($this->node->id(), $this->webUser->id());
$this->saveComment($this->node->id(), $this->webUser->id());
// Tests number of comments in teaser view.
$this->drupalLogin($this->webUser);
$this->drupalGet('node');
// Number of comments.
$expected_value = [
'type' => 'literal',
'value' => 2,
'datatype' => 'http://www.w3.org/2001/XMLSchema#integer',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $this->nodeUri, 'http://rdfs.org/sioc/ns#num_replies', $expected_value), 'Number of comments found in RDF output of teaser view (sioc:num_replies).');
$this->drupalGet($this->node->toUrl());
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $this->nodeUri, 'http://rdfs.org/sioc/ns#num_replies', $expected_value), 'Number of comments found in RDF output of full node view mode (sioc:num_replies).');
}
/**
* Tests comment author link markup has not been broken by RDF.
*/
public function testCommentRdfAuthorMarkup() {
// Post a comment as a registered user.
$this->saveComment($this->node->id(), $this->webUser->id());
// Give the user access to view user profiles so the profile link shows up.
user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['access user profiles']);
$this->drupalLogin($this->webUser);
// Ensure that the author link still works properly after the author output
// is modified by the RDF module.
$this->drupalGet('node/' . $this->node->id());
$this->assertLink($this->webUser->getAccountName());
$this->assertLinkByHref('user/' . $this->webUser->id());
}
/**
* Tests if RDFa markup for meta information is present in comments.
*
* Tests presence of RDFa markup for the title, date and author and homepage
* on comments from registered and anonymous users.
*/
public function testCommentRdfaMarkup() {
// Posts comment #1 on behalf of registered user.
$comment1 = $this->saveComment($this->node->id(), $this->webUser->id());
// Tests comment #1 with access to the user profile.
$this->drupalLogin($this->webUser);
$this->_testBasicCommentRdfaMarkup($comment1);
// Tests comment #1 with no access to the user profile (as anonymous user).
$this->drupalLogout();
$this->_testBasicCommentRdfaMarkup($comment1);
// Posts comment #2 as anonymous user.
$anonymous_user = [];
$anonymous_user['name'] = $this->randomMachineName();
$anonymous_user['mail'] = 'tester@simpletest.org';
$anonymous_user['homepage'] = 'http://example.org/';
$comment2 = $this->saveComment($this->node->id(), 0, $anonymous_user);
// Tests comment #2 as anonymous user.
$this->_testBasicCommentRdfaMarkup($comment2, $anonymous_user);
// Tests comment #2 as logged in user.
$this->drupalLogin($this->webUser);
$this->_testBasicCommentRdfaMarkup($comment2, $anonymous_user);
}
/**
* Tests RDF comment replies.
*/
public function testCommentReplyOfRdfaMarkup() {
// Posts comment #1 on behalf of registered user.
$this->drupalLogin($this->webUser);
$comment_1 = $this->saveComment($this->node->id(), $this->webUser->id());
$comment_1_uri = $comment_1->toUrl('canonical', ['absolute' => TRUE])->toString();
// Posts a reply to the first comment.
$comment_2 = $this->saveComment($this->node->id(), $this->webUser->id(), NULL, $comment_1->id());
$comment_2_uri = $comment_2->toUrl('canonical', ['absolute' => TRUE])->toString();
// Tests the reply_of relationship of a first level comment.
$this->drupalGet($this->node->toUrl());
$expected_value = [
'type' => 'uri',
'value' => $this->nodeUri,
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $comment_1_uri, 'http://rdfs.org/sioc/ns#reply_of', $expected_value), 'Comment relation to its node found in RDF output (sioc:reply_of).');
// Tests the reply_of relationship of a second level comment.
$expected_value = [
'type' => 'uri',
'value' => $this->nodeUri,
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $comment_2_uri, 'http://rdfs.org/sioc/ns#reply_of', $expected_value), 'Comment relation to its node found in RDF output (sioc:reply_of).');
$expected_value = [
'type' => 'uri',
'value' => $comment_1_uri,
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $comment_2_uri, 'http://rdfs.org/sioc/ns#reply_of', $expected_value), 'Comment relation to its parent comment found in RDF output (sioc:reply_of).');
}
/**
* Helper function for testCommentRdfaMarkup().
*
* Tests the current page for basic comment RDFa markup.
*
* @param $comment
* Comment object.
* @param $account
* An array containing information about an anonymous user.
*/
public function _testBasicCommentRdfaMarkup(CommentInterface $comment, $account = []) {
$this->drupalGet($this->node->toUrl());
$comment_uri = $comment->toUrl('canonical', ['absolute' => TRUE])->toString();
// Comment type.
$expected_value = [
'type' => 'uri',
'value' => 'http://rdfs.org/sioc/types#Comment',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $comment_uri, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', $expected_value), 'Comment type found in RDF output (sioct:Comment).');
// Comment type.
$expected_value = [
'type' => 'uri',
'value' => 'http://rdfs.org/sioc/ns#Post',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $comment_uri, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', $expected_value), 'Comment type found in RDF output (sioc:Post).');
// Comment title.
$expected_value = [
'type' => 'literal',
'value' => $comment->getSubject(),
'lang' => 'en',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $comment_uri, 'http://purl.org/dc/terms/title', $expected_value), 'Comment subject found in RDF output (dc:title).');
// Comment date.
$expected_value = [
'type' => 'literal',
'value' => $this->container->get('date.formatter')->format($comment->getCreatedTime(), 'custom', 'c', 'UTC'),
'datatype' => 'http://www.w3.org/2001/XMLSchema#dateTime',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $comment_uri, 'http://purl.org/dc/terms/date', $expected_value), 'Comment date found in RDF output (dc:date).');
// Comment date.
$expected_value = [
'type' => 'literal',
'value' => $this->container->get('date.formatter')->format($comment->getCreatedTime(), 'custom', 'c', 'UTC'),
'datatype' => 'http://www.w3.org/2001/XMLSchema#dateTime',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $comment_uri, 'http://purl.org/dc/terms/created', $expected_value), 'Comment date found in RDF output (dc:created).');
// Comment body.
$expected_value = [
'type' => 'literal',
'value' => $comment->comment_body->value . "\n",
'lang' => 'en',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $comment_uri, 'http://purl.org/rss/1.0/modules/content/encoded', $expected_value), 'Comment body found in RDF output (content:encoded).');
// The comment author can be a registered user or an anonymous user.
if ($comment->getOwnerId() > 0) {
// Comment relation to author.
$expected_value = [
'type' => 'uri',
'value' => Url::fromRoute('entity.user.canonical', ['user' => $comment->getOwnerId()], ['absolute' => TRUE])->toString(),
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $comment_uri, 'http://rdfs.org/sioc/ns#has_creator', $expected_value), 'Comment relation to author found in RDF output (sioc:has_creator).');
}
else {
// The author is expected to be a blank node.
$this->assertTrue($this->rdfElementIsBlankNode($this->getSession()->getPage()->getContent(), $this->baseUri, $comment_uri, '<http://rdfs.org/sioc/ns#has_creator>'));
}
// Author name.
$name = empty($account["name"]) ? $this->webUser->getAccountName() : $account["name"] . " (not verified)";
$expected_value = [
'type' => 'literal',
'value' => $name,
];
$this->assertTrue($this->hasRdfChildProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $comment_uri, '<http://rdfs.org/sioc/ns#has_creator>', 'http://xmlns.com/foaf/0.1/name', $expected_value), 'Comment author name found in RDF output (foaf:name).');
// Comment author homepage (only for anonymous authors).
if ($comment->getOwnerId() == 0) {
$expected_value = [
'type' => 'uri',
'value' => 'http://example.org/',
];
$this->assertTrue($this->hasRdfChildProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $comment_uri, '<http://rdfs.org/sioc/ns#has_creator>', 'http://xmlns.com/foaf/0.1/page', $expected_value), 'Comment author link found in RDF output (foaf:page).');
}
}
/**
* Creates a comment entity.
*
* @param $nid
* Node id which will hold the comment.
* @param $uid
* User id of the author of the comment. Can be NULL if $contact provided.
* @param $contact
* Set to NULL for no contact info, TRUE to ignore success checking, and
* array of values to set contact info.
* @param $pid
* Comment id of the parent comment in a thread.
*
* @return \Drupal\comment\Entity\Comment
* The saved comment.
*/
public function saveComment($nid, $uid, $contact = NULL, $pid = 0) {
$values = [
'entity_id' => $nid,
'entity_type' => 'node',
'field_name' => 'comment',
'uid' => $uid,
'pid' => $pid,
'subject' => $this->randomMachineName(),
'comment_body' => $this->randomMachineName(),
'status' => 1,
];
if ($contact) {
$values += $contact;
}
$comment = Comment::create($values);
$comment->save();
return $comment;
}
}
@@ -0,0 +1,166 @@
<?php
namespace Drupal\Tests\rdf\Functional;
use Drupal\Core\Url;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Tests\rdf\Traits\RdfParsingTrait;
use Drupal\Tests\taxonomy\Functional\TaxonomyTestBase;
/**
* Tests RDFa markup generation for taxonomy term fields.
*
* @group rdf
*/
class EntityReferenceFieldAttributesTest extends TaxonomyTestBase {
use RdfParsingTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['rdf', 'field_test', 'file', 'image'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* URI of the front page of the Drupal site.
*
* @var string
*/
protected $baseUri;
/**
* The name of the taxonomy term reference field used in the test.
*
* @var string
*/
protected $fieldName;
/**
* The vocabulary object used in the test.
*
* @var \Drupal\taxonomy\VocabularyInterface
*/
protected $vocabulary;
protected function setUp() {
parent::setUp();
$web_user = $this->drupalCreateUser(['bypass node access', 'administer taxonomy']);
$this->drupalLogin($web_user);
$this->vocabulary = $this->createVocabulary();
// Create the field.
$this->fieldName = 'field_taxonomy_test';
$handler_settings = [
'target_bundles' => [
$this->vocabulary->id() => $this->vocabulary->id(),
],
'auto_create' => TRUE,
];
$this->createEntityReferenceField('node', 'article', $this->fieldName, 'Tags', 'taxonomy_term', 'default', $handler_settings, FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
/** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
$display_repository = \Drupal::service('entity_display.repository');
$display_repository->getFormDisplay('node', 'article')
->setComponent($this->fieldName, ['type' => 'options_select'])
->save();
$display_repository->getViewDisplay('node', 'article', 'full')
->setComponent($this->fieldName, ['type' => 'entity_reference_label'])
->save();
// Set the RDF mapping for the new field.
rdf_get_mapping('node', 'article')
->setFieldMapping($this->fieldName, [
'properties' => ['dc:subject'],
'mapping_type' => 'rel',
])
->save();
rdf_get_mapping('taxonomy_term', $this->vocabulary->id())
->setBundleMapping(['types' => ['skos:Concept']])
->setFieldMapping('name', ['properties' => ['rdfs:label']])
->save();
// Prepares commonly used URIs.
$this->baseUri = Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString();
}
/**
* Tests if file fields in teasers have correct resources.
*
* Ensure that file fields have the correct resource as the object in RDFa
* when displayed as a teaser.
*/
public function testNodeTeaser() {
// Set the teaser display to show this field.
\Drupal::service('entity_display.repository')
->getViewDisplay('node', 'article', 'teaser')
->setComponent($this->fieldName, ['type' => 'entity_reference_label'])
->save();
// Create a term in each vocabulary.
$term1 = $this->createTerm($this->vocabulary);
$term2 = $this->createTerm($this->vocabulary);
$taxonomy_term_1_uri = $term1->toUrl('canonical', ['absolute' => TRUE])->toString();
$taxonomy_term_2_uri = $term2->toUrl('canonical', ['absolute' => TRUE])->toString();
// Create the node.
$node = $this->drupalCreateNode(['type' => 'article']);
$node->set($this->fieldName, [
['target_id' => $term1->id()],
['target_id' => $term2->id()],
]);
// Render the node.
$node_render_array = \Drupal::entityTypeManager()
->getViewBuilder('node')
->view($node, 'teaser');
$html = \Drupal::service('renderer')->renderRoot($node_render_array);
// Node relations to taxonomy terms.
$node_uri = $node->toUrl('canonical', ['absolute' => TRUE])->toString();
$expected_value = [
'type' => 'uri',
'value' => $taxonomy_term_1_uri,
];
$this->assertTrue($this->hasRdfProperty($html, $this->baseUri, $node_uri, 'http://purl.org/dc/terms/subject', $expected_value), 'Node to term relation found in RDF output (dc:subject).');
$expected_value = [
'type' => 'uri',
'value' => $taxonomy_term_2_uri,
];
$this->assertTrue($this->hasRdfProperty($html, $this->baseUri, $node_uri, 'http://purl.org/dc/terms/subject', $expected_value), 'Node to term relation found in RDF output (dc:subject).');
// Taxonomy terms triples.
// Term 1.
$expected_value = [
'type' => 'uri',
'value' => 'http://www.w3.org/2004/02/skos/core#Concept',
];
// @todo Enable with https://www.drupal.org/node/2072791.
// $this->assertTrue($graph->hasProperty($taxonomy_term_1_uri, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', $expected_value), 'Taxonomy term type found in RDF output (skos:Concept).');
$expected_value = [
'type' => 'literal',
'value' => $term1->getName(),
];
// $this->assertTrue($graph->hasProperty($taxonomy_term_1_uri, 'http://www.w3.org/2000/01/rdf-schema#label', $expected_value), 'Taxonomy term name found in RDF output (rdfs:label).');
// Term 2.
$expected_value = [
'type' => 'uri',
'value' => 'http://www.w3.org/2004/02/skos/core#Concept',
];
// $this->assertTrue($graph->hasProperty($taxonomy_term_2_uri, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', $expected_value), 'Taxonomy term type found in RDF output (skos:Concept).');
$expected_value = [
'type' => 'literal',
'value' => $term2->getName(),
];
// $this->assertTrue($graph->hasProperty($taxonomy_term_2_uri, 'http://www.w3.org/2000/01/rdf-schema#label', $expected_value), 'Taxonomy term name found in RDF output (rdfs:label).');
}
}
@@ -0,0 +1,115 @@
<?php
namespace Drupal\Tests\rdf\Functional;
use Drupal\Core\Url;
use Drupal\Tests\file\Functional\FileFieldTestBase;
use Drupal\file\Entity\File;
use Drupal\Tests\rdf\Traits\RdfParsingTrait;
/**
* Tests the RDFa markup of filefields.
*
* @group rdf
*/
class FileFieldAttributesTest extends FileFieldTestBase {
use RdfParsingTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['rdf', 'file'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* URI of the front page of the Drupal site.
*
* @var string
*/
protected $baseUri;
/**
* The name of the file field used in the test.
*
* @var string
*/
protected $fieldName;
/**
* The file object used in the test.
*
* @var \Drupal\file\FileInterface
*/
protected $file;
/**
* The node object used in the test.
*
* @var \Drupal\node\NodeInterface
*/
protected $node;
protected function setUp() {
parent::setUp();
$node_storage = $this->container->get('entity_type.manager')->getStorage('node');
$this->fieldName = strtolower($this->randomMachineName());
$type_name = 'article';
$this->createFileField($this->fieldName, 'node', $type_name);
// Set the teaser display to show this field.
\Drupal::service('entity_display.repository')
->getViewDisplay('node', 'article', 'teaser')
->setComponent($this->fieldName, ['type' => 'file_default'])
->save();
// Set the RDF mapping for the new field.
$mapping = rdf_get_mapping('node', 'article');
$mapping->setFieldMapping($this->fieldName, ['properties' => ['rdfs:seeAlso'], 'mapping_type' => 'rel'])->save();
$test_file = $this->getTestFile('text');
// Create a new node with the uploaded file.
$nid = $this->uploadNodeFile($test_file, $this->fieldName, $type_name);
$node_storage->resetCache([$nid]);
$this->node = $node_storage->load($nid);
$this->file = File::load($this->node->{$this->fieldName}->target_id);
// Prepares commonly used URIs.
$this->baseUri = Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString();
}
/**
* Tests if file fields in teasers have correct resources.
*
* Ensure that file fields have the correct resource as the object in RDFa
* when displayed as a teaser.
*/
public function testNodeTeaser() {
// Render the teaser.
$node_render_array = \Drupal::entityTypeManager()
->getViewBuilder('node')
->view($this->node, 'teaser');
$html = \Drupal::service('renderer')->renderRoot($node_render_array);
$node_uri = $this->node->toUrl('canonical', ['absolute' => TRUE])->toString();
$file_uri = file_create_url($this->file->getFileUri());
// Node relation to attached file.
$expected_value = [
'type' => 'uri',
'value' => $file_uri,
];
$this->assertTrue($this->hasRdfProperty($html, $this->baseUri, $node_uri, 'http://www.w3.org/2000/01/rdf-schema#seeAlso', $expected_value), 'Node to file relation found in RDF output (rdfs:seeAlso).');
$this->drupalGet('node');
}
}
@@ -0,0 +1,68 @@
<?php
namespace Drupal\Tests\rdf\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests hook_rdf_namespaces().
*
* @group rdf
*/
class GetRdfNamespacesTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['rdf', 'rdf_test_namespaces'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests getting RDF namespaces.
*/
public function testGetRdfNamespaces() {
// Fetches the front page and extracts RDFa 1.1 prefixes.
$this->drupalGet('');
// We have to use the find() method on the driver directly because //html is
// prepended to all xpath queries otherwise.
$driver = $this->getSession()->getDriver();
$element = $driver->find('//html[contains(@prefix, "rdfs: http://www.w3.org/2000/01/rdf-schema#")]');
$this->assertCount(1, $element, 'A prefix declared once is displayed.');
$element = $driver->find('//html[contains(@prefix, "foaf: http://xmlns.com/foaf/0.1/")]');
$this->assertCount(1, $element, 'The same prefix declared in several implementations of hook_rdf_namespaces() is valid as long as all the namespaces are the same.');
$element = $driver->find('//html[contains(@prefix, "foaf1: http://xmlns.com/foaf/0.1/")]');
$this->assertCount(1, $element, 'Two prefixes can be assigned the same namespace.');
$element = $driver->find('//html[contains(@prefix, "dc: http://purl.org/dc/terms/")]');
$this->assertCount(1, $element, 'When a prefix has conflicting namespaces, the first declared one is used.');
// Get all RDF namespaces.
$ns = rdf_get_namespaces();
$this->assertEqual($ns['rdfs'], 'http://www.w3.org/2000/01/rdf-schema#', 'A prefix declared once is included.');
$this->assertEqual($ns['foaf'], 'http://xmlns.com/foaf/0.1/', 'The same prefix declared in several implementations of hook_rdf_namespaces() is valid as long as all the namespaces are the same.');
$this->assertEqual($ns['foaf1'], 'http://xmlns.com/foaf/0.1/', 'Two prefixes can be assigned the same namespace.');
// Enable rdf_conflicting_namespaces to ensure that an exception is thrown
// when RDF namespaces are conflicting.
\Drupal::service('module_installer')->install(['rdf_conflicting_namespaces'], TRUE);
try {
$ns = rdf_get_namespaces();
$this->fail('Expected exception not thrown for conflicting namespace declaration.');
}
catch (\Exception $e) {
$this->pass('Expected exception thrown: ' . $e->getMessage());
}
}
}
@@ -0,0 +1,35 @@
<?php
namespace Drupal\Tests\rdf\Functional\Hal;
use Drupal\Tests\rdf\Functional\Rest\RdfMappingResourceTestBase;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
/**
* @group hal
*/
class RdfMappingHalJsonAnonTest extends RdfMappingResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
}
@@ -0,0 +1,40 @@
<?php
namespace Drupal\Tests\rdf\Functional\Hal;
use Drupal\Tests\rdf\Functional\Rest\RdfMappingResourceTestBase;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
* @group hal
*/
class RdfMappingHalJsonBasicAuthTest extends RdfMappingResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal', 'basic_auth'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}
@@ -0,0 +1,40 @@
<?php
namespace Drupal\Tests\rdf\Functional\Hal;
use Drupal\Tests\rdf\Functional\Rest\RdfMappingResourceTestBase;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
/**
* @group hal
*/
class RdfMappingHalJsonCookieTest extends RdfMappingResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['hal'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected static $format = 'hal_json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/hal+json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
}
@@ -0,0 +1,134 @@
<?php
namespace Drupal\Tests\rdf\Functional;
use Drupal\Core\Url;
use Drupal\image\Entity\ImageStyle;
use Drupal\Tests\image\Functional\ImageFieldTestBase;
use Drupal\node\Entity\Node;
use Drupal\file\Entity\File;
use Drupal\Tests\rdf\Traits\RdfParsingTrait;
use Drupal\Tests\TestFileCreationTrait;
/**
* Tests the RDFa markup of imagefields.
*
* @group rdf
*/
class ImageFieldAttributesTest extends ImageFieldTestBase {
use RdfParsingTrait;
use TestFileCreationTrait {
getTestFiles as drupalGetTestFiles;
}
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['rdf', 'image'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* URI of the front page of the Drupal site.
*
* @var string
*/
protected $baseUri;
/**
* The name of the image field used in the test.
*
* @var string
*/
protected $fieldName;
/**
* The file object used in the test.
*
* @var \Drupal\file\FileInterface
*/
protected $file;
/**
* The node object used in the test.
*
* @var \Drupal\node\NodeInterface
*/
protected $node;
protected function setUp() {
parent::setUp();
$this->fieldName = 'field_image';
// Create the image field.
$this->createImageField($this->fieldName, 'article');
// Set the RDF mapping for the new field.
rdf_get_mapping('node', 'article')
->setFieldMapping($this->fieldName, [
'properties' => ['og:image'],
'mapping_type' => 'rel',
])
->setBundleMapping(['types' => []])
->save();
// Get the test image that simpletest provides.
$image = current($this->drupalGetTestFiles('image'));
// Save a node with the image.
$nid = $this->uploadNodeImage($image, $this->fieldName, 'article', $this->randomMachineName());
$this->node = Node::load($nid);
$this->file = File::load($this->node->{$this->fieldName}->target_id);
// Prepares commonly used URIs.
$this->baseUri = Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString();
}
/**
* Tests that image fields in teasers have correct resources.
*/
public function testNodeTeaser() {
// Set the display options for the teaser.
$display_options = [
'type' => 'image',
'settings' => ['image_style' => 'medium', 'image_link' => 'content'],
];
$display = \Drupal::service('entity_display.repository')
->getViewDisplay('node', 'article', 'teaser');
$display->setComponent($this->fieldName, $display_options)
->save();
// Render the teaser.
$node_render_array = \Drupal::entityTypeManager()
->getViewBuilder('node')
->view($this->node, 'teaser');
$html = \Drupal::service('renderer')->renderRoot($node_render_array);
// Construct the node and image URIs for testing.
$node_uri = $this->node->toUrl('canonical', ['absolute' => TRUE])->toString();
$image_uri = ImageStyle::load('medium')->buildUrl($this->file->getFileUri());
// Test relations from node to image.
$expected_value = [
'type' => 'uri',
'value' => $image_uri,
];
$this->assertTrue($this->hasRdfProperty($html, $this->baseUri, $node_uri, 'http://ogp.me/ns#image', $expected_value), 'Node to file relation found in RDF output (og:image).');
// Test image type.
$expected_value = [
'type' => 'uri',
'value' => 'http://xmlns.com/foaf/0.1/Image',
];
$this->assertTrue($this->hasRdfProperty($html, $this->baseUri, $image_uri, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', $expected_value), 'Term type found in RDF output (skos:Concept).');
}
}
@@ -0,0 +1,106 @@
<?php
namespace Drupal\Tests\rdf\Functional;
use Drupal\Core\Url;
use Drupal\Tests\node\Functional\NodeTestBase;
use Drupal\Tests\rdf\Traits\RdfParsingTrait;
/**
* Tests the RDFa markup of Nodes.
*
* @group rdf
*/
class NodeAttributesTest extends NodeTestBase {
use RdfParsingTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['rdf'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* URI of the front page of the Drupal site.
*
* @var string
*/
protected $baseUri;
protected function setUp() {
parent::setUp();
rdf_get_mapping('node', 'article')
->setBundleMapping([
'types' => ['sioc:Item', 'foaf:Document'],
])
->setFieldMapping('title', [
'properties' => ['dc:title'],
])
->setFieldMapping('created', [
'properties' => ['dc:date', 'dc:created'],
'datatype' => 'xsd:dateTime',
'datatype_callback' => ['callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value'],
])
->save();
// Prepares commonly used URIs.
$this->baseUri = Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString();
}
/**
* Creates a node of type article and tests its RDFa markup.
*/
public function testNodeAttributes() {
// Create node with single quotation mark title to ensure it does not get
// escaped more than once.
$node = $this->drupalCreateNode([
'type' => 'article',
'title' => $this->randomMachineName(8) . "'",
]);
$node_uri = $node->toUrl('canonical', ['absolute' => TRUE])->toString();
$this->drupalGet($node->toUrl());
// Inspects RDF graph output.
// Node type.
$expected_value = [
'type' => 'uri',
'value' => 'http://rdfs.org/sioc/ns#Item',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $node_uri, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', $expected_value), 'Node type found in RDF output (sioc:Item).');
// Node type.
$expected_value = [
'type' => 'uri',
'value' => 'http://xmlns.com/foaf/0.1/Document',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $node_uri, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', $expected_value), 'Node type found in RDF output (foaf:Document).');
// Node title.
$expected_value = [
'type' => 'literal',
'value' => $node->getTitle(),
'lang' => 'en',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $node_uri, 'http://purl.org/dc/terms/title', $expected_value), 'Node title found in RDF output (dc:title).');
// Node date (date format must be UTC).
$expected_value = [
'type' => 'literal',
'value' => \Drupal::service('date.formatter')->format($node->getCreatedTime(), 'custom', 'c', 'UTC'),
'datatype' => 'http://www.w3.org/2001/XMLSchema#dateTime',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $node_uri, 'http://purl.org/dc/terms/date', $expected_value), 'Node date found in RDF output (dc:date).');
// Node date (date format must be UTC).
$expected_value = [
'type' => 'literal',
'value' => \Drupal::service('date.formatter')->format($node->getCreatedTime(), 'custom', 'c', 'UTC'),
'datatype' => 'http://www.w3.org/2001/XMLSchema#dateTime',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $node_uri, 'http://purl.org/dc/terms/created', $expected_value), 'Node date found in RDF output (dc:created).');
}
}
@@ -0,0 +1,29 @@
<?php
namespace Drupal\Tests\rdf\Functional\Rest;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
/**
* @group rest
*/
class RdfMappingJsonAnonTest extends RdfMappingResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
}
@@ -0,0 +1,39 @@
<?php
namespace Drupal\Tests\rdf\Functional\Rest;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
* @group rest
*/
class RdfMappingJsonBasicAuthTest extends RdfMappingResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}
@@ -0,0 +1,34 @@
<?php
namespace Drupal\Tests\rdf\Functional\Rest;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
/**
* @group rest
*/
class RdfMappingJsonCookieTest extends RdfMappingResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
}
@@ -0,0 +1,125 @@
<?php
namespace Drupal\Tests\rdf\Functional\Rest;
use Drupal\node\Entity\NodeType;
use Drupal\rdf\Entity\RdfMapping;
use Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase;
abstract class RdfMappingResourceTestBase extends EntityResourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['node', 'rdf'];
/**
* {@inheritdoc}
*/
protected static $entityTypeId = 'rdf_mapping';
/**
* @var \Drupal\rdf\RdfMappingInterface
*/
protected $entity;
/**
* {@inheritdoc}
*/
protected function setUpAuthorization($method) {
$this->grantPermissionsToTestedRole(['administer site configuration']);
}
/**
* {@inheritdoc}
*/
protected function createEntity() {
// Create a "Camelids" node type.
$camelids = NodeType::create([
'name' => 'Camelids',
'type' => 'camelids',
]);
$camelids->save();
// Create the RDF mapping.
$llama = RdfMapping::create([
'targetEntityType' => 'node',
'bundle' => 'camelids',
]);
$llama->setBundleMapping([
'types' => ['sioc:Item', 'foaf:Document'],
])
->setFieldMapping('title', [
'properties' => ['dc:title'],
])
->setFieldMapping('created', [
'properties' => ['dc:date', 'dc:created'],
'datatype' => 'xsd:dateTime',
'datatype_callback' => ['callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value'],
])
->save();
return $llama;
}
/**
* {@inheritdoc}
*/
protected function getExpectedNormalizedEntity() {
return [
'bundle' => 'camelids',
'dependencies' => [
'config' => [
'node.type.camelids',
],
'module' => [
'node',
],
],
'fieldMappings' => [
'title' => [
'properties' => [
'dc:title',
],
],
'created' => [
'properties' => [
'dc:date',
'dc:created',
],
'datatype' => 'xsd:dateTime',
'datatype_callback' => [
'callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value',
],
],
],
'id' => 'node.camelids',
'langcode' => 'en',
'status' => TRUE,
'targetEntityType' => 'node',
'types' => [
'sioc:Item',
'foaf:Document',
],
'uuid' => $this->entity->uuid(),
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPostEntity() {
// @todo Update in https://www.drupal.org/node/2300677.
}
/**
* {@inheritdoc}
*/
protected function getExpectedCacheContexts() {
return [
'user.permissions',
];
}
}
@@ -0,0 +1,31 @@
<?php
namespace Drupal\Tests\rdf\Functional\Rest;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class RdfMappingXmlAnonTest extends RdfMappingResourceTestBase {
use AnonResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
}
@@ -0,0 +1,41 @@
<?php
namespace Drupal\Tests\rdf\Functional\Rest;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class RdfMappingXmlBasicAuthTest extends RdfMappingResourceTestBase {
use BasicAuthResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}
@@ -0,0 +1,36 @@
<?php
namespace Drupal\Tests\rdf\Functional\Rest;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class RdfMappingXmlCookieTest extends RdfMappingResourceTestBase {
use CookieResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
}
@@ -0,0 +1,514 @@
<?php
namespace Drupal\Tests\rdf\Functional;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
use Drupal\node\Entity\NodeType;
use Drupal\node\NodeInterface;
use Drupal\Tests\BrowserTestBase;
use Drupal\comment\Entity\Comment;
use Drupal\taxonomy\Entity\Term;
use Drupal\Tests\rdf\Traits\RdfParsingTrait;
/**
* Tests the RDF mappings and RDFa markup of the standard profile.
*
* @group rdf
*/
class StandardProfileTest extends BrowserTestBase {
use RdfParsingTrait;
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'classy';
/**
* The profile used during tests.
*
* This purposefully uses the standard profile.
*
* @var string
*/
public $profile = 'standard';
/**
* @var string
*/
protected $baseUri;
/**
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* @var \Drupal\user\UserInterface
*/
protected $webUser;
/**
* @var \Drupal\taxonomy\TermInterface
*/
protected $term;
/**
* @var \Drupal\file\FileInterface
*/
protected $image;
/**
* @var \Drupal\node\NodeInterface
*/
protected $article;
/**
* @var \Drupal\comment\CommentInterface
*/
protected $articleComment;
/**
* @var \Drupal\node\NodeInterface
*/
protected $page;
/**
* @var string
*/
protected $imageUri;
/**
* @var string
*/
protected $termUri;
/**
* @var string
*/
protected $articleUri;
/**
* @var string
*/
protected $pageUri;
/**
* @var string
*/
protected $authorUri;
/**
* @var string
*/
protected $articleCommentUri;
/**
* @var string
*/
protected $commenterUri;
protected function setUp() {
parent::setUp();
$this->baseUri = Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString();
// Create two test users.
$this->adminUser = $this->drupalCreateUser([
'administer content types',
'administer comments',
'access comments',
'access content',
]);
$this->webUser = $this->drupalCreateUser([
'access comments',
'post comments',
'skip comment approval',
'access content',
]);
$this->drupalLogin($this->adminUser);
// Create term.
$this->term = Term::create([
'name' => $this->randomMachineName(),
'description' => $this->randomMachineName(),
'vid' => 'tags',
]);
$this->term->save();
// Create image.
\Drupal::service('file_system')->copy($this->root . '/core/misc/druplicon.png', 'public://example.jpg');
$this->image = File::create(['uri' => 'public://example.jpg']);
$this->image->save();
// Create article.
$article_settings = [
'type' => 'article',
'promote' => NodeInterface::PROMOTED,
'field_image' => [
[
'target_id' => $this->image->id(),
],
],
'field_tags' => [
[
'target_id' => $this->term->id(),
],
],
];
$this->article = $this->drupalCreateNode($article_settings);
// Create second article to test teaser list.
$this->drupalCreateNode(['type' => 'article', 'promote' => NodeInterface::PROMOTED]);
// Create article comment.
$this->articleComment = $this->saveComment($this->article->id(), $this->webUser->id(), NULL, 0);
// Create page.
$this->page = $this->drupalCreateNode(['type' => 'page']);
// Set URIs.
// Image.
$image_file = $this->article->get('field_image')->entity;
$this->imageUri = ImageStyle::load('large')->buildUrl($image_file->getFileUri());
// Term.
$this->termUri = $this->term->toUrl('canonical', ['absolute' => TRUE])->toString();
// Article.
$this->articleUri = $this->article->toUrl('canonical', ['absolute' => TRUE])->toString();
// Page.
$this->pageUri = $this->page->toUrl('canonical', ['absolute' => TRUE])->toString();
// Author.
$this->authorUri = $this->adminUser->toUrl('canonical', ['absolute' => TRUE])->toString();
// Comment.
$this->articleCommentUri = $this->articleComment->toUrl('canonical', ['absolute' => TRUE])->toString();
// Commenter.
$this->commenterUri = $this->webUser->toUrl('canonical', ['absolute' => TRUE])->toString();
$this->drupalLogout();
}
/**
* Tests that data is exposed correctly when using standard profile.
*
* Because tests using standard profile take a very long time to run, and
* because there is no manipulation of config or data within the test, simply
* run all the tests from within this function.
*/
public function testRdfaOutput() {
$this->doFrontPageRdfaTests();
$this->doArticleRdfaTests();
$this->doPageRdfaTests();
$this->doUserRdfaTests();
$this->doTermRdfaTests();
}
/**
* Tests that data is exposed in the front page teasers.
*/
protected function doFrontPageRdfaTests() {
// Feed the HTML into the parser.
$this->drupalGet(Url::fromRoute('<front>'));
// Ensure that both articles are listed.
// $this->assertEqual(2, count($this->getRdfGraph(Url::fromRoute('<front>'), $this->baseUri)->allOfType('http://schema.org/Article')), 'Two articles found on front page.');
$this->assertEqual(2, $this->getElementByRdfTypeCount(Url::fromRoute('<front>'), $this->baseUri, 'http://schema.org/Article'), 'Two articles found on front page.');
// Test interaction count.
$expected_value = [
'type' => 'literal',
'value' => 'UserComments:1',
'lang' => 'en',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $this->articleUri, 'http://schema.org/interactionCount', $expected_value), 'Teaser comment count was found (schema:interactionCount).');
// Test the properties that are common between pages and articles and are
// displayed in full and teaser mode.
$this->assertRdfaCommonNodeProperties($this->article, "Teaser");
// Test properties that are displayed in both teaser and full mode.
$this->assertRdfaArticleProperties("Teaser");
// @todo Once the image points to the original instead of the processed
// image, move this to testArticleProperties().
$expected_value = [
'type' => 'uri',
'value' => $this->imageUri,
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $this->articleUri, 'http://schema.org/image', $expected_value), 'Teaser image was found (schema:image).');
}
/**
* Tests that article data is exposed using RDFa.
*
* Two fields are not tested for output here. Changed date is not displayed
* on the page, so there is no test for output in node view. Comment count is
* displayed in teaser view, so it is tested in the front article tests.
*/
protected function doArticleRdfaTests() {
// Feed the HTML into the parser.
$this->drupalGet($this->article->toUrl());
// Type.
$this->assertEqual($this->getElementRdfType($this->article->toUrl(), $this->baseUri, $this->articleUri), 'schema:Article', 'Article type was found (schema:Article).');
// Test the properties that are common between pages and articles.
$this->assertRdfaCommonNodeProperties($this->article, "Article");
// Test properties that are displayed in both teaser and full mode.
$this->assertRdfaArticleProperties("Article");
// Test the comment properties displayed on articles.
$this->assertRdfaNodeCommentProperties();
// @todo Once the image points to the original instead of the processed
// image, move this to testArticleProperties().
$expected_value = [
'type' => 'uri',
'value' => $this->imageUri,
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $this->articleUri, 'http://schema.org/image', $expected_value), 'Teaser image was found (schema:image).');
}
/**
* Tests that page data is exposed using RDFa.
*
* Two fields are not tested for output here. Changed date is not displayed
* on the page, so there is no test for output in node view. Comment count is
* displayed in teaser view, so it is tested in the front page tests.
*/
protected function doPageRdfaTests() {
// The standard profile hides the created date on pages. Revert display to
// true for testing.
// @todo Clean-up standard profile defaults.
$node_type = NodeType::load('page');
$node_type->setDisplaySubmitted(TRUE);
$node_type->save();
// Type.
$this->assertEqual($this->getElementRdfType($this->page->toUrl(), $this->baseUri, $this->pageUri), 'schema:WebPage', 'Page type was found (schema:WebPage).');
// Test the properties that are common between pages and articles.
$this->assertRdfaCommonNodeProperties($this->page, "Page");
}
/**
* Tests that user data is exposed on user page.
*/
protected function doUserRdfaTests() {
$this->drupalLogin($this->rootUser);
// User type.
$this->assertEqual($this->getElementRdfType($this->adminUser->toUrl(), $this->baseUri, $this->authorUri), 'schema:Person', 'User type was found (schema:Person) on user page.');
// User name.
$expected_value = [
'type' => 'literal',
'value' => $this->adminUser->label(),
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $this->authorUri, 'http://schema.org/name', $expected_value), 'User name was found (schema:name) on user page.');
$this->drupalLogout();
}
/**
* Tests that term data is exposed on term page.
*/
protected function doTermRdfaTests() {
// Term type.
$this->assertEqual($this->getElementRdfType($this->term->toUrl(), $this->baseUri, $this->termUri), 'schema:Thing', 'Term type was found (schema:Thing) on term page.');
// Term name.
$expected_value = [
'type' => 'literal',
'value' => $this->term->getName(),
'lang' => 'en',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $this->termUri, 'http://schema.org/name', $expected_value), 'Term name was found (schema:name) on term page.');
// @todo Add test for term description once it is a field:
// https://www.drupal.org/node/569434.
}
/**
* Tests output for properties held in common between articles and pages.
*
* @param \Drupal\node\NodeInterface $node
* The node being displayed.
* @param string $message_prefix
* The word to use in the test assertion message.
*
* @throws \Drupal\Core\Entity\EntityMalformedException
*/
protected function assertRdfaCommonNodeProperties(NodeInterface $node, $message_prefix) {
$this->drupalGet($node->toUrl());
$uri = $node->toUrl('canonical', ['absolute' => TRUE])->toString();
// Title.
$expected_value = [
'type' => 'literal',
'value' => $node->get('title')->value,
'lang' => 'en',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $uri, 'http://schema.org/name', $expected_value), "$message_prefix title was found (schema:name).");
// Created date.
$expected_value = [
'type' => 'literal',
'value' => $this->container->get('date.formatter')->format($node->get('created')->value, 'custom', 'c', 'UTC'),
'lang' => 'en',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $uri, 'http://schema.org/dateCreated', $expected_value), "$message_prefix created date was found (schema:dateCreated) in teaser.");
// Body.
$expected_value = [
'type' => 'literal',
'value' => $node->get('body')->value,
'lang' => 'en',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $uri, 'http://schema.org/text', $expected_value), "$message_prefix body was found (schema:text) in teaser.");
// Author.
$expected_value = [
'type' => 'uri',
'value' => $this->authorUri,
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $uri, 'http://schema.org/author', $expected_value), "$message_prefix author was found (schema:author) in teaser.");
// Author type.
$this->assertEqual($this->getElementRdfType($node->toUrl(), $this->baseUri, $this->authorUri), 'schema:Person', '$message_prefix author type was found (schema:Person).');
// Author name.
$expected_value = [
'type' => 'literal',
'value' => $this->adminUser->label(),
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $this->authorUri, 'http://schema.org/name', $expected_value), "$message_prefix author name was found (schema:name).");
}
/**
* Tests output for article properties displayed in both view modes.
*
* @param string $message_prefix
* The word to use in the test assertion message.
*/
protected function assertRdfaArticleProperties($message_prefix) {
// Tags.
$expected_value = [
'type' => 'uri',
'value' => $this->termUri,
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $this->articleUri, 'http://schema.org/about', $expected_value), "$message_prefix tag was found (schema:about).");
// Tag type.
// @todo Enable with https://www.drupal.org/node/2072791.
// $this->assertEqual($graph->type($this->termUri), 'schema:Thing', 'Tag type was found (schema:Thing).');
// Tag name.
$expected_value = [
'type' => 'literal',
'value' => $this->term->getName(),
'lang' => 'en',
];
// @todo Enable with https://www.drupal.org/node/2072791.
// $this->assertTrue($graph->hasProperty($this->termUri, 'http://schema.org/name', $expected_value), "$message_prefix name was found (schema:name).");
}
/**
* Tests output for comment properties on nodes in full page view mode.
*/
protected function assertRdfaNodeCommentProperties() {
$this->drupalGet($this->article->toUrl());
// Relationship between node and comment.
$expected_value = [
'type' => 'uri',
'value' => $this->articleCommentUri,
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $this->articleUri, 'http://schema.org/comment', $expected_value), "Relationship between node and comment found (schema:comment).");
// Comment type.
$this->assertEqual($this->getElementRdfType($this->article->toUrl(), $this->baseUri, $this->articleCommentUri), 'schema:Comment', 'Comment type was found (schema:Comment).');
// Comment title.
$expected_value = [
'type' => 'literal',
'value' => $this->articleComment->get('subject')->value,
'lang' => 'en',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $this->articleCommentUri, 'http://schema.org/name', $expected_value), "Article comment title was found (schema:name).");
// Comment created date.
$expected_value = [
'type' => 'literal',
'value' => $this->container->get('date.formatter')->format($this->articleComment->get('created')->value, 'custom', 'c', 'UTC'),
'lang' => 'en',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $this->articleCommentUri, 'http://schema.org/dateCreated', $expected_value), "Article comment created date was found (schema:dateCreated).");
// Comment body.
$text = $this->articleComment->get('comment_body')->value;
$expected_value = [
'type' => 'literal',
// There is an extra carriage return in the when parsing comments as
// output by Bartik, so it must be added to the expected value.
'value' => "$text
",
'lang' => 'en',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $this->articleCommentUri, 'http://schema.org/text', $expected_value), "Article comment body was found (schema:text).");
// Comment uid.
$expected_value = [
'type' => 'uri',
'value' => $this->commenterUri,
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $this->articleCommentUri, 'http://schema.org/author', $expected_value), "Article comment author was found (schema:author).");
// Comment author type.
$this->assertEqual($this->getElementRdfType($this->article->toUrl(), $this->baseUri, $this->commenterUri), 'schema:Person', 'Comment author type was found (schema:Person).');
// Comment author name.
$expected_value = [
'type' => 'literal',
'value' => $this->webUser->getAccountName(),
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $this->commenterUri, 'http://schema.org/name', $expected_value), "Comment author name was found (schema:name).");
}
/**
* Creates a comment entity.
*
* @param int $nid
* Node id which will hold the comment.
* @param int $uid
* User id of the author of the comment. Can be NULL if $contact provided.
* @param mixed $contact
* Set to NULL for no contact info, TRUE to ignore success checking, and
* array of values to set contact info.
* @param int $pid
* Comment id of the parent comment in a thread.
*
* @return \Drupal\comment\Entity\Comment
* The saved comment.
*/
protected function saveComment($nid, $uid, $contact = NULL, $pid = 0) {
$values = [
'entity_id' => $nid,
'entity_type' => 'node',
'field_name' => 'comment',
'uid' => $uid,
'pid' => $pid,
'subject' => $this->randomMachineName(),
'comment_body' => $this->randomMachineName(),
'status' => 1,
];
if ($contact) {
$values += $contact;
}
$comment = Comment::create($values);
$comment->save();
return $comment;
}
}
@@ -0,0 +1,98 @@
<?php
namespace Drupal\Tests\rdf\Functional;
use Drupal\Core\Url;
use Drupal\Tests\taxonomy\Functional\TaxonomyTestBase;
use Drupal\Tests\rdf\Traits\RdfParsingTrait;
/**
* Tests the RDFa markup of Taxonomy terms.
*
* @group rdf
*/
class TaxonomyAttributesTest extends TaxonomyTestBase {
use RdfParsingTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['rdf', 'views'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* URI of the front page of the Drupal site.
*
* @var string
*/
protected $baseUri;
/**
* Vocabulary created for testing purposes.
*
* @var \Drupal\taxonomy\VocabularyInterface
*/
protected $vocabulary;
protected function setUp() {
parent::setUp();
$this->vocabulary = $this->createVocabulary();
// RDF mapping - term bundle.
rdf_get_mapping('taxonomy_term', $this->vocabulary->id())
->setBundleMapping(['types' => ['skos:Concept']])
->setFieldMapping('name', [
'properties' => ['rdfs:label', 'skos:prefLabel'],
])
->save();
// Prepares commonly used URIs.
$this->baseUri = Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString();
}
/**
* Creates a random term and ensures the RDF output is correct.
*/
public function testTaxonomyTermRdfaAttributes() {
$term = $this->createTerm($this->vocabulary);
$term_uri = $term->toUrl('canonical', ['absolute' => TRUE])->toString();
$this->drupalGet('taxonomy/term/' . $term->id());
$this->drupalGet($term->toUrl());
// Inspects RDF graph output.
// Term type.
$expected_value = [
'type' => 'uri',
'value' => 'http://www.w3.org/2004/02/skos/core#Concept',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $term_uri, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', $expected_value), 'Term type found in RDF output (skos:Concept).');
// Term label.
$expected_value = [
'type' => 'literal',
'value' => $term->getName(),
'lang' => 'en',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $term_uri, 'http://www.w3.org/2000/01/rdf-schema#label', $expected_value), 'Term label found in RDF output (rdfs:label).');
// Term label.
$expected_value = [
'type' => 'literal',
'value' => $term->getName(),
'lang' => 'en',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $term_uri, 'http://www.w3.org/2004/02/skos/core#prefLabel', $expected_value), 'Term label found in RDF output (skos:prefLabel).');
// @todo Add test for term description once it is a field:
// https://www.drupal.org/node/569434.
}
}
@@ -0,0 +1,117 @@
<?php
namespace Drupal\Tests\rdf\Functional;
use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\rdf\Traits\RdfParsingTrait;
/**
* Tests the RDFa markup of Users.
*
* @group rdf
*/
class UserAttributesTest extends BrowserTestBase {
use RdfParsingTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['rdf', 'node'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* URI of the front page of the Drupal site.
*
* @var string
*/
protected $baseUri;
protected function setUp() {
parent::setUp();
rdf_get_mapping('user', 'user')
->setBundleMapping([
'types' => ['sioc:UserAccount'],
])
->setFieldMapping('name', [
'properties' => ['foaf:name'],
])
->save();
// Prepares commonly used URIs.
$this->baseUri = Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString();
}
/**
* Tests if default mapping for user is being used.
*
* Creates a random user and ensures the default mapping for the user is
* being used.
*/
public function testUserAttributesInMarkup() {
// Creates users that should and should not be truncated
// by template_preprocess_username (20 characters)
// one of these users tests right on the cusp (20).
$user1 = $this->drupalCreateUser(['access user profiles']);
$authors = [
$this->drupalCreateUser([], $this->randomMachineName(30)),
$this->drupalCreateUser([], $this->randomMachineName(20)),
$this->drupalCreateUser([], $this->randomMachineName(5)),
];
$this->drupalLogin($user1);
$this->drupalCreateContentType(['type' => 'article']);
/** @var \Drupal\user\UserInterface[] $authors */
foreach ($authors as $author) {
$account_uri = $author->toUrl('canonical', ['absolute' => TRUE])->toString();
$this->drupalGet('user/' . $author->id());
// Inspects RDF graph output.
// User type.
$expected_value = [
'type' => 'uri',
'value' => 'http://rdfs.org/sioc/ns#UserAccount',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $account_uri, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', $expected_value), 'User type found in RDF output (sioc:UserAccount).');
// User name.
$expected_value = [
'type' => 'literal',
'value' => $author->getAccountName(),
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $account_uri, 'http://xmlns.com/foaf/0.1/name', $expected_value), 'User name found in RDF output (foaf:name).');
// User creates a node.
$this->drupalLogin($author);
$node = $this->drupalCreateNode(['type' => 'article', 'promote' => 1]);
$this->drupalLogin($user1);
$this->drupalGet('node/' . $node->id());
// Ensures the default bundle mapping for user is used on the Authored By
// information on the node.
$expected_value = [
'type' => 'uri',
'value' => 'http://rdfs.org/sioc/ns#UserAccount',
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $account_uri, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', $expected_value), 'User type found in RDF output (sioc:UserAccount).');
// User name.
$expected_value = [
'type' => 'literal',
'value' => $author->getAccountName(),
];
$this->assertTrue($this->hasRdfProperty($this->getSession()->getPage()->getContent(), $this->baseUri, $account_uri, 'http://xmlns.com/foaf/0.1/name', $expected_value), 'User name found in RDF output (foaf:name).');
}
}
}
@@ -0,0 +1,111 @@
<?php
namespace Drupal\Tests\rdf\Kernel;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests the RDF mapping CRUD functions.
*
* @group rdf
*/
class CrudTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['entity_test', 'rdf', 'system'];
/**
* @var string
*/
protected $prefix;
/**
* @var string
*/
protected $entityType;
/**
* @var string
*/
protected $bundle;
protected function setUp() {
parent::setUp();
$this->prefix = 'rdf.mapping';
$this->entityType = $this->bundle = 'entity_test';
}
/**
* Tests creation of RDF mapping.
*/
public function testMappingCreation() {
$mapping_config_name = "{$this->prefix}.{$this->entityType}.{$this->bundle}";
// Save bundle mapping config.
rdf_get_mapping($this->entityType, $this->bundle)->save();
// Test that config file was saved.
$mapping_config = \Drupal::configFactory()->listAll('rdf.mapping.');
$this->assertContains($mapping_config_name, $mapping_config, 'Rdf mapping config saved.');
}
/**
* Test the handling of bundle mappings.
*/
public function testBundleMapping() {
// Test that the bundle mapping can be saved.
$types = ['sioc:Post', 'foaf:Document'];
rdf_get_mapping($this->entityType, $this->bundle)
->setBundleMapping(['types' => $types])
->save();
$bundle_mapping = rdf_get_mapping($this->entityType, $this->bundle)
->getBundleMapping();
$this->assertEqual($types, $bundle_mapping['types'], 'Bundle mapping saved.');
// Test that the bundle mapping can be edited.
$types = ['schema:BlogPosting'];
rdf_get_mapping($this->entityType, $this->bundle)
->setBundleMapping(['types' => $types])
->save();
$bundle_mapping = rdf_get_mapping($this->entityType, $this->bundle)
->getBundleMapping();
$this->assertEqual($types, $bundle_mapping['types'], 'Bundle mapping updated.');
}
/**
* Test the handling of field mappings.
*/
public function testFieldMapping() {
$field_name = 'created';
// Test that the field mapping can be saved.
$mapping = [
'properties' => ['dc:created'],
'datatype' => 'xsd:dateTime',
'datatype_callback' => ['callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value'],
];
rdf_get_mapping($this->entityType, $this->bundle)
->setFieldMapping($field_name, $mapping)
->save();
$field_mapping = rdf_get_mapping($this->entityType, $this->bundle)
->getFieldMapping($field_name);
$this->assertEqual($mapping, $field_mapping, 'Field mapping saved.');
// Test that the field mapping can be edited.
$mapping = [
'properties' => ['dc:date'],
'datatype' => 'foo:bar',
'datatype_callback' => ['callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value'],
];
rdf_get_mapping($this->entityType, $this->bundle)
->setFieldMapping($field_name, $mapping)
->save();
$field_mapping = rdf_get_mapping($this->entityType, $this->bundle)
->getFieldMapping($field_name);
$this->assertEqual($mapping, $field_mapping, 'Field mapping updated.');
}
}
@@ -0,0 +1,54 @@
<?php
namespace Drupal\Tests\rdf\Kernel\Field;
use Drupal\entity_test\Entity\EntityTest;
/**
* Tests RDFa output by datetime field formatters.
*
* @group rdf
*/
class DateTimeFieldRdfaTest extends FieldRdfaTestBase {
/**
* {@inheritdoc}
*/
protected $fieldType = 'datetime';
/**
* The 'value' property value for testing.
*
* @var string
*/
protected $testValue = '2014-01-28T06:01:01';
/**
* {@inheritdoc}
*/
public static $modules = ['datetime'];
protected function setUp() {
parent::setUp();
$this->createTestField();
// Add the mapping.
$mapping = rdf_get_mapping('entity_test', 'entity_test');
$mapping->setFieldMapping($this->fieldName, [
'properties' => ['schema:dateCreated'],
])->save();
// Set up test entity.
$this->entity = EntityTest::create([]);
$this->entity->{$this->fieldName}->value = $this->testValue;
}
/**
* Tests the default formatter.
*/
public function testDefaultFormatter() {
$this->assertFormatterRdfa(['type' => 'datetime_default'], 'http://schema.org/dateCreated', ['value' => $this->testValue . 'Z', 'type' => 'literal', 'datatype' => 'http://www.w3.org/2001/XMLSchema#dateTime']);
}
}
@@ -0,0 +1,51 @@
<?php
namespace Drupal\Tests\rdf\Kernel\Field;
use Drupal\entity_test\Entity\EntityTest;
/**
* Tests RDFa output by email field formatters.
*
* @group rdf
*/
class EmailFieldRdfaTest extends FieldRdfaTestBase {
/**
* {@inheritdoc}
*/
protected $fieldType = 'email';
/**
* {@inheritdoc}
*/
public static $modules = ['text'];
protected function setUp() {
parent::setUp();
$this->createTestField();
// Add the mapping.
$mapping = rdf_get_mapping('entity_test', 'entity_test');
$mapping->setFieldMapping($this->fieldName, [
'properties' => ['schema:email'],
])->save();
// Set up test values.
$this->testValue = 'test@example.com';
$this->entity = EntityTest::create([]);
$this->entity->{$this->fieldName}->value = $this->testValue;
}
/**
* Tests all email formatters.
*/
public function testAllFormatters() {
// Test the plain formatter.
$this->assertFormatterRdfa(['type' => 'string'], 'http://schema.org/email', ['value' => $this->testValue]);
// Test the mailto formatter.
$this->assertFormatterRdfa(['type' => 'email_mailto'], 'http://schema.org/email', ['value' => $this->testValue]);
}
}
@@ -0,0 +1,95 @@
<?php
namespace Drupal\Tests\rdf\Kernel\Field;
use Drupal\Tests\field\Traits\EntityReferenceTestTrait;
use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;
/**
* Tests the RDFa output of the entity reference field formatter.
*
* @group rdf
*/
class EntityReferenceRdfaTest extends FieldRdfaTestBase {
use EntityReferenceTestTrait;
/**
* {@inheritdoc}
*/
protected $fieldType = 'entity_reference';
/**
* The entity type used in this test.
*
* @var string
*/
protected $entityType = 'entity_test';
/**
* The bundle used in this test.
*
* @var string
*/
protected $bundle = 'entity_test';
/**
* The term for testing.
*
* @var \Drupal\taxonomy\Entity\Term
*/
protected $targetEntity;
/**
* {@inheritdoc}
*/
public static $modules = ['text', 'filter'];
protected function setUp() {
parent::setUp();
$this->installEntitySchema('entity_test_rev');
// Give anonymous users permission to view test entities.
$this->installConfig(['user']);
Role::load(RoleInterface::ANONYMOUS_ID)
->grantPermission('view test entity')
->save();
$this->createEntityReferenceField($this->entityType, $this->bundle, $this->fieldName, 'Field test', $this->entityType);
// Add the mapping.
$mapping = rdf_get_mapping('entity_test', 'entity_test');
$mapping->setFieldMapping($this->fieldName, [
'properties' => ['schema:knows'],
])->save();
// Create the entity to be referenced.
$this->targetEntity = $this->container->get('entity_type.manager')
->getStorage($this->entityType)
->create(['name' => $this->randomMachineName()]);
$this->targetEntity->save();
// Create the entity that will have the entity reference field.
$this->entity = $this->container->get('entity_type.manager')
->getStorage($this->entityType)
->create(['name' => $this->randomMachineName()]);
$this->entity->save();
$this->entity->{$this->fieldName}->entity = $this->targetEntity;
$this->uri = $this->getAbsoluteUri($this->entity);
}
/**
* Tests all the entity reference formatters.
*/
public function testAllFormatters() {
$entity_uri = $this->getAbsoluteUri($this->targetEntity);
// Tests the label formatter.
$this->assertFormatterRdfa(['type' => 'entity_reference_label'], 'http://schema.org/knows', ['value' => $entity_uri, 'type' => 'uri']);
// Tests the entity formatter.
$this->assertFormatterRdfa(['type' => 'entity_reference_entity_view'], 'http://schema.org/knows', ['value' => $entity_uri, 'type' => 'uri']);
}
}
@@ -0,0 +1,57 @@
<?php
namespace Drupal\Tests\rdf\Kernel\Field;
use Drupal\entity_test\Entity\EntityTest;
/**
* Tests the RDFa output of a text field formatter with a datatype callback.
*
* @group rdf
*/
class FieldRdfaDatatypeCallbackTest extends FieldRdfaTestBase {
/**
* {@inheritdoc}
*/
protected $fieldType = 'text';
/**
* {@inheritdoc}
*/
public static $modules = ['text', 'filter', 'rdf_test'];
protected function setUp() {
parent::setUp();
$this->createTestField();
$this->installConfig(['filter']);
// Add the mapping.
$mapping = rdf_get_mapping('entity_test', 'entity_test');
$mapping->setFieldMapping($this->fieldName, [
'properties' => ['schema:interactionCount'],
'datatype_callback' => [
'callable' => 'Drupal\rdf_test\TestDataConverter::convertFoo',
],
])->save();
// Set up test values.
$this->testValue = $this->randomMachineName();
$this->entity = EntityTest::create();
$this->entity->{$this->fieldName}->value = $this->testValue;
$this->entity->save();
$this->uri = $this->getAbsoluteUri($this->entity);
}
/**
* Tests the default formatter.
*/
public function testDefaultFormatter() {
// Expected value is the output of the datatype callback, not the raw value.
$this->assertFormatterRdfa(['type' => 'text_default'], 'http://schema.org/interactionCount', ['value' => 'foo' . $this->testValue]);
}
}
@@ -0,0 +1,186 @@
<?php
namespace Drupal\Tests\rdf\Kernel\Field;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\rdf\Traits\RdfParsingTrait;
abstract class FieldRdfaTestBase extends FieldKernelTestBase {
use RdfParsingTrait;
/**
* The machine name of the field type to test.
*
* @var string
*/
protected $fieldType;
/**
* The name of the field to create for testing.
*
* @var string
*/
protected $fieldName = 'field_test';
/**
* The URI to identify the entity.
*
* @var string
*/
protected $uri = 'http://ex.com';
/**
* The entity to render for testing.
*
* @var \Drupal\Core\Entity\ContentEntityBase
*/
protected $entity;
/**
* TRUE if verbose debugging is enabled.
*
* @var bool
*/
protected $debug = FALSE;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['rdf'];
/**
* @var string
*/
protected $testValue;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
\Drupal::service('router.builder')->rebuild();
}
/**
* Helper function to test the formatter's RDFa.
*
* @param array $formatter
* An associative array describing the formatter to test and its settings
* containing:
* - type: The machine name of the field formatter to test.
* - settings: The settings of the field formatter to test.
* @param string $property
* The property that should be found.
* @param array $expected_rdf_value
* An associative array describing the expected value of the property
* containing:
* - value: The actual value of the string or URI.
* - type: The type of RDF value, e.g. 'literal' for a string, or 'uri'.
* Defaults to 'literal'.
* - datatype: (optional) The datatype of the value (e.g. xsd:dateTime).
*/
protected function assertFormatterRdfa($formatter, $property, $expected_rdf_value) {
$expected_rdf_value += ['type' => 'literal'];
// The field formatter will be rendered inside the entity. Set the field
// formatter in the entity display options before rendering the entity.
\Drupal::service('entity_display.repository')
->getViewDisplay('entity_test', 'entity_test')
->setComponent($this->fieldName, $formatter)
->save();
$build = \Drupal::entityTypeManager()
->getViewBuilder($this->entity->getEntityTypeId())
->view($this->entity, 'default');
$output = \Drupal::service('renderer')->renderRoot($build);
$this->setRawContent($output);
$this->assertTrue($this->hasRdfProperty($output, $this->uri, $this->uri, $property, $expected_rdf_value), "Formatter {$formatter['type']} exposes data correctly for {$this->fieldType} fields.");
}
/**
* Creates the field for testing.
*
* @param array $field_settings
* (optional) An array of field settings.
*/
protected function createTestField($field_settings = []) {
FieldStorageConfig::create([
'field_name' => $this->fieldName,
'entity_type' => 'entity_test',
'type' => $this->fieldType,
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => $this->fieldName,
'bundle' => 'entity_test',
'settings' => $field_settings,
])->save();
}
/**
* Gets the absolute URI of an entity.
*
* @param \Drupal\Core\Entity\ContentEntityBase $entity
* The entity for which to generate the URI.
*
* @return string
* The absolute URI.
*/
protected function getAbsoluteUri($entity) {
return $entity->toUrl('canonical', ['absolute' => TRUE])->toString();
}
/**
* Parses a content and return the html element.
*
* @param string $content
* The html to parse.
*
* @return array
* An array containing simplexml objects.
*/
protected function parseContent($content) {
$htmlDom = new \DOMDocument();
@$htmlDom->loadHTML('<?xml encoding="UTF-8">' . $content);
$elements = simplexml_import_dom($htmlDom);
return $elements;
}
/**
* Performs an xpath search on a certain content.
*
* The search is relative to the root element of the $content variable.
*
* @param string $content
* The html to parse.
* @param string $xpath
* The xpath string to use in the search.
* @param array $arguments
* Some arguments for the xpath.
*
* @return array|false
* The return value of the xpath search. For details on the xpath string
* format and return values see the SimpleXML documentation,
* http://php.net/manual/function.simplexml-element-xpath.php.
*/
protected function xpathContent($content, $xpath, array $arguments = []) {
if ($elements = $this->parseContent($content)) {
$xpath = $this->buildXPathQuery($xpath, $arguments);
$result = $elements->xpath($xpath);
// Some combinations of PHP / libxml versions return an empty array
// instead of the documented FALSE. Forcefully convert any falsish values
// to an empty array to allow foreach(...) constructions.
return $result ? $result : [];
}
else {
return FALSE;
}
}
}
@@ -0,0 +1,184 @@
<?php
namespace Drupal\Tests\rdf\Kernel\Field;
use Drupal\entity_test\Entity\EntityTest;
/**
* Tests the placement of RDFa in link field formatters.
*
* @group rdf
*/
class LinkFieldRdfaTest extends FieldRdfaTestBase {
/**
* {@inheritdoc}
*/
protected $fieldType = 'link';
/**
* {@inheritdoc}
*/
public static $modules = ['link', 'text'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->createTestField();
// Add the mapping.
$mapping = rdf_get_mapping('entity_test', 'entity_test');
$mapping->setFieldMapping($this->fieldName, [
'properties' => ['schema:link'],
])->save();
}
/**
* Tests all formatters with link to external page.
*/
public function testAllFormattersExternal() {
// Set up test values.
$this->testValue = 'http://test.me/foo/bar/neque/porro/quisquam/est/qui-dolorem?path=foo/bar/neque/porro/quisquam/est/qui-dolorem';
$this->entity = EntityTest::create([]);
$this->entity->{$this->fieldName}->uri = $this->testValue;
// Set up the expected result.
$expected_rdf = [
'value' => $this->testValue,
'type' => 'uri',
];
$this->runTestAllFormatters($expected_rdf, 'external');
}
/**
* Tests all formatters with link to internal page.
*/
public function testAllFormattersInternal() {
// Set up test values.
$this->testValue = 'admin';
$this->entity = EntityTest::create([]);
$this->entity->{$this->fieldName}->uri = 'internal:/admin';
// Set up the expected result.
// AssertFormatterRdfa looks for a full path.
$expected_rdf = [
'value' => $this->uri . '/' . $this->testValue,
'type' => 'uri',
];
$this->runTestAllFormatters($expected_rdf, 'internal');
}
/**
* Tests all formatters with link to frontpage.
*/
public function testAllFormattersFront() {
// Set up test values.
$this->testValue = '/';
$this->entity = EntityTest::create([]);
$this->entity->{$this->fieldName}->uri = 'internal:/';
// Set up the expected result.
$expected_rdf = [
'value' => $this->uri . '/',
'type' => 'uri',
];
$this->runTestAllFormatters($expected_rdf, 'front');
}
/**
* Helper function to test all link formatters.
*/
public function runTestAllFormatters($expected_rdf, $type = NULL) {
// Test the link formatter: trim at 80, no other settings.
$formatter = [
'type' => 'link',
'settings' => [
'trim_length' => 80,
'url_only' => FALSE,
'url_plain' => FALSE,
'rel' => '',
'target' => '',
],
];
$this->assertFormatterRdfa($formatter, 'http://schema.org/link', $expected_rdf);
// Test the link formatter: trim at 40, nofollow, new window.
$formatter = [
'type' => 'link',
'settings' => [
'trim_length' => 40,
'url_only' => FALSE,
'url_plain' => FALSE,
'rel' => 'nofollow',
'target' => '_blank',
],
];
$this->assertFormatterRdfa($formatter, 'http://schema.org/link', $expected_rdf);
// Test the link formatter: trim at 40, URL only (not plaintext) nofollow,
// new window.
$formatter = [
'type' => 'link',
'settings' => [
'trim_length' => 40,
'url_only' => TRUE,
'url_plain' => FALSE,
'rel' => 'nofollow',
'target' => '_blank',
],
];
$this->assertFormatterRdfa($formatter, 'http://schema.org/link', $expected_rdf);
// Test the link_separate formatter: trim at 40, nofollow, new window.
$formatter = [
'type' => 'link_separate',
'settings' => [
'trim_length' => 40,
'rel' => 'nofollow',
'target' => '_blank',
],
];
$this->assertFormatterRdfa($formatter, 'http://schema.org/link', $expected_rdf);
// Change the expected value here to literal. When formatted as plaintext
// then the RDF is expecting a 'literal' not a 'uri'.
$expected_rdf = [
'value' => $this->testValue,
'type' => 'literal',
];
// Test the link formatter: trim at 20, url only (as plaintext.)
$formatter = [
'type' => 'link',
'settings' => [
'trim_length' => 20,
'url_only' => TRUE,
'url_plain' => TRUE,
'rel' => '0',
'target' => '0',
],
];
$this->assertFormatterRdfa($formatter, 'http://schema.org/link', $expected_rdf);
// Test the link formatter: do not trim, url only (as plaintext.)
$formatter = [
'type' => 'link',
'settings' => [
'trim_length' => 0,
'url_only' => TRUE,
'url_plain' => TRUE,
'rel' => '0',
'target' => '0',
],
];
$this->assertFormatterRdfa($formatter, 'http://schema.org/link', $expected_rdf);
}
}
@@ -0,0 +1,204 @@
<?php
namespace Drupal\Tests\rdf\Kernel\Field;
use Drupal\entity_test\Entity\EntityTest;
/**
* Tests RDFa output by number field formatters.
*
* @group rdf
*/
class NumberFieldRdfaTest extends FieldRdfaTestBase {
/**
* Tests the integer formatter.
*/
public function testIntegerFormatter() {
$this->fieldType = 'integer';
$testValue = 3;
$this->createTestField();
$this->createTestEntity($testValue);
$this->assertFormatterRdfa(['type' => 'number_integer'], 'http://schema.org/baseSalary', ['value' => $testValue]);
// Test that the content attribute is not created.
$result = $this->xpathContent($this->getRawContent(), '//div[contains(@class, "field__items") and @content]');
$this->assertEmpty($result);
}
/**
* Tests the integer formatter with settings.
*/
public function testIntegerFormatterWithSettings() {
\Drupal::service('theme_installer')->install(['classy']);
$this->config('system.theme')->set('default', 'classy')->save();
$this->fieldType = 'integer';
$formatter = [
'type' => 'number_integer',
'settings' => [
'thousand_separator' => '.',
'prefix_suffix' => TRUE,
],
];
$testValue = 3333333.33;
$field_settings = [
'prefix' => '#',
'suffix' => ' llamas.',
];
$this->createTestField($field_settings);
$this->createTestEntity($testValue);
$this->assertFormatterRdfa($formatter, 'http://schema.org/baseSalary', ['value' => $testValue]);
// Test that the content attribute is created.
$result = $this->xpathContent($this->getRawContent(), '//div[contains(@class, "field__item") and @content=:testValue]', [':testValue' => $testValue]);
$this->assertNotEmpty($result);
}
/**
* Tests the float formatter.
*/
public function testFloatFormatter() {
$this->fieldType = 'float';
$testValue = 3.33;
$this->createTestField();
$this->createTestEntity($testValue);
$this->assertFormatterRdfa(['type' => 'number_unformatted'], 'http://schema.org/baseSalary', ['value' => $testValue]);
// Test that the content attribute is not created.
$result = $this->xpathContent($this->getRawContent(), '//div[contains(@class, "field__items") and @content]');
$this->assertEmpty($result);
}
/**
* Tests the float formatter with settings.
*/
public function testFloatFormatterWithSettings() {
\Drupal::service('theme_installer')->install(['classy']);
$this->config('system.theme')->set('default', 'classy')->save();
$this->fieldType = 'float';
$formatter = [
'type' => 'number_decimal',
'settings' => [
'thousand_separator' => '.',
'decimal_separator' => ',',
'prefix_suffix' => TRUE,
],
];
$testValue = 3333333.33;
$field_settings = [
'prefix' => '$',
'suffix' => ' more.',
];
$this->createTestField($field_settings);
$this->createTestEntity($testValue);
$this->assertFormatterRdfa($formatter, 'http://schema.org/baseSalary', ['value' => $testValue]);
// Test that the content attribute is created.
$result = $this->xpathContent($this->getRawContent(), '//div[contains(@class, "field__item") and @content=:testValue]', [':testValue' => $testValue]);
$this->assertNotEmpty($result);
}
/**
* Tests the float formatter with a scale. Scale is not exercised.
*/
public function testFloatFormatterWithScale() {
$this->fieldType = 'float';
$formatter = [
'type' => 'number_decimal',
'settings' => [
'scale' => 5,
],
];
$testValue = 3.33;
$this->createTestField();
$this->createTestEntity($testValue);
$this->assertFormatterRdfa($formatter, 'http://schema.org/baseSalary', ['value' => $testValue]);
// Test that the content attribute is not created.
$result = $this->xpathContent($this->getRawContent(), '//div[contains(@class, "field__items") and @content]');
$this->assertEmpty($result);
}
/**
* Tests the float formatter with a scale. Scale is exercised.
*/
public function testFloatFormatterWithScaleExercised() {
\Drupal::service('theme_installer')->install(['classy']);
$this->config('system.theme')->set('default', 'classy')->save();
$this->fieldType = 'float';
$formatter = [
'type' => 'number_decimal',
'settings' => [
'scale' => 5,
],
];
$testValue = 3.1234567;
$this->createTestField();
$this->createTestEntity($testValue);
$this->assertFormatterRdfa($formatter, 'http://schema.org/baseSalary', ['value' => $testValue]);
// Test that the content attribute is created.
$result = $this->xpathContent($this->getRawContent(), '//div[contains(@class, "field__item") and @content=:testValue]', [':testValue' => $testValue]);
$this->assertNotEmpty($result);
}
/**
* Tests the decimal formatter.
*/
public function testDecimalFormatter() {
$this->fieldType = 'decimal';
$testValue = 3.33;
$this->createTestField();
$this->createTestEntity($testValue);
$this->assertFormatterRdfa(['type' => 'number_decimal'], 'http://schema.org/baseSalary', ['value' => $testValue]);
// Test that the content attribute is not created.
$result = $this->xpathContent($this->getRawContent(), '//div[contains(@class, "field__items") and @content]');
$this->assertEmpty($result);
}
/**
* Tests the decimal formatter with settings.
*/
public function testDecimalFormatterWithSettings() {
\Drupal::service('theme_installer')->install(['classy']);
$this->config('system.theme')->set('default', 'classy')->save();
$this->fieldType = 'decimal';
$formatter = [
'type' => 'number_decimal',
'settings' => [
'thousand_separator' => 't',
'decimal_separator' => '#',
'prefix_suffix' => TRUE,
],
];
$testValue = 3333333.33;
$field_settings = [
'prefix' => '$',
'suffix' => ' more.',
];
$this->createTestField($field_settings);
$this->createTestEntity($testValue);
$this->assertFormatterRdfa($formatter, 'http://schema.org/baseSalary', ['value' => $testValue]);
// Test that the content attribute is created.
$result = $this->xpathContent($this->getRawContent(), '//div[contains(@class, "field__item") and @content=:testValue]', [':testValue' => $testValue]);
$this->assertNotEmpty($result);
}
/**
* Creates the RDF mapping for the field.
*/
protected function createTestEntity($testValue) {
// Add the mapping.
$mapping = rdf_get_mapping('entity_test', 'entity_test');
$mapping->setFieldMapping($this->fieldName, [
'properties' => ['schema:baseSalary'],
])->save();
// Set up test entity.
$this->entity = EntityTest::create([]);
$this->entity->{$this->fieldName}->value = $testValue;
}
}
@@ -0,0 +1,58 @@
<?php
namespace Drupal\Tests\rdf\Kernel\Field;
use Drupal\entity_test\Entity\EntityTest;
/**
* Tests RDFa output by text field formatters.
*
* @group rdf
*/
class StringFieldRdfaTest extends FieldRdfaTestBase {
/**
* {@inheritdoc}
*/
protected $fieldType = 'string';
/**
* The 'value' property value for testing.
*
* @var string
*/
protected $testValue = 'test_text_value';
/**
* The 'summary' property value for testing.
*
* @var string
*/
protected $testSummary = 'test_summary_value';
protected function setUp() {
parent::setUp();
$this->createTestField();
// Add the mapping.
$mapping = rdf_get_mapping('entity_test', 'entity_test');
$mapping->setFieldMapping($this->fieldName, [
'properties' => ['schema:text'],
])->save();
// Set up test entity.
$this->entity = EntityTest::create();
$this->entity->{$this->fieldName}->value = $this->testValue;
$this->entity->{$this->fieldName}->summary = $this->testSummary;
}
/**
* Tests string formatters.
*/
public function testStringFormatters() {
// Tests the string formatter.
$this->assertFormatterRdfa(['type' => 'string'], 'http://schema.org/text', ['value' => $this->testValue]);
}
}
@@ -0,0 +1,69 @@
<?php
namespace Drupal\Tests\rdf\Kernel\Field;
use Drupal\entity_test\Entity\EntityTest;
/**
* Tests RDFa output by telephone field formatters.
*
* @group rdf
*/
class TelephoneFieldRdfaTest extends FieldRdfaTestBase {
/**
* A test value for the telephone field.
*
* @var string
*/
protected $testValue;
/**
* {@inheritdoc}
*/
protected $fieldType = 'telephone';
/**
* {@inheritdoc}
*/
public static $modules = ['telephone', 'text'];
protected function setUp() {
parent::setUp();
$this->createTestField();
// Add the mapping.
$mapping = rdf_get_mapping('entity_test', 'entity_test');
$mapping->setFieldMapping($this->fieldName, [
'properties' => ['schema:telephone'],
])->save();
// Set up test values.
$this->testValue = '555-555-5555';
$this->entity = EntityTest::create([]);
$this->entity->{$this->fieldName}->value = $this->testValue;
}
/**
* Tests the field formatters.
*/
public function testAllFormatters() {
// Tests the plain formatter.
$this->assertFormatterRdfa(['type' => 'string'], 'http://schema.org/telephone', ['value' => $this->testValue]);
// Tests the telephone link formatter.
$this->assertFormatterRdfa(['type' => 'telephone_link'], 'http://schema.org/telephone', ['value' => 'tel:' . $this->testValue, 'type' => 'uri']);
$formatter = [
'type' => 'telephone_link',
'settings' => ['title' => 'Contact us'],
];
$expected_rdf_value = [
'value' => 'tel:' . $this->testValue,
'type' => 'uri',
];
// Tests the telephone link formatter with custom title.
$this->assertFormatterRdfa($formatter, 'http://schema.org/telephone', $expected_rdf_value);
}
}
@@ -0,0 +1,73 @@
<?php
namespace Drupal\Tests\rdf\Kernel\Field;
use Drupal\entity_test\Entity\EntityTest;
/**
* Tests RDFa output by text field formatters.
*
* @group rdf
*/
class TextFieldRdfaTest extends FieldRdfaTestBase {
/**
* {@inheritdoc}
*/
protected $fieldType = 'text';
/**
* The 'value' property value for testing.
*
* @var string
*/
protected $testValue = 'test_text_value';
/**
* The 'summary' property value for testing.
*
* @var string
*/
protected $testSummary = 'test_summary_value';
/**
* {@inheritdoc}
*/
public static $modules = ['text', 'filter'];
protected function setUp() {
parent::setUp();
$this->installConfig(['filter']);
$this->createTestField();
// Add the mapping.
$mapping = rdf_get_mapping('entity_test', 'entity_test');
$mapping->setFieldMapping($this->fieldName, [
'properties' => ['schema:text'],
])->save();
// Set up test entity.
$this->entity = EntityTest::create();
$this->entity->{$this->fieldName}->value = $this->testValue;
$this->entity->{$this->fieldName}->summary = $this->testSummary;
}
/**
* Tests all formatters.
*
* @todo Check for the summary mapping.
*/
public function testAllFormatters() {
$formatted_value = strip_tags($this->entity->{$this->fieldName}->processed);
// Tests the default formatter.
$this->assertFormatterRdfa(['type' => 'text_default'], 'http://schema.org/text', ['value' => $formatted_value]);
// Tests the summary formatter.
$this->assertFormatterRdfa(['type' => 'text_summary_or_trimmed'], 'http://schema.org/text', ['value' => $formatted_value]);
// Tests the trimmed formatter.
$this->assertFormatterRdfa(['type' => 'text_trimmed'], 'http://schema.org/text', ['value' => $formatted_value]);
}
}
@@ -0,0 +1,395 @@
<?php
namespace Drupal\Tests\rdf\Kernel\Migrate\d7;
use Drupal\rdf\RdfMappingInterface;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**
* Tests RDF mappings migration from Drupal 7 to 8.
*
* @group rdf
*/
class MigrateRdfMappingTest extends MigrateDrupal7TestBase {
/**
* {@inheritdoc}
*/
public static $modules = [
'menu_ui',
'node',
'rdf',
'taxonomy',
'text',
];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installConfig(static::$modules);
$this->executeMigrations([
'd7_node_type',
'd7_taxonomy_vocabulary',
'd7_rdf_mapping',
]);
}
/**
* Asserts various aspects of a RDF mapping.
*
* @param string $entity_type
* The entity type.
* @param string $bundle
* The bundle.
* @param string[] $types
* The expected RDF types.
* @param array[] $field_mappings
* The expected RDF field mappings.
*/
protected function assertRdfMapping($entity_type, $bundle, $types, $field_mappings) {
$rdf_mapping = rdf_get_mapping($entity_type, $bundle);
$this->assertInstanceOf(RdfMappingInterface::class, $rdf_mapping);
$this->assertSame($types, $rdf_mapping->getBundleMapping());
foreach ($field_mappings as $field => $mapping) {
$this->assertSame($mapping, $rdf_mapping->getFieldMapping($field));
}
}
/**
* Tests RDF mappings migration from Drupal 7 to 8.
*/
public function testRdfMappingMigration() {
$this->assertRdfMapping(
'node',
'article',
[
'types' => [
'sioc:Item',
'foaf:Document',
],
],
[
'field_image' => [
'properties' => [
'og:image',
'rdfs:seeAlso',
],
'mapping_type' => 'rel',
],
'field_tags' => [
'properties' => [
'dc:subject',
],
'mapping_type' => 'rel',
],
'title' => [
'properties' => [
'dc:title',
],
],
'created' => [
'properties' => [
'dc:date',
'dc:created',
],
'datatype' => 'xsd:dateTime',
'datatype_callback' => [
'callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value',
],
],
'changed' => [
'properties' => [
'dc:modified',
],
'datatype' => 'xsd:dateTime',
'datatype_callback' => [
'callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value',
],
],
'body' => [
'properties' => [
'content:encoded',
],
],
'uid' => [
'properties' => [
'sioc:has_creator',
],
'mapping_type' => 'rel',
],
'name' => [
'properties' => [
'foaf:name',
],
],
'comment_count' => [
'properties' => [
'sioc:num_replies',
],
'datatype' => 'xsd:integer',
],
'last_activity' => [
'properties' => [
'sioc:last_activity_date',
],
'datatype' => 'xsd:dateTime',
'datatype_callback' => [
'callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value',
],
],
]
);
$this->assertRdfMapping(
'node',
'blog',
[
'types' => [
'sioc:Post',
'sioct:BlogPost',
],
],
[
'title' => [
'properties' => [
'dc:title',
],
],
'created' => [
'properties' => [
'dc:date',
'dc:created',
],
'datatype' => 'xsd:dateTime',
'datatype_callback' => [
'callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value',
],
],
'changed' => [
'properties' => [
'dc:modified',
],
'datatype' => 'xsd:dateTime',
'datatype_callback' => [
'callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value',
],
],
'body' => [
'properties' => [
'content:encoded',
],
],
'uid' => [
'properties' => [
'sioc:has_creator',
],
'mapping_type' => 'rel',
],
'name' => [
'properties' => [
'foaf:name',
],
],
'comment_count' => [
'properties' => [
'sioc:num_replies',
],
'datatype' => 'xsd:integer',
],
'last_activity' => [
'properties' => [
'sioc:last_activity_date',
],
'datatype' => 'xsd:dateTime',
'datatype_callback' => [
'callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value',
],
],
]
);
$this->assertRdfMapping(
'node',
'forum',
[
'types' => [
'sioc:Post',
'sioct:BoardPost',
],
],
[
'taxonomy_forums' => [
'properties' => [
'sioc:has_container',
],
'mapping_type' => 'rel',
],
'title' => [
'properties' => [
'dc:title',
],
],
'created' => [
'properties' => [
'dc:date',
'dc:created',
],
'datatype' => 'xsd:dateTime',
'datatype_callback' => [
'callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value',
],
],
'changed' => [
'properties' => [
'dc:modified',
],
'datatype' => 'xsd:dateTime',
'datatype_callback' => [
'callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value',
],
],
'body' => [
'properties' => [
'content:encoded',
],
],
'uid' => [
'properties' => [
'sioc:has_creator',
],
'mapping_type' => 'rel',
],
'name' => [
'properties' => [
'foaf:name',
],
],
'comment_count' => [
'properties' => [
'sioc:num_replies',
],
'datatype' => 'xsd:integer',
],
'last_activity' => [
'properties' => [
'sioc:last_activity_date',
],
'datatype' => 'xsd:dateTime',
'datatype_callback' => [
'callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value',
],
],
]
);
$this->assertRdfMapping(
'node',
'page',
[
'types' => [
'foaf:Document',
],
],
[
'title' => [
'properties' => [
'dc:title',
],
],
'created' => [
'properties' => [
'dc:date',
'dc:created',
],
'datatype' => 'xsd:dateTime',
'datatype_callback' => [
'callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value',
],
],
'changed' => [
'properties' => [
'dc:modified',
],
'datatype' => 'xsd:dateTime',
'datatype_callback' => [
'callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value',
],
],
'body' => [
'properties' => [
'content:encoded',
],
],
'uid' => [
'properties' => [
'sioc:has_creator',
],
'mapping_type' => 'rel',
],
'name' => [
'properties' => [
'foaf:name',
],
],
'comment_count' => [
'properties' => [
'sioc:num_replies',
],
'datatype' => 'xsd:integer',
],
'last_activity' => [
'properties' => [
'sioc:last_activity_date',
],
'datatype' => 'xsd:dateTime',
'datatype_callback' => [
'callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value',
],
],
]
);
$this->assertRdfMapping(
'taxonomy_term',
'forums',
[
'types' => [
'sioc:Container',
'sioc:Forum',
],
],
[
'name' => [
'properties' => [
'rdfs:label',
'skos:prefLabel',
],
],
'description' => [
'properties' => [
'skos:definition',
],
],
'vid' => [
'properties' => [
'skos:inScheme',
],
'mapping_type' => 'rel',
],
'parent' => [
'properties' => [
'skos:broader',
],
'mapping_type' => 'rel',
],
]
);
// Clear the map table and check that the migration runs successfully when
// the rdf mappings already exist.
$id_map = $this->getMigration('d7_rdf_mapping')->getIdMap();
$id_map->destroy();
$this->executeMigration('d7_rdf_mapping');
}
}
@@ -0,0 +1,228 @@
<?php
namespace Drupal\Tests\rdf\Kernel\Plugin\migrate\source\d7;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
/**
* Tests Drupal 7 RDF mappings source plugin.
*
* @covers \Drupal\rdf\Plugin\migrate\source\d7\RdfMapping
*
* @group rdf
*/
class RdfMappingTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
public static $modules = [
'comment',
'migrate_drupal',
'node',
'rdf',
'taxonomy',
'user',
];
/**
* {@inheritdoc}
*/
public function providerSource() {
$tests = [];
// The source data.
$tests[0]['source_data']['rdf_mapping'] = [
[
'type' => 'comment',
'bundle' => 'comment_node_article',
'mapping' => 'a:8:{s:7:"rdftype";a:2:{i:0;s:9:"sioc:Post";i:1;s:13:"sioct:Comment";}s:5:"title";a:1:{s:10:"predicates";a:1:{i:0;s:8:"dc:title";}}s:7:"created";a:3:{s:10:"predicates";a:2:{i:0;s:7:"dc:date";i:1;s:10:"dc:created";}s:8:"datatype";s:12:"xsd:dateTime";s:8:"callback";s:12:"date_iso8601";}s:7:"changed";a:3:{s:10:"predicates";a:1:{i:0;s:11:"dc:modified";}s:8:"datatype";s:12:"xsd:dateTime";s:8:"callback";s:12:"date_iso8601";}s:12:"comment_body";a:1:{s:10:"predicates";a:1:{i:0;s:15:"content:encoded";}}s:3:"pid";a:2:{s:10:"predicates";a:1:{i:0;s:13:"sioc:reply_of";}s:4:"type";s:3:"rel";}s:3:"uid";a:2:{s:10:"predicates";a:1:{i:0;s:16:"sioc:has_creator";}s:4:"type";s:3:"rel";}s:4:"name";a:1:{s:10:"predicates";a:1:{i:0;s:9:"foaf:name";}}}',
],
[
'type' => 'node',
'bundle' => 'article',
'mapping' => 'a:9:{s:7:"rdftype";a:2:{i:0;s:9:"sioc:Item";i:1;s:13:"foaf:Document";}s:5:"title";a:1:{s:10:"predicates";a:1:{i:0;s:8:"dc:title";}}s:7:"created";a:3:{s:10:"predicates";a:2:{i:0;s:7:"dc:date";i:1;s:10:"dc:created";}s:8:"datatype";s:12:"xsd:dateTime";s:8:"callback";s:12:"date_iso8601";}s:7:"changed";a:3:{s:10:"predicates";a:1:{i:0;s:11:"dc:modified";}s:8:"datatype";s:12:"xsd:dateTime";s:8:"callback";s:12:"date_iso8601";}s:4:"body";a:1:{s:10:"predicates";a:1:{i:0;s:15:"content:encoded";}}s:3:"uid";a:2:{s:10:"predicates";a:1:{i:0;s:16:"sioc:has_creator";}s:4:"type";s:3:"rel";}s:4:"name";a:1:{s:10:"predicates";a:1:{i:0;s:9:"foaf:name";}}s:13:"comment_count";a:2:{s:10:"predicates";a:1:{i:0;s:16:"sioc:num_replies";}s:8:"datatype";s:11:"xsd:integer";}s:13:"last_activity";a:3:{s:10:"predicates";a:1:{i:0;s:23:"sioc:last_activity_date";}s:8:"datatype";s:12:"xsd:dateTime";s:8:"callback";s:12:"date_iso8601";}}',
],
[
'type' => 'taxonomy_term',
'bundle' => 'tags',
'mapping' => 'a:5:{s:7:"rdftype";a:1:{i:0;s:12:"skos:Concept";}s:4:"name";a:1:{s:10:"predicates";a:2:{i:0;s:10:"rdfs:label";i:1;s:14:"skos:prefLabel";}}s:11:"description";a:1:{s:10:"predicates";a:1:{i:0;s:15:"skos:definition";}}s:3:"vid";a:2:{s:10:"predicates";a:1:{i:0;s:13:"skos:inScheme";}s:4:"type";s:3:"rel";}s:6:"parent";a:2:{s:10:"predicates";a:1:{i:0;s:12:"skos:broader";}s:4:"type";s:3:"rel";}}',
],
[
'type' => 'user',
'bundle' => 'user',
'mapping' => 'a:3:{s:7:"rdftype";a:1:{i:0;s:16:"sioc:UserAccount";}s:4:"name";a:1:{s:10:"predicates";a:1:{i:0;s:9:"foaf:name";}}s:8:"homepage";a:2:{s:10:"predicates";a:1:{i:0;s:9:"foaf:page";}s:4:"type";s:3:"rel";}}',
],
];
// The expected results.
$tests[0]['expected_data'] = [
[
'type' => 'comment',
'bundle' => 'comment_node_article',
'types' => [
'sioc:Post',
'sioct:Comment',
],
'fieldMappings' => [
'changed' => [
'predicates' => [
'dc:modified',
],
'datatype' => 'xsd:dateTime',
'callback' => 'date_iso8601',
],
'comment_body' => [
'predicates' => [
'content:encoded',
],
],
'created' => [
'predicates' => [
'dc:date',
'dc:created',
],
'datatype' => 'xsd:dateTime',
'callback' => 'date_iso8601',
],
'name' => [
'predicates' => [
'foaf:name',
],
],
'pid' => [
'predicates' => [
'sioc:reply_of',
],
'type' => 'rel',
],
'title' => [
'predicates' => [
'dc:title',
],
],
'uid' => [
'predicates' => [
'sioc:has_creator',
],
'type' => 'rel',
],
],
],
[
'type' => 'node',
'bundle' => 'article',
'types' => [
'sioc:Item',
'foaf:Document',
],
'fieldMappings' => [
'body' => [
'predicates' => [
'content:encoded',
],
],
'changed' => [
'predicates' => [
'dc:modified',
],
'datatype' => 'xsd:dateTime',
'callback' => 'date_iso8601',
],
'comment_count' => [
'predicates' => [
'sioc:num_replies',
],
'datatype' => 'xsd:integer',
],
'created' => [
'predicates' => [
'dc:date',
'dc:created',
],
'datatype' => 'xsd:dateTime',
'callback' => 'date_iso8601',
],
'last_activity' => [
'predicates' => [
'sioc:last_activity_date',
],
'datatype' => 'xsd:dateTime',
'callback' => 'date_iso8601',
],
'name' => [
'predicates' => [
'foaf:name',
],
],
'title' => [
'predicates' => [
'dc:title',
],
],
'uid' => [
'predicates' => [
'sioc:has_creator',
],
'type' => 'rel',
],
],
],
[
'type' => 'taxonomy_term',
'bundle' => 'tags',
'types' => [
'skos:Concept',
],
'fieldMappings' => [
'description' => [
'predicates' => [
'skos:definition',
],
],
'name' => [
'predicates' => [
'rdfs:label',
'skos:prefLabel',
],
],
'parent' => [
'predicates' => [
'skos:broader',
],
'type' => 'rel',
],
'vid' => [
'predicates' => [
'skos:inScheme',
],
'type' => 'rel',
],
],
],
[
'type' => 'user',
'bundle' => 'user',
'types' => [
'sioc:UserAccount',
],
'fieldMappings' => [
'homepage' => [
'predicates' => [
'foaf:page',
],
'type' => 'rel',
],
'name' => [
'predicates' => [
'foaf:name',
],
],
],
],
];
return $tests;
}
}
@@ -0,0 +1,135 @@
<?php
namespace Drupal\Tests\rdf\Kernel;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests RDFa attribute generation from RDF mapping.
*
* @group rdf
*/
class RdfaAttributesTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['rdf'];
/**
* Test attribute creation for mappings which use 'property'.
*/
public function testProperty() {
$properties = ['dc:title'];
$mapping = ['properties' => $properties];
$expected_attributes = ['property' => $properties];
$this->_testAttributes($expected_attributes, $mapping);
}
/**
* Test attribute creation for mappings which use 'datatype'.
*/
public function testDatatype() {
$properties = ['foo:bar1'];
$datatype = 'foo:bar1type';
$mapping = [
'datatype' => $datatype,
'properties' => $properties,
];
$expected_attributes = [
'datatype' => $datatype,
'property' => $properties,
];
$this->_testAttributes($expected_attributes, $mapping);
}
/**
* Test attribute creation for mappings which override human-readable content.
*/
public function testDatatypeCallback() {
$properties = ['dc:created'];
$datatype = 'xsd:dateTime';
$date = 1252750327;
$iso_date = $this->container->get('date.formatter')->format($date, 'custom', 'c', 'UTC');
$mapping = [
'datatype' => $datatype,
'properties' => $properties,
'datatype_callback' => ['callable' => 'Drupal\rdf\CommonDataConverter::dateIso8601Value'],
];
$expected_attributes = [
'datatype' => $datatype,
'property' => $properties,
'content' => $iso_date,
];
$this->_testAttributes($expected_attributes, $mapping, ['value' => $date]);
}
/**
* Test attribute creation for mappings which use data converters.
*/
public function testDatatypeCallbackWithConverter() {
$properties = ['schema:interactionCount'];
$data = "23";
$content = "UserComments:23";
$mapping = [
'properties' => $properties,
'datatype_callback' => [
'callable' => 'Drupal\rdf\SchemaOrgDataConverter::interactionCount',
'arguments' => ['interaction_type' => 'UserComments'],
],
];
$expected_attributes = [
'property' => $properties,
'content' => $content,
];
$this->_testAttributes($expected_attributes, $mapping, $data);
}
/**
* Test attribute creation for mappings which use 'rel'.
*/
public function testRel() {
$properties = ['sioc:has_creator', 'dc:creator'];
$mapping = [
'properties' => $properties,
'mapping_type' => 'rel',
];
$expected_attributes = ['rel' => $properties];
$this->_testAttributes($expected_attributes, $mapping);
}
/**
* Helper function to test attribute generation.
*
* @param array $expected_attributes
* The expected return of rdf_rdfa_attributes.
* @param array $field_mapping
* The field mapping to merge into the RDF mapping config.
* @param mixed $data
* The data to pass into the datatype callback, if specified.
*/
protected function _testAttributes($expected_attributes, $field_mapping, $data = NULL) {
$mapping = rdf_get_mapping('node', 'article')
->setFieldMapping('field_test', $field_mapping)
->getPreparedFieldMapping('field_test');
$attributes = rdf_rdfa_attributes($mapping, $data);
ksort($expected_attributes);
ksort($attributes);
$this->assertEqual($expected_attributes, $attributes);
}
}
@@ -0,0 +1,352 @@
<?php
// @codingStandardsIgnoreFile
namespace Drupal\Tests\rdf\Traits;
/**
* This is copy of \EasyRdf_ParsedUri from the easyrdf/easyrdf library.
*
* It fixes a PHP 7.4 deprecation in \EasyRdf_ParsedUri::normalize().
*
* @todo https://www.drupal.org/project/drupal/issues/3110972 Remove this work
* around.
*/
/**
* EasyRdf
*
* LICENSE
*
* Copyright (c) 2009-2013 Nicholas J Humfrey. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author 'Nicholas J Humfrey" may be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package EasyRdf
* @copyright Copyright (c) 2009-2013 Nicholas J Humfrey
* @license http://www.opensource.org/licenses/bsd-license.php
*/
/**
* A RFC3986 compliant URI parser
*
* @package EasyRdf
* @copyright Copyright (c) 2009-2013 Nicholas J Humfrey
* @license http://www.opensource.org/licenses/bsd-license.php
* @link http://www.ietf.org/rfc/rfc3986.txt
*/
class EasyRdf_ParsedUri
{
// For all URIs:
private $scheme = null;
private $fragment = null;
// For hierarchical URIs:
private $authority = null;
private $path = null;
private $query = null;
const URI_REGEX = "|^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?|";
/** Constructor for creating a new parsed URI
*
* The $uri parameter can either be a string or an
* associative array with the following keys:
* scheme, authority, path, query, fragment
*
* @param mixed $uri The URI as a string or an array
* @return object EasyRdf_ParsedUri
*/
public function __construct($uri = null)
{
if (is_string($uri)) {
if (preg_match(self::URI_REGEX, $uri, $matches)) {
if (!empty($matches[1])) {
$this->scheme = isset($matches[2]) ? $matches[2] : '';
}
if (!empty($matches[3])) {
$this->authority = isset($matches[4]) ? $matches[4] : '';
}
$this->path = isset($matches[5]) ? $matches[5] : '';
if (!empty($matches[6])) {
$this->query = isset($matches[7]) ? $matches[7] : '';
}
if (!empty($matches[8])) {
$this->fragment = isset($matches[9]) ? $matches[9] : '';
}
}
} elseif (is_array($uri)) {
$this->scheme = isset($uri['scheme']) ? $uri['scheme'] : null;
$this->authority = isset($uri['authority']) ? $uri['authority'] : null;
$this->path = isset($uri['path']) ? $uri['path'] : null;
$this->query = isset($uri['query']) ? $uri['query'] : null;
$this->fragment = isset($uri['fragment']) ? $uri['fragment'] : null;
}
}
/** Returns true if this is an absolute (complete) URI
* @return boolean
*/
public function isAbsolute()
{
return $this->scheme !== null;
}
/** Returns true if this is an relative (partial) URI
* @return boolean
*/
public function isRelative()
{
return $this->scheme === null;
}
/** Returns the scheme of the URI (e.g. http)
* @return string
*/
public function getScheme()
{
return $this->scheme;
}
/** Sets the scheme of the URI (e.g. http)
* @param string $scheme The new value for the scheme of the URI
*/
public function setScheme($scheme)
{
$this->scheme = $scheme;
}
/** Returns the authority of the URI (e.g. www.example.com:8080)
* @return string
*/
public function getAuthority()
{
return $this->authority;
}
/** Sets the authority of the URI (e.g. www.example.com:8080)
* @param string $authority The new value for the authority component of the URI
*/
public function setAuthority($authority)
{
$this->authority = $authority;
}
/** Returns the path of the URI (e.g. /foo/bar)
* @return string
*/
public function getPath()
{
return $this->path;
}
/** Set the path of the URI (e.g. /foo/bar)
* @param string $path The new value for the path component of the URI
*/
public function setPath($path)
{
$this->path = $path;
}
/** Returns the query string part of the URI (e.g. foo=bar)
* @return string
*/
public function getQuery()
{
return $this->query;
}
/** Set the query string of the URI (e.g. foo=bar)
* @param string $query The new value for the query string component of the URI
*/
public function setQuery($query)
{
$this->query = $query;
}
/** Returns the fragment part of the URI (i.e. after the #)
* @return string
*/
public function getFragment()
{
return $this->fragment;
}
/** Set the fragment of the URI (i.e. after the #)
* @param string $fragment The new value for the fragment component of the URI
*/
public function setFragment($fragment)
{
$this->fragment = $fragment;
}
/**
* Normalizes the path of this URI if it has one. Normalizing a path means
* that any unnecessary '.' and '..' segments are removed. For example, the
* URI http://example.com/a/b/../c/./d would be normalized to
* http://example.com/a/c/d
*
* @return object EasyRdf_ParsedUri
*/
public function normalize()
{
if (empty($this->path)) {
return $this;
}
// Remove ./ from the start
if (substr($this->path, 0, 2) == './') {
// Remove both characters
$this->path = substr($this->path, 2);
}
// Remove /. from the end
if (substr($this->path, -2) == '/.') {
// Remove only the last dot, not the slash!
$this->path = substr($this->path, 0, -1);
}
if (substr($this->path, -3) == '/..') {
$this->path .= '/';
}
// Split the path into its segments
$segments = explode('/', $this->path);
$newSegments = array();
// Remove all unnecessary '.' and '..' segments
foreach ($segments as $segment) {
if ($segment == '..') {
// Remove the previous part of the path
$count = count($newSegments);
if ($count > 0 && $newSegments[$count-1]) {
array_pop($newSegments);
}
} elseif ($segment == '.') {
// Ignore
continue;
} else {
array_push($newSegments, $segment);
}
}
// Construct the new normalized path
$this->path = implode('/', $newSegments);
// Allow easy chaining of methods
return $this;
}
/**
* Resolves a relative URI using this URI as the base URI.
*/
public function resolve($relUri)
{
// If it is a string, then convert it to a parsed object
if (is_string($relUri)) {
$relUri = new EasyRdf_ParsedUri($relUri);
}
// This code is based on the pseudocode in section 5.2.2 of RFC3986
$target = new EasyRdf_ParsedUri();
if ($relUri->scheme) {
$target->scheme = $relUri->scheme;
$target->authority = $relUri->authority;
$target->path = $relUri->path;
$target->query = $relUri->query;
} else {
if ($relUri->authority) {
$target->authority = $relUri->authority;
$target->path = $relUri->path;
$target->query = $relUri->query;
} else {
if (empty($relUri->path)) {
$target->path = $this->path;
if ($relUri->query) {
$target->query = $relUri->query;
} else {
$target->query = $this->query;
}
} else {
if (substr($relUri->path, 0, 1) == '/') {
$target->path = $relUri->path;
} else {
$path = $this->path;
$lastSlash = strrpos($path, '/');
if ($lastSlash !== false) {
$path = substr($path, 0, $lastSlash + 1);
} else {
$path = '/';
}
$target->path .= $path . $relUri->path;
}
$target->query = $relUri->query;
}
$target->authority = $this->authority;
}
$target->scheme = $this->scheme;
}
$target->fragment = $relUri->fragment;
$target->normalize();
return $target;
}
/** Convert the parsed URI back into a string
*
* @return string The URI as a string
*/
public function toString()
{
$str = '';
if ($this->scheme !== null) {
$str .= $this->scheme . ':';
}
if ($this->authority !== null) {
$str .= '//' . $this->authority;
}
$str .= $this->path;
if ($this->query !== null) {
$str .= '?' . $this->query;
}
if ($this->fragment !== null) {
$str .= '#' . $this->fragment;
}
return $str;
}
/** Magic method to convert the URI, when casted, back to a string
*
* @return string The URI as a string
*/
public function __toString()
{
return $this->toString();
}
}
@@ -0,0 +1,146 @@
<?php
namespace Drupal\Tests\rdf\Traits;
use Drupal\Core\Url;
/**
* Override \EasyRdf_ParsedUri for PHP 7.4 compatibility.
*
* @todo https://www.drupal.org/project/drupal/issues/3110972 Remove this work
* around.
*/
class_alias('\Drupal\Tests\rdf\Traits\EasyRdf_ParsedUri', '\EasyRdf_ParsedUri');
/**
* Defines a trait for parsing RDF properties from HTML.
*/
trait RdfParsingTrait {
/**
* Checks if a html document contains a resource with a given property value.
*
* @param string $html
* The HTML to parse.
* @param string $base_uri
* The base URI for the html being parsed.
* @param string $resource
* The URI of the resource which should have the given property.
* @param string $property
* The property being tested.
* @param array $value
* The expected value. This should include the following keys:
* - type: one of literal, uri and bnode
* - value: the expected value
* - datatype: the expected datatype in URI format - e.g.
* - http://www.w3.org/2001/XMLSchema#integer
* - http://www.w3.org/2001/XMLSchema#dateTime
* - lang: language code of the property.
*
* @return bool
* TRUE if the property exists with the given value.
*/
protected function hasRdfProperty($html, $base_uri, $resource, $property, array $value) {
$parser = new \EasyRdf_Parser_Rdfa();
$graph = new \EasyRdf_Graph();
$parser->parse($graph, $html, 'rdfa', $base_uri);
return $graph->hasProperty($resource, $property, $value);
}
/**
* Checks if a html document contains a resource with a given property value.
*
* @param string $html
* The HTML to parse.
* @param string $base_uri
* The base URI for the html being parsed.
* @param string $resource
* The URI of the resource which should have the given property.
* @param string $parent_property
* The parent property being tested.
* @param string $child_property
* The child property being tested.
* @param array $value
* The expected value. This should include the following keys:
* - type: one of literal, uri and bnode
* - value: the expected value
* - datatype: the expected datatype in URI format - e.g.
* - http://www.w3.org/2001/XMLSchema#integer
* - http://www.w3.org/2001/XMLSchema#dateTime
* - lang: language code of the property.
*
* @return bool
* TRUE if the property exists with the given value.
*/
protected function hasRdfChildProperty($html, $base_uri, $resource, $parent_property, string $child_property, array $value) {
$parser = new \EasyRdf_Parser_Rdfa();
$graph = new \EasyRdf_Graph();
$parser->parse($graph, $html, 'rdfa', $base_uri);
$node = $graph->get($resource, $parent_property);
return $graph->hasProperty($node, $child_property, $value);
}
/**
* Counts the number of resources of the provided type.
*
* @param \Drupal\Core\Url $url
* URL of the document.
* @param string $base_uri
* The base URI for the html being parsed.
* @param string $type
* Type of resource to count.
*
* @return int
* The number of resources of the provided type.
*/
protected function getElementByRdfTypeCount(Url $url, $base_uri, $type) {
$parser = new \EasyRdf_Parser_Rdfa();
$graph = new \EasyRdf_Graph();
$parser->parse($graph, $this->drupalGet($url), 'rdfa', $base_uri);
return count($graph->allOfType($type));
}
/**
* Gets type of RDF Element.
*
* @param \Drupal\Core\Url $url
* URL of the document.
* @param string $base_uri
* The base URI for the html being parsed.
* @param string $resource_uri
* The URI of the resource from where to get element.
*
* @return string|null
* The type of resource or NULL if the resource has no type.
*/
protected function getElementRdfType(Url $url, $base_uri, $resource_uri) {
$parser = new \EasyRdf_Parser_Rdfa();
$graph = new \EasyRdf_Graph();
$parser->parse($graph, $this->drupalGet($url), 'rdfa', $base_uri);
return $graph->type($resource_uri);
}
/**
* Checks if RDF Node property is blank.
*
* @param string $html
* The HTML to parse.
* @param string $base_uri
* The base URI for the html being parsed.
* @param string $resource_uri
* The URI of the resource which should have the given property.
* @param string $property
* The property being tested.
*
* @return bool
* TRUE if the given property is blank.
*/
protected function rdfElementIsBlankNode($html, $base_uri, $resource_uri, $property) {
$parser = new \EasyRdf_Parser_Rdfa();
$graph = new \EasyRdf_Graph();
$parser->parse($graph, $html, 'rdfa', $base_uri);
return $graph->get($resource_uri, $property)->isBnode();
}
}
@@ -0,0 +1,133 @@
<?php
namespace Drupal\Tests\rdf\Unit;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Tests\UnitTestCase;
use Drupal\rdf\Entity\RdfMapping;
/**
* @coversDefaultClass \Drupal\rdf\Entity\RdfMapping
* @group rdf
*/
class RdfMappingConfigEntityUnitTest extends UnitTestCase {
/**
* The entity type used for testing.
*
* @var \Drupal\Core\Entity\EntityTypeInterface|\PHPUnit\Framework\MockObject\MockObject
*/
protected $entityType;
/**
* The entity type manager used for testing.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface|\PHPUnit\Framework\MockObject\MockObject
*/
protected $entityTypeManager;
/**
* The ID of the type of the entity under test.
*
* @var string
*/
protected $entityTypeId;
/**
* The UUID generator used for testing.
*
* @var \Drupal\Component\Uuid\UuidInterface|\PHPUnit\Framework\MockObject\MockObject
*/
protected $uuid;
/**
* {@inheritdoc}
*/
protected function setUp() {
$this->entityTypeId = $this->randomMachineName();
$this->entityType = $this->createMock('\Drupal\Core\Entity\EntityTypeInterface');
$this->entityType->expects($this->any())
->method('getProvider')
->will($this->returnValue('entity'));
$this->entityTypeManager = $this->createMock(EntityTypeManagerInterface::class);
$this->uuid = $this->createMock('\Drupal\Component\Uuid\UuidInterface');
$container = new ContainerBuilder();
$container->set('entity_type.manager', $this->entityTypeManager);
$container->set('uuid', $this->uuid);
\Drupal::setContainer($container);
}
/**
* @covers ::calculateDependencies
*/
public function testCalculateDependencies() {
$target_entity_type_id = $this->randomMachineName(16);
$target_entity_type = $this->createMock('\Drupal\Core\Entity\EntityTypeInterface');
$target_entity_type->expects($this->any())
->method('getProvider')
->will($this->returnValue('test_module'));
$values = ['targetEntityType' => $target_entity_type_id];
$target_entity_type->expects($this->any())
->method('getBundleEntityType')
->will($this->returnValue(NULL));
$target_entity_type->expects($this->any())
->method('getBundleConfigDependency')
->will($this->returnValue(['type' => 'module', 'name' => 'test_module']));
$this->entityTypeManager->expects($this->at(0))
->method('getDefinition')
->with($target_entity_type_id)
->will($this->returnValue($target_entity_type));
$this->entityTypeManager->expects($this->at(1))
->method('getDefinition')
->with($this->entityTypeId)
->will($this->returnValue($this->entityType));
$this->entityTypeManager->expects($this->at(2))
->method('getDefinition')
->with($this->entityTypeId)
->will($this->returnValue($this->entityType));
$entity = new RdfMapping($values, $this->entityTypeId);
$dependencies = $entity->calculateDependencies()->getDependencies();
$this->assertArrayNotHasKey('config', $dependencies);
$this->assertContains('test_module', $dependencies['module']);
}
/**
* @covers ::calculateDependencies
*/
public function testCalculateDependenciesWithEntityBundle() {
$target_entity_type_id = $this->randomMachineName(16);
$target_entity_type = $this->createMock('\Drupal\Core\Entity\EntityTypeInterface');
$target_entity_type->expects($this->any())
->method('getProvider')
->will($this->returnValue('test_module'));
$bundle_id = $this->randomMachineName(10);
$values = ['targetEntityType' => $target_entity_type_id , 'bundle' => $bundle_id];
$target_entity_type->expects($this->any())
->method('getBundleConfigDependency')
->will($this->returnValue(['type' => 'config', 'name' => 'test_module.type.' . $bundle_id]));
$this->entityTypeManager->expects($this->at(0))
->method('getDefinition')
->with($target_entity_type_id)
->will($this->returnValue($target_entity_type));
$this->entityTypeManager->expects($this->at(1))
->method('getDefinition')
->with($this->entityTypeId)
->will($this->returnValue($this->entityType));
$entity = new RdfMapping($values, $this->entityTypeId);
$dependencies = $entity->calculateDependencies()->getDependencies();
$this->assertContains('test_module.type.' . $bundle_id, $dependencies['config']);
$this->assertContains('test_module', $dependencies['module']);
}
}