1473375b1990ae9db1656fbeed29a8a6e901fb8a
[yaffs-website] / web / core / modules / field / tests / src / Kernel / EntityReference / EntityReferenceFormatterTest.php
1 <?php
2
3 namespace Drupal\Tests\field\Kernel\EntityReference;
4
5 use Drupal\Core\Cache\Cache;
6 use Drupal\Core\Cache\CacheableMetadata;
7 use Drupal\Core\Field\FieldStorageDefinitionInterface;
8 use Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceEntityFormatter;
9 use Drupal\field\Entity\FieldConfig;
10 use Drupal\field\Entity\FieldStorageConfig;
11 use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
12 use Drupal\filter\Entity\FilterFormat;
13 use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
14 use Drupal\user\Entity\Role;
15 use Drupal\user\RoleInterface;
16 use Drupal\entity_test\Entity\EntityTestLabel;
17
18 /**
19  * Tests the formatters functionality.
20  *
21  * @group entity_reference
22  */
23 class EntityReferenceFormatterTest extends EntityKernelTestBase {
24
25   use EntityReferenceTestTrait;
26
27   /**
28    * The entity type used in this test.
29    *
30    * @var string
31    */
32   protected $entityType = 'entity_test';
33
34   /**
35    * The bundle used in this test.
36    *
37    * @var string
38    */
39   protected $bundle = 'entity_test';
40
41   /**
42    * The name of the field used in this test.
43    *
44    * @var string
45    */
46   protected $fieldName = 'field_test';
47
48   /**
49    * The entity to be referenced in this test.
50    *
51    * @var \Drupal\Core\Entity\EntityInterface
52    */
53   protected $referencedEntity;
54
55   /**
56    * The entity that is not yet saved to its persistent storage to be referenced
57    * in this test.
58    *
59    * @var \Drupal\Core\Entity\EntityInterface
60    */
61   protected $unsavedReferencedEntity;
62
63   protected function setUp() {
64     parent::setUp();
65
66     // Use Classy theme for testing markup output.
67     \Drupal::service('theme_handler')->install(['classy']);
68     $this->config('system.theme')->set('default', 'classy')->save();
69     $this->installEntitySchema('entity_test');
70     // Grant the 'view test entity' permission.
71     $this->installConfig(['user']);
72     Role::load(RoleInterface::ANONYMOUS_ID)
73       ->grantPermission('view test entity')
74       ->save();
75
76     // The label formatter rendering generates links, so build the router.
77     $this->container->get('router.builder')->rebuild();
78
79     $this->createEntityReferenceField($this->entityType, $this->bundle, $this->fieldName, 'Field test', $this->entityType, 'default', [], FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
80
81     // Set up a field, so that the entity that'll be referenced bubbles up a
82     // cache tag when rendering it entirely.
83     FieldStorageConfig::create([
84       'field_name' => 'body',
85       'entity_type' => $this->entityType,
86       'type' => 'text',
87       'settings' => [],
88     ])->save();
89     FieldConfig::create([
90       'entity_type' => $this->entityType,
91       'bundle' => $this->bundle,
92       'field_name' => 'body',
93       'label' => 'Body',
94     ])->save();
95     entity_get_display($this->entityType, $this->bundle, 'default')
96       ->setComponent('body', [
97         'type' => 'text_default',
98         'settings' => [],
99       ])
100       ->save();
101
102     FilterFormat::create([
103       'format' => 'full_html',
104       'name' => 'Full HTML',
105     ])->save();
106
107     // Create the entity to be referenced.
108     $this->referencedEntity = $this->container->get('entity_type.manager')
109       ->getStorage($this->entityType)
110       ->create(['name' => $this->randomMachineName()]);
111     $this->referencedEntity->body = [
112       'value' => '<p>Hello, world!</p>',
113       'format' => 'full_html',
114     ];
115     $this->referencedEntity->save();
116
117     // Create another entity to be referenced but do not save it.
118     $this->unsavedReferencedEntity = $this->container->get('entity_type.manager')
119       ->getStorage($this->entityType)
120       ->create(['name' => $this->randomMachineName()]);
121     $this->unsavedReferencedEntity->body = [
122       'value' => '<p>Hello, unsaved world!</p>',
123       'format' => 'full_html',
124     ];
125   }
126
127   /**
128    * Assert inaccessible items don't change the data of the fields.
129    */
130   public function testAccess() {
131     // Revoke the 'view test entity' permission for this test.
132     Role::load(RoleInterface::ANONYMOUS_ID)
133       ->revokePermission('view test entity')
134       ->save();
135
136     $field_name = $this->fieldName;
137
138     $referencing_entity = $this->container->get('entity_type.manager')
139       ->getStorage($this->entityType)
140       ->create(['name' => $this->randomMachineName()]);
141     $referencing_entity->save();
142     $referencing_entity->{$field_name}->entity = $this->referencedEntity;
143
144     // Assert user doesn't have access to the entity.
145     $this->assertFalse($this->referencedEntity->access('view'), 'Current user does not have access to view the referenced entity.');
146
147     $formatter_manager = $this->container->get('plugin.manager.field.formatter');
148
149     // Get all the existing formatters.
150     foreach ($formatter_manager->getOptions('entity_reference') as $formatter => $name) {
151       // Set formatter type for the 'full' view mode.
152       entity_get_display($this->entityType, $this->bundle, 'default')
153         ->setComponent($field_name, [
154           'type' => $formatter,
155         ])
156         ->save();
157
158       // Invoke entity view.
159       entity_view($referencing_entity, 'default');
160
161       // Verify the un-accessible item still exists.
162       $this->assertEqual($referencing_entity->{$field_name}->target_id, $this->referencedEntity->id(), format_string('The un-accessible item still exists after @name formatter was executed.', ['@name' => $name]));
163     }
164   }
165
166   /**
167    * Tests the merging of cache metadata.
168    */
169   public function testCustomCacheTagFormatter() {
170     /** @var \Drupal\Core\Render\RendererInterface $renderer */
171     $renderer = $this->container->get('renderer');
172     $formatter = 'entity_reference_custom_cache_tag';
173     $build = $this->buildRenderArray([$this->referencedEntity], $formatter);
174
175     $renderer->renderRoot($build);
176     $this->assertTrue(in_array('custom_cache_tag', $build['#cache']['tags']));
177   }
178
179   /**
180    * Tests the ID formatter.
181    */
182   public function testIdFormatter() {
183     $formatter = 'entity_reference_entity_id';
184     $build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter);
185
186     $this->assertEqual($build[0]['#plain_text'], $this->referencedEntity->id(), sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter));
187     $this->assertEqual($build[0]['#cache']['tags'], $this->referencedEntity->getCacheTags(), sprintf('The %s formatter has the expected cache tags.', $formatter));
188     $this->assertTrue(!isset($build[1]), sprintf('The markup returned by the %s formatter is correct for an item with a unsaved entity.', $formatter));
189   }
190
191   /**
192    * Tests the entity formatter.
193    */
194   public function testEntityFormatter() {
195     /** @var \Drupal\Core\Render\RendererInterface $renderer */
196     $renderer = $this->container->get('renderer');
197     $formatter = 'entity_reference_entity_view';
198     $build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter);
199
200     // Test the first field item.
201     $expected_rendered_name_field_1 = '
202             <div class="field field--name-name field--type-string field--label-hidden field__item">' . $this->referencedEntity->label() . '</div>
203       ';
204     $expected_rendered_body_field_1 = '
205   <div class="clearfix text-formatted field field--name-body field--type-text field--label-above">
206     <div class="field__label">Body</div>
207               <div class="field__item"><p>Hello, world!</p></div>
208           </div>
209 ';
210     $renderer->renderRoot($build[0]);
211     $this->assertEqual($build[0]['#markup'], 'default | ' . $this->referencedEntity->label() . $expected_rendered_name_field_1 . $expected_rendered_body_field_1, sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter));
212     $expected_cache_tags = Cache::mergeTags(\Drupal::entityManager()->getViewBuilder($this->entityType)->getCacheTags(), $this->referencedEntity->getCacheTags());
213     $expected_cache_tags = Cache::mergeTags($expected_cache_tags, FilterFormat::load('full_html')->getCacheTags());
214     $this->assertEqual($build[0]['#cache']['tags'], $expected_cache_tags, format_string('The @formatter formatter has the expected cache tags.', ['@formatter' => $formatter]));
215
216     // Test the second field item.
217     $expected_rendered_name_field_2 = '
218             <div class="field field--name-name field--type-string field--label-hidden field__item">' . $this->unsavedReferencedEntity->label() . '</div>
219       ';
220     $expected_rendered_body_field_2 = '
221   <div class="clearfix text-formatted field field--name-body field--type-text field--label-above">
222     <div class="field__label">Body</div>
223               <div class="field__item"><p>Hello, unsaved world!</p></div>
224           </div>
225 ';
226
227     $renderer->renderRoot($build[1]);
228     $this->assertEqual($build[1]['#markup'], 'default | ' . $this->unsavedReferencedEntity->label() . $expected_rendered_name_field_2 . $expected_rendered_body_field_2, sprintf('The markup returned by the %s formatter is correct for an item with a unsaved entity.', $formatter));
229   }
230
231   /**
232    * Tests the recursive rendering protection of the entity formatter.
233    */
234   public function testEntityFormatterRecursiveRendering() {
235     /** @var \Drupal\Core\Render\RendererInterface $renderer */
236     $renderer = $this->container->get('renderer');
237     $formatter = 'entity_reference_entity_view';
238     $view_builder = $this->entityManager->getViewBuilder($this->entityType);
239
240     // Set the default view mode to use the 'entity_reference_entity_view'
241     // formatter.
242     entity_get_display($this->entityType, $this->bundle, 'default')
243       ->setComponent($this->fieldName, [
244         'type' => $formatter,
245       ])
246       ->save();
247
248     $referencing_entity_1 = entity_create($this->entityType, ['name' => $this->randomMachineName()]);
249     $referencing_entity_1->save();
250
251     // Create a self-reference.
252     $referencing_entity_1->{$this->fieldName}->entity = $referencing_entity_1;
253     $referencing_entity_1->save();
254
255     // Check that the recursive rendering stops after it reaches the specified
256     // limit.
257     $build = $view_builder->view($referencing_entity_1, 'default');
258     $output = $renderer->renderRoot($build);
259
260     // The title of entity_test entities is printed twice by default, so we have
261     // to multiply the formatter's recursive rendering protection limit by 2.
262     // Additionally, we have to take into account 2 additional occurrences of
263     // the entity title because we're rendering the full entity, not just the
264     // reference field.
265     $expected_occurrences = EntityReferenceEntityFormatter::RECURSIVE_RENDER_LIMIT * 2 + 2;
266     $actual_occurrences = substr_count($output, $referencing_entity_1->name->value);
267     $this->assertEqual($actual_occurrences, $expected_occurrences);
268
269     // Repeat the process with another entity in order to check that the
270     // 'recursive_render_id' counter is generated properly.
271     $referencing_entity_2 = entity_create($this->entityType, ['name' => $this->randomMachineName()]);
272     $referencing_entity_2->save();
273     $referencing_entity_2->{$this->fieldName}->entity = $referencing_entity_2;
274     $referencing_entity_2->save();
275
276     $build = $view_builder->view($referencing_entity_2, 'default');
277     $output = $renderer->renderRoot($build);
278
279     $actual_occurrences = substr_count($output, $referencing_entity_2->name->value);
280     $this->assertEqual($actual_occurrences, $expected_occurrences);
281
282     // Now render both entities at the same time and check again.
283     $build = $view_builder->viewMultiple([$referencing_entity_1, $referencing_entity_2], 'default');
284     $output = $renderer->renderRoot($build);
285
286     $actual_occurrences = substr_count($output, $referencing_entity_1->name->value);
287     $this->assertEqual($actual_occurrences, $expected_occurrences);
288
289     $actual_occurrences = substr_count($output, $referencing_entity_2->name->value);
290     $this->assertEqual($actual_occurrences, $expected_occurrences);
291   }
292
293   /**
294    * Renders the same entity referenced from different places.
295    */
296   public function testEntityReferenceRecursiveProtectionWithManyRenderedEntities() {
297     $formatter = 'entity_reference_entity_view';
298     $view_builder = $this->entityManager->getViewBuilder($this->entityType);
299
300     // Set the default view mode to use the 'entity_reference_entity_view'
301     // formatter.
302     entity_get_display($this->entityType, $this->bundle, 'default')
303       ->setComponent($this->fieldName, [
304         'type' => $formatter,
305       ])
306       ->save();
307
308     $storage = $this->entityManager->getStorage($this->entityType);
309     /** @var \Drupal\Core\Entity\ContentEntityInterface $referenced_entity */
310     $referenced_entity = $storage->create(['name' => $this->randomMachineName()]);
311
312     $range = range(0, 30);
313     $referencing_entities = array_map(function () use ($storage, $referenced_entity) {
314       $referencing_entity = $storage->create([
315         'name' => $this->randomMachineName(),
316         $this->fieldName => $referenced_entity,
317       ]);
318       $referencing_entity->save();
319       return $referencing_entity;
320     }, $range);
321
322     $build = $view_builder->viewMultiple($referencing_entities, 'default');
323     $output = $this->render($build);
324
325     // The title of entity_test entities is printed twice by default, so we have
326     // to multiply the formatter's recursive rendering protection limit by 2.
327     // Additionally, we have to take into account 2 additional occurrences of
328     // the entity title because we're rendering the full entity, not just the
329     // reference field.
330     $expected_occurrences = 30 * 2 + 2;
331     $actual_occurrences = substr_count($output, $referenced_entity->get('name')->value);
332     $this->assertEquals($expected_occurrences, $actual_occurrences);
333   }
334
335
336   /**
337    * Tests the label formatter.
338    */
339   public function testLabelFormatter() {
340     $this->installEntitySchema('entity_test_label');
341     /** @var \Drupal\Core\Render\RendererInterface $renderer */
342     $renderer = $this->container->get('renderer');
343     $formatter = 'entity_reference_label';
344
345     // The 'link' settings is TRUE by default.
346     $build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter);
347
348     $expected_field_cacheability = [
349       'contexts' => [],
350       'tags' => [],
351       'max-age' => Cache::PERMANENT,
352     ];
353     $this->assertEqual($build['#cache'], $expected_field_cacheability, 'The field render array contains the entity access cacheability metadata');
354     $expected_item_1 = [
355       '#type' => 'link',
356       '#title' => $this->referencedEntity->label(),
357       '#url' => $this->referencedEntity->urlInfo(),
358       '#options' => $this->referencedEntity->urlInfo()->getOptions(),
359       '#cache' => [
360         'contexts' => [
361           'user.permissions',
362         ],
363         'tags' => $this->referencedEntity->getCacheTags(),
364       ],
365     ];
366     $this->assertEqual($renderer->renderRoot($build[0]), $renderer->renderRoot($expected_item_1), sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter));
367     $this->assertEqual(CacheableMetadata::createFromRenderArray($build[0]), CacheableMetadata::createFromRenderArray($expected_item_1));
368
369     // The second referenced entity is "autocreated", therefore not saved and
370     // lacking any URL info.
371     $expected_item_2 = [
372       '#plain_text' => $this->unsavedReferencedEntity->label(),
373       '#cache' => [
374         'contexts' => [
375           'user.permissions',
376         ],
377         'tags' => $this->unsavedReferencedEntity->getCacheTags(),
378         'max-age' => Cache::PERMANENT,
379       ],
380     ];
381     $this->assertEqual($build[1], $expected_item_2, sprintf('The render array returned by the %s formatter is correct for an item with a unsaved entity.', $formatter));
382
383     // Test with the 'link' setting set to FALSE.
384     $build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter, ['link' => FALSE]);
385     $this->assertEqual($build[0]['#plain_text'], $this->referencedEntity->label(), sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter));
386     $this->assertEqual($build[1]['#plain_text'], $this->unsavedReferencedEntity->label(), sprintf('The markup returned by the %s formatter is correct for an item with a unsaved entity.', $formatter));
387
388     // Test an entity type that doesn't have any link templates, which means
389     // \Drupal\Core\Entity\EntityInterface::urlInfo() will throw an exception
390     // and the label formatter will output only the label instead of a link.
391     $field_storage_config = FieldStorageConfig::loadByName($this->entityType, $this->fieldName);
392     $field_storage_config->setSetting('target_type', 'entity_test_label');
393     $field_storage_config->save();
394
395     $referenced_entity_with_no_link_template = EntityTestLabel::create([
396       'name' => $this->randomMachineName(),
397     ]);
398     $referenced_entity_with_no_link_template->save();
399
400     $build = $this->buildRenderArray([$referenced_entity_with_no_link_template], $formatter, ['link' => TRUE]);
401     $this->assertEqual($build[0]['#plain_text'], $referenced_entity_with_no_link_template->label(), sprintf('The markup returned by the %s formatter is correct for an entity type with no valid link template.', $formatter));
402   }
403
404   /**
405    * Sets field values and returns a render array as built by
406    * \Drupal\Core\Field\FieldItemListInterface::view().
407    *
408    * @param \Drupal\Core\Entity\EntityInterface[] $referenced_entities
409    *   An array of entity objects that will be referenced.
410    * @param string $formatter
411    *   The formatted plugin that will be used for building the render array.
412    * @param array $formatter_options
413    *   Settings specific to the formatter. Defaults to the formatter's default
414    *   settings.
415    *
416    * @return array
417    *   A render array.
418    */
419   protected function buildRenderArray(array $referenced_entities, $formatter, $formatter_options = []) {
420     // Create the entity that will have the entity reference field.
421     $referencing_entity = $this->container->get('entity_type.manager')
422       ->getStorage($this->entityType)
423       ->create(['name' => $this->randomMachineName()]);
424
425     $items = $referencing_entity->get($this->fieldName);
426
427     // Assign the referenced entities.
428     foreach ($referenced_entities as $referenced_entity) {
429       $items[] = ['entity' => $referenced_entity];
430     }
431
432     // Build the renderable array for the field.
433     return $items->view(['type' => $formatter, 'settings' => $formatter_options]);
434   }
435
436 }