Updated all the contrib modules to their latest versions.
[yaffs-website] / web / modules / contrib / pathauto / src / Plugin / pathauto / AliasType / EntityAliasTypeBase.php
1 <?php
2
3 namespace Drupal\pathauto\Plugin\pathauto\AliasType;
4
5 use Drupal\Core\Database\Connection;
6 use Drupal\Core\Entity\EntityTypeManagerInterface;
7 use Drupal\Core\Entity\FieldableEntityInterface;
8 use Drupal\Core\Extension\ModuleHandlerInterface;
9 use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
10 use Drupal\Core\Language\LanguageManagerInterface;
11 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
12 use Drupal\Core\Plugin\Context\Context;
13 use Drupal\Core\Plugin\ContextAwarePluginBase;
14 use Drupal\Core\Messenger\MessengerTrait;
15 use Drupal\pathauto\AliasTypeBatchUpdateInterface;
16 use Drupal\pathauto\AliasTypeInterface;
17 use Drupal\pathauto\PathautoState;
18 use Symfony\Component\DependencyInjection\ContainerInterface;
19
20 /**
21  * A pathauto alias type plugin for entities with canonical links.
22  *
23  * @AliasType(
24  *   id = "canonical_entities",
25  *   deriver = "\Drupal\pathauto\Plugin\Deriver\EntityAliasTypeDeriver"
26  * )
27  */
28 class EntityAliasTypeBase extends ContextAwarePluginBase implements AliasTypeInterface, AliasTypeBatchUpdateInterface, ContainerFactoryPluginInterface {
29
30   use MessengerTrait;
31
32   /**
33    * The module handler service.
34    *
35    * @var \Drupal\Core\Extension\ModuleHandlerInterface
36    */
37   protected $moduleHandler;
38
39   /**
40    * The language manager service.
41    *
42    * @var \Drupal\Core\Language\LanguageManagerInterface
43    */
44   protected $languageManager;
45
46   /**
47    * The entity manager service.
48    *
49    * @var \Drupal\Core\Entity\EntityTypeManagerInterface
50    */
51   protected $entityTypeManager;
52
53   /**
54    * The key/value manager service.
55    *
56    * @var \Drupal\Core\KeyValueStore\KeyValueFactoryInterface
57    */
58   protected $keyValue;
59
60   /**
61    * The database connection.
62    *
63    * @var \Drupal\Core\Database\Connection
64    */
65   protected $database;
66
67   /**
68    * The path prefix for this entity type.
69    *
70    * @var string
71    */
72   protected $prefix;
73
74   /**
75    * Constructs a EntityAliasTypeBase instance.
76    *
77    * @param array $configuration
78    *   A configuration array containing information about the plugin instance.
79    * @param string $plugin_id
80    *   The plugin_id for the plugin instance.
81    * @param mixed $plugin_definition
82    *   The plugin implementation definition.
83    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
84    *   The module handler service.
85    * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
86    *   The language manager service.
87    * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
88    *   The entity manager service.
89    * @param \Drupal\Core\KeyValueStore\KeyValueFactoryInterface $key_value
90    *   The key/value manager service.
91    * @param \Drupal\Core\Database\Connection $database
92    *   The database connection.
93    */
94   public function __construct(array $configuration, $plugin_id, $plugin_definition, ModuleHandlerInterface $module_handler, LanguageManagerInterface $language_manager, EntityTypeManagerInterface $entity_type_manager, KeyValueFactoryInterface $key_value, Connection $database) {
95     parent::__construct($configuration, $plugin_id, $plugin_definition);
96     $this->moduleHandler = $module_handler;
97     $this->languageManager = $language_manager;
98     $this->entityTypeManager = $entity_type_manager;
99     $this->keyValue = $key_value;
100     $this->database = $database;
101   }
102
103   /**
104    * {@inheritdoc}
105    */
106   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
107     return new static(
108       $configuration,
109       $plugin_id,
110       $plugin_definition,
111       $container->get('module_handler'),
112       $container->get('language_manager'),
113       $container->get('entity_type.manager'),
114       $container->get('keyvalue'),
115       $container->get('database')
116     );
117   }
118
119   /**
120    * {@inheritdoc}
121    */
122   public function getLabel() {
123     $definition = $this->getPluginDefinition();
124     // Cast the admin label to a string since it is an object.
125     // @see \Drupal\Core\StringTranslation\TranslationWrapper
126     return (string) $definition['label'];
127   }
128
129   /**
130    * {@inheritdoc}
131    */
132   public function getTokenTypes() {
133     $definition = $this->getPluginDefinition();
134     return $definition['types'];
135   }
136
137   /**
138    * {@inheritdoc}
139    */
140   public function batchUpdate($action, &$context) {
141     if (!isset($context['sandbox']['current'])) {
142       $context['sandbox']['count'] = 0;
143       $context['sandbox']['current'] = 0;
144     }
145
146     $entity_type = $this->entityTypeManager->getDefinition($this->getEntityTypeId());
147     $id_key = $entity_type->getKey('id');
148
149     $query = $this->database->select($entity_type->get('base_table'), 'base_table');
150     $query->leftJoin('url_alias', 'ua', "CONCAT('" . $this->getSourcePrefix() . "' , base_table.$id_key) = ua.source");
151     $query->addField('base_table', $id_key, 'id');
152
153     switch ($action) {
154       case 'create':
155         $query->isNull('ua.source');
156         break;
157
158       case 'update':
159         $query->isNotNull('ua.source');
160         break;
161
162       case 'all':
163         // Nothing to do. We want all paths.
164         break;
165
166       default:
167         // Unknown action. Abort!
168         return;
169     }
170     $query->condition('base_table.' . $id_key, $context['sandbox']['current'], '>');
171     $query->orderBy('base_table.' . $id_key);
172     $query->addTag('pathauto_bulk_update');
173     $query->addMetaData('entity', $this->getEntityTypeId());
174
175     // Get the total amount of items to process.
176     if (!isset($context['sandbox']['total'])) {
177       $context['sandbox']['total'] = $query->countQuery()->execute()->fetchField();
178
179       // If there are no entities to update, then stop immediately.
180       if (!$context['sandbox']['total']) {
181         $context['finished'] = 1;
182         return;
183       }
184     }
185
186     $query->range(0, 25);
187     $ids = $query->execute()->fetchCol();
188
189     $updates = $this->bulkUpdate($ids);
190     $context['sandbox']['count'] += count($ids);
191     $context['sandbox']['current'] = !empty($ids) ? max($ids) : 0;
192     $context['results']['updates'] += $updates;
193     $context['message'] = $this->t('Updated alias for %label @id.', array('%label' => $entity_type->getLabel(), '@id' => end($ids)));
194
195     if ($context['sandbox']['count'] != $context['sandbox']['total']) {
196       $context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total'];
197     }
198   }
199
200   /**
201    * {@inheritdoc}
202    */
203   public function batchDelete(&$context) {
204     if (!isset($context['sandbox']['current'])) {
205       $context['sandbox']['count'] = 0;
206       $context['sandbox']['current'] = 0;
207     }
208
209     $entity_type = $this->entityTypeManager->getDefinition($this->getEntityTypeId());
210     $id_key = $entity_type->getKey('id');
211
212     $query = $this->database->select($entity_type->get('base_table'), 'base_table');
213     $query->innerJoin('url_alias', 'ua', "CONCAT('" . $this->getSourcePrefix() . "' , base_table.$id_key) = ua.source");
214     $query->addField('base_table', $id_key, 'id');
215     $query->addField('ua', 'pid');
216     $query->condition('ua.pid', $context['sandbox']['current'], '>');
217     $query->orderBy('ua.pid');
218     $query->addTag('pathauto_bulk_delete');
219     $query->addMetaData('entity', $this->getEntityTypeId());
220
221     // Get the total amount of items to process.
222     if (!isset($context['sandbox']['total'])) {
223       $context['sandbox']['total'] = $query->countQuery()->execute()->fetchField();
224
225       // If there are no entities to delete, then stop immediately.
226       if (!$context['sandbox']['total']) {
227         $context['finished'] = 1;
228         return;
229       }
230     }
231
232     $query->range(0, 100);
233     $pids_by_id = $query->execute()->fetchAllKeyed();
234
235     PathautoState::bulkDelete($this->getEntityTypeId(), $pids_by_id);
236     $context['sandbox']['count'] += count($pids_by_id);
237     $context['sandbox']['current'] = max($pids_by_id);
238     $context['results']['deletions'][] = $this->getLabel();
239
240     if ($context['sandbox']['count'] != $context['sandbox']['total']) {
241       $context['finished'] = $context['sandbox']['count'] / $context['sandbox']['total'];
242     }
243   }
244
245   /**
246    * Returns the entity type ID.
247    *
248    * @return string
249    *   The entity type ID.
250    */
251   protected function getEntityTypeId() {
252     return $this->getDerivativeId();
253   }
254
255   /**
256    * Update the URL aliases for multiple entities.
257    *
258    * @param array $ids
259    *   An array of entity IDs.
260    * @param array $options
261    *   An optional array of additional options.
262    *
263    * @return int
264    *   The number of updated URL aliases.
265    */
266   protected function bulkUpdate(array $ids, array $options = array()) {
267     $options += array('message' => FALSE);
268     $updates = 0;
269
270     $entities = $this->entityTypeManager->getStorage($this->getEntityTypeId())->loadMultiple($ids);
271     foreach ($entities as $entity) {
272       // Update aliases for the entity's default language and its translations.
273       foreach ($entity->getTranslationLanguages() as $langcode => $language) {
274         $translated_entity = $entity->getTranslation($langcode);
275         $result = \Drupal::service('pathauto.generator')->updateEntityAlias($translated_entity, 'bulkupdate', $options);
276         if ($result) {
277           $updates++;
278         }
279       }
280     }
281
282     if (!empty($options['message'])) {
283       $this->messenger->addMessage($this->translationManager
284         ->formatPlural(count($ids), 'Updated 1 %label URL alias.', 'Updated @count %label URL aliases.'), [
285           '%label' => $this->getLabel(),
286         ]);
287     }
288
289     return $updates;
290   }
291
292   /**
293    * Deletes the URL aliases for multiple entities.
294    *
295    * @param int[] $pids_by_id
296    *   A list of path IDs keyed by entity ID.
297    *
298    * @deprecated Use \Drupal\pathauto\PathautoState::bulkDelete() instead.
299    */
300   protected function bulkDelete(array $pids_by_id) {
301     PathautoState::bulkDelete($this->getEntityTypeId(), $pids_by_id);
302   }
303
304   /**
305    * {@inheritdoc}
306    */
307   public function calculateDependencies() {
308     $dependencies = [];
309     $dependencies['module'][] = $this->entityTypeManager->getDefinition($this->getEntityTypeId())->getProvider();
310     return $dependencies;
311   }
312
313   /**
314    * {@inheritdoc}
315    */
316   public function applies($object) {
317     return $object instanceof FieldableEntityInterface && $object->getEntityTypeId() == $this->getEntityTypeId();
318   }
319
320   /**
321    * {@inheritdoc}
322    */
323   public function getSourcePrefix() {
324     if (empty($this->prefix)) {
325       $entity_type = $this->entityTypeManager->getDefinition($this->getEntityTypeId());
326       $path = $entity_type->getLinkTemplate('canonical');
327       $this->prefix = substr($path, 0, strpos($path, '{'));
328     }
329     return $this->prefix;
330   }
331
332   /**
333    * {@inheritdoc}
334    */
335   public function setContextValue($name, $value) {
336     // Overridden to avoid merging existing cacheability metadata, which is not
337     // relevant for alias type plugins.
338     $this->context[$name] = new Context($this->getContextDefinition($name), $value);
339     return $this;
340   }
341
342 }