You are here

class KeyConfigOverrideAddForm in Key 8

KeyConfigOverrideAddForm class.

Hierarchy

Expanded class hierarchy of KeyConfigOverrideAddForm

File

src/Form/KeyConfigOverrideAddForm.php, line 19

Namespace

Drupal\key\Form
View source
class KeyConfigOverrideAddForm extends EntityForm {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

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

  /**
   * The Key Configuration Override entity storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $storage;

  /**
   * The configuration entity type definitions.
   *
   * @var \Drupal\Core\Entity\EntityTypeInterface[]
   */
  protected $configEntityTypeDefinitions;

  /**
   * The current request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

  /**
   * Constructs a KeyConfigOverrideAddForm.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity manager.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Config\StorageInterface $config_storage
   *   The config storage.
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   The current request stack.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, ConfigFactoryInterface $config_factory, StorageInterface $config_storage, RequestStack $request_stack) {
    $this->entityTypeManager = $entity_type_manager;
    $this->configFactory = $config_factory;
    $this->configStorage = $config_storage;
    $this->storage = $entity_type_manager
      ->getStorage('key_config_override');
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('config.factory'), $container
      ->get('config.storage'), $container
      ->get('request_stack'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'key_config_override_add_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config_type = $form_state
      ->getValue('config_type');
    $config_name = $form_state
      ->getValue('config_name');
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Key configuration override name'),
      '#description' => $this
        ->t('A human readable name for this override.'),
      '#size' => 30,
      '#maxlength' => 64,
      '#required' => TRUE,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#required' => TRUE,
      '#size' => 30,
      '#maxlength' => 64,
      '#machine_name' => [
        'exists' => [
          $this->storage,
          'load',
        ],
      ],
    ];
    $entity_types = array_map(function (EntityTypeInterface $definition) {
      return $definition
        ->getLabel();
    }, $this
      ->getConfigEntityTypeDefinitions());

    // Sort the entity types by label.
    uasort($entity_types, 'strnatcasecmp');

    // Add the simple configuration type to the top of the list.
    $config_types = [
      'system.simple' => $this
        ->t('Simple configuration'),
    ] + $entity_types;
    $form['config_type'] = [
      '#title' => $this
        ->t('Configuration type'),
      '#type' => 'select',
      '#options' => $config_types,
      '#required' => TRUE,
      '#ajax' => [
        'callback' => '::changeConfigObject',
        'wrapper' => 'edit-config-object-wrapper',
      ],
    ];
    $form['config_object'] = [
      '#type' => 'container',
      '#prefix' => '<div id="edit-config-object-wrapper">',
      '#suffix' => '</div>',
    ];
    $form['config_object']['config_name'] = [
      '#title' => $this
        ->t('Configuration name'),
      '#type' => 'select',
      '#options' => $this
        ->getConfigNames($config_type),
      '#required' => TRUE,
      '#ajax' => [
        'callback' => '::changeConfigObject',
        'wrapper' => 'edit-config-object-wrapper',
      ],
    ];
    $form['config_object']['config_item'] = [
      '#title' => $this
        ->t('Configuration item'),
      '#type' => 'select',
      '#options' => $this
        ->getConfigItems($config_type, $config_name),
      '#required' => TRUE,
    ];
    $request = $this->requestStack
      ->getCurrentRequest();
    $query_key = $request->query
      ->get('key');
    $form['key_id'] = [
      '#title' => $this
        ->t('Key'),
      '#type' => 'key_select',
      '#default_value' => $query_key,
      '#required' => TRUE,
    ];
    $form['clear_overridden'] = [
      '#title' => $this
        ->t('Clear overridden value'),
      '#type' => 'checkbox',
      '#description' => $this
        ->t('Check this field to clear any existing value for the overridden configuration item. This is important to make sure potentially sensitive data is removed from the configuration.'),
      '#default_value' => TRUE,
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);

    // Add the entity prefix when the form is submitted.
    if ($form_state
      ->isSubmitted()) {
      $definitions = $this
        ->getConfigEntityTypeDefinitions();
      $config_type = $form_state
        ->getValue('config_type');
      if (array_key_exists($config_type, $definitions)) {
        $config_prefix = $definitions[$config_type]
          ->getConfigPrefix();
      }
      else {
        $config_prefix = '';
      }
      $form_state
        ->setValue('config_prefix', $config_prefix);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $form_state
      ->setRedirectUrl($this->entity
      ->toUrl('collection'));
    $saved = parent::save($form, $form_state);

    // Clear the overridden value, if requested.
    if ($saved && $form_state
      ->getValue('clear_overridden')) {
      $override = $this->entity;
      $type = $override
        ->getConfigType();
      $name = $override
        ->getConfigName();
      $item = $override
        ->getConfigItem();
      if ($type !== 'system.simple') {
        $definition = $this->entityTypeManager
          ->getDefinition($type);
        $name = $definition
          ->getConfigPrefix() . '.' . $name;
      }
      $config = $this
        ->configFactory()
        ->getEditable($name);
      $config
        ->set($item, NULL);
      $config
        ->save();
    }
    return $saved;
  }

  /**
   * Updates the configuration object container element.
   */
  public function changeConfigObject($form, FormStateInterface $form_state) {
    return $form['config_object'];
  }

  /**
   * Get the configuration entity type definitions.
   *
   * @param bool $with_excluded
   *   Whether or not to include excluded configuration types.
   *
   * @return \Drupal\Core\Entity\EntityTypeInterface[]
   *   The entity type definitions.
   */
  protected function getConfigEntityTypeDefinitions($with_excluded = FALSE) {
    if (!isset($this->configEntityTypeDefinitions)) {
      $config_entity_type_definitions = [];
      foreach ($this->entityTypeManager
        ->getDefinitions() as $entity_type => $definition) {
        if ($definition
          ->entityClassImplements(ConfigEntityInterface::class)) {
          $config_entity_type_definitions[$entity_type] = $definition;
        }
      }
      $this->configEntityTypeDefinitions = $config_entity_type_definitions;
    }
    if ($with_excluded) {
      $definitions = $this->configEntityTypeDefinitions;
    }
    else {
      $definitions = array_diff_key($this->configEntityTypeDefinitions, $this
        ->excludedConfigTypes());
    }
    return $definitions;
  }

  /**
   * Get the configuration names for a specified configuration type.
   *
   * @param string|null $config_type
   *   The configuration type.
   *
   * @return array
   *   The configuration names.
   */
  protected function getConfigNames($config_type = NULL) {
    $names = [
      '' => $this
        ->t('- Select -'),
    ];

    // Handle entity configuration types.
    if ($config_type && $config_type !== 'system.simple') {
      $entity_storage = $this->entityTypeManager
        ->getStorage($config_type);
      foreach ($entity_storage
        ->loadMultiple() as $entity) {
        $entity_id = $entity
          ->id();
        if ($label = $entity
          ->label()) {
          $names[$entity_id] = new TranslatableMarkup('@label (@id)', [
            '@label' => $label,
            '@id' => $entity_id,
          ]);
        }
        else {
          $names[$entity_id] = $entity_id;
        }
      }
    }
    elseif ($config_type == 'system.simple') {

      // Gather the configuration entity prefixes.
      $config_prefixes = array_map(function (EntityTypeInterface $definition) {
        return $definition
          ->getConfigPrefix() . '.';
      }, $this
        ->getConfigEntityTypeDefinitions(TRUE));

      // Get all configuration names.
      $names = $this->configStorage
        ->listAll();
      $names = array_combine($names, $names);

      // Filter out any names that match a configuration entity prefix.
      foreach ($names as $config_name) {
        foreach ($config_prefixes as $config_prefix) {
          if (strpos($config_name, $config_prefix) === 0) {
            unset($names[$config_name]);
          }
        }
      }
    }
    return $names;
  }

  /**
   * Get the configuration items for a specified configuration name.
   *
   * @param string|null $config_type
   *   The configuration type.
   * @param string|null $config_name
   *   The configuration name.
   *
   * @return array
   *   The configuration items.
   */
  protected function getConfigItems($config_type = NULL, $config_name = NULL) {
    $config_items = [];
    if (!$config_name) {
      return $config_items;
    }

    // For simple configuration, use the configuration name. For configuration
    // entities, use a combination of the prefix and configuration name.
    if ($config_type == 'system.simple') {
      $name = $config_name;
    }
    else {
      $definition = $this
        ->getConfigEntityTypeDefinitions()[$config_type];
      $name = $definition
        ->getConfigPrefix() . '.' . $config_name;
    }
    $config_object = $this->configFactory
      ->get($name);
    $config_array = $config_object
      ->get();
    $config_items += $this
      ->flattenConfigItemList($config_array);
    $config_items = array_combine($config_items, $config_items);
    return $config_items;
  }

  /**
   * Define the list of configuration types to exclude.
   *
   * @return array
   *   The configuration types to exclude.
   */
  protected function excludedConfigTypes() {
    $exclude = [
      'key',
      'key_config_override',
    ];
    return array_combine($exclude, $exclude);
  }

  /**
   * Recursively create a flat array of configuration items.
   *
   * @param array $config_array
   *   An array of configuration items.
   * @param string $prefix
   *   A prefix to add to nested items.
   * @param int $level
   *   The current level of nesting.
   *
   * @return array
   *   The flattened array of configuration items.
   */
  protected function flattenConfigItemList(array $config_array, $prefix = '', $level = 0) {
    $config_items = [];

    // Define items to ignore.
    $ignore = [
      'uuid',
      '_core',
    ];
    foreach ($config_array as $key => $value) {
      if (in_array($key, $ignore) && $level == 0) {
        continue;
      }
      if (is_array($value) && $level < 5) {
        $config_items = array_merge($config_items, $this
          ->flattenConfigItemList($value, $prefix . $key . '.', $level + 1));
      }
      else {
        $config_items[] = $prefix . $key;
      }
    }
    return $config_items;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityForm::$entity protected property The entity being used by this form. 7
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::form public function Gets the actual form array to be built. 30
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides FormInterface::submitForm 17
EntityForm::__get public function
EntityForm::__set public function
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
KeyConfigOverrideAddForm::$configEntityTypeDefinitions protected property The configuration entity type definitions.
KeyConfigOverrideAddForm::$configFactory protected property The config factory. Overrides FormBase::$configFactory
KeyConfigOverrideAddForm::$configStorage protected property The config storage.
KeyConfigOverrideAddForm::$entityTypeManager protected property The entity type manager. Overrides EntityForm::$entityTypeManager
KeyConfigOverrideAddForm::$requestStack protected property The current request stack. Overrides FormBase::$requestStack
KeyConfigOverrideAddForm::$storage protected property The Key Configuration Override entity storage.
KeyConfigOverrideAddForm::buildForm public function Form constructor. Overrides EntityForm::buildForm
KeyConfigOverrideAddForm::changeConfigObject public function Updates the configuration object container element.
KeyConfigOverrideAddForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
KeyConfigOverrideAddForm::excludedConfigTypes protected function Define the list of configuration types to exclude.
KeyConfigOverrideAddForm::flattenConfigItemList protected function Recursively create a flat array of configuration items.
KeyConfigOverrideAddForm::getConfigEntityTypeDefinitions protected function Get the configuration entity type definitions.
KeyConfigOverrideAddForm::getConfigItems protected function Get the configuration items for a specified configuration name.
KeyConfigOverrideAddForm::getConfigNames protected function Get the configuration names for a specified configuration type.
KeyConfigOverrideAddForm::getFormId public function Returns a unique string identifying the form. Overrides EntityForm::getFormId
KeyConfigOverrideAddForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
KeyConfigOverrideAddForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
KeyConfigOverrideAddForm::__construct public function Constructs a KeyConfigOverrideAddForm.
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.