| 1 |
<?php |
| 2 |
|
| 3 |
namespace Safe; |
| 4 |
|
| 5 |
use DateInterval; |
| 6 |
use DateTimeInterface; |
| 7 |
use DateTimeZone; |
| 8 |
use Safe\Exceptions\DatetimeException; |
| 9 |
|
| 10 |
/** this class implements a safe version of the Datetime class */ |
| 11 |
class DateTime extends \DateTime |
| 12 |
{ |
| 13 |
//switch from regular datetime to safe version |
| 14 |
private static function createFromRegular(\DateTime $datetime): self |
| 15 |
{ |
| 16 |
return new self($datetime->format('Y-m-d H:i:s.u'), $datetime->getTimezone()); |
| 17 |
} |
| 18 |
|
| 19 |
/** |
| 20 |
* @param string $format |
| 21 |
* @param string $time |
| 22 |
* @param DateTimeZone|null $timezone |
| 23 |
* @throws DatetimeException |
| 24 |
*/ |
| 25 |
public static function createFromFormat($format, $time, $timezone = null): self |
| 26 |
{ |
| 27 |
$datetime = parent::createFromFormat($format, $time, $timezone); |
| 28 |
if ($datetime === false) { |
| 29 |
throw DatetimeException::createFromPhpError(); |
| 30 |
} |
| 31 |
return self::createFromRegular($datetime); |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* @param DateTimeInterface $datetime2 The date to compare to. |
| 36 |
* @param boolean $absolute [optional] Whether to return absolute difference. |
| 37 |
* @return DateInterval The DateInterval object representing the difference between the two dates. |
| 38 |
* @throws DatetimeException |
| 39 |
*/ |
| 40 |
public function diff($datetime2, $absolute = false): DateInterval |
| 41 |
{ |
| 42 |
/** @var \DateInterval|false $result */ |
| 43 |
$result = parent::diff($datetime2, $absolute); |
| 44 |
if ($result === false) { |
| 45 |
throw DatetimeException::createFromPhpError(); |
| 46 |
} |
| 47 |
return $result; |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* @param string $modify A date/time string. Valid formats are explained in <a href="https://secure.php.net/manual/en/datetime.formats.php">Date and Time Formats</a>. |
| 52 |
* @return DateTime Returns the DateTime object for method chaining. |
| 53 |
* @throws DatetimeException |
| 54 |
*/ |
| 55 |
public function modify($modify): self |
| 56 |
{ |
| 57 |
/** @var DateTime|false $result */ |
| 58 |
$result = parent::modify($modify); |
| 59 |
if ($result === false) { |
| 60 |
throw DatetimeException::createFromPhpError(); |
| 61 |
} |
| 62 |
return $result; |
| 63 |
} |
| 64 |
|
| 65 |
/** |
| 66 |
* @param int $year |
| 67 |
* @param int $month |
| 68 |
* @param int $day |
| 69 |
* @return DateTime |
| 70 |
* @throws DatetimeException |
| 71 |
*/ |
| 72 |
public function setDate($year, $month, $day): self |
| 73 |
{ |
| 74 |
/** @var DateTime|false $result */ |
| 75 |
$result = parent::setDate($year, $month, $day); |
| 76 |
if ($result === false) { |
| 77 |
throw DatetimeException::createFromPhpError(); |
| 78 |
} |
| 79 |
return $result; |
| 80 |
} |
| 81 |
} |
| 82 |
|