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 Drupal Gutenberg Context #4

Merged
merged 3 commits into from
Jun 10, 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
56 changes: 56 additions & 0 deletions src/DrupalGutenbergContext.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace Frontkom\DrupalBehatDefinitions;

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

/**
* Some steps to use with Drupal Gutenberg.
*/
class DrupalGutenbergContext extends RawDrupalContext {

/**
* Get the text format to use.
*
* This is to make it possible to override in a subclass.
*/
protected function getTextFormat() {
return 'gutenberg';
}

/**
* Step to write in a gutenberg field.
*
* @Then I create gutenberg content from file :file in :entity_type with title :title and field name :field_name
* @Then I create gutenberg content from file :file in content :title and field name :field_name
* @Then I create gutenberg content from file :file in content :title
*/
public function appendContentFromFile($file, $title, $field_name = 'body', $entity_type = 'node') {
$storage = \Drupal::entityTypeManager()->getStorage($entity_type);
$definition = \Drupal::entityTypeManager()->getDefinition($entity_type);
$entities = $storage->loadByProperties([$definition->getKey('label') => $title]);
$entity = reset($entities);
if (!$entity instanceof FieldableEntityInterface) {
throw new \Exception("Entity with title $title not found");
}
if (!$entity->hasField($field_name)) {
throw new \Exception("Entity with title $title does not have field $field_name");
}
/** @var \Drupal\Core\Field\FieldItemListInterface $field */
$field = $entity->get($field_name);
$format = $this->getTextFormat();
$content = file_get_contents(DRUPAL_ROOT . '/../tests/files/gutenberg/' . $file);
$current_content = '';
if (!$field->isEmpty()) {
$value = $field->first()->getValue();
$current_content = $value['value'];
}
$field->setValue([
'value' => sprintf("%s\n%s", $current_content, $content),
'format' => $format,
]);
$entity->save();
}

}
Loading