Updated all the contrib modules to their latest versions.
[yaffs-website] / web / modules / contrib / metatag / src / Form / MetatagDefaultsForm.php
1 <?php
2
3 namespace Drupal\metatag\Form;
4
5 use Drupal\Core\Entity\ContentEntityType;
6 use Drupal\Core\Entity\EntityForm;
7 use Drupal\Core\Entity\EntityTypeInterface;
8 use Drupal\Core\Form\FormStateInterface;
9 use Drupal\metatag\MetatagManager;
10 use Drupal\page_manager\Entity\PageVariant;
11
12 /**
13  * Class MetatagDefaultsForm.
14  *
15  * @package Drupal\metatag\Form
16  */
17 class MetatagDefaultsForm extends EntityForm {
18
19   /**
20    * {@inheritdoc}
21    */
22   public function form(array $form, FormStateInterface $form_state) {
23     $form = parent::form($form, $form_state);
24     $metatag_defaults = $this->entity;
25     $metatag_manager = \Drupal::service('metatag.manager');
26
27     $form['#ajax_wrapper_id'] = 'metatag-defaults-form-ajax-wrapper';
28     $ajax = [
29       'wrapper' => $form['#ajax_wrapper_id'],
30       'callback' => '::rebuildForm',
31     ];
32     $form['#prefix'] = '<div id="' . $form['#ajax_wrapper_id'] . '">';
33     $form['#suffix'] = '</div>';
34
35     $default_type = NULL;
36     if (!empty($metatag_defaults)) {
37       $default_type = $metatag_defaults->getOriginalId();
38     }
39     else {
40       $form_state->set('default_type', $default_type);
41     }
42
43     $token_types = empty($default_type) ? [] : [explode('__', $default_type)[0]];
44
45     // Add the token browser at the top.
46     $form += \Drupal::service('metatag.token')->tokenBrowser($token_types);
47
48     // If this is a new Metatag defaults, then list available bundles.
49     if ($metatag_defaults->isNew()) {
50       $options = $this->getAvailableBundles();
51       $form['id'] = [
52         '#type' => 'select',
53         '#title' => $this->t('Type'),
54         '#description' => $this->t('Select the type of default meta tags you would like to add.'),
55         '#options' => $options,
56         '#required' => TRUE,
57         '#default_value' => $default_type,
58         '#ajax' => $ajax + [
59           'trigger_as' => [
60             'name' => 'select_id_submit',
61           ],
62         ],
63       ];
64       $form['select_id_submit'] = [
65         '#type' => 'submit',
66         '#value' => $this->t('Submit'),
67         '#name' => 'select_id_submit',
68         '#ajax' => $ajax,
69         '#attributes' => [
70           'class' => ['js-hide'],
71         ],
72       ];
73       $values = [];
74     }
75     else {
76       $values = $metatag_defaults->get('tags');
77     }
78
79     // Retrieve configuration settings.
80     $settings = $this->config('metatag.settings');
81     $entity_type_groups = $settings->get('entity_type_groups');
82
83     // Find the current entity type and bundle.
84     $metatag_defaults_id = $metatag_defaults->id();
85     $type_parts = explode('__', $metatag_defaults_id);
86     $entity_type = $type_parts[0];
87     $entity_bundle = isset($type_parts[1]) ? $type_parts[1] : NULL;
88
89     // See if there are requested groups for this entity type and bundle.
90     $groups = !empty($entity_type_groups[$entity_type]) && !empty($entity_type_groups[$entity_type][$entity_bundle]) ? $entity_type_groups[$entity_type][$entity_bundle] : [];
91     // Limit the form to requested groups, if any.
92     if (!empty($groups)) {
93       $form = $metatag_manager->form($values, $form, [$entity_type], $groups);
94     }
95     // Otherwise, display all groups.
96     else {
97       $form = $metatag_manager->form($values, $form);
98     }
99
100     return $form;
101   }
102
103   /**
104    * Ajax form submit handler that will return the whole rebuilt form.
105    *
106    * @param array $form
107    *   An associative array containing the structure of the form.
108    * @param \Drupal\Core\Form\FormStateInterface $form_state
109    *   The current state of the form.
110    *
111    * @return array
112    *   The form structure.
113    */
114   public function rebuildForm(array &$form, FormStateInterface $form_state) {
115     return $form;
116   }
117
118   /**
119    * {@inheritdoc}
120    */
121   protected function actions(array $form, FormStateInterface $form_state) {
122     $actions = parent::actions($form, $form_state);
123     if (isset($actions['delete'])) {
124       $actions['delete']['#access'] = $actions['delete']['#access'] && !in_array($this->entity->id(), MetatagManager::protectedDefaults());
125     }
126     return $actions;
127   }
128
129   /**
130    * {@inheritdoc}
131    */
132   public function submitForm(array &$form, FormStateInterface $form_state) {
133     if ($form_state->getTriggeringElement()['#name'] == 'select_id_submit') {
134       $form_state->set('default_type', $form_state->getValue('id'));
135       $form_state->setRebuild();
136     }
137     else {
138       parent::submitForm($form, $form_state);
139     }
140   }
141
142   /**
143    * {@inheritdoc}
144    */
145   public function save(array $form, FormStateInterface $form_state) {
146     $metatag_defaults = $this->entity;
147
148     // Set the label on new defaults.
149     if ($metatag_defaults->isNew()) {
150       $metatag_defaults_id = $form_state->getValue('id');
151
152       $type_parts = explode('__', $metatag_defaults_id);
153       $entity_type = $type_parts[0];
154       $entity_bundle = isset($type_parts[1]) ? $type_parts[1] : NULL;
155
156       // Get the entity label.
157       $entity_manager = \Drupal::service('entity_type.manager');
158       $entity_info = $entity_manager->getDefinitions();
159       $entity_label = (string) $entity_info[$entity_type]->get('label');
160
161       if (!is_null($entity_bundle)) {
162         // Get the bundle label.
163         $bundle_manager = \Drupal::service('entity_type.bundle.info');
164         $bundle_info = $bundle_manager->getBundleInfo($entity_type);
165         if ($entity_type === 'page_variant') {
166           // Check if page manager is enabled and try to load the page variant
167           // so the label of the variant can be used.
168           $moduleHandler = \Drupal::service('module_handler');
169           if ($moduleHandler->moduleExists('metatag_page_manager')) {
170             $page_variant = PageVariant::load($entity_bundle);
171             $page = $page_variant->getPage();
172             if ($page_variant) {
173               $entity_label .= ': ' . $page->label() . ': ' . $page_variant->label();
174             }
175           }
176         }
177         else {
178           $entity_label .= ': ' . $bundle_info[$entity_bundle]['label'];
179         }
180       }
181
182       // Set the label to the config entity.
183       $this->entity->set('label', $entity_label);
184     }
185
186     // Set tags within the Metatag entity.
187     $tag_manager = \Drupal::service('plugin.manager.metatag.tag');
188     $tags = $tag_manager->getDefinitions();
189     $tag_values = [];
190     foreach ($tags as $tag_id => $tag_definition) {
191       if ($form_state->hasValue($tag_id)) {
192         // Some plugins need to process form input before storing it. Hence, we
193         // set it and then get it.
194         $tag = $tag_manager->createInstance($tag_id);
195         $tag->setValue($form_state->getValue($tag_id));
196         if (!empty($tag->value())) {
197           $tag_values[$tag_id] = $tag->value();
198         }
199       }
200     }
201     $metatag_defaults->set('tags', $tag_values);
202     $status = $metatag_defaults->save();
203
204     switch ($status) {
205       case SAVED_NEW:
206         drupal_set_message($this->t('Created the %label Metatag defaults.', [
207           '%label' => $metatag_defaults->label(),
208         ]));
209         break;
210
211       default:
212         drupal_set_message($this->t('Saved the %label Metatag defaults.', [
213           '%label' => $metatag_defaults->label(),
214         ]));
215     }
216
217     $form_state->setRedirectUrl($metatag_defaults->toUrl('collection'));
218   }
219
220   /**
221    * Returns an array of available bundles to override.
222    *
223    * @return array
224    *   A list of available bundles as $id => $label.
225    */
226   protected function getAvailableBundles() {
227     $options = [];
228     $entity_types = static::getSupportedEntityTypes();
229     /** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager */
230     $entity_manager = \Drupal::service('entity_type.manager');
231     /** @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info */
232     $bundle_info = \Drupal::service('entity_type.bundle.info');
233     $metatags_defaults_manager = $entity_manager->getStorage('metatag_defaults');
234     foreach ($entity_types as $entity_type => $entity_label) {
235       if (empty($metatags_defaults_manager->load($entity_type))) {
236         $options[$entity_label][$entity_type] = "$entity_label (Default)";
237       }
238
239       $bundles = $bundle_info->getBundleInfo($entity_type);
240       foreach ($bundles as $bundle_id => $bundle_metadata) {
241         $metatag_defaults_id = $entity_type . '__' . $bundle_id;
242
243         if (empty($metatags_defaults_manager->load($metatag_defaults_id))) {
244           $options[$entity_label][$metatag_defaults_id] = $bundle_metadata['label'];
245         }
246       }
247     }
248     return $options;
249   }
250
251   /**
252    * Returns a list of supported entity types.
253    *
254    * @return array
255    *   A list of available entity types as $machine_name => $label.
256    */
257   public static function getSupportedEntityTypes() {
258     $entity_types = [];
259
260     /** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager */
261     $entity_manager = \Drupal::service('entity_type.manager');
262
263     // A list of entity types that are not supported.
264     $unsupported_types = [
265       // Custom blocks.
266       'block_content',
267       // Comments.
268       'comment',
269       // Contact messages are the messages submitted on individual contact forms
270       // so obviously shouldn't get meta tags.
271       'contact_message',
272       // Menu items.
273       'menu_link_content',
274       // Shortcut items.
275       'shortcut',
276     ];
277
278     // Make a list of supported content types.
279     foreach ($entity_manager->getDefinitions() as $entity_name => $definition) {
280       // Skip some entity types that we don't want to support.
281       if (in_array($entity_name, $unsupported_types)) {
282         continue;
283       }
284
285       // Identify supported entities.
286       if ($definition instanceof ContentEntityType) {
287         // Only work with entity types that have a list of links, i.e. publicly
288         // viewable.
289         $links = $definition->get('links');
290         if (!empty($links)) {
291           $entity_types[$entity_name] = static::getEntityTypeLabel($definition);
292         }
293       }
294     }
295
296     return $entity_types;
297   }
298
299   /**
300    * Returns the text label for the entity type specified.
301    *
302    * @param \Drupal\Core\Entity\EntityTypeInterface $entityType
303    *   The entity type to process.
304    *
305    * @return string
306    *   A label.
307    */
308   public static function getEntityTypeLabel(EntityTypeInterface $entityType) {
309     $label = $entityType->getLabel();
310
311     if (is_a($label, 'Drupal\Core\StringTranslation\TranslatableMarkup')) {
312       /** @var \Drupal\Core\StringTranslation\TranslatableMarkup $label */
313       $label = $label->render();
314     }
315
316     return $label;
317   }
318
319 }