You are here

class SystemStateEdit in Devel 8.3

Same name and namespace in other branches
  1. 8 src/Form/SystemStateEdit.php \Drupal\devel\Form\SystemStateEdit
  2. 8.2 src/Form/SystemStateEdit.php \Drupal\devel\Form\SystemStateEdit
  3. 4.x src/Form/SystemStateEdit.php \Drupal\devel\Form\SystemStateEdit

Form API form to edit a state.

Hierarchy

Expanded class hierarchy of SystemStateEdit

1 string reference to 'SystemStateEdit'
devel.routing.yml in ./devel.routing.yml
devel.routing.yml

File

src/Form/SystemStateEdit.php, line 16

Namespace

Drupal\devel\Form
View source
class SystemStateEdit extends FormBase {

  /**
   * The state store.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected $state;

  /**
   * Constructs a new SystemStateEdit object.
   *
   * @param \Drupal\Core\State\StateInterface $state
   *   The state service.
   */
  public function __construct(StateInterface $state) {
    $this->state = $state;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('state'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $state_name = '') {

    // Get the old value.
    $old_value = $this->state
      ->get($state_name);
    if (!isset($old_value)) {
      $this
        ->messenger()
        ->addWarning($this
        ->t('State @name does not exist in the system.', [
        '@name' => $state_name,
      ]));
      return;
    }

    // Only simple structures are allowed to be edited.
    $disabled = !$this
      ->checkObject($old_value);
    if ($disabled) {
      $this
        ->messenger()
        ->addWarning($this
        ->t('Only simple structures are allowed to be edited. State @name contains objects.', [
        '@name' => $state_name,
      ]));
    }

    // First we will show the user the content of the variable about to be edited.
    $form['value'] = [
      '#type' => 'item',
      '#title' => $this
        ->t('Current value for %name', [
        '%name' => $state_name,
      ]),
      '#markup' => kpr($old_value, TRUE),
    ];
    $transport = 'plain';
    if (!$disabled && is_array($old_value)) {
      try {
        $old_value = Yaml::encode($old_value);
        $transport = 'yaml';
      } catch (InvalidDataTypeException $e) {
        $this
          ->messenger()
          ->addError($this
          ->t('Invalid data detected for @name : %error', [
          '@name' => $state_name,
          '%error' => $e
            ->getMessage(),
        ]));
        return;
      }
    }

    // Store in the form the name of the state variable.
    $form['state_name'] = [
      '#type' => 'value',
      '#value' => $state_name,
    ];

    // Set the transport format for the new value. Values:
    //  - plain
    //  - yaml.
    $form['transport'] = [
      '#type' => 'value',
      '#value' => $transport,
    ];
    $form['new_value'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('New value'),
      '#default_value' => $disabled ? '' : $old_value,
      '#disabled' => $disabled,
      '#rows' => 15,
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
      '#disabled' => $disabled,
    ];
    $form['actions']['cancel'] = [
      '#type' => 'link',
      '#title' => $this
        ->t('Cancel'),
      '#url' => Url::fromRoute('devel.state_system_page'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    if ($values['transport'] == 'yaml') {

      // Try to parse the new provided value.
      try {
        $parsed_value = Yaml::decode($values['new_value']);
        $form_state
          ->setValue('parsed_value', $parsed_value);
      } catch (InvalidDataTypeException $e) {
        $form_state
          ->setErrorByName('new_value', $this
          ->t('Invalid input: %error', [
          '%error' => $e
            ->getMessage(),
        ]));
      }
    }
    else {
      $form_state
        ->setValue('parsed_value', $values['new_value']);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Save the state.
    $values = $form_state
      ->getValues();
    $this->state
      ->set($values['state_name'], $values['parsed_value']);
    $form_state
      ->setRedirectUrl(Url::fromRoute('devel.state_system_page'));
    $this
      ->messenger()
      ->addMessage($this
      ->t('Variable %variable was successfully edited.', [
      '%variable' => $values['state_name'],
    ]));
    $this
      ->logger('devel')
      ->info('Variable %variable was successfully edited.', [
      '%variable' => $values['state_name'],
    ]);
  }

  /**
   * Helper function to determine if a variable is or contains an object.
   *
   * @param $data
   *   Input data to check
   *
   * @return bool
   *   TRUE if the variable is not an object and does not contain one.
   */
  protected function checkObject($data) {
    if (is_object($data)) {
      return FALSE;
    }
    if (is_array($data)) {

      // If the current object is an array, then check recursively.
      foreach ($data as $value) {

        // If there is an object the whole container is "contaminated".
        if (!$this
          ->checkObject($value)) {
          return FALSE;
        }
      }
    }

    // All checks pass.
    return TRUE;
  }

}

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
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
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.
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.
SystemStateEdit::$state protected property The state store.
SystemStateEdit::buildForm public function Form constructor. Overrides FormInterface::buildForm
SystemStateEdit::checkObject protected function Helper function to determine if a variable is or contains an object.
SystemStateEdit::create public static function Instantiates a new instance of this class. Overrides FormBase::create
SystemStateEdit::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SystemStateEdit::submitForm public function Form submission handler. Overrides FormInterface::submitForm
SystemStateEdit::validateForm public function Form validation handler. Overrides FormBase::validateForm
SystemStateEdit::__construct public function Constructs a new SystemStateEdit object.
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.