6dce67b45f51c90e6e64a70b5881a2dde9c282d5
[yaffs-website] / web / core / modules / field / tests / src / Kernel / EntityReference / EntityReferenceItemTest.php
1 <?php
2
3 namespace Drupal\Tests\field\Kernel\EntityReference;
4
5 use Drupal\comment\Entity\Comment;
6 use Drupal\Component\Render\FormattableMarkup;
7 use Drupal\Component\Utility\Unicode;
8 use Drupal\Core\Field\FieldItemListInterface;
9 use Drupal\Core\Field\FieldItemInterface;
10 use Drupal\Core\Field\FieldStorageDefinitionInterface;
11 use Drupal\Core\StringTranslation\TranslatableMarkup;
12 use Drupal\Core\Language\LanguageInterface;
13 use Drupal\entity_test\Entity\EntityTest;
14 use Drupal\entity_test\Entity\EntityTestStringId;
15 use Drupal\field\Entity\FieldConfig;
16 use Drupal\field\Entity\FieldStorageConfig;
17 use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
18 use Drupal\node\NodeInterface;
19 use Drupal\Tests\field\Kernel\FieldKernelTestBase;
20 use Drupal\file\Entity\File;
21 use Drupal\node\Entity\Node;
22 use Drupal\taxonomy\Entity\Term;
23 use Drupal\taxonomy\Entity\Vocabulary;
24 use Drupal\user\Entity\User;
25
26
27 /**
28  * Tests the new entity API for the entity reference field type.
29  *
30  * @group entity_reference
31  */
32 class EntityReferenceItemTest extends FieldKernelTestBase {
33
34   use EntityReferenceTestTrait;
35
36   /**
37    * Modules to install.
38    *
39    * @var array
40    */
41   public static $modules = ['node', 'comment', 'file', 'taxonomy', 'text', 'filter', 'views', 'field'];
42
43   /**
44    * The taxonomy vocabulary to test with.
45    *
46    * @var \Drupal\taxonomy\VocabularyInterface
47    */
48   protected $vocabulary;
49
50   /**
51    * The taxonomy term to test with.
52    *
53    * @var \Drupal\taxonomy\TermInterface
54    */
55   protected $term;
56
57   /**
58    * The test entity with a string ID.
59    *
60    * @var \Drupal\entity_test\Entity\EntityTestStringId
61    */
62   protected $entityStringId;
63
64   /**
65    * Sets up the test.
66    */
67   protected function setUp() {
68     parent::setUp();
69
70     $this->installEntitySchema('entity_test_string_id');
71     $this->installEntitySchema('taxonomy_term');
72     $this->installEntitySchema('node');
73     $this->installEntitySchema('comment');
74     $this->installEntitySchema('file');
75
76     $this->installSchema('comment', ['comment_entity_statistics']);
77     $this->installSchema('node', ['node_access']);
78
79     $this->vocabulary = Vocabulary::create([
80       'name' => $this->randomMachineName(),
81       'vid' => Unicode::strtolower($this->randomMachineName()),
82       'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
83     ]);
84     $this->vocabulary->save();
85
86     $this->term = Term::create([
87       'name' => $this->randomMachineName(),
88       'vid' => $this->vocabulary->id(),
89       'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
90     ]);
91     $this->term->save();
92
93     $this->entityStringId = EntityTestStringId::create([
94       'id' => $this->randomMachineName(),
95     ]);
96     $this->entityStringId->save();
97
98     // Use the util to create an instance.
99     $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_taxonomy_term', 'Test content entity reference', 'taxonomy_term');
100     $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_entity_test_string_id', 'Test content entity reference with string ID', 'entity_test_string_id');
101     $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_taxonomy_vocabulary', 'Test config entity reference', 'taxonomy_vocabulary');
102     $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_node', 'Test node entity reference', 'node', 'default', [], FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
103     $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_user', 'Test user entity reference', 'user');
104     $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_comment', 'Test comment entity reference', 'comment');
105     $this->createEntityReferenceField('entity_test', 'entity_test', 'field_test_file', 'Test file entity reference', 'file');
106   }
107
108   /**
109    * Tests the entity reference field type for referencing content entities.
110    */
111   public function testContentEntityReferenceItem() {
112     $tid = $this->term->id();
113
114     // Just being able to create the entity like this verifies a lot of code.
115     $entity = EntityTest::create();
116     $entity->field_test_taxonomy_term->target_id = $tid;
117     $entity->name->value = $this->randomMachineName();
118     $entity->save();
119
120     $entity = EntityTest::load($entity->id());
121     $this->assertTrue($entity->field_test_taxonomy_term instanceof FieldItemListInterface, 'Field implements interface.');
122     $this->assertTrue($entity->field_test_taxonomy_term[0] instanceof FieldItemInterface, 'Field item implements interface.');
123     $this->assertEqual($entity->field_test_taxonomy_term->target_id, $tid);
124     $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $this->term->getName());
125     $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $tid);
126     $this->assertEqual($entity->field_test_taxonomy_term->entity->uuid(), $this->term->uuid());
127     // Verify that the label for the target ID property definition is correct.
128     $label = $entity->field_test_taxonomy_term->getFieldDefinition()->getFieldStorageDefinition()->getPropertyDefinition('target_id')->getLabel();
129     $this->assertTrue($label instanceof TranslatableMarkup);
130     $this->assertEqual($label->render(), 'Taxonomy term ID');
131
132     // Change the name of the term via the reference.
133     $new_name = $this->randomMachineName();
134     $entity->field_test_taxonomy_term->entity->setName($new_name);
135     $entity->field_test_taxonomy_term->entity->save();
136     // Verify it is the correct name.
137     $term = Term::load($tid);
138     $this->assertEqual($term->getName(), $new_name);
139
140     // Make sure the computed term reflects updates to the term id.
141     $term2 = Term::create([
142       'name' => $this->randomMachineName(),
143       'vid' => $this->term->bundle(),
144       'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
145     ]);
146     $term2->save();
147
148     // Test all the possible ways of assigning a value.
149     $entity->field_test_taxonomy_term->target_id = $term->id();
150     $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $term->id());
151     $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term->getName());
152
153     $entity->field_test_taxonomy_term = [['target_id' => $term2->id()]];
154     $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $term2->id());
155     $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term2->getName());
156
157     // Test value assignment via the computed 'entity' property.
158     $entity->field_test_taxonomy_term->entity = $term;
159     $this->assertEqual($entity->field_test_taxonomy_term->target_id, $term->id());
160     $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term->getName());
161
162     $entity->field_test_taxonomy_term = [['entity' => $term2]];
163     $this->assertEqual($entity->field_test_taxonomy_term->target_id, $term2->id());
164     $this->assertEqual($entity->field_test_taxonomy_term->entity->getName(), $term2->getName());
165
166     // Test assigning an invalid item throws an exception.
167     try {
168       $entity->field_test_taxonomy_term = ['target_id' => 'invalid', 'entity' => $term2];
169       $this->fail('Assigning an invalid item throws an exception.');
170     }
171     catch (\InvalidArgumentException $e) {
172       $this->pass('Assigning an invalid item throws an exception.');
173     }
174
175     // Delete terms so we have nothing to reference and try again
176     $term->delete();
177     $term2->delete();
178     $entity = EntityTest::create(['name' => $this->randomMachineName()]);
179     $entity->save();
180
181     // Test the generateSampleValue() method.
182     $entity = EntityTest::create();
183     $entity->field_test_taxonomy_term->generateSampleItems();
184     $entity->field_test_taxonomy_vocabulary->generateSampleItems();
185     $this->entityValidateAndSave($entity);
186
187     // Tests that setting an integer target ID together with an entity object
188     // succeeds and does not cause any exceptions. There is no assertion here,
189     // as the assignment should not throw any exceptions and if it does the
190     // test will fail.
191     // @see \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::setValue().
192     $user = User::create(['name' => $this->randomString()]);
193     $user->save();
194     $entity = EntityTest::create(['user_id' => ['target_id' => (int) $user->id(), 'entity' => $user]]);
195   }
196
197   /**
198    * Tests referencing content entities with string IDs.
199    */
200   public function testContentEntityReferenceItemWithStringId() {
201     $entity = EntityTest::create();
202     $entity->field_test_entity_test_string_id->target_id = $this->entityStringId->id();
203     $entity->save();
204     $storage = \Drupal::entityManager()->getStorage('entity_test');
205     $storage->resetCache();
206     $this->assertEqual($this->entityStringId->id(), $storage->load($entity->id())->field_test_entity_test_string_id->target_id);
207     // Verify that the label for the target ID property definition is correct.
208     $label = $entity->field_test_taxonomy_term->getFieldDefinition()->getFieldStorageDefinition()->getPropertyDefinition('target_id')->getLabel();
209     $this->assertTrue($label instanceof TranslatableMarkup);
210     $this->assertEqual($label->render(), 'Taxonomy term ID');
211   }
212
213   /**
214    * Tests the entity reference field type for referencing config entities.
215    */
216   public function testConfigEntityReferenceItem() {
217     $referenced_entity_id = $this->vocabulary->id();
218
219     // Just being able to create the entity like this verifies a lot of code.
220     $entity = EntityTest::create();
221     $entity->field_test_taxonomy_vocabulary->target_id = $referenced_entity_id;
222     $entity->name->value = $this->randomMachineName();
223     $entity->save();
224
225     $entity = EntityTest::load($entity->id());
226     $this->assertTrue($entity->field_test_taxonomy_vocabulary instanceof FieldItemListInterface, 'Field implements interface.');
227     $this->assertTrue($entity->field_test_taxonomy_vocabulary[0] instanceof FieldItemInterface, 'Field item implements interface.');
228     $this->assertEqual($entity->field_test_taxonomy_vocabulary->target_id, $referenced_entity_id);
229     $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->label(), $this->vocabulary->label());
230     $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->id(), $referenced_entity_id);
231     $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->uuid(), $this->vocabulary->uuid());
232
233     // Change the name of the term via the reference.
234     $new_name = $this->randomMachineName();
235     $entity->field_test_taxonomy_vocabulary->entity->set('name', $new_name);
236     $entity->field_test_taxonomy_vocabulary->entity->save();
237     // Verify it is the correct name.
238     $vocabulary = Vocabulary::load($referenced_entity_id);
239     $this->assertEqual($vocabulary->label(), $new_name);
240
241     // Make sure the computed term reflects updates to the term id.
242     $vocabulary2 = $vocabulary = Vocabulary::create([
243       'name' => $this->randomMachineName(),
244       'vid' => Unicode::strtolower($this->randomMachineName()),
245       'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
246     ]);
247     $vocabulary2->save();
248
249     $entity->field_test_taxonomy_vocabulary->target_id = $vocabulary2->id();
250     $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->id(), $vocabulary2->id());
251     $this->assertEqual($entity->field_test_taxonomy_vocabulary->entity->label(), $vocabulary2->label());
252
253     // Delete terms so we have nothing to reference and try again
254     $this->vocabulary->delete();
255     $vocabulary2->delete();
256     $entity = EntityTest::create(['name' => $this->randomMachineName()]);
257     $entity->save();
258   }
259
260   /**
261    * Tests entity auto create.
262    */
263   public function testEntityAutoCreate() {
264     // The term entity is unsaved here.
265     $term = Term::create([
266       'name' => $this->randomMachineName(),
267       'vid' => $this->term->bundle(),
268       'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
269     ]);
270     $entity = EntityTest::create();
271     // Now assign the unsaved term to the field.
272     $entity->field_test_taxonomy_term->entity = $term;
273     $entity->name->value = $this->randomMachineName();
274     // This is equal to storing an entity to tempstore or cache and retrieving
275     // it back. An example for this is node preview.
276     $entity = serialize($entity);
277     $entity = unserialize($entity);
278     // And then the entity.
279     $entity->save();
280     $term = \Drupal::entityManager()->loadEntityByUuid($term->getEntityTypeId(), $term->uuid());
281     $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $term->id());
282   }
283
284   /**
285    * Test saving order sequence doesn't matter.
286    */
287   public function testEntitySaveOrder() {
288     // The term entity is unsaved here.
289     $term = Term::create([
290       'name' => $this->randomMachineName(),
291       'vid' => $this->term->bundle(),
292       'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
293     ]);
294     $entity = EntityTest::create();
295     // Now assign the unsaved term to the field.
296     $entity->field_test_taxonomy_term->entity = $term;
297     $entity->name->value = $this->randomMachineName();
298     // Now get the field value.
299     $value = $entity->get('field_test_taxonomy_term');
300     $this->assertTrue(empty($value['target_id']));
301     $this->assertNull($entity->field_test_taxonomy_term->target_id);
302     // And then set it.
303     $entity->field_test_taxonomy_term = $value;
304     // Now save the term.
305     $term->save();
306     // And then the entity.
307     $entity->save();
308     $this->assertEqual($entity->field_test_taxonomy_term->entity->id(), $term->id());
309   }
310
311   /**
312    * Tests that the 'handler' field setting stores the proper plugin ID.
313    */
314   public function testSelectionHandlerSettings() {
315     $field_name = Unicode::strtolower($this->randomMachineName());
316     $field_storage = FieldStorageConfig::create([
317       'field_name' => $field_name,
318       'entity_type' => 'entity_test',
319       'type' => 'entity_reference',
320       'settings' => [
321         'target_type' => 'entity_test'
322       ],
323     ]);
324     $field_storage->save();
325
326     // Do not specify any value for the 'handler' setting in order to verify
327     // that the default handler with the correct derivative is used.
328     $field = FieldConfig::create([
329       'field_storage' => $field_storage,
330       'bundle' => 'entity_test',
331     ]);
332     $field->save();
333     $field = FieldConfig::load($field->id());
334     $this->assertEqual($field->getSetting('handler'), 'default:entity_test');
335
336     // Change the target_type in the field storage, and check that the handler
337     // was correctly reassigned in the field.
338     $field_storage->setSetting('target_type', 'entity_test_rev');
339     $field_storage->save();
340     $field = FieldConfig::load($field->id());
341     $this->assertEqual($field->getSetting('handler'), 'default:entity_test_rev');
342
343     // Change the handler to another, non-derivative plugin.
344     $field->setSetting('handler', 'views');
345     $field->save();
346     $field = FieldConfig::load($field->id());
347     $this->assertEqual($field->getSetting('handler'), 'views');
348
349     // Change the target_type in the field storage again, and check that the
350     // non-derivative handler was unchanged.
351     $field_storage->setSetting('target_type', 'entity_test_rev');
352     $field_storage->save();
353     $field = FieldConfig::load($field->id());
354     $this->assertEqual($field->getSetting('handler'), 'views');
355   }
356
357   /**
358    * Tests ValidReferenceConstraint with newly created and unsaved entities.
359    */
360   public function testAutocreateValidation() {
361     // The term entity is unsaved here.
362     $term = Term::create([
363       'name' => $this->randomMachineName(),
364       'vid' => $this->term->bundle(),
365       'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
366     ]);
367     $entity = EntityTest::create([
368       'field_test_taxonomy_term' => [
369         'entity' => $term,
370         'target_id' => NULL,
371       ],
372     ]);
373     $errors = $entity->validate();
374     // Using target_id of NULL is valid with an unsaved entity.
375     $this->assertEqual(0, count($errors));
376     // Using target_id of NULL is not valid with a saved entity.
377     $term->save();
378     $entity = EntityTest::create([
379       'field_test_taxonomy_term' => [
380         'entity' => $term,
381         'target_id' => NULL,
382       ],
383     ]);
384     $errors = $entity->validate();
385     $this->assertEqual(1, count($errors));
386     $this->assertEqual($errors[0]->getMessage(), 'This value should not be null.');
387     $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_taxonomy_term.0');
388     // This should rectify the issue, favoring the entity over the target_id.
389     $entity->save();
390     $errors = $entity->validate();
391     $this->assertEqual(0, count($errors));
392
393     // Test with an unpublished and unsaved node.
394     $title = $this->randomString();
395     $node = Node::create([
396       'title' => $title,
397       'type' => 'node',
398       'status' => NodeInterface::NOT_PUBLISHED,
399     ]);
400
401     $entity = EntityTest::create([
402       'field_test_node' => [
403         'entity' => $node,
404       ],
405     ]);
406
407     $errors = $entity->validate();
408     $this->assertEqual(1, count($errors));
409     $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $title]));
410     $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_node.0.entity');
411
412     // Publish the node and try again.
413     $node->setPublished(TRUE);
414     $errors = $entity->validate();
415     $this->assertEqual(0, count($errors));
416
417     // Test with a mix of valid and invalid nodes.
418     $unsaved_unpublished_node_title = $this->randomString();
419     $unsaved_unpublished_node = Node::create([
420       'title' => $unsaved_unpublished_node_title,
421       'type' => 'node',
422       'status' => NodeInterface::NOT_PUBLISHED,
423     ]);
424
425     $saved_unpublished_node_title = $this->randomString();
426     $saved_unpublished_node = Node::create([
427       'title' => $saved_unpublished_node_title,
428       'type' => 'node',
429       'status' => NodeInterface::NOT_PUBLISHED,
430     ]);
431     $saved_unpublished_node->save();
432
433     $saved_published_node_title = $this->randomString();
434     $saved_published_node = Node::create([
435       'title' => $saved_published_node_title,
436       'type' => 'node',
437       'status' => NodeInterface::PUBLISHED,
438     ]);
439     $saved_published_node->save();
440
441     $entity = EntityTest::create([
442       'field_test_node' => [
443         [
444           'entity' => $unsaved_unpublished_node,
445         ],
446         [
447           'target_id' => $saved_unpublished_node->id(),
448         ],
449         [
450           'target_id' => $saved_published_node->id(),
451         ],
452       ],
453     ]);
454
455     $errors = $entity->validate();
456     $this->assertEqual(2, count($errors));
457     $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $unsaved_unpublished_node_title]));
458     $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_node.0.entity');
459     $this->assertEqual($errors[1]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $saved_unpublished_node->id()]));
460     $this->assertEqual($errors[1]->getPropertyPath(), 'field_test_node.1.target_id');
461
462     // Publish one of the nodes and try again.
463     $saved_unpublished_node->setPublished(TRUE);
464     $saved_unpublished_node->save();
465     $errors = $entity->validate();
466     $this->assertEqual(1, count($errors));
467     $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $unsaved_unpublished_node_title]));
468     $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_node.0.entity');
469
470     // Publish the last invalid node and try again.
471     $unsaved_unpublished_node->setPublished(TRUE);
472     $errors = $entity->validate();
473     $this->assertEqual(0, count($errors));
474
475     // Test with an unpublished and unsaved comment.
476     $title = $this->randomString();
477     $comment = Comment::create([
478       'subject' => $title,
479       'comment_type' => 'comment',
480       'status' => 0,
481     ]);
482
483     $entity = EntityTest::create([
484       'field_test_comment' => [
485         'entity' => $comment,
486       ],
487     ]);
488
489     $errors = $entity->validate();
490     $this->assertEqual(1, count($errors));
491     $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'comment', '%label' => $title]));
492     $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_comment.0.entity');
493
494     // Publish the comment and try again.
495     $comment->setPublished(TRUE);
496     $errors = $entity->validate();
497     $this->assertEqual(0, count($errors));
498
499     // Test with an inactive and unsaved user.
500     $name = $this->randomString();
501     $user = User::create([
502       'name' => $name,
503       'status' => 0,
504     ]);
505
506     $entity = EntityTest::create([
507       'field_test_user' => [
508         'entity' => $user,
509       ],
510     ]);
511
512     $errors = $entity->validate();
513     $this->assertEqual(1, count($errors));
514     $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'user', '%label' => $name]));
515     $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_user.0.entity');
516
517     // Activate the user and try again.
518     $user->activate();
519     $errors = $entity->validate();
520     $this->assertEqual(0, count($errors));
521
522     // Test with a temporary and unsaved file.
523     $filename = $this->randomMachineName() . '.txt';
524     $file = File::create([
525       'filename' => $filename,
526       'status' => 0,
527     ]);
528
529     $entity = EntityTest::create([
530       'field_test_file' => [
531         'entity' => $file,
532       ],
533     ]);
534
535     $errors = $entity->validate();
536     $this->assertEqual(1, count($errors));
537     $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'file', '%label' => $filename]));
538     $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_file.0.entity');
539
540     // Set the file as permanent and try again.
541     $file->setPermanent();
542     $errors = $entity->validate();
543     $this->assertEqual(0, count($errors));
544   }
545
546 }