Home > Net >  Extend DateTimeImmutable to enforce "only midnight datetimes"
Extend DateTimeImmutable to enforce "only midnight datetimes"

Time:08-13

In PHP, I'm trying to extend \DateTimeImmutable to ensure that my custom type always has a time of midnight.

I want to do this to prevent bugs caused by using a non-midnight datetime when I must use a midnight datetime.

Here's my code:

class MyDateTimeImmutableMidnightUTC extends \DateTimeImmutable {
  public function __construct(string $datetime) {
    $object = new \DateTimeImmutable($datetime, new \DateTimeZone('UTC'));
    $time = $object->format('H:i:s');
    if ($time !== '00:00:00') {
      throw new MyOutOfBoundsException("Midnight UTC datetime called with a non-midnight time! datetime: $datetime time: $time");
    }
    parent::__construct($datetime, new \DateTimeZone('UTC'));
  }
}

This code works but I am creating two identical objects-- one to test if the time is midnight, and then another to actually use via the parent constructor. This duplication seems like a code smell to me; how can I override \DateTimeImmutable to enforce a midnight time without duplicated objects?

CodePudding user response:

You can just call the parent constructor first and check the time with $this:

class MyDateTimeImmutableMidnightUTC extends \DateTimeImmutable {
    public function __construct(string $datetime) {
        parent::__construct($datetime, new \DateTimeZone('UTC'));
        $time = $this->format('H:i:s');
        if ($time !== '00:00:00') {
            throw new MyOutOfBoundsException("Midnight UTC datetime called with a non-midnight time! datetime: $datetime time: $time");
        }
    }
}

https://3v4l.org/UdMcb

  • Related