Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a step for file in entity #5

Merged
merged 2 commits into from
Jun 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions src/DrupalFeatureContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Frontkom\DrupalBehatDefinitions;

use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\DrupalExtension\Context\RawDrupalContext;

/**
Expand Down Expand Up @@ -56,4 +57,47 @@ 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);
if (!$entity instanceof FieldableEntityInterface) {
throw new \Exception("Entity is not a fieldable entity");
}
$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)));
}

}
Loading