View source
<?php
namespace Drupal\views\Tests\Handler;
use Drupal\user\Entity\Role;
use Drupal\user\Entity\User;
use Drupal\views\Entity\View;
use Drupal\views\Tests\ViewKernelTestBase;
use Drupal\views\Views;
abstract class FieldFieldAccessTestBase extends ViewKernelTestBase {
protected $userWithAccess;
protected $userWithoutAccess;
public static $modules = [
'user',
];
protected function setUp($import_test_views = TRUE) {
parent::setUp($import_test_views);
$this
->installEntitySchema('user');
$role_with_access = Role::create([
'id' => 'with_access',
'permissions' => [
'view test entity field',
],
]);
$role_with_access
->save();
$role_without_access = Role::create([
'id' => 'without_access',
'permissions' => [],
]);
$role_without_access
->save();
$this->userWithAccess = User::create([
'name' => $this
->randomMachineName(),
'roles' => [
$role_with_access
->id(),
],
]);
$this->userWithAccess
->save();
$this->userWithoutAccess = User::create([
'name' => $this
->randomMachineName(),
'roles' => [
$role_without_access
->id(),
],
]);
$this->userWithoutAccess
->save();
}
protected function assertFieldAccess($entity_type_id, $field_name, $field_content) {
\Drupal::state()
->set('views_field_access_test-field', $field_name);
$entity_type = \Drupal::entityManager()
->getDefinition($entity_type_id);
$view_id = $this
->randomMachineName();
$data_table = $entity_type
->getDataTable();
$base_table = $data_table && $field_name !== 'uuid' ? $data_table : $entity_type
->getBaseTable();
$entity = View::create([
'id' => $view_id,
'base_table' => $base_table,
'display' => [
'default' => [
'display_plugin' => 'default',
'id' => 'default',
'display_options' => [
'fields' => [
$field_name => [
'table' => $base_table,
'field' => $field_name,
'id' => $field_name,
'plugin_id' => 'field',
],
],
],
],
],
]);
$entity
->save();
$account_switcher = \Drupal::service('account_switcher');
$renderer = \Drupal::service('renderer');
$account_switcher
->switchTo($this->userWithAccess);
$executable = Views::getView($view_id);
$build = $executable
->preview();
$this
->setRawContent($renderer
->renderRoot($build));
$this
->assertText($field_content);
$this
->assertTrue(isset($executable->field[$field_name]));
$account_switcher
->switchTo($this->userWithoutAccess);
$executable = Views::getView($view_id);
$build = $executable
->preview();
$this
->setRawContent($renderer
->renderRoot($build));
$this
->assertNoText($field_content);
$this
->assertFalse(isset($executable->field[$field_name]));
\Drupal::state()
->delete('views_field_access_test-field');
}
}