summaryrefslogtreecommitdiffstats
path: root/core/lib/Drupal/Core/TypedData/Plugin/DataType/DurationIso8601.php
blob: 8b3899acf786b7facbc9cc415ed33af0566aa46b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php

namespace Drupal\Core\TypedData\Plugin\DataType;

use Drupal\Core\TypedData\Type\DurationInterface;

/**
 * The duration ISO8601 data type.
 *
 * The plain value of this data type is a ISO8601 duration string.
 *
 * @DataType(
 *   id = "duration_iso8601",
 *   label = @Translation("Duration")
 * )
 */
class DurationIso8601 extends StringData implements DurationInterface {

  /**
   * {@inheritdoc}
   */
  public function getDuration() {
    if ($this->value) {
      // @todo: Add support for negative intervals on top of the DateInterval
      // constructor.
      return new \DateInterval($this->value);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function setDuration(\DateInterval $duration, $notify = TRUE) {
    // Generate an ISO 8601 formatted string as supported by
    // DateInterval::__construct() and setValue().
    $this->value = $duration->format('%rP%yY%mM%dDT%hH%mM%sS');
    // Notify the parent of any changes.
    if ($notify && isset($this->parent)) {
      $this->parent->onChange($this->name);
    }
  }

}