summaryrefslogtreecommitdiff
path: root/tests/Utils/TestCallable.php
blob: 526ddf4070d49e3a7b818f3a6f738c7cc4a62ed8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php

declare(strict_types=1);

namespace Lightscale\Router\Test\Utils;

use Closure;
use PHPUnit\Framework\Assert;

class TestCallable
{
    private Closure $cb;

    /** @var TestCall[] */
    private array $calls;

    final public function __construct(callable $cb)
    {
        $this->cb = Closure::fromCallable($cb);
    }

    public static function make(callable $cb): static
    {
        return new static($cb);
    }

    public function __invoke(mixed ...$args): mixed
    {
        $call = new TestCall(
            args: $args,
            return: ($this->cb)(...$args),
        );
        $this->calls[] = $call;

        return $call->return;
    }

    public function getCallCount(): int
    {
        return count($this->calls);
    }

    /** @return TestCall[] */
    public function getCalls(): array
    {
        return $this->calls;
    }

    public function getLastCall(): ?TestCall
    {
        return $this->calls[$this->getCallCount() - 1] ?? null;
    }

    public function assertIsCalled(): void
    {
        Assert::assertGreaterThan(0, $this->getCallCount(), 'Not been called');
    }

    public function assertNotCalled(): void
    {
        Assert::assertSame(0, $this->getCallCount());
    }

    public function assertCalledTimes(int $amount): void
    {
        Assert::assertSame($amount, $this->getCallCount());
    }
}