Yaffs site version 1.1
[yaffs-website] / web / modules / contrib / blazy / tests / src / Traits / BlazyCreationTestTrait.php
1 <?php
2
3 namespace Drupal\Tests\blazy\Traits;
4
5 use Drupal\Core\Field\BaseFieldDefinition;
6 use Drupal\Core\Entity\Entity\EntityViewDisplay;
7 use Drupal\node\Entity\NodeType;
8 use Drupal\field\Entity\FieldConfig;
9 use Drupal\field\Entity\FieldStorageConfig;
10 use Drupal\file\Entity\File;
11 use Drupal\filter\Entity\FilterFormat;
12 use Drupal\image\Plugin\Field\FieldType\ImageItem;
13
14 /**
15  * A Trait common for Blazy tests.
16  *
17  * @todo: Consider using ContentTypeCreationTrait, TestFileCreationTrait.
18  */
19 trait BlazyCreationTestTrait {
20
21   /**
22    * Testing node type.
23    *
24    * @var \Drupal\node\Entity\NodeType
25    */
26   protected $nodeType;
27
28   /**
29    * The field storage definition.
30    *
31    * @var \Drupal\field\FieldStorageConfigInterface
32    */
33   protected $fieldStorageDefinition;
34
35   /**
36    * The field definition.
37    *
38    * @var \Drupal\Core\Field\FieldDefinitionInterface
39    */
40   protected $fieldDefinition;
41
42   /**
43    * Setup formatter displays, default to image, and update its settings.
44    *
45    * @param string $bundle
46    *   The bundle name.
47    * @param array $data
48    *   May contain formatter settings to be added to defaults.
49    *
50    * @return \Drupal\Core\Entity\Entity\EntityViewDisplay
51    *   The formatter display instance.
52    */
53   protected function setUpFormatterDisplay($bundle = '', array $data = []) {
54     $view_mode  = empty($data['view_mode']) ? 'default' : $data['view_mode'];
55     $plugin_id  = empty($data['plugin_id']) ? $this->testPluginId : $data['plugin_id'];
56     $field_name = empty($data['field_name']) ? $this->testFieldName : $data['field_name'];
57     $settings   = empty($data['settings']) ? [] : $data['settings'];
58     $display_id = $this->entityType . '.' . $bundle . '.' . $view_mode;
59     $storage    = $this->blazyManager->getEntityTypeManager()->getStorage('entity_view_display');
60     $display    = $storage->load($display_id);
61
62     if (!$display) {
63       $values = [
64         'targetEntityType' => $this->entityType,
65         'bundle'           => $bundle,
66         'mode'             => $view_mode,
67         'status'           => TRUE,
68       ];
69
70       $display = $storage->create($values);
71     }
72
73     $settings['current_view_mode'] = $settings['view_mode'] = $view_mode;
74     $display->setComponent($field_name, [
75       'type'     => $plugin_id,
76       'settings' => $settings,
77       'label'    => 'hidden',
78     ]);
79
80     $display->save();
81
82     return $display;
83   }
84
85   /**
86    * Gets the field definition.
87    *
88    * @param string $field_name
89    *   Formatted field name.
90    *
91    * @return \Drupal\Core\Field\FieldDefinitionInterface
92    *   The field definition.
93    *
94    * @see BaseFieldDefinition::createFromFieldStorageDefinition()
95    */
96   protected function getBlazyFieldDefinition($field_name = '') {
97     if (!$this->fieldDefinition) {
98       $field_name = empty($field_name) ? $this->testFieldName : $field_name;
99       $field_storage_config = $this->getBlazyFieldStorageDefinition($field_name);
100
101       $this->fieldDefinition = BaseFieldDefinition::createFromFieldStorageDefinition($field_storage_config);
102     }
103     return $this->fieldDefinition;
104   }
105
106   /**
107    * Gets the field storage configuration.
108    *
109    * @param string $field_name
110    *   Formatted field name.
111    *
112    * @return \Drupal\field\FieldStorageConfigInterface
113    *   The field storage definition.
114    */
115   protected function getBlazyFieldStorageDefinition($field_name = '') {
116     if (!$this->fieldStorageDefinition) {
117       $field_name = empty($field_name) ? $this->testFieldName : $field_name;
118       $field_storage_definitions = $this->entityFieldManager->getFieldStorageDefinitions($this->entityType);
119       $this->fieldStorageDefinition = $field_storage_definitions[$field_name];
120     }
121     return $this->fieldStorageDefinition;
122   }
123
124   /**
125    * Returns the field formatter instance.
126    *
127    * @param string $plugin_id
128    *   Formatter plugin ID.
129    * @param string $field_name
130    *   Formatted field name.
131    *
132    * @return \Drupal\Core\Field\FormatterInterface|null
133    *   The field formatter instance.
134    */
135   protected function getFormatterInstance($plugin_id = '', $field_name = '') {
136     $plugin_id  = empty($plugin_id) ? $this->testPluginId : $plugin_id;
137     $field_name = empty($field_name) ? $this->testFieldName : $field_name;
138     $settings   = $this->getFormatterSettings() + $this->formatterPluginManager->getDefaultSettings($plugin_id);
139
140     $options = [
141       'field_definition' => $this->getBlazyFieldDefinition($field_name),
142       'configuration' => [
143         'type' => $plugin_id,
144         'settings' => $settings,
145       ],
146       'view_mode' => 'default',
147     ];
148
149     return $this->formatterPluginManager->getInstance($options);
150   }
151
152   /**
153    * Build dummy content types.
154    *
155    * @param string $bundle
156    *   The bundle name.
157    * @param array $settings
158    *   (Optional) configurable settings.
159    */
160   protected function setUpContentTypeTest($bundle = '', array $settings = []) {
161     $node_type = NodeType::load($bundle);
162     $restricted_html = $this->blazyManager->entityLoad('restricted_html', 'filter_format');
163
164     if (empty($node_type)) {
165       $node_type = NodeType::create([
166         'type' => $bundle,
167         'name' => $bundle,
168       ]);
169       $node_type->save();
170     }
171
172     if (!$restricted_html) {
173       FilterFormat::create([
174         'format'  => 'restricted_html',
175         'name'    => 'Basic HML',
176         'weight'  => 2,
177         'filters' => [],
178       ])->save();
179     }
180
181     node_add_body_field($node_type);
182
183     if (!empty($this->testFieldName)) {
184       $settings['fields'][$this->testFieldName] = empty($this->testFieldType) ? 'image' : $this->testFieldType;
185     }
186     if (!empty($settings['field_name']) && !empty($settings['field_type'])) {
187       $settings['fields'][$settings['field_name']] = $settings['field_type'];
188     }
189
190     $data = [];
191     foreach ($settings['fields'] as $field_name => $field_type) {
192       $data['field_name'] = $field_name;
193       $data['field_type'] = $field_type;
194       $this->setUpFieldConfig($bundle, $data);
195     }
196
197     $node_type->save();
198
199     return $node_type;
200   }
201
202   /**
203    * Build dummy nodes with optional fields.
204    *
205    * @param string $bundle
206    *   The bundle name.
207    * @param array $settings
208    *   (Optional) configurable settings.
209    *
210    * @return \Drupal\node\Entity\Node|null
211    *   The node instance.
212    */
213   protected function setUpContentWithItems($bundle = '', array $settings = []) {
214     $title = empty($settings['title']) ? $this->testPluginId : $settings['title'];
215     $data  = empty($settings['values']) ? [] : $settings['values'];
216
217     $values = $data + [
218       'title'  => $title . ' : ' . $this->randomMachineName(),
219       'type'   => $bundle,
220       'status' => TRUE,
221     ];
222
223     $node = $this->blazyManager->getEntityTypeManager()
224       ->getStorage($this->entityType)
225       ->create($values);
226
227     $node->save();
228
229     if (isset($node->body)) {
230       $node->body->value  = $this->getRandomGenerator()->paragraphs($this->maxParagraphs);
231       $node->body->format = 'restricted_html';
232     }
233
234     if (!empty($this->testFieldName)) {
235       $settings['fields'][$this->testFieldName] = empty($this->testFieldType) ? 'image' : $this->testFieldType;
236     }
237     if (!empty($settings['field_name']) && !empty($settings['field_type'])) {
238       $settings['fields'][$settings['field_name']] = $settings['field_type'];
239     }
240
241     if (!empty($settings['fields'])) {
242       foreach ($settings['fields'] as $field_name => $field_type) {
243         $multiple = $field_type == 'image' || strpos($field_name, 'mul') !== FALSE;
244
245         if (strpos($field_name, 'empty') !== FALSE) {
246           continue;
247         }
248
249         if (isset($this->entityFieldName) && ($field_name == $this->entityFieldName)) {
250           continue;
251         }
252
253         $max = $multiple ? $this->maxItems : 2;
254         $node->{$field_name}->generateSampleItems($max);
255       }
256     }
257
258     $node->save();
259     $this->testItems = $node->{$this->testFieldName};
260     $this->entity = $node;
261
262     return $node;
263   }
264
265   /**
266    * Setup a new image field.
267    *
268    * @param string $bundle
269    *   The bundle name.
270    * @param array $data
271    *   (Optional) A list of field data.
272    */
273   protected function setUpFieldConfig($bundle = '', array $data = []) {
274     $config     = [];
275     $default    = empty($this->testFieldType) ? 'image' : $this->testFieldType;
276     $field_type = empty($data['field_type']) ? $default : $data['field_type'];
277     $field_name = empty($data['field_name']) ? $this->testFieldName : $data['field_name'];
278     $multiple   = strpos($field_name, 'mul') !== FALSE;
279
280     if (in_array($field_type, ['file', 'image'])) {
281       $config['file_directory']  = $this->testPluginId;
282       $config['file_extensions'] = 'png gif jpg jpeg';
283
284       if ($field_type == 'file') {
285         $config['file_extensions'] .= ' txt';
286       }
287
288       if ($field_type == 'image') {
289         $config['title_field'] = 1;
290         $config['title_field_required'] = 1;
291       }
292
293       $multiple = TRUE;
294     }
295
296     $field_storage = FieldStorageConfig::loadByName($this->entityType, $field_name);
297
298     $storage_settings = [];
299     if ($field_type == 'entity_reference') {
300       $storage_settings['target_type'] = isset($this->targetType) ? $this->targetType : $this->entityType;
301       $bundle = $this->bundle;
302       $multiple = FALSE;
303     }
304
305     if ($field_name == 'field_image') {
306       $multiple = FALSE;
307     }
308
309     if (!$field_storage) {
310       FieldStorageConfig::create([
311         'entity_type' => $this->entityType,
312         'field_name'  => $field_name,
313         'type'        => $field_type,
314         'cardinality' => $multiple ? -1 : 1,
315         'settings'    => $storage_settings,
316       ])->save();
317     }
318
319     $field_config = FieldConfig::loadByName($this->entityType, $bundle, $field_name);
320
321     if ($field_type == 'entity_reference' && !empty($this->targetBundles)) {
322       $config['handler'] = 'default';
323       $config['handler_settings']['target_bundles'] = $this->targetBundles;
324       $config['handler_settings']['sort']['field'] = '_none';
325       $bundle = $this->bundle;
326     }
327
328     if (!$field_config) {
329       $field_config = FieldConfig::create([
330         'field_storage' => $field_storage,
331         'field_name'    => $field_name,
332         'entity_type'   => $this->entityType,
333         'bundle'        => $bundle,
334         'label'         => str_replace('_', ' ', $field_name),
335         'settings'      => $config,
336       ]);
337
338       $field_config->save();
339     }
340
341     return $field_config;
342   }
343
344   /**
345    * Sets field values as built by FieldItemListInterface::view().
346    *
347    * @param \Drupal\Core\Entity\EntityInterface[] $referenced_entities
348    *   An array of entity objects that will be referenced.
349    * @param string $type
350    *   The formatter plugin ID.
351    * @param array $settings
352    *   Settings specific to the formatter. Defaults to the formatter's defaults.
353    *
354    * @return array
355    *   A render array.
356    */
357   protected function buildEntityReferenceRenderArray(array $referenced_entities, $type = '', array $settings = []) {
358     $type  = empty($type) ? $this->entityPluginId : $type;
359     $items = $this->referencingEntity->get($this->entityFieldName);
360
361     // Assign the referenced entities.
362     foreach ($referenced_entities as $referenced_entity) {
363       $items[] = ['entity' => $referenced_entity];
364     }
365
366     // Build the renderable array for the field.
367     $data['type'] = $type;
368     if ($settings) {
369       $data['settings'] = $settings;
370     }
371     return $items->view($data);
372   }
373
374   /**
375    * Sets field values as built by FieldItemListInterface::view().
376    *
377    * @param \Drupal\Core\Entity\EntityInterface[] $entity
378    *   An entity object that will be displayed.
379    * @param array $settings
380    *   Settings specific to the formatter. Defaults to the formatter's defaults.
381    *
382    * @return array
383    *   A render array.
384    */
385   protected function collectRenderDisplay(array $entity, array $settings = []) {
386     $view_mode = empty($settings['view_mode']) ? 'default' : $settings['view_mode'];
387
388     $display = EntityViewDisplay::collectRenderDisplay($entity, $view_mode);
389
390     return $display->build($entity);
391   }
392
393   /**
394    * Build dummy contents with entity references.
395    *
396    * @param array $settings
397    *   (Optional) configurable settings.
398    */
399   protected function setUpContentWithEntityReference(array $settings = []) {
400     $target_bundle   = $this->targetBundle;
401     $bundle          = $this->bundle;
402     $fields          = empty($settings['fields']) ? [] : $settings['fields'];
403     $image_settings  = empty($settings['image_settings']) ? [] : $settings['image_settings'];
404     $entity_settings = empty($settings['entity_settings']) ? [] : $settings['entity_settings'];
405     $er_field_name   = empty($settings['entity_field_name']) ? $this->entityFieldName : $settings['entity_field_name'];
406     $er_plugin_id    = empty($settings['entity_plugin_id']) ? $this->entityPluginId : $settings['entity_plugin_id'];
407
408     // Create referenced entity.
409     $referenced_data['title'] = 'Referenced ' . $this->testPluginId;
410
411     // Create dummy fields.
412     $referenced_data['fields'] = $fields + $this->getDefaultFields();
413
414     // Create referenced entity type.
415     $this->setUpContentTypeTest($target_bundle, $referenced_data);
416
417     // Create referencing entity type.
418     $referencing_data['fields'] = [
419       $er_field_name => 'entity_reference',
420     ];
421     $this->setUpContentTypeTest($bundle, $referencing_data);
422
423     // 1. Build the referenced entities.
424     $referenced_formatter_link = [
425       'field_name' => 'field_link',
426       'plugin_id'  => 'link',
427       'settings'   => [],
428     ];
429     $this->setUpFormatterDisplay($target_bundle, $referenced_formatter_link);
430
431     $referenced_formatter_data = [
432       'field_name' => $this->testFieldName,
433       'plugin_id'  => $this->testPluginId,
434       'settings'   => $image_settings + $this->getFormatterSettings(),
435     ];
436     $this->referencedDisplay = $this->setUpFormatterDisplay($target_bundle, $referenced_formatter_data);
437
438     // Create referenced entities.
439     $this->referencedEntity = $this->setUpContentWithItems($target_bundle, $referenced_data);
440
441     // 2. Build the referencing entity.
442     $referencing_formatter_settings = $this->getDefaultFields(TRUE);
443     $referencing_formatter_data = [
444       'field_name' => $er_field_name,
445       'plugin_id'  => $er_plugin_id,
446       'settings'   => empty($entity_settings) ? $referencing_formatter_settings : array_merge($referencing_formatter_settings, $entity_settings),
447     ];
448     $this->referencingDisplay = $this->setUpFormatterDisplay($bundle, $referencing_formatter_data);
449   }
450
451   /**
452    * Create referencing entity.
453    */
454   protected function createReferencingEntity(array $data = []) {
455     if (empty($data['values']) && $this->referencedEntity->id()) {
456       $data['values'] = [
457         $this->entityFieldName => [
458           ['target_id' => $this->referencedEntity->id()],
459         ],
460       ];
461     }
462
463     return $this->setUpContentWithItems($this->bundle, $data);
464   }
465
466   /**
467    * Set up dummy image.
468    */
469   protected function setUpRealImage() {
470     $this->uri = $this->getImagePath();
471     $item = $this->dummyItem;
472
473     if (isset($this->testItems[0])) {
474       $item = $this->testItems[0];
475
476       if ($item instanceof ImageItem) {
477         $this->uri = ($entity = $item->entity) && empty($item->uri) ? $entity->getFileUri() : $item->uri;
478       }
479     }
480
481     $this->testItem = $item;
482
483     $this->data = [
484       'settings' => $this->getFormatterSettings(),
485       'item'     => $item,
486     ];
487
488     $this->imageFactory = $this->container->get('image.factory');
489   }
490
491   /**
492    * Returns path to the stored image location.
493    */
494   protected function getImagePath($is_dir = FALSE) {
495     $path   = \Drupal::root() . '/sites/default/files/simpletest/' . $this->testPluginId;
496     $name   = $this->testPluginId . '.png';
497     $source = \Drupal::root() . '/core/misc/druplicon.png';
498     $uri    = $path . '/' . $name;
499
500     if (!is_file($uri)) {
501       file_prepare_directory($path, FILE_CREATE_DIRECTORY);
502       file_unmanaged_copy($source, $uri, FILE_EXISTS_REPLACE);
503     }
504
505     $item = File::create([
506       'uri' => $uri,
507       'uid' => \Drupal::currentUser()->id(),
508       'status' => FILE_STATUS_PERMANENT,
509     ]);
510
511     $item->save();
512     $uri = ($entity = $item->entity) && empty($item->uri) ? $entity->getFileUri() : $item->uri;
513
514     $this->dummyUri = $uri;
515     $this->dummyItem = $item;
516
517     $this->dummyData = [
518       'settings' => $this->getFormatterSettings(),
519       'item'     => $item,
520     ];
521
522     return $is_dir ? $path : $uri;
523   }
524
525 }