FieldBlockTest.php 9.02 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

namespace Drupal\Tests\layout_builder\Kernel;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
10
use Drupal\Core\Field\FieldDefinitionInterface;
11 12
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterPluginManager;
13
use Drupal\Core\Plugin\Context\EntityContextDefinition;
14 15 16
use Drupal\Core\Session\AccountInterface;
use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
use Drupal\layout_builder\Plugin\Block\FieldBlock;
17 18 19 20
use Prophecy\Argument;
use Prophecy\Promise\PromiseInterface;
use Prophecy\Promise\ReturnPromise;
use Prophecy\Promise\ThrowPromise;
21
use Prophecy\Prophecy\ProphecyInterface;
22
use Psr\Log\LoggerInterface;
23 24 25 26 27 28 29

/**
 * @coversDefaultClass \Drupal\layout_builder\Plugin\Block\FieldBlock
 * @group Field
 */
class FieldBlockTest extends EntityKernelTestBase {

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * The logger.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    $this->entityFieldManager = $this->prophesize(EntityFieldManagerInterface::class);
    $this->logger = $this->prophesize(LoggerInterface::class);
  }

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
  /**
   * Tests entity access.
   *
   * @covers ::blockAccess
   * @dataProvider providerTestBlockAccessNotAllowed
   */
  public function testBlockAccessEntityNotAllowed($expected, $entity_access) {
    $entity = $this->prophesize(FieldableEntityInterface::class);
    $block = $this->getTestBlock($entity);

    $account = $this->prophesize(AccountInterface::class);
    $entity->access('view', $account->reveal(), TRUE)->willReturn($entity_access);
    $entity->hasField()->shouldNotBeCalled();

    $access = $block->access($account->reveal(), TRUE);
    $this->assertSame($expected, $access->isAllowed());
  }

  /**
   * Provides test data for ::testBlockAccessEntityNotAllowed().
   */
  public function providerTestBlockAccessNotAllowed() {
    $data = [];
    $data['entity_forbidden'] = [
      FALSE,
      AccessResult::forbidden(),
    ];
    $data['entity_neutral'] = [
      FALSE,
      AccessResult::neutral(),
    ];
    return $data;
  }

  /**
   * Tests unfieldable entity.
   *
   * @covers ::blockAccess
   */
  public function testBlockAccessEntityAllowedNotFieldable() {
    $entity = $this->prophesize(EntityInterface::class);
    $block = $this->getTestBlock($entity);

    $account = $this->prophesize(AccountInterface::class);
    $entity->access('view', $account->reveal(), TRUE)->willReturn(AccessResult::allowed());

    $access = $block->access($account->reveal(), TRUE);
    $this->assertSame(FALSE, $access->isAllowed());
  }

  /**
   * Tests fieldable entity without a particular field.
   *
   * @covers ::blockAccess
   */
  public function testBlockAccessEntityAllowedNoField() {
    $entity = $this->prophesize(FieldableEntityInterface::class);
    $block = $this->getTestBlock($entity);

    $account = $this->prophesize(AccountInterface::class);
    $entity->access('view', $account->reveal(), TRUE)->willReturn(AccessResult::allowed());
    $entity->hasField('the_field_name')->willReturn(FALSE);
    $entity->get('the_field_name')->shouldNotBeCalled();

    $access = $block->access($account->reveal(), TRUE);
    $this->assertSame(FALSE, $access->isAllowed());
  }

  /**
   * Tests field access.
   *
   * @covers ::blockAccess
   * @dataProvider providerTestBlockAccessNotAllowed
   */
  public function testBlockAccessEntityAllowedFieldNotAllowed($expected, $field_access) {
    $entity = $this->prophesize(FieldableEntityInterface::class);
    $block = $this->getTestBlock($entity);

    $account = $this->prophesize(AccountInterface::class);
    $entity->access('view', $account->reveal(), TRUE)->willReturn(AccessResult::allowed());
    $entity->hasField('the_field_name')->willReturn(TRUE);
    $field = $this->prophesize(FieldItemListInterface::class);
    $entity->get('the_field_name')->willReturn($field->reveal());

    $field->access('view', $account->reveal(), TRUE)->willReturn($field_access);
    $field->isEmpty()->shouldNotBeCalled();

    $access = $block->access($account->reveal(), TRUE);
    $this->assertSame($expected, $access->isAllowed());
  }

  /**
   * Tests populated vs empty build.
   *
   * @covers ::blockAccess
   * @covers ::build
   * @dataProvider providerTestBlockAccessEntityAllowedFieldHasValue
   */
  public function testBlockAccessEntityAllowedFieldHasValue($expected, $is_empty) {
    $entity = $this->prophesize(FieldableEntityInterface::class);
    $block = $this->getTestBlock($entity);

    $account = $this->prophesize(AccountInterface::class);
    $entity->access('view', $account->reveal(), TRUE)->willReturn(AccessResult::allowed());
    $entity->hasField('the_field_name')->willReturn(TRUE);
    $field = $this->prophesize(FieldItemListInterface::class);
    $entity->get('the_field_name')->willReturn($field->reveal());

    $field->access('view', $account->reveal(), TRUE)->willReturn(AccessResult::allowed());
    $field->isEmpty()->willReturn($is_empty)->shouldBeCalled();

    $access = $block->access($account->reveal(), TRUE);
    $this->assertSame($expected, $access->isAllowed());
  }

  /**
   * Provides test data for ::testBlockAccessEntityAllowedFieldHasValue().
   */
  public function providerTestBlockAccessEntityAllowedFieldHasValue() {
    $data = [];
    $data['empty'] = [
      FALSE,
      TRUE,
    ];
    $data['populated'] = [
      TRUE,
      FALSE,
    ];
    return $data;
  }

  /**
   * Instantiates a block for testing.
   *
   * @param \Prophecy\Prophecy\ProphecyInterface $entity_prophecy
   *   An entity prophecy for use as an entity context value.
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param array $plugin_definition
   *   The plugin implementation definition.
   *
   * @return \Drupal\layout_builder\Plugin\Block\FieldBlock
   *   The block to test.
   */
  protected function getTestBlock(ProphecyInterface $entity_prophecy, array $configuration = [], array $plugin_definition = []) {
    $entity_prophecy->getCacheContexts()->willReturn([]);
    $entity_prophecy->getCacheTags()->willReturn([]);
    $entity_prophecy->getCacheMaxAge()->willReturn(0);

    $plugin_definition += [
      'provider' => 'test',
      'default_formatter' => '',
      'category' => 'Test',
      'admin_label' => 'Test Block',
      'bundles' => ['entity_test'],
      'context' => [
210
        'entity' => EntityContextDefinition::fromEntityTypeId('entity_test')->setLabel('Test'),
211 212 213 214 215 216 217
      ],
    ];
    $formatter_manager = $this->prophesize(FormatterPluginManager::class);
    $module_handler = $this->prophesize(ModuleHandlerInterface::class);

    $block = new FieldBlock(
      $configuration,
218
      'field_block:entity_test:entity_test:the_field_name',
219
      $plugin_definition,
220
      $this->entityFieldManager->reveal(),
221
      $formatter_manager->reveal(),
222 223
      $module_handler->reveal(),
      $this->logger->reveal()
224 225 226 227 228
    );
    $block->setContextValue('entity', $entity_prophecy->reveal());
    return $block;
  }

229 230 231 232
  /**
   * @covers ::build
   * @dataProvider providerTestBuild
   */
233
  public function testBuild(PromiseInterface $promise, $expected_markup, $log_message = '', $log_arguments = []) {
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    $entity = $this->prophesize(FieldableEntityInterface::class);
    $field = $this->prophesize(FieldItemListInterface::class);
    $entity->get('the_field_name')->willReturn($field->reveal());
    $field->view(Argument::type('array'))->will($promise);

    $field_definition = $this->prophesize(FieldDefinitionInterface::class);
    $field_definition->getLabel()->willReturn('The Field Label');
    $this->entityFieldManager->getFieldDefinitions('entity_test', 'entity_test')->willReturn(['the_field_name' => $field_definition]);

    if ($log_message) {
      $this->logger->warning($log_message, $log_arguments)->shouldBeCalled();
    }
    else {
      $this->logger->warning(Argument::cetera())->shouldNotBeCalled();
    }

    $block = $this->getTestBlock($entity);
    $expected = [
      '#cache' => [
        'contexts' => [],
        'tags' => [],
        'max-age' => 0,
      ],
    ];
    if ($expected_markup) {
      $expected['content']['#markup'] = $expected_markup;
    }

    $actual = $block->build();
    $this->assertEquals($expected, $actual);
  }

  /**
   * Provides test data for ::testBuild().
   */
  public function providerTestBuild() {
    $data = [];
271
    $data['array'] = [
272 273 274
      new ReturnPromise([['content' => ['#markup' => 'The field value']]]),
      'The field value',
    ];
275
    $data['empty array'] = [
276 277 278
      new ReturnPromise([[]]),
      '',
    ];
279
    $data['exception'] = [
280 281 282 283 284 285 286 287
      new ThrowPromise(new \Exception('The exception message')),
      '',
      'The field "%field" failed to render with the error of "%error".',
      ['%field' => 'the_field_name', '%error' => 'The exception message'],
    ];
    return $data;
  }

288
}