Last active
September 21, 2019 10:21
-
-
Save gheydon/9274b31b90c3325a916ee27f042da4cb to your computer and use it in GitHub Desktop.
Rebuild all pathauto paths from hook_post_update()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Regenerate node url's. | |
*/ | |
function example_post_update_regenerate_node_urls(&$sandbox) { | |
return rmitonline_regenerate_urls($sandbox, 'node', ['article', 'blog']); | |
} | |
/** | |
* Regenerate taxonomy term url's. | |
*/ | |
function example_post_update_regenerate_taxonomy_term_urls(&$sandbox) { | |
return rmitonline_regenerate_urls($sandbox, 'taxonomy_term', ['example']); | |
} | |
/** | |
* Generate URL for an entity type and a list of bundles. | |
*/ | |
function example_regenerate_urls(&$sandbox, $entity_type_id, $bundles) { | |
$chunk_size = 10; | |
/** @var \Drupal\pathauto\PathautoGenerator $pathautoGenerator */ | |
$pathautoGenerator = \Drupal::service('pathauto.generator'); | |
$entity_type_manager = \Drupal::entityTypeManager(); | |
$entity_type = $entity_type_manager->getDefinition($entity_type_id); | |
$storage_manager = $entity_type_manager->getStorage($entity_type_id); | |
$id_field = $entity_type->getKey('id'); | |
if (empty($sandbox['entity_chunks'])) { | |
$select = \Drupal::database()->select($entity_type->getBaseTable(), 'base_table'); | |
$select->addField('base_table', $id_field, $id_field . '_1'); | |
$select->addField('base_table', $id_field); | |
$select->condition('base_table.' . $entity_type->getKey('bundle'), $bundles, 'IN'); | |
$ids = $select->execute()->fetchAllKeyed(); | |
$sandbox['total'] = count($ids); | |
$sandbox['entity_chunks'] = array_chunk($ids, $chunk_size); | |
} | |
$ids = array_pop($sandbox['entity_chunks']); | |
foreach ($storage_manager->loadMultiple($ids) as $entity) { | |
$entity->path->pathauto = PathautoState::CREATE; | |
$pathautoGenerator->updateEntityAlias($entity, 'bulkupdate', ['message' => FALSE, 'force' => TRUE]); | |
\Drupal::keyValue('pathauto_state.' . $entity->getEntityTypeId()) | |
->set(PathautoState::getPathautoStateKey($entity->id()), PathautoState::CREATE); | |
} | |
$sandbox['#finished'] = empty($sandbox['entity_chunks']) ? 1 : ($sandbox['total'] - (count($sandbox['entity_chunks']) * $chunk_size)) / $sandbox['total']; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment