From cc649f895bdd555e96f640f3f80d4e3ad0f3d568 Mon Sep 17 00:00:00 2001 From: "Eirik S. Morland" Date: Thu, 13 Jun 2024 14:48:23 +0200 Subject: [PATCH 1/2] Add a step for file in entity --- src/DrupalFeatureContext.php | 40 ++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/DrupalFeatureContext.php b/src/DrupalFeatureContext.php index 5b6c122..9b1fedd 100644 --- a/src/DrupalFeatureContext.php +++ b/src/DrupalFeatureContext.php @@ -56,4 +56,44 @@ public function getContentNid($title, $type) { return reset($nids); } + /** + * Step definition for attaching files to entities. + * + * @Then /^I attach file "([^"]*)" to "([^"]*)" "([^"]*)" "([^"]*)" in field "([^"]*)"$/ + */ + public function iAttachFileToInField($file_name, $entity_type, $content_type, $title, $field) { + $storage = \Drupal::entityTypeManager()->getStorage($entity_type); + $definition = \Drupal::entityTypeManager()->getDefinition($entity_type); + $entities = $storage->loadByProperties([ + $definition->getKey('label') => $title, + $definition->getKey('bundle') => $content_type, + ]); + if (count($entities) === 0) { + throw new \Exception("No $entity_type found with title $title"); + } + if (count($entities) > 1) { + throw new \Exception("Multiple $entity_type found with title $title"); + } + $entity = reset($entities); + $file = $this->createFile($file_name); + $entity->set($field, $file); + $entity->save(); + } + + /** + * Helper to create a file from the assets dir. + */ + public function createFile($path) { + /** @var \Drupal\file\FileRepositoryInterface $file_repo */ + $file_repo = \Drupal::service('file.repository'); + if ($this->getMinkParameter('files_path')) { + $fullPath = rtrim(realpath($this->getMinkParameter('files_path')), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $path; + if (is_file($fullPath)) { + $path = $fullPath; + } + } + $contents = file_get_contents($path); + return $file_repo->writeData($contents, sprintf('public://%s', basename($path))); + } + } From 657f59ee7a2c1acc6844d73b9ea2f7d497c5640f Mon Sep 17 00:00:00 2001 From: "Eirik S. Morland" Date: Thu, 13 Jun 2024 14:54:34 +0200 Subject: [PATCH 2/2] Maybe fix stan --- src/DrupalFeatureContext.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/DrupalFeatureContext.php b/src/DrupalFeatureContext.php index 9b1fedd..d0a8948 100644 --- a/src/DrupalFeatureContext.php +++ b/src/DrupalFeatureContext.php @@ -2,6 +2,7 @@ namespace Frontkom\DrupalBehatDefinitions; +use Drupal\Core\Entity\FieldableEntityInterface; use Drupal\DrupalExtension\Context\RawDrupalContext; /** @@ -75,6 +76,9 @@ public function iAttachFileToInField($file_name, $entity_type, $content_type, $t throw new \Exception("Multiple $entity_type found with title $title"); } $entity = reset($entities); + if (!$entity instanceof FieldableEntityInterface) { + throw new \Exception("Entity is not a fieldable entity"); + } $file = $this->createFile($file_name); $entity->set($field, $file); $entity->save();