diff --git a/src/SparqlEntityStorage.php b/src/SparqlEntityStorage.php index 4702437..98df5bf 100644 --- a/src/SparqlEntityStorage.php +++ b/src/SparqlEntityStorage.php @@ -21,6 +21,7 @@ use Drupal\Core\Language\LanguageManagerInterface; use Drupal\sparql_entity_storage\Database\Driver\sparql\ConnectionInterface; use Drupal\sparql_entity_storage\Entity\Query\Sparql\SparqlArg; +use Drupal\sparql_entity_storage\Entity\SparqlGraph; use Drupal\sparql_entity_storage\Exception\DuplicatedIdException; use EasyRdf\Graph; use EasyRdf\Literal; @@ -186,6 +187,19 @@ protected static function getGraph($graph_uri) { return $graph; } + /** + * {@inheritdoc} + */ + public function create(array $values = []) { + /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */ + $entity = parent::create($values); + // Ensure the default graph if no explicit graph has been set. + if ($entity->get('graph')->isEmpty()) { + $entity->set('graph', SparqlGraph::DEFAULT); + } + return $entity; + } + /** * {@inheritdoc} */ diff --git a/tests/src/Kernel/EntityCreationTest.php b/tests/src/Kernel/EntityCreationTest.php index 61a6494..2655836 100644 --- a/tests/src/Kernel/EntityCreationTest.php +++ b/tests/src/Kernel/EntityCreationTest.php @@ -4,6 +4,8 @@ namespace Drupal\Tests\sparql_entity_storage\Kernel; +use Drupal\rdf_entity\RdfInterface; +use Drupal\sparql_entity_storage\Entity\SparqlGraph; use Drupal\sparql_entity_storage\Exception\DuplicatedIdException; use Drupal\sparql_test\Entity\SparqlTest; @@ -49,4 +51,31 @@ public function testOverlappingIds(): void { ])->save(); } + /** + * Tests that the default graph is set on entity creation. + * + * @covers ::create + */ + public function testDefaultGraphSetOnCreate(): void { + // Check that the default graph is set when no graph is specified. + $entity = SparqlTest::create([ + 'type' => 'waffle', + 'id' => 'http://example.com/kempense-galet', + 'title' => 'Kempense galet', + ]); + + $this->assertEquals(SparqlGraph::DEFAULT, $entity->get('graph')->target_id); + + // Check that it is possible to specify a custom graph. + /** @var \Drupal\rdf_entity\RdfInterface $entity */ + $entity = SparqlTest::create([ + 'type' => 'waffle', + 'id' => 'http://example.com/liege-waffle', + 'title' => 'Liège waffle', + 'graph' => 'custom_graph', + ]); + + $this->assertEquals('custom_graph', $entity->get('graph')->target_id); + } + }