eav_field-2.x-dev/tests/src/Traits/EavFieldTestTrait.php
tests/src/Traits/EavFieldTestTrait.php
<?php
namespace Drupal\Tests\eav_field\Traits;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Url;
use Drupal\eav_field\Plugin\Field\FieldType\EavItemListInterface;
use Drupal\node\NodeInterface;
trait EavFieldTestTrait {
/**
* Return last added attribute id.
*/
public function getLastAddedEavAttributeId() {
$query = \Drupal::database()->select('eav_attribute', 'a');
$query->addExpression('MAX(a.aid)');
return $query->execute()->fetchField();
}
/**
* Return entity eav field items.
*/
public function getEavFieldItems(EntityInterface $entity, string $field_name = 'field_eav'): ?EavItemListInterface {
return $entity->get($field_name);
}
/**
* Return entity eav form url.
*/
public function getEntityEavFormUrl(int $entity_id, $entity_type = 'node', $field_name = 'field_eav'): Url {
return Url::fromRoute("entity.$entity_type.edit_eav", [$entity_type => $entity_id, 'field_name' => $field_name]);
}
/**
* Create EAV field.
*/
public function createEavField($entity_type_id, $entity_bundle, $field_name, $field_label): void {
$this->createField(
entity_type: $entity_type_id,
entity_bundle: $entity_bundle,
field_name: $field_name,
field_type: 'eav',
field_label: $field_label,
widget_type: 'eav_widget',
formatter_type: 'eav_formatter',
);
drupal_flush_all_caches();
}
/**
* Create product node.
*/
public function createProductNode(int $category = NULL, string $title = 'Test product'): NodeInterface {
return $this->createNode([
'type' => 'product',
'title' => $title,
'field_category' => $category,
]);
}
/**
* Reset entity storage caches.
*/
public function resetEntityStorageCaches(): void {
$entity_type_manager = \Drupal::entityTypeManager(); // Dont use $this->container->get('entity_type.manager'), it's not work
foreach ($entity_type_manager->getDefinitions() as $id => $definition) {
$entity_type_manager->getStorage($id)->resetCache();
}
}
/**
* Check system message text.
*/
public function seeSystemMessage($message): void {
$this->assertSession()->elementTextContains('css', 'div[data-drupal-messages]', $message);
}
/**
* Return formatted value for entity reference widget.
*/
public function formatEntityReferenceWidgetValue(EntityInterface $entity): string {
return $entity->label() . ' (' . $entity->id() . ')';
}
/**
* Return rows count in db table.
*/
public function getDbTableRowsCount(string $table_name): int {
return (int)\Drupal::database()
->select($table_name)
->countQuery()
->execute()
->fetchField();
}
/**
* Open EAV form page.
*/
public function drupalGetEavFormPage(int $entity_id, string $entity_type = 'node', string $field_name = 'field_eav'): void {
$this->drupalGet($this->getEntityEavFormUrl($entity_id, $entity_type, $field_name));
$this->dontSeeErrorMessage();
}
}
