You are here

public function FieldValueTest::testFieldValue in Twig Field Value 2.0.x

Same name in this branch
  1. 2.0.x tests/src/Kernel/FieldValueTest.php \Drupal\Tests\twig_field_value\Kernel\FieldValueTest::testFieldValue()
  2. 2.0.x tests/src/Unit/FieldValue/FieldValueTest.php \Drupal\Tests\twig_field_value\Unit\FieldValue\FieldValueTest::testFieldValue()
Same name and namespace in other branches
  1. 8 tests/src/Kernel/FieldValueTest.php \Drupal\Tests\twig_field_value\Kernel\FieldValueTest::testFieldValue()

Check if inaccessible content is _not_ displayed.

File

tests/src/Kernel/FieldValueTest.php, line 51

Class

FieldValueTest
@coversDefaultClass \Drupal\twig_field_value\Twig\Extension\FieldValueExtension @group twig_field_value

Namespace

Drupal\Tests\twig_field_value\Kernel

Code

public function testFieldValue() {
  $entity1 = EntityTest::create([
    'name' => 'entity1',
  ]);
  $entity1
    ->save();

  // The label is important,
  // \Drupal\entity_test\EntityTestAccessControlHandler returns
  // AccessResult::forbidden for it.
  $entity2 = EntityTest::create([
    'name' => 'forbid_access',
  ]);
  $entity2
    ->save();
  $entity3 = EntityTest::create([
    'name' => 'entity3',
  ]);
  $entity3
    ->save();
  $entity = EntityTest::create([
    'field_reference' => [
      $entity1
        ->id(),
      $entity2
        ->id(),
      $entity3
        ->id(),
    ],
  ]);
  $entity
    ->save();
  $render_field = function (FieldableEntityInterface $entity) {
    return $entity
      ->get('field_reference')
      ->view([
      'type' => 'entity_reference_label',
      'settings' => [
        'link' => FALSE,
      ],
    ]);
  };
  $element = $render_field($entity);

  // Check the field values by rendering the formatter without any filter.
  $content = \Drupal::service('renderer')
    ->renderPlain($element);
  $this
    ->assertContains('entity1', (string) $content);
  $this
    ->assertNotContains('forbid_access', (string) $content);
  $this
    ->assertContains('entity3', (string) $content);

  // Check output of the field_value filter.
  $element = [
    '#type' => 'inline_template',
    '#template' => '{{ field|field_value|safe_join(", ") }}',
    '#context' => [
      'field' => $render_field($entity),
    ],
  ];
  $content = \Drupal::service('renderer')
    ->renderPlain($element);
  $this
    ->assertSame('entity1, entity3', (string) $content);
}