Lines 100.00% 8 / 8
Functions and Methods 100.00% 5 / 5
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
PreviousStateRule 100.00% 8 / 8 100.00% 5 / 5 9 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 excludingUnavailable 100.00% 1 / 1 100.00% 1 / 1 1
 allowingAny 100.00% 1 / 1 100.00% 1 / 1 1
 allowingOnly 100.00% 1 / 1 100.00% 1 / 1 1
 permits 100.00% 4 / 4 100.00% 1 / 1 5
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Support\Stream;
6
7use Stewart\Contracts\State\StateChange;
8
9/** @internal */
10final readonly class PreviousStateRule
11{
12    /** @param list<string>|null $allowedStates */
13    private function __construct(
14        private ?array $allowedStates,
15        private bool $requiresKnownPrevious,
16    ) {}
17
18    public static function excludingUnavailable(): self
19    {
20        return new self(null, true);
21    }
22
23    public static function allowingAny(): self
24    {
25        return new self(null, false);
26    }
27
28    public static function allowingOnly(string ...$states): self
29    {
30        return new self(array_values($states), false);
31    }
32
33    public function permits(StateChange $change): bool
34    {
35        $previous = $change->from;
36
37        if ($this->allowedStates !== null) {
38            return $previous !== null && \in_array($previous->state, $this->allowedStates, true);
39        }
40
41        return !$this->requiresKnownPrevious || ($previous !== null && !$previous->isUnavailable());
42    }
43}