View source
<?php
namespace Drupal\KernelTests\Core\Field;
use Drupal\Core\Access\AccessResult;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\KernelTests\KernelTestBase;
use Drupal\user\Entity\User;
class FieldAccessTest extends KernelTestBase {
protected static $modules = [
'entity_test',
'field',
'system',
'text',
'filter',
'user',
];
protected $activeUid;
protected function setUp() : void {
parent::setUp();
$this
->installConfig([
'field',
]);
$this
->installEntitySchema('entity_test');
$this
->installEntitySchema('entity_test_mul');
$this
->installEntitySchema('entity_test_mul_langcode_key');
$this
->installEntitySchema('entity_test_mul_changed');
$this
->installEntitySchema('entity_test_rev');
$this
->installEntitySchema('entity_test_mulrev');
$this
->installEntitySchema('entity_test_mulrev_changed');
$this
->installEntitySchema('user');
$this->container
->get('module_handler')
->loadInclude('entity_test', 'install');
entity_test_install();
}
public function testFieldAccess() {
$values = [
'name' => $this
->randomMachineName(),
'user_id' => 1,
'field_test_text' => [
'value' => 'no access value',
'format' => 'full_html',
],
];
$entity = EntityTest::create($values);
$values = [
'name' => 'test',
];
$account = User::create($values);
$this
->assertFalse($entity->field_test_text
->access('view', $account), 'Access to the field was denied.');
$expected = AccessResult::forbidden()
->addCacheableDependency($entity);
$this
->assertEquals($expected, $entity->field_test_text
->access('view', $account, TRUE), 'Access to the field was denied.');
$entity->field_test_text = 'access alter value';
$this
->assertFalse($entity->field_test_text
->access('view', $account), 'Access to the field was denied.');
$this
->assertEquals($expected, $entity->field_test_text
->access('view', $account, TRUE), 'Access to the field was denied.');
$entity->field_test_text = 'standard value';
$this
->assertTrue($entity->field_test_text
->access('view', $account), 'Access to the field was granted.');
$this
->assertEquals(AccessResult::allowed(), $entity->field_test_text
->access('view', $account, TRUE), 'Access to the field was granted.');
}
}