PHP code example of snicco / testable-clock

1. Go to this page and download the library: Download snicco/testable-clock library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

snicco / testable-clock example snippets


use Snicco\Component\TestableClock\Clock;
use Snicco\Component\TestableClock\SystemClock;
use Snicco\Component\TestableClock\TestClock;

class IsTrialExpired {
    
    private  Clock $clock;
    
    public function __construct(Clock $clock) {
        $this->clock = $clock;
    }
        
    public function __invoke(object $trial) {
        return $trial->expiresAt > $this->clock->currentTimestamp();
    }
        
}

// In production code
$clock = SystemClock::fromUTC();

// or
$clock = new SystemClock(new DateTimeZone('Europe/Berlin'));

$is_trial_expired = new IsTrialExpired($clock)

// In test code
$test_clock = new TestClock();

$is_trial_expired = new IsTrialExpired($test_clock)

use Snicco\Component\TestableClock\TestClock;

$clock = new TestClock();

$time_0 = $clock->currentTimestamp();

var_dump(time() === $time_0); // true

sleep(10);

$time_01 = $clock->currentTimestamp();

var_dump($time_01 === $time_0); // true
var_dump(time() === $time_01); // false

$clock->travelIntoFuture(10);

$time_02 = $clock->currentTimestamp();

var_dump(time() === $time_02); // true

$time_03 = $clock->travelIntoPast(10);

var_dump($time_03 === $time_01); // true