Last active
January 21, 2019 07:51
-
-
Save bcremer/376e4fbec425d6fb213eda826aa9c459 to your computer and use it in GitHub Desktop.
Thread on Twitter: https://twitter.com/benjamincremer/status/1086327888717041664
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// $clock implements Clock | |
// interface Clock | |
// { | |
// public function now() : DateTimeImmutable; | |
// } | |
// setup | |
$startDate = Date::fromString('2019-01-04'); | |
// variant 1A) Tell, Don't Ask | |
$isNotPast = $startDate->isNotInThePast($clock); | |
// variant 1B) | |
$isNotPast = (new IsNotInThePastValidator($clock)) | |
->isNotInThePast($startDate); | |
// ==== Add Offset Support, Check if given Date is today in another Timezone | |
// Example: It's 2019-01-04 08:00 in UTC | |
// User Submitted 2019-01-03 as Checkindate | |
// Check if 2019-01-03 is still today for an earlier timezone. | |
// setup | |
$startDate = Date::fromString('2019-01-04'); | |
$offset = '-0800'; | |
// variant 2A) Tell, Don't Ask | |
$isNotPast = $startDate->isNotInThePast($clock, $offset); | |
// via @matthiasnoback | |
$isNotPast = $startDate->isNotInThePast($clock->now(), $offset); | |
// via @mathiasverraes https://twitter.com/mathiasverraes/status/1086356193847721990 | |
$clock = new Clock($earliestTimezone) | |
!$clock->isInPast($someDate) | |
$clock->now()->isLaterThan($someDate) | |
// via @rosstuck https://twitter.com/rosstuck/status/1086364229119152128 | |
SearchDate::basedOn($userInput, $clock) | |
// variant 2B) | |
$isNotPast = (new IsNotInThePastValidator($clock, $offset)) | |
->isNotInThePast($startDate); | |
// variant 2C) | |
$isNotPast = (new IsNotInThePastValidator($clock)) | |
->isNotInThePast($startDate, $offset); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class IsNotInThePastValidator | |
{ | |
public function isNotInThePast(Clock $clock, string $offset): bool | |
{ | |
$today = self::fromDateTime( | |
$clock->now()->setTimezone(new \DateTimeZone($offset) | |
); | |
return $this->equals($today) || $this->isLaterThan($today); | |
} | |
} | |
class IsNotInThePastValidator | |
{ | |
public function __construct(Clock $clock, string $offset) | |
{ | |
$this->clock = $clock; | |
$this->timezone = new \DateTimeZone($offset); | |
} | |
public function isNotInThePast(Date $date): bool | |
{ | |
$today = Date::fromDateTime( | |
$this->clock->now()->setTimezone($this->timezone) | |
); | |
return $date->equals($today) || $date->isLaterThan($today); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment