View source
<?php
namespace Drupal\rng\Plugin\Condition;
use Drupal\Core\Condition\ConditionPluginBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Datetime\DrupalDateTime;
class CurrentTime extends ConditionPluginBase {
public function defaultConfiguration() {
return [
'date' => NULL,
'enable' => FALSE,
] + parent::defaultConfiguration();
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
if (is_numeric($this->configuration['date'])) {
$date = DrupalDateTime::createFromTimestamp($this
->getDate());
}
else {
$date = new DrupalDateTime();
}
$form['date'] = [
'#type' => 'datetime',
'#date_date_element' => 'date',
'#title' => $this
->t('Date'),
'#default_value' => $date,
'#size' => 20,
'#weight' => 50,
];
$form['enable'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Enable this condition?'),
'#default_value' => $this
->getConfiguration()['enable'],
];
$form['negate'] = [
'#type' => 'radios',
'#title' => $this
->t('Timing'),
'#description' => $this
->t('Condition will be true if the time when evaluating this condition is before or after the date.'),
'#options' => [
0 => $this
->t('After this date'),
1 => $this
->t('Before this date'),
],
'#default_value' => (int) $this
->isNegated(),
'#weight' => 100,
];
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$enabled = $form_state
->getValue('enable');
if (!$enabled) {
return;
}
$this
->setConfig('enable', $enabled);
$this
->setConfig('date', $form_state
->getValue('date')
->format('U'));
parent::submitConfigurationForm($form, $form_state);
}
public function summary() {
$t_args = [
'@date' => DrupalDateTime::createFromTimestamp($this
->getDate()),
];
if (!$this
->isNegated()) {
return $this
->t('Current date is after @date', $t_args);
}
else {
return $this
->t('Current date is before @date', $t_args);
}
}
public function getDate() {
return $this->configuration['date'];
}
public function getDateFormatted() {
return is_numeric($this
->getDate()) ? DrupalDateTime::createFromTimestamp($this
->getDate()) : $this
->t('Not configured');
}
public function evaluate() {
$date = $this
->getDate();
if ($date && is_numeric($date)) {
if (!$this
->isNegated()) {
return time() > $date;
}
else {
return time() < $date;
}
}
return FALSE;
}
}