holistic-agency / frozen
clock, system and random interfaces
dev-main
2023-05-12 10:04 UTC
Requires (Dev)
- phpstan/phpstan: ^1.4
- phpunit/phpunit: ^9.5
Provides
This package is auto-updated.
Last update: 2024-07-12 14:07:56 UTC
README
Very light and agnostic set of interfaces and implementations designed to fake or render unpredictable return values of some PHP native functions.
Installation
composer require holistic-agency/frozen:dev-main
Usage
ClockInterface
The Clock now()
method returns a new DateTimeImmutable object
with the current time acccording to the php date.timezone
setting.
The FrozenClock now()
method returns the DateTimeInterface object
passed to the constructor.
// src/MyClass.php use HolisticAgency\Frozen\ClockInterface; class MyClass { public function myMethod(ClockInterface $clock) { // some code ... $now = $clock->now()->format('Y-m-d H:i:s T'); // some code ... } } // src/Elsewhere.php use HolisticAgency\Frozen\Clock; $myClass = new Myclass(); $myClass->myMethod(new Clock()); // tests/MyClassTest.php use HolisticAgency\Frozen\FrozenClock; class MyClassTest { public function testMyMethod() { // Given $myTestClass = new MyClass(); $frozen = new FrozenClock(new DateTimeImmutable('2022-02-05 16:32:29 CET')); // When $actual = $myTestClass->myMethod($frozen); // Then // assert what you need // knowing $now is equal to '2022-02-05 16:32:29 CET' // inside myMethod() } }
RandomizerInterface
The Randomizer random()
method returns an integer from a mt_rand()
call.
The FrozenRandomizer random()
method returns the value passed to the constructor.
$random = new Randomizer(); $unknon = $random->random(); // an integer between 0 and PHP_INT_MAX included $random = new Randomizer(1, 6); $dieType = 'D' . strval($random->max); // D6 $dieRoll = $random->random() ; // an integer between 1 and 6 included if ($dieRoll == $this->min) { echo 'You loose.'; // if 1 is rolled } $guesser = new FrozenRandomizer(10); $cheater = $guesser->random(); // Always 10
SystemInterface
PlatformInterface
NetworkInterface
Example
// src/MyNetwork.php use HolisticAgency\Frozen\NetworkInterface; class MyNetwork { public checkIfRemoteIsAvailable(NetworkInterface $system, string $remote): bool { return $system->resolve($remote) != ''; } } // tests/MyNetworkTest.php use HolisticAgency\Frozen\FrozenNetwork; class MyNetworkTest { public function testCheckIfRemoteIsAvailable() { // Given $myTestClass = new MyNetwork(); $frozen = new FrozenNetwork( 'production.local', '192.168.1.10', 'app.my.org', ['proxy.inside.local' => '10.10.0.10'], ); // When $actual1 = $myTestClass->checkIfRemoteIsAvailable($frozen, 'api.outside.net'); $actual2 = $myTestClass->checkIfRemoteIsAvailable($frozen, 'proxy.inside.local'); // Then // $actual1 is false // $actual2 is tue } }