65 lines
1.6 KiB
PHP
65 lines
1.6 KiB
PHP
<?php
|
|
|
|
/**
|
|
* @file
|
|
* Helpers serveur pour le site Le Shed.
|
|
*/
|
|
|
|
use Drupal\Core\Entity\EntityInterface;
|
|
use Drupal\taxonomy\TermInterface;
|
|
|
|
/**
|
|
* Vocabulaires dont les termes doivent avoir un alias vers la vue archives
|
|
* filtrée par filtre contextuel tid.
|
|
*
|
|
* @var array
|
|
*/
|
|
const LESHED_HELPERS_VOCABULARIES = [
|
|
'type_de_projet' => 'projets',
|
|
'type_d_evenement' => 'evenements',
|
|
];
|
|
|
|
/**
|
|
* Crée ou met à jour l'alias d'URL pour les termes des vocabulaires gérés.
|
|
*/
|
|
function leshed_helpers_taxonomy_term_insert(EntityInterface $entity) {
|
|
leshed_helpers_ensure_term_alias($entity);
|
|
}
|
|
|
|
function leshed_helpers_taxonomy_term_update(EntityInterface $entity) {
|
|
leshed_helpers_ensure_term_alias($entity);
|
|
}
|
|
|
|
function leshed_helpers_ensure_term_alias(EntityInterface $entity) {
|
|
if (!($entity instanceof TermInterface)) {
|
|
return;
|
|
}
|
|
|
|
$vid = $entity->bundle();
|
|
if (!isset(LESHED_HELPERS_VOCABULARIES[$vid])) {
|
|
return;
|
|
}
|
|
|
|
$base_path = LESHED_HELPERS_VOCABULARIES[$vid];
|
|
$tid = $entity->id();
|
|
$cleaner = \Drupal::service('pathauto.alias_cleaner');
|
|
$slug = $cleaner->cleanString($entity->label());
|
|
$alias_path = '/' . $base_path . '/' . $slug;
|
|
$internal_path = '/' . $base_path . '/' . $tid;
|
|
|
|
$storage = \Drupal::entityTypeManager()->getStorage('path_alias');
|
|
$langcode = $entity->language()->getId();
|
|
|
|
// Supprime l'ancien alias s'il existe (par internal path).
|
|
$existing = $storage->loadByProperties(['path' => $internal_path, 'langcode' => $langcode]);
|
|
foreach ($existing as $old) {
|
|
$old->delete();
|
|
}
|
|
|
|
$storage->create([
|
|
'path' => $internal_path,
|
|
'alias' => $alias_path,
|
|
'langcode' => $langcode,
|
|
])->save();
|
|
}
|