You are here

class CleanerSettingsForm in Cleaner 8

Same name and namespace in other branches
  1. 8.2 src/Form/CleanerSettingsForm.php \Drupal\cleaner\Form\CleanerSettingsForm

Class CleanerSettingsForm.

@package Drupal\cleaner\Form

Hierarchy

Expanded class hierarchy of CleanerSettingsForm

1 string reference to 'CleanerSettingsForm'
cleaner.routing.yml in ./cleaner.routing.yml
cleaner.routing.yml

File

src/Form/CleanerSettingsForm.php, line 15

Namespace

Drupal\cleaner\Form
View source
class CleanerSettingsForm extends ConfigFormBase {

  /**
   * Static array with the time intervals.
   *
   * @var array
   */
  private static $intervals = [
    900 => '15 min',
    1800 => '30 min',
    3600 => '1 hour',
    7200 => '2 hour',
    14400 => '4 hours',
    21600 => '6 hours',
    43200 => '12 hours',
    86400 => '1 day',
    172800 => '2 days',
    259200 => '3 days',
    604800 => '1 week',
  ];

  /**
   * FirstSettingsForm constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactory $config_factory
   *   The factory for configuration objects.
   */
  public function __construct(ConfigFactory $config_factory) {
    parent::__construct($config_factory);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return parent::create($container);
  }

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

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

  /**
   * Get cache tables table.
   */
  protected function getCacheTablesTable() {

    // Get all CACHE tables form database.
    $list = self::getAllCacheTables();
    if (!empty($list)) {

      // Prepare table's rows.
      $rows = self::prepareRows($list);

      // Create theme table rendered HTML.
      $table = self::themeTable($rows);
      return $this
        ->t('The current cache tables are:') . $table;
    }
    return $this
      ->t('There is no cache tables in the database.');
  }

  /**
   * Get list of all cache tables.
   *
   * @return mixed
   *   List of all cache tables.
   */
  private static function getAllCacheTables() {
    $query = \Drupal::database()
      ->select('INFORMATION_SCHEMA.TABLES', 'tables')
      ->fields('tables', [
      'table_name',
      'table_schema',
    ])
      ->condition('table_schema', \Drupal::database()
      ->getConnectionOptions()['database'])
      ->condition('table_name', 'cache_%', 'LIKE')
      ->condition('table_name', 'cachetags', '<>');
    return $query
      ->execute()
      ->fetchCol();
  }

  /**
   * Prepare table rows array.
   *
   * @param array $list
   *   All cache tables form database.
   *
   * @return array
   *   Table rows array.
   */
  private static function prepareRows(array $list) {
    $table_rows = [];
    $cols = 4;
    $count = count($list);
    $rows = ceil($count / $cols);
    $list = array_pad($list, $rows * $cols, ' ');
    for ($i = 0; $i < $count; $i += $cols) {
      $table_rows[] = array_slice($list, $i, $cols);
    }
    return $table_rows;
  }

  /**
   * Render the table.
   *
   * @param array $rows
   *   Table rows.
   *
   * @return string
   *   Rendered HTML.
   */
  private static function themeTable($rows = []) {
    return \Drupal::theme()
      ->render('table', [
      'rows' => $rows,
      'attributes' => [
        'class' => [
          'cleaner-cache-tables',
        ],
      ],
    ]);
  }

  /**
   * Gets the session lifetime and expired sessions count.
   *
   * @return array
   *   Session lifetime and expired sessions count.
   */
  private static function getSessionSettings() {

    // Get cookies params array.
    $lifetime = (int) session_get_cookie_params()['lifetime'];

    // Get current database connection.
    $connection = \Drupal::database();

    // Select old sessions from the sessions db table.
    $count = $connection
      ->select('sessions', 's')
      ->fields('s', [
      'sid',
      'timestamp',
    ])
      ->condition('timestamp', REQUEST_TIME - $lifetime, '<');
    $count = count((array) $count
      ->execute()
      ->fetchCol());
    return [
      'lifetime' => $lifetime,
      'old_sessions' => $count,
    ];
  }

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

    // Get config handler.
    $conf = $this
      ->config(CLEANER_SETTINGS);

    // Prepare Yes/No options array.
    $yes_no = [
      $this
        ->t('No:'),
      $this
        ->t('Yes:'),
    ];

    // Attach the "cleaner-admin" library for some admin page styling.
    $form['cleaner']['#attached']['library'][] = 'cleaner/cleaner-admin';

    // Cron interval settings.
    $form['cleaner']['cleaner_cron'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Run interval'),
      '#options' => array_merge([
        0 => $this
          ->t('Every time'),
      ], self::$intervals),
      '#default_value' => (int) $conf
        ->get('cleaner_cron'),
      '#description' => $this
        ->t('This is how often the options below will occur. <br> The actions will occur on the next Cron run after this interval expires. <br>"Every time" means on every Cron run.'),
    ];

    // Cache clearing settings.
    $form['cleaner']['cleaner_clear_cache'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Clean up cache'),
      '#default_value' => (int) $conf
        ->get('cleaner_clear_cache'),
      '#description' => $this
        ->getCacheTablesTable(),
    ];

    // Additional tables clearing settings.
    $form['cleaner']['cleaner_additional_tables'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Additional tables to clear'),
      '#default_value' => (string) $conf
        ->get('cleaner_additional_tables'),
      '#description' => $this
        ->t('A comma separated list of table names which also needs to be cleared.'),
    ];

    // Watchdog clearing settings.
    $form['cleaner']['cleaner_empty_watchdog'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Clean up Watchdog'),
      '#default_value' => (int) $conf
        ->get('cleaner_empty_watchdog'),
      '#description' => $this
        ->t('There is a standard setting for controlling Watchdog contents. This is more useful for test sites.'),
    ];

    // Get session settings.
    $session_settings = self::getSessionSettings();

    // Sessions clearing settings.
    $form['cleaner']['cleaner_clean_sessions'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Clean up Sessions table'),
      '#default_value' => (int) $conf
        ->get('cleaner_clean_sessions'),
      '#description' => $this
        ->t('The sessions table can quickly become full with old, abandoned sessions. <br>This will delete all sessions older than @interval (as set by your site administrator). <br>There are currently @count such sessions.', [
        '@interval' => $session_settings['lifetime'],
        '@count' => $session_settings['old_sessions'],
      ]),
    ];

    // We can only offer OPTIMIZE to MySQL users.
    if (\Drupal::database()
      ->driver() == 'mysql') {

      // Database(MySQL) optimizing settings.
      $form['cleaner']['cleaner_optimize_db'] = [
        '#type' => 'radios',
        '#options' => $yes_no + [
          '2' => $this
            ->t('Local only:'),
        ],
        '#title' => $this
          ->t('Optimize tables with "overhead" space'),
        '#default_value' => (int) $conf
          ->get('cleaner_optimize_db'),
        '#description' => $this
          ->t('The module will compress (optimize) all database tables with unused space.<br><strong>NOTE</strong>: During an optimization, the table will locked against any other activity; on a high vloume site, this may be undesirable. "Local only" means do not replicate the optimization (if it is being done).'),
      ];
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = \Drupal::configFactory()
      ->getEditable(CLEANER_SETTINGS);
    foreach ($form_state
      ->getValues() as $name => $value) {
      if (stripos($name, 'cleaner') !== FALSE) {
        $config
          ->set($name, $value);
      }
    }
    $config
      ->save();
    parent::submitForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CleanerSettingsForm::$intervals private static property Static array with the time intervals.
CleanerSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
CleanerSettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
CleanerSettingsForm::getAllCacheTables private static function Get list of all cache tables.
CleanerSettingsForm::getCacheTablesTable protected function Get cache tables table.
CleanerSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
CleanerSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
CleanerSettingsForm::getSessionSettings private static function Gets the session lifetime and expired sessions count.
CleanerSettingsForm::prepareRows private static function Prepare table rows array.
CleanerSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
CleanerSettingsForm::themeTable private static function Render the table.
CleanerSettingsForm::__construct public function FirstSettingsForm constructor. Overrides ConfigFormBase::__construct
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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.