View source
<?php
declare (strict_types=1);
namespace Drupal\mongodb_watchdog\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\mongodb_watchdog\Logger;
use Symfony\Component\DependencyInjection\ContainerInterface;
class OverviewFilterForm extends FormBase {
const SESSION_KEY = 'mongodb_watchdog_overview_filter';
protected $watchdog;
public function __construct(Logger $watchdog) {
$this->watchdog = $watchdog;
}
public function buildForm(array $form, FormStateInterface $formState) : array {
$filters = $this
->getFilters();
$form['filters'] = [
'#type' => 'details',
'#title' => $this
->t('Filter log messages'),
'#open' => TRUE,
];
$sessionFilter = $_SESSION[static::SESSION_KEY] ?? [];
foreach ($filters as $key => $filter) {
$form['filters']['status'][$key] = [
'#title' => $filter['title'],
'#type' => 'select',
'#multiple' => TRUE,
'#size' => 8,
'#options' => $filter['options'],
];
if (!empty($sessionFilter[$key])) {
$form['filters']['status'][$key]['#default_value'] = $sessionFilter[$key];
}
}
$form['filters']['actions'] = [
'#type' => 'actions',
'#attributes' => [
'class' => [
'container-inline',
],
],
];
$form['filters']['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Filter'),
];
if (!empty($sessionFilter)) {
$form['filters']['actions']['reset'] = [
'#type' => 'submit',
'#value' => $this
->t('Reset'),
'#limit_validation_errors' => [],
'#submit' => [
'::resetForm',
],
];
}
return $form;
}
public static function create(ContainerInterface $container) : self {
$watchdog = $container
->get(Logger::SERVICE_LOGGER);
return new static($watchdog);
}
public function getFilters() : array {
$filters = [];
foreach ($this->watchdog
->templateTypes() as $type) {
$types[$type] = $this
->t($type);
}
if (!empty($types)) {
$filters['type'] = [
'title' => $this
->t('Type'),
'where' => "w.type = ?",
'options' => $types,
];
}
$filters['severity'] = [
'title' => $this
->t('Severity'),
'where' => 'w.severity = ?',
'options' => RfcLogLevel::getLevels(),
];
return $filters;
}
public function getFormId() : string {
return 'mongodb-watchdog__filter-form';
}
public function submitForm(array &$form, FormStateInterface $formState) : void {
$filters = array_keys($this
->getFilters());
foreach ($filters as $name) {
if ($formState
->hasValue($name)) {
$_SESSION[static::SESSION_KEY][$name] = $formState
->getValue($name);
}
}
}
public function resetForm() : void {
$_SESSION[static::SESSION_KEY] = [];
}
public function validateForm(array &$form, FormStateInterface $formState) : void {
if ($formState
->isValueEmpty('type') && $formState
->isValueEmpty('severity')) {
$formState
->setErrorByName('type', $this
->t('You must select something to filter by.'));
}
}
}