mirror of
https://github.com/beste/clock.git
synced 2026-10-17 19:27:35 +00:00
Harden WrappingClock validation
Wrapping an object should not call it just to validate the return value. Instead, we check the method signature when the object is wrapped, and the return value at runtime. We were implicitly checking it already with the `assert()` calls.
This commit is contained in:
+19
-11
@@ -4,9 +4,12 @@ declare(strict_types=1);
|
||||
|
||||
namespace Beste\Clock;
|
||||
|
||||
use Closure;
|
||||
use DateTimeImmutable;
|
||||
use InvalidArgumentException;
|
||||
use Psr\Clock\ClockInterface;
|
||||
use ReflectionMethod;
|
||||
use UnexpectedValueException;
|
||||
|
||||
final class WrappingClock implements ClockInterface
|
||||
{
|
||||
@@ -17,6 +20,9 @@ final class WrappingClock implements ClockInterface
|
||||
$this->wrappedClock = $wrappedClock;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidArgumentException when the given object doesn't behave like a clock.
|
||||
*/
|
||||
public static function wrapping(object $clock): self
|
||||
{
|
||||
if ($clock instanceof ClockInterface) {
|
||||
@@ -24,28 +30,30 @@ final class WrappingClock implements ClockInterface
|
||||
}
|
||||
|
||||
if (!method_exists($clock, 'now')) {
|
||||
throw new InvalidArgumentException('$clock must implement StellaMaris\Clock\ClockInterface or have a now() method');
|
||||
throw new InvalidArgumentException('$clock must implement Psr\Clock\ClockInterface or have a now() method');
|
||||
}
|
||||
|
||||
if (!($clock->now() instanceof DateTimeImmutable)) {
|
||||
throw new InvalidArgumentException('$clock->now() must return a DateTimeImmutable');
|
||||
$method = new ReflectionMethod($clock, 'now');
|
||||
|
||||
if (!$method->isPublic() || $method->getNumberOfRequiredParameters() > 0) {
|
||||
throw new InvalidArgumentException('$clock->now() must be public and accept no required parameters');
|
||||
}
|
||||
|
||||
$wrappedClock = new class($clock) implements ClockInterface {
|
||||
private object $clock;
|
||||
$wrappedClock = new class($method->getClosure($clock)) implements ClockInterface {
|
||||
private Closure $now;
|
||||
|
||||
public function __construct(object $clock)
|
||||
public function __construct(Closure $now)
|
||||
{
|
||||
$this->clock = $clock;
|
||||
$this->now = $now;
|
||||
}
|
||||
|
||||
public function now(): DateTimeImmutable
|
||||
{
|
||||
assert(method_exists($this->clock, 'now'));
|
||||
$now = ($this->now)();
|
||||
|
||||
$now = $this->clock->now();
|
||||
|
||||
assert($now instanceof DateTimeImmutable);
|
||||
if (!$now instanceof DateTimeImmutable) {
|
||||
throw new UnexpectedValueException('$clock->now() must return a DateTimeImmutable');
|
||||
}
|
||||
|
||||
return $now;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user