时钟、系统和随机接口

dev-main 2023-05-12 10:04 UTC

This package is auto-updated.

Last update: 2024-09-12 14:30:53 UTC


README

非常轻量且无偏见的一套接口和实现,旨在伪造或生成某些PHP原生函数不可预测的返回值。

安装

composer require holistic-agency/frozen:dev-main

使用

ClockInterface

时钟的now()方法返回一个新的DateTimeImmutable对象,其当前时间根据php的date.timezone设置。

FrozenClock的now()方法返回构造函数传入的DateTimeInterface对象。

// 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

随机数的random()方法返回一个由mt_rand()调用的整数。

FrozenRandomizer的random()方法返回构造函数传入的值。

$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

示例

// 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
    }
}