Lines 85.71% 12 / 14
Functions and Methods 84.61% 11 / 13
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
StateChange 85.71% 12 / 14 84.61% 11 / 13 17.84 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 fromCurrentState 100.00% 1 / 1 100.00% 1 / 1 1
 withFrom 100.00% 1 / 1 100.00% 1 / 1 1
 isReconstructed 0.00% 0 / 1 0.00% 0 / 1 2
 isInitial 100.00% 1 / 1 100.00% 1 / 1 1
 isNew 100.00% 1 / 1 100.00% 1 / 1 2
 isRemoved 100.00% 1 / 1 100.00% 1 / 1 1
 hasStateChanged 100.00% 1 / 1 100.00% 1 / 1 1
 changedTo 100.00% 1 / 1 100.00% 1 / 1 2
 changedFrom 100.00% 1 / 1 100.00% 1 / 1 2
 findCausingContext 100.00% 1 / 1 100.00% 1 / 1 1
 wasCausedBy 100.00% 2 / 2 100.00% 1 / 1 2
 getDomain 0.00% 0 / 1 0.00% 0 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Contracts\State;
6
7use Stewart\Contracts\Entity\EntityId;
8use Stewart\Contracts\Time\Instant;
9
10final readonly class StateChange
11{
12    public function __construct(
13        public EntityId $entityId,
14        public ?EntityState $from,
15        public ?EntityState $to,
16        public ?Instant $firedAt = null,
17        public ?EventContext $context = null,
18        public StateChangeOrigin $origin = StateChangeOrigin::Live,
19    ) {}
20
21    public static function fromCurrentState(EntityState $state): self
22    {
23        return new self($state->entityId, $state, $state, origin: StateChangeOrigin::Initial);
24    }
25
26    public function withFrom(?EntityState $from): self
27    {
28        return new self($this->entityId, $from, $this->to, $this->firedAt, $this->context, $this->origin);
29    }
30
31    public function isReconstructed(): bool
32    {
33        return $this->origin === StateChangeOrigin::Resync;
34    }
35
36    public function isInitial(): bool
37    {
38        return $this->origin === StateChangeOrigin::Initial;
39    }
40
41    public function isNew(): bool
42    {
43        return $this->from === null && $this->to !== null;
44    }
45
46    public function isRemoved(): bool
47    {
48        return $this->to === null;
49    }
50
51    public function hasStateChanged(): bool
52    {
53        return $this->from?->state !== $this->to?->state;
54    }
55
56    public function changedTo(string $state): bool
57    {
58        return $this->to?->state === $state && $this->from?->state !== $state;
59    }
60
61    public function changedFrom(string $state): bool
62    {
63        return $this->from?->state === $state && $this->to?->state !== $state;
64    }
65
66    public function findCausingContext(): ?EventContext
67    {
68        return $this->context ?? $this->to?->context;
69    }
70
71    public function wasCausedBy(EventContext $context): bool
72    {
73        $causing = $this->findCausingContext();
74
75        return $causing !== null && $context->isSameOrParentOf($causing);
76    }
77
78    public function getDomain(): string
79    {
80        return $this->entityId->domain;
81    }
82}