class MigrateMessageController

Same name in this branch
  1. 11.x core/modules/migrate_drupal_ui/src/Controller/MigrateMessageController.php \Drupal\migrate_drupal_ui\Controller\MigrateMessageController
Same name and namespace in other branches
  1. 10 core/modules/migrate/src/Controller/MigrateMessageController.php \Drupal\migrate\Controller\MigrateMessageController
  2. 10 core/modules/migrate_drupal_ui/src/Controller/MigrateMessageController.php \Drupal\migrate_drupal_ui\Controller\MigrateMessageController

Provides controller methods for the Message form.

Hierarchy

Expanded class hierarchy of MigrateMessageController

1 file declares its use of MigrateMessageController
MigrateMessageController.php in core/modules/migrate_drupal_ui/src/Controller/MigrateMessageController.php

File

core/modules/migrate/src/Controller/MigrateMessageController.php, line 23

Namespace

Drupal\migrate\Controller
View source
class MigrateMessageController extends ControllerBase {
    
    /**
     * Constructs a MigrateController.
     *
     * @param \Drupal\Core\Database\Connection $database
     *   A database connection.
     * @param \Drupal\Core\Form\FormBuilderInterface $formBuilder
     *   The form builder service.
     * @param \Drupal\migrate\Plugin\MigrationPluginManagerInterface $migrationPluginManager
     *   The migration plugin manager.
     */
    public function __construct(Connection $database, FormBuilderInterface $formBuilder, MigrationPluginManagerInterface $migrationPluginManager) {
        $this->formBuilder = $formBuilder;
    }
    
    /**
     * Displays an overview of migrate messages.
     *
     * @return array
     *   A render array as expected by
     *   \Drupal\Core\Render\RendererInterface::render().
     */
    public function overview() : array {
        // Check if there are migrate_message tables.
        $tables = $this->database
            ->schema()
            ->findTables('migrate_message_%');
        if (empty($tables)) {
            $build['no_tables'] = [
                '#type' => 'item',
                '#markup' => $this->t('There are no migration message tables.'),
            ];
            return $build;
        }
        // There are migrate_message tables so build the overview form.
        $migrations = $this->migrationPluginManager
            ->createInstances([]);
        $header = [
            $this->t('Migration'),
            $this->t('Machine Name'),
            $this->t('Messages'),
        ];
        // Display the number of messages for each migration.
        $rows = [];
        foreach ($migrations as $id => $migration) {
            $message_count = $migration->getIdMap()
                ->messageCount();
            // The message count is zero when there are no messages or when the
            // message table does not exist.
            if ($message_count == 0) {
                continue;
            }
            $row = [];
            $row['label'] = $migration->label();
            $row['machine_name'] = $id;
            $route_parameters = [
                'migration_id' => $migration->id(),
            ];
            $row['messages'] = [
                'data' => [
                    '#type' => 'link',
                    '#title' => $message_count,
                    '#url' => Url::fromRoute('migrate.messages.detail', $route_parameters),
                ],
            ];
            $rows[] = $row;
        }
        $build['migrations_table'] = [
            '#type' => 'table',
            '#header' => $header,
            '#rows' => $rows,
            '#empty' => $this->t('No migration messages available.'),
        ];
        $build['message_pager'] = [
            '#type' => 'pager',
        ];
        return $build;
    }
    
    /**
     * Displays a listing of migration messages for the given migration ID.
     *
     * @param string $migration_id
     *   A migration ID.
     * @param \Symfony\Component\HttpFoundation\Request $request
     *   The request.
     *
     * @return array
     *   A render array.
     */
    public function details(string $migration_id, Request $request) : array {
        
        /** @var \Drupal\migrate\Plugin\MigrationInterface $migration */
        $migration = $this->migrationPluginManager
            ->createInstance($migration_id);
        if (!$migration) {
            throw new NotFoundHttpException();
        }
        // Get the map and message table names.
        $map_table = $migration->getIdMap()
            ->mapTableName();
        $message_table = $migration->getIdMap()
            ->messageTableName();
        // If the map table does not exist then do not continue.
        if (!$this->database
            ->schema()
            ->tableExists($map_table)) {
            throw new NotFoundHttpException();
        }
        // If there is a map table but no message table display an error.
        if (!$this->database
            ->schema()
            ->tableExists($message_table)) {
            $this->messenger()
                ->addError($this->t('The message table is missing for this migration.'));
            return [];
        }
        // Create the column header names.
        $header = [];
        $source_plugin = $migration->getSourcePlugin();
        // Create the column header names from the source plugin fields() method.
        // Fallback to the source_id name when the source ID is missing from
        // fields() method.
        try {
            $fields = $source_plugin->fields();
        } catch (DatabaseConnectionRefusedException|DatabaseNotFoundException|RequirementsException|\PDOException $e) {
        }
        $source_id_field_names = array_keys($source_plugin->getIds());
        $count = 1;
        foreach ($source_id_field_names as $source_id_field_name) {
            $display_name = preg_replace([
                '/^[Tt]he /',
                '/\\.$/',
            ], '', $fields[$source_id_field_name] ?? $source_id_field_name);
            $header[] = [
                'data' => ucfirst($display_name),
                'field' => 'sourceid' . $count++,
                'class' => [
                    RESPONSIVE_PRIORITY_MEDIUM,
                ],
            ];
        }
        $header[] = [
            'data' => $this->t('Severity level'),
            'field' => 'level',
            'class' => [
                RESPONSIVE_PRIORITY_LOW,
            ],
        ];
        $header[] = [
            'data' => $this->t('Message'),
            'field' => 'message',
        ];
        $levels = [
            MigrationInterface::MESSAGE_ERROR => $this->t('Error'),
            MigrationInterface::MESSAGE_WARNING => $this->t('Warning'),
            MigrationInterface::MESSAGE_NOTICE => $this->t('Notice'),
            MigrationInterface::MESSAGE_INFORMATIONAL => $this->t('Info'),
        ];
        // Gets each message row and the source ID(s) for that message.
        $query = $this->database
            ->select($message_table, 'msg')
            ->extend('\\Drupal\\Core\\Database\\Query\\PagerSelectExtender')
            ->extend('\\Drupal\\Core\\Database\\Query\\TableSortExtender');
        // Not all messages have a matching row in the map table.
        $query->leftJoin($map_table, 'map', 'msg.source_ids_hash = map.source_ids_hash');
        $query->fields('msg');
        $query->fields('map');
        $filter = $this->buildFilterQuery($request);
        if (!empty($filter['where'])) {
            $query->where($filter['where'], $filter['args']);
        }
        $result = $query->limit(50)
            ->orderByHeader($header)
            ->execute();
        // Build the rows to display.
        $rows = [];
        $add_explanation = FALSE;
        $num_ids = count($source_id_field_names);
        foreach ($result as $message_row) {
            $new_row = [];
            for ($count = 1; $count <= $num_ids; $count++) {
                $map_key = 'sourceid' . $count;
                $new_row[$map_key] = $message_row->{$map_key} ?? NULL;
                if (empty($new_row[$map_key])) {
                    $new_row[$map_key] = $this->t('Not available');
                    $add_explanation = TRUE;
                }
            }
            $new_row['level'] = $levels[$message_row->level];
            $new_row['message'] = $message_row->message;
            $rows[] = $new_row;
        }
        // Build the complete form.
        $build['message_filter_form'] = $this->formBuilder
            ->getForm('Drupal\\migrate\\Form\\MessageForm');
        $build['message_table'] = [
            '#type' => 'table',
            '#header' => $header,
            '#rows' => $rows,
            '#empty' => $this->t('No messages for this migration.'),
            '#attributes' => [
                'id' => 'admin-migrate-msg',
                'class' => [
                    'admin-migrate-msg',
                ],
            ],
        ];
        $build['message_pager'] = [
            '#type' => 'pager',
        ];
        if ($add_explanation) {
            $build['explanation'] = [
                '#type' => 'item',
                '#markup' => $this->t("When there is an error processing a row, the migration system saves the error message but not the source ID(s) of the row. That is why some messages in this table have 'Not available' in the source ID column(s)."),
            ];
        }
        return $build;
    }
    
    /**
     * Builds a query for migrate message administration.
     *
     * @param \Symfony\Component\HttpFoundation\Request $request
     *   The request.
     *
     * @return array|null
     *   An associative array with keys 'where' and 'args' or NULL if there were
     *   no filters set.
     */
    protected function buildFilterQuery(Request $request) : ?array {
        $session_filters = $request->getSession()
            ->get('migration_messages_overview_filter', []);
        if (empty($session_filters)) {
            return NULL;
        }
        // Build query.
        $where = $args = [];
        foreach ($session_filters as $filter) {
            $filter_where = [];
            switch ($filter['type']) {
                case 'array':
                    foreach ($filter['value'] as $value) {
                        $filter_where[] = $filter['where'];
                        $args[] = $value;
                    }
                    break;
                case 'string':
                    $filter_where[] = $filter['where'];
                    $args[] = '%' . $filter['value'] . '%';
                    break;
                default:
                    $filter_where[] = $filter['where'];
                    $args[] = $filter['value'];
            }
            if (!empty($filter_where)) {
                $where[] = '(' . implode(' OR ', $filter_where) . ')';
            }
        }
        $where = !empty($where) ? implode(' AND ', $where) : '';
        return [
            'where' => $where,
            'args' => $args,
        ];
    }
    
    /**
     * Gets the title for the details page.
     *
     * @param string $migration_id
     *   A migration ID.
     *
     * @return \Drupal\Core\StringTranslation\TranslatableMarkup
     *   The translated title.
     */
    public function title(string $migration_id) : TranslatableMarkup {
        return $this->t('Messages of %migration', [
            '%migration' => $migration_id,
        ]);
    }

}

Members

Title Sort descending Modifiers Object type Summary Overrides
AutowireTrait::create public static function Instantiates a new instance of the implementing class using autowiring. 32
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 2
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 1
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 1
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 2
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 1
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 1
ControllerBase::redirect protected function Returns a redirect response object for the specified route.
ControllerBase::state protected function Returns the state storage service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 16
MessengerTrait::messenger public function Gets the messenger. 16
MessengerTrait::setMessenger public function Sets the messenger.
MigrateMessageController::buildFilterQuery protected function Builds a query for migrate message administration.
MigrateMessageController::details public function Displays a listing of migration messages for the given migration ID.
MigrateMessageController::overview public function Displays an overview of migrate messages. 1
MigrateMessageController::title public function Gets the title for the details page.
MigrateMessageController::__construct public function Constructs a MigrateController.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 2
RedirectDestinationTrait::getDestinationArray protected function Prepares a &#039;destination&#039; URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.