You are here

class ConfigInspectorController in Configuration Inspector 8

Defines a controller for the config_inspector module.

Hierarchy

Expanded class hierarchy of ConfigInspectorController

File

src/Controller/ConfigInspectorController.php, line 21

Namespace

Drupal\config_inspector\Controller
View source
class ConfigInspectorController extends ControllerBase {

  /**
   * The config storage.
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
  protected $configStorage;

  /**
   * The configuration inspector manager.
   *
   * @var \Drupal\config_inspector\ConfigInspectorManager
   */
  protected $configInspectorManager;

  /**
   * The string translation manager.
   *
   * @var \Drupal\Core\StringTranslation\TranslationManager
   */
  protected $translationManager;

  /**
   * The form builder.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The dumper.
   *
   * @var \Drupal\devel\DevelDumperManagerInterface
   */
  protected $dumper;

  /**
   * {@inheritdoc}
   */
  public function __construct(StorageInterface $storage, ConfigInspectorManager $config_inspector_manager, TranslationManager $translation_manager, FormBuilderInterface $form_builder, ModuleHandlerInterface $module_handler) {
    $this->configStorage = $storage;
    $this->configInspectorManager = $config_inspector_manager;
    $this->translationManager = $translation_manager;
    $this->formBuilder = $form_builder;
    $this->moduleHandler = $module_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $form = new static($container
      ->get('config.storage'), $container
      ->get('plugin.manager.config_inspector'), $container
      ->get('string_translation'), $container
      ->get('form_builder'), $container
      ->get('module_handler'));
    if ($container
      ->has('devel.dumper')) {
      $form->dumper = $container
        ->get('devel.dumper');
    }
    return $form;
  }

  /**
   * Builds a page listing all configuration keys to inspect.
   *
   * @return array
   *   A render array representing the list.
   */
  public function overview() {
    $page['#attached']['library'][] = 'system/drupal.debounce';
    $page['#attached']['library'][] = 'config_inspector/config_inspector';
    $page['filters'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'table-filter',
          'js-show',
        ],
      ],
    ];
    $page['filters']['text'] = [
      '#type' => 'search',
      '#title' => $this
        ->t('Search'),
      '#size' => 30,
      '#placeholder' => $this
        ->t('Search for a configuration key'),
      '#attributes' => [
        'id' => 'schema-filter-text',
        'autocomplete' => 'off',
        'title' => $this
          ->t('Enter a part of the configuration key to filter by.'),
      ],
    ];
    $page['filters']['schema_has_errors'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Only show errors'),
      '#label_attributes' => [
        'for' => 'schema-has-errors',
      ],
      '#attributes' => [
        'id' => 'schema-has-errors',
      ],
    ];
    $page['table'] = [
      '#type' => 'table',
      '#header' => [
        'name' => $this
          ->t('Configuration key'),
        'schema' => $this
          ->t('Schema'),
        'list' => $this
          ->t('List'),
        'tree' => $this
          ->t('Tree'),
        'form' => $this
          ->t('Form'),
        'raw' => $this
          ->t('Raw data'),
        'download' => $this
          ->t('Download'),
      ],
      '#attributes' => [
        'class' => [
          'config-inspector-list',
        ],
      ],
    ];
    foreach ($this->configStorage
      ->listAll() as $name) {
      $label = '<span class="table-filter-text-source">' . $name . '</span>';

      // Elements without a schema are displayed to help debugging.
      if (!$this->configInspectorManager
        ->hasSchema($name)) {
        $page['table'][] = [
          'name' => [
            '#markup' => $label,
          ],
          'schema' => [
            '#markup' => $this
              ->t('None'),
            '#wrapper_attributes' => [
              'data-has-errors' => TRUE,
            ],
          ],
          'list' => [
            '#markup' => $this
              ->t('N/A'),
          ],
          'tree' => [
            '#markup' => $this
              ->t('N/A'),
          ],
          'form' => [
            '#markup' => $this
              ->t('N/A'),
          ],
          'raw' => Link::createFromRoute($this
            ->t('Raw data'), 'config_inspector.raw_page', [
            'name' => $name,
          ])
            ->toRenderable(),
          'download' => Link::createFromRoute($this
            ->t('Download'), 'config_inspector.download', [
            'name' => $name,
          ])
            ->toRenderable(),
        ];
      }
      else {
        $schema = $this
          ->t('Correct');
        $result = $this->configInspectorManager
          ->checkValues($name);
        if (is_array($result)) {

          // The no-schema case is covered above already, if we got errors, the
          // schema is partial.
          $schema = $this->translationManager
            ->formatPlural(count($result), '@count error', '@count errors');
        }
        $page['table'][] = [
          'name' => [
            '#markup' => $label,
          ],
          'schema' => [
            '#markup' => $schema,
            '#wrapper_attributes' => [
              'data-has-errors' => is_array($result),
            ],
          ],
          'list' => [
            '#markup' => Link::createFromRoute($this
              ->t('List'), 'config_inspector.list_page', [
              'name' => $name,
            ])
              ->toString(),
          ],
          'tree' => [
            '#markup' => Link::createFromRoute($this
              ->t('Tree'), 'config_inspector.tree_page', [
              'name' => $name,
            ])
              ->toString(),
          ],
          'form' => [
            '#markup' => Link::createFromRoute($this
              ->t('Form'), 'config_inspector.form_page', [
              'name' => $name,
            ])
              ->toString(),
          ],
          'raw' => [
            '#markup' => Link::createFromRoute($this
              ->t('Raw data'), 'config_inspector.raw_page', [
              'name' => $name,
            ])
              ->toString(),
          ],
          'download' => [
            '#markup' => Link::createFromRoute($this
              ->t('Download'), 'config_inspector.download', [
              'name' => $name,
            ])
              ->toString(),
          ],
        ];
      }
    }
    return $page;
  }

  /**
   * List (table) inspection view of the configuration.
   *
   * @param string $name
   *   Configuration name.
   *
   * @return array
   *   A render array for a list view.
   */
  public function getList($name) {
    $config_schema = $this->configInspectorManager
      ->getConfigSchema($name);
    $output = $this
      ->formatList($name, $config_schema);
    $output['#title'] = $this
      ->t('List of configuration data for %name', [
      '%name' => $name,
    ]);
    return $output;
  }

  /**
   * Tree inspection view of the configuration.
   *
   * @param string $name
   *   Configuration name.
   *
   * @return array
   *   A render array for a tree view.
   */
  public function getTree($name) {
    $config_schema = $this->configInspectorManager
      ->getConfigSchema($name);
    $output = $this
      ->formatTree($config_schema);
    $output['#title'] = $this
      ->t('Tree of configuration data for %name', [
      '%name' => $name,
    ]);
    return $output;
  }

  /**
   * Form based configuration data inspection.
   *
   * @param string $name
   *   Configuration name.
   *
   * @return array
   *   A render array for a form view.
   */
  public function getForm($name) {
    $config_schema = $this->configInspectorManager
      ->getConfigSchema($name);
    $output = $this->formBuilder
      ->getForm('\\Drupal\\config_inspector\\Form\\ConfigInspectorItemForm', $config_schema);
    $output['#title'] = $this
      ->t('Raw configuration data for %name', [
      '%name' => $name,
    ]);
    return $output;
  }

  /**
   * Raw configuration data inspection.
   *
   * @param string $name
   *   Configuration name.
   *
   * @return array
   *   A render array for a raw dump view.
   */
  public function getRawData($name) {
    $data = $this->configInspectorManager
      ->getConfigData($name);
    $output = [
      '#title' => $this
        ->t('Raw configuration data for %name', [
        '%name' => $name,
      ]),
      'config' => $this
        ->formatData($data, 'Configuration data'),
      'schema' => $this
        ->formatData(NULL, 'Configuration schema'),
      'validation' => $this
        ->formatData(TRUE, 'Configuration validation'),
    ];
    if ($this->configInspectorManager
      ->hasSchema($name)) {
      $definition = $this->configInspectorManager
        ->getDefinition($name);
      $output['schema'] = $this
        ->formatData($definition, 'Configuration schema');
      $result = $this->configInspectorManager
        ->checkValues($name);
      if (is_array($result)) {
        $output['validation'] = $this
          ->formatData($result, 'Configuration validation');
      }
    }
    return $output;
  }

  /**
   * Download raw data.
   *
   * @param string $name
   *   Configuration name.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   Return config as a response yaml file.
   */
  public function download($name) {
    $data = $this->configInspectorManager
      ->getConfigData($name);
    $data = Yaml::encode($data);
    $headers = [
      'Content-disposition' => 'attachment; filename="' . $name . '.yml"',
    ];
    return new Response($data, 200, $headers);
  }

  /**
   * Format config schema as list table.
   *
   * @param string $config_name
   *   The config name.
   * @param array|object $config_schema
   *   An array of config elements with key.
   *
   * @return array
   *   The list table as a render array.
   */
  protected function formatList($config_name, $config_schema) {
    $rows = [];
    $errors = (array) $this->configInspectorManager
      ->checkValues($config_name);
    $schema = $this->configInspectorManager
      ->convertConfigElementToList($config_schema);
    foreach ($schema as $key => $element) {
      $definition = $element
        ->getDataDefinition();
      $rows[] = [
        'class' => isset($errors[$config_name . ':' . $key]) ? [
          'config-inspector-error',
        ] : [],
        'data' => [
          [
            'class' => [
              'icon',
            ],
            'data' => '',
          ],
          $key,
          $definition['label'],
          $definition['type'],
          $this
            ->formatValue($element),
          @$errors[$config_name . ':' . $key] ?: '',
        ],
      ];
    }
    return [
      '#attached' => [
        'library' => [
          'config_inspector/config_inspector',
        ],
      ],
      '#type' => 'table',
      '#header' => [
        '',
        $this
          ->t('Name'),
        $this
          ->t('Label'),
        $this
          ->t('Type'),
        $this
          ->t('Value'),
        $this
          ->t('Error'),
      ],
      '#rows' => $rows,
    ];
  }

  /**
   * Format config schema as a tree.
   *
   * @param array|object $schema
   *   The schema.
   * @param bool $collapsed
   *   (Optional) Indicates whether the details are collapsed by default.
   * @param string $base_key
   *   Prefix used in the description.
   *
   * @return array
   *   The tree in the form of a render array.
   */
  public function formatTree($schema, $collapsed = FALSE, $base_key = '') {
    $build = [];
    foreach ($schema as $key => $element) {
      $definition = $element
        ->getDataDefinition();
      $label = $definition['label'] ?: $this
        ->t('N/A');
      $type = $definition['type'];
      $element_key = $base_key . $key;
      if ($element instanceof ArrayElement) {
        $build[$key] = [
          '#type' => 'details',
          '#title' => $label,
          '#description' => $element_key . ' (' . $type . ')',
          '#description_display' => 'after',
          '#open' => !$collapsed,
        ] + $this
          ->formatTree($element, TRUE, $element_key . '.');
      }
      else {
        $build[$key] = [
          '#type' => 'item',
          '#title' => $label,
          '#plain_text' => $this
            ->formatValue($element),
          '#description' => $element_key . ' (' . $type . ')',
          '#description_display' => 'after',
        ];
      }
    }
    return $build;
  }

  /**
   * Formats a value as a string, for readable output.
   *
   * @param \Drupal\Core\TypedData\TypedDataInterface $element
   *   The value element.
   *
   * @return string
   *   The value in string form.
   */
  protected function formatValue(TypedDataInterface $element) {
    $value = $element
      ->getValue();
    if (is_bool($value)) {
      return $value ? 'true' : 'false';
    }
    if (is_scalar($value)) {
      return $value;
    }
    if (empty($value)) {
      return '<' . $this
        ->t('empty') . '>';
    }
    return '<' . gettype($value) . '>';
  }

  /**
   * Helper function to dump data in a reasonably reviewable fashion.
   *
   * @param string $data
   *   The displayed data.
   * @param string $title
   *   (Optional) The title. Defaults to "Data'.
   *
   * @return array
   *   The render array.
   */
  protected function formatData($data, $title = 'Data') {
    if ($this->dumper && $this->moduleHandler
      ->moduleExists('devel')) {
      $output = $this->dumper
        ->export($data, $title);
    }
    else {
      $output = '<h2>' . $title . '</h2>';
      $output .= '<pre>';
      $output .= htmlspecialchars(var_export($data, TRUE));
      $output .= '</pre>';
      $output .= '<br />';
    }
    return [
      '#markup' => $output,
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigInspectorController::$configInspectorManager protected property The configuration inspector manager.
ConfigInspectorController::$configStorage protected property The config storage.
ConfigInspectorController::$dumper protected property The dumper.
ConfigInspectorController::$formBuilder protected property The form builder. Overrides ControllerBase::$formBuilder
ConfigInspectorController::$moduleHandler protected property The module handler. Overrides ControllerBase::$moduleHandler
ConfigInspectorController::$translationManager protected property The string translation manager.
ConfigInspectorController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
ConfigInspectorController::download public function Download raw data.
ConfigInspectorController::formatData protected function Helper function to dump data in a reasonably reviewable fashion.
ConfigInspectorController::formatList protected function Format config schema as list table.
ConfigInspectorController::formatTree public function Format config schema as a tree.
ConfigInspectorController::formatValue protected function Formats a value as a string, for readable output.
ConfigInspectorController::getForm public function Form based configuration data inspection.
ConfigInspectorController::getList public function List (table) inspection view of the configuration.
ConfigInspectorController::getRawData public function Raw configuration data inspection.
ConfigInspectorController::getTree public function Tree inspection view of the configuration.
ConfigInspectorController::overview public function Builds a page listing all configuration keys to inspect.
ConfigInspectorController::__construct public function
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 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. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
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. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator 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. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' 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. 1
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.