Version 1
[yaffs-website] / web / core / modules / views / src / Plugin / views / field / TimeInterval.php
1 <?php
2
3 namespace Drupal\views\Plugin\views\field;
4
5 use Drupal\Core\Datetime\DateFormatterInterface;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\views\ResultRow;
8 use Symfony\Component\DependencyInjection\ContainerInterface;
9
10 /**
11  * A handler to provide proper displays for time intervals.
12  *
13  * @ingroup views_field_handlers
14  *
15  * @ViewsField("time_interval")
16  */
17 class TimeInterval extends FieldPluginBase {
18
19   /**
20    * The date formatter service.
21    *
22    * @var \Drupal\Core\Datetime\DateFormatterInterface
23    */
24   protected $dateFormatter;
25
26   /**
27    * Constructs a TimeInterval plugin object.
28    *
29    * @param array $configuration
30    *   A configuration array containing information about the plugin instance.
31    * @param string $plugin_id
32    *   The plugin_id for the plugin instance.
33    * @param mixed $plugin_definition
34    *   The plugin implementation definition.
35    * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
36    *   The date formatter service.
37    */
38   public function __construct(array $configuration, $plugin_id, $plugin_definition, DateFormatterInterface $date_formatter) {
39     $this->dateFormatter = $date_formatter;
40     parent::__construct($configuration, $plugin_id, $plugin_definition);
41   }
42
43   /**
44    * {@inheritdoc}
45    */
46   public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
47     return new static(
48       $configuration,
49       $plugin_id,
50       $plugin_definition,
51       $container->get('date.formatter')
52     );
53   }
54
55   /**
56    * {@inheritdoc}
57    */
58   protected function defineOptions() {
59     $options = parent::defineOptions();
60
61     $options['granularity'] = ['default' => 2];
62
63     return $options;
64   }
65
66   /**
67    * {@inheritdoc}
68    */
69   public function buildOptionsForm(&$form, FormStateInterface $form_state) {
70     parent::buildOptionsForm($form, $form_state);
71
72     $form['granularity'] = [
73       '#type' => 'textfield',
74       '#title' => $this->t('Granularity'),
75       '#description' => $this->t('How many different units to display in the string.'),
76       '#default_value' => $this->options['granularity'],
77     ];
78   }
79
80   /**
81    * {@inheritdoc}
82    */
83   public function render(ResultRow $values) {
84     $value = $values->{$this->field_alias};
85     return $this->dateFormatter->formatInterval($value, isset($this->options['granularity']) ? $this->options['granularity'] : 2);
86   }
87
88 }