You are here

class WatchdogPruneSettings in Watchdog Prune 8.2

Same name and namespace in other branches
  1. 8 src/Form/WatchdogPruneSettings.php \Drupal\watchdog_prune\Form\WatchdogPruneSettings

Class WatchdogPruneSettings.

@package Drupal\watchdog_prune\Form.

Hierarchy

Expanded class hierarchy of WatchdogPruneSettings

1 string reference to 'WatchdogPruneSettings'
watchdog_prune.routing.yml in ./watchdog_prune.routing.yml
watchdog_prune.routing.yml

File

src/Form/WatchdogPruneSettings.php, line 15

Namespace

Drupal\watchdog_prune\Form
View source
class WatchdogPruneSettings extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return "watchdog_prune_settings";
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'watchdog_prune.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('watchdog_prune.settings');
    $database = \Drupal::service('database.replica');
    $form['mark_top'] = [
      '#markup' => "<p>" . $this
        ->t("This module allows you to delete watchdog entries, on cron run, based on certain criteria (like age or watchdog entry types).In order for this module to work, Drupal's built in setting <strong>Database log messages to keep</strong>\n        must be set to <strong>All</strong>. <br><br><strong>You must have a correctly configured cron task for this module to work.</strong>") . "</p>",
    ];
    $form['core_fs'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('From Drupal Core'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    ];
    $form['core_fs']['dblog_row_limit'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('[From Drupal Core:] Database log messages to keep'),
      '#options' => [
        '0' => 'All',
      ],
      '#default_value' => 0,
      '#description' => $this
        ->t('For this module to function, we must keep this Drupal Core setting set to <strong>All</strong>.  This setting is provided here simply as a reminder of where this setting is coming from.'),
    ];
    $prune_age_options = WatchdogPruneSettings::pruneAgeOptions();
    $form['watchdog_prune_age'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Delete watchdog entries older than:'),
      '#options' => $prune_age_options,
      '#default_value' => empty($config
        ->get('watchdog_prune_age')) ? '-18 MONTHS' : $config
        ->get('watchdog_prune_age'),
      '#description' => $this
        ->t('Watchdog entries older than this time will be deleted on each cron run. This will ignore all watchdog types entered in "Delete watchdog entries by type" settings.'),
    ];
    $watchdog_types = $database
      ->query('SELECT DISTINCT(type) FROM {watchdog}')
      ->fetchCol();
    if (count($watchdog_types) === 0) {
      $watchdog_types = $this
        ->t('Watchdog is empty');
    }
    else {
      $watchdog_types = implode(', ', $watchdog_types);
    }
    $phpdate_reference = Link::fromTextAndUrl($this
      ->t('PHP Date Manual'), Url::fromUri('http://php.net/manual/en/datetime.formats.relative.php', [
      'attributes' => [
        'target' => '_blank',
      ],
    ]))
      ->toString();
    $form['watchdog_prune_age_type'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Delete watchdog entries by type'),
      '#description' => $this
        ->t('Configure different prune time for each watchdog type, enter separate values on new line. Currently <em>logged</em> watchdog entry types are (<em>' . $watchdog_types . '</em>). For all available values for age check the ' . $phpdate_reference . '
        <br><br>Insert values with format
        <br><b><h4>watchdog_entry_type|age</h4></b>
        <br>Examples
        <br><b>php|-1 MONTH</b>
        <br><b>system|-1 MONTH</b>
      </br>This will delete all watchdog entries of type php and system which are older than a month on cron run.'),
      '#rows' => 10,
      '#cols' => 40,
      '#default_value' => empty($config
        ->get('watchdog_prune_age_type')) ? '' : $config
        ->get('watchdog_prune_age_type'),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $prune_type = $form_state
      ->getValue('watchdog_prune_age_type');
    if (!empty($prune_type)) {
      $prune_type = explode("\n", $prune_type);
      if (is_array($prune_type)) {
        $current_date = strtotime('today');
        foreach ($prune_type as $key => $value) {
          $watchdog_prune_settings = explode("|", $value);
          $user_entered_date = strtotime(trim($watchdog_prune_settings[1]));
          if ($current_date < $user_entered_date) {
            $form_state
              ->setErrorByName('watchdog_prune_age_type', $this
              ->t('Incorrect value for <b>' . implode("|", $watchdog_prune_settings) . '</b> Watchdog Prune age must be older than todays date'));
          }
        }
      }
    }
  }

  /**
   * Implements submitForm().
   *
   * @param array $form
   *   Processess $form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Processess $form_state.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $watchdog_prune_age = $form_state
      ->getValue('watchdog_prune_age');
    $watchdog_prune_age_type = $form_state
      ->getValue('watchdog_prune_age_type');
    $this
      ->config('watchdog_prune.settings')
      ->set('watchdog_prune_age', $watchdog_prune_age)
      ->set('watchdog_prune_age_type', $watchdog_prune_age_type)
      ->save();
    \Drupal::messenger()
      ->addMessage('The configuration options have been saved.', 'status');
  }

  /**
   * Implements pruneAgeOptions().
   *
   * Gets the Prune age options.
   *
   * @return array
   *   An array of Prune age options.
   */
  protected static function pruneAgeOptions() {
    $prune_age_options = [
      '' => t('None - do not prune based on age'),
      '-1 WEEK' => t('1 week'),
      '-2 WEEKS' => t('2 weeks'),
      '-3 WEEKS' => t('3 weeks'),
      '-1 MONTH' => t('1 month'),
      '-2 MONTHS' => t('2 months'),
      '-3 MONTHS' => t('3 months'),
      '-6 MONTHS' => t('6 months'),
      '-9 MONTHS' => t('9 months'),
      '-12 MONTHS' => t('12 months (1 year)'),
      '-18 MONTHS' => t('18 months (1.5 years)'),
      '-24 MONTHS' => t('24 months (2 years)'),
      '-30 MONTHS' => t('30 months (2.5 years)'),
      '-36 MONTHS' => t('36 months (3 years)'),
    ];
    return $prune_age_options;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 13
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 11
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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::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.
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.
WatchdogPruneSettings::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
WatchdogPruneSettings::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
WatchdogPruneSettings::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
WatchdogPruneSettings::pruneAgeOptions protected static function Implements pruneAgeOptions().
WatchdogPruneSettings::submitForm public function Implements submitForm(). Overrides ConfigFormBase::submitForm
WatchdogPruneSettings::validateForm public function Form validation handler. Overrides FormBase::validateForm