Last active
February 3, 2021 13:58
-
-
Save guillemcanal/8e07b4a02089c3449797c0690b4be09f to your computer and use it in GitHub Desktop.
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 | |
interface TimeProvider | |
{ | |
public function now(): \DateTimeImmutable; | |
} | |
class SystemTime implements TimeProvider | |
{ | |
public function now(): \DateTimeImmutable | |
{ | |
return new \DateTimeImmutable(); | |
} | |
} | |
class FakeTime implements TimeProvider | |
{ | |
public function __construct( | |
private \DateTimeImmutable $nowDate | |
){} | |
public function now(): \DateTimeImmutable | |
{ | |
return $this->nowDate; | |
} | |
} | |
class HappyFridayVoucher | |
{ | |
public function __construct( | |
private ?TimeProvider $timeProvider = null | |
){ | |
$this->timeProvider = $timeProvider ?? new SystemTime(); | |
} | |
public function valid(): bool | |
{ | |
return $this->timeProvider->now()->format('l') === 'Friday'; | |
} | |
} | |
$voucher = new HappyFridayVoucher( | |
new FakeTime( | |
new \DateTimeImmutable('friday') | |
) | |
); | |
$voucher->valid(); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment