DurationIso8601.php 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. namespace Drupal\Core\TypedData\Plugin\DataType;
  3. use Drupal\Core\TypedData\Type\DurationInterface;
  4. /**
  5. * The duration ISO8601 data type.
  6. *
  7. * The plain value of this data type is a ISO8601 duration string.
  8. *
  9. * @DataType(
  10. * id = "duration_iso8601",
  11. * label = @Translation("Duration")
  12. * )
  13. */
  14. class DurationIso8601 extends StringData implements DurationInterface {
  15. /**
  16. * {@inheritdoc}
  17. */
  18. public function getDuration() {
  19. if ($this->value) {
  20. // @todo: Add support for negative intervals on top of the DateInterval
  21. // constructor.
  22. return new \DateInterval($this->value);
  23. }
  24. }
  25. /**
  26. * {@inheritdoc}
  27. */
  28. public function setDuration(\DateInterval $duration, $notify = TRUE) {
  29. // Generate an ISO 8601 formatted string as supported by
  30. // DateInterval::__construct() and setValue().
  31. $this->value = $duration->format('%rP%yY%mM%dDT%hH%mM%sS');
  32. // Notify the parent of any changes.
  33. if ($notify && isset($this->parent)) {
  34. $this->parent->onChange($this->name);
  35. }
  36. }
  37. }