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