You are here

function webform_update_8153 in Webform 6.x

Same name and namespace in other branches
  1. 8.5 includes/webform.install.update.inc \webform_update_8153()

Issue #3014933: Webform paths not being removed when a webform is deleted.

File

includes/webform.install.update.inc, line 2825
Archived Webform update hooks.

Code

function webform_update_8153() {

  // Load all webforms to improve performance.
  $webform = Webform::loadMultiple();
  if (\Drupal::entityTypeManager()
    ->hasDefinition('path_alias')) {
    $storage = \Drupal::entityTypeManager()
      ->getStorage('path_alias');
    $ids = $storage
      ->getQuery()
      ->condition('path', '/webform/', 'STARTS_WITH')
      ->execute();

    /** @var \Drupal\path_alias\PathAliasInterface $path_alias */
    foreach ($storage
      ->loadMultiple($ids) as $path_alias) {
      if (preg_match('#^/webform/([^/]+)/(?:drafts|submissions)$#', $path_alias
        ->getPath(), $match)) {

        // Check if the webform still exists.
        $webform_id = $match[1];
        if (!isset($webform[$webform_id])) {
          $path_alias
            ->delete();
        }
      }
    }
  }
  else {
    $database = \Drupal::database();
    $select = $database
      ->select('url_alias', 'u');
    $select
      ->fields('u', [
      'pid',
      'source',
      'alias',
      'langcode',
    ]);
    $select
      ->condition('source', '/webform/%', 'LIKE');
    $result = $select
      ->execute();
    while ($record = $result
      ->fetchAssoc()) {
      if (preg_match('#^/webform/([^/]+)/(?:drafts|submissions)$#', $record['source'], $match)) {

        // Check if the webform still exists.
        $webform_id = $match[1];
        if (!isset($webform[$webform_id])) {

          // Delete the broken URL alias.
          $database
            ->delete('url_alias')
            ->condition('pid', $record['pid'])
            ->execute();
        }
      }
    }
  }
}