ProfileTokenTest.php in Profile 8
File
tests/src/Kernel/ProfileTokenTest.php
View source
<?php
namespace Drupal\Tests\profile\Kernel;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityViewBuilderInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\profile\Entity\Profile;
use Drupal\profile\Entity\ProfileType;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
class ProfileTokenTest extends EntityKernelTestBase {
public static $modules = [
'system',
'filter',
'profile',
'views',
'token',
];
protected $user;
protected $profileStorage;
protected $viewBuilder;
protected function setUp() {
parent::setUp();
$this
->installEntitySchema('profile');
$this
->installEntitySchema('view');
$this
->installSchema('user', [
'users_data',
]);
$this
->installConfig(self::$modules);
$entity_type_manager = $this->container
->get('entity_type.manager');
$this->profileStorage = $entity_type_manager
->getStorage('profile');
$this->viewBuilder = $entity_type_manager
->getViewBuilder('profile');
$this->user = $this
->createUser();
}
public function testToken() {
$profile_type = ProfileType::create([
'id' => 'test_defaults',
'label' => 'test_defaults',
]);
$profile_type
->save();
$field_storage = FieldStorageConfig::create([
'field_name' => 'profile_fullname',
'entity_type' => 'profile',
'type' => 'text',
]);
$field_storage
->save();
$field = FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => $profile_type
->id(),
'label' => 'Full name',
]);
$field
->save();
$profile = Profile::create([
'type' => $profile_type
->id(),
'uid' => $this->user
->id(),
'profile_fullname' => $this
->randomMachineName(),
]);
$profile
->save();
$profile = $this
->reloadEntity($profile);
$token_service = \Drupal::service('token');
$field_token = '[user:' . $profile_type
->id() . ':profile_fullname]';
$field_token_output = $token_service
->replace($field_token, [
'user' => $this->user,
]);
$entity_token = '[user:' . $profile_type
->id() . ']';
$entity_token_output = $token_service
->replace($entity_token, [
'user' => $this->user,
]);
$entity_type_manager = \Drupal::entityTypeManager();
$view_builder = $entity_type_manager
->getViewBuilder('profile');
$entity_view = $view_builder
->view($profile, 'token');
$field_view = $view_builder
->viewField($profile
->get('profile_fullname'));
$field_output['#pre_render'][] = '\\Drupal\\token\\TokenFieldRender::preRender';
$renderer = \Drupal::service('renderer');
$rendered_field = $renderer
->renderPlain($field_view);
$rendered_entity = $renderer
->renderRoot($entity_view);
$this
->assertStringContainsString($field_token_output, $rendered_field);
$this
->assertStringContainsString($entity_token_output, $rendered_entity);
}
}