View source
<?php
namespace Drupal\calendar\Plugin\views\argument_validator;
use Drupal\calendar\DateArgumentWrapper;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\Context\ContextDefinition;
use Drupal\views\Plugin\views\argument\ArgumentPluginBase;
use Drupal\views\Plugin\views\argument\Date;
use Drupal\views\Plugin\views\argument_validator\ArgumentValidatorPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
class CalendarValidator extends ArgumentValidatorPluginBase {
protected $argumentWrapper;
protected $dateFormatter;
public function __construct(array $configuration, $plugin_id, $plugin_definition, DateFormatterInterface $dateFormatter) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->dateFormatter = $dateFormatter;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('date.formatter'));
}
public function validateArgument($arg) {
if (isset($this->argumentWrapper) && $this->argumentWrapper
->validateValue($arg)) {
$date = $this->argumentWrapper
->createDateTime();
$january = '';
if ($this->options['replacement_format'] === 'Y') {
$january = 'January';
}
$time = strtotime($january . $date
->format($this->options['replacement_format']));
$this->argument->validated_title = $this->dateFormatter
->format($time, 'custom', $this->options['replacement_format']);
return TRUE;
}
return FALSE;
}
public function setArgument(ArgumentPluginBase $argument) {
parent::setArgument($argument);
if ($argument instanceof Date) {
$this->argumentWrapper = new DateArgumentWrapper($argument);
}
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['replacement_format'] = [
'default' => '',
];
return $options;
}
protected function getDefaultReplacementFormat() {
switch ($this->argumentWrapper
->getGranularity()) {
case 'month':
return 'F Y';
case 'year':
return 'Y';
case 'week':
return 'F j, Y';
case 'day':
return 'l, F j, Y';
default:
return 'F j, Y';
}
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
if (!isset($this->argumentWrapper)) {
return;
}
if ($this->options['replacement_format']) {
$default = $this->options['replacement_format'];
}
else {
$default = $this
->getDefaultReplacementFormat();
}
$form['replacement_format'] = [
'#type' => 'textfield',
'#title' => $this
->t('Replacement date pattern'),
'#default_value' => $default,
'#description' => $this
->t('Provide a date pattern to be used when replace this arguments as a title.'),
];
}
public function getContextDefinition() {
return new ContextDefinition('string', $this->argument
->adminLabel(), FALSE);
}
}