1 | <?php |
||
2 | |||
3 | namespace Zenstruck\ScheduleBundle\Schedule; |
||
4 | |||
5 | use Symfony\Component\Console\Helper\Helper; |
||
6 | |||
7 | /** |
||
8 | * @author Kevin Bond <[email protected]> |
||
9 | */ |
||
10 | abstract class RunContext |
||
11 | { |
||
12 | /** @var \DateTimeImmutable */ |
||
13 | private $startTime; |
||
14 | |||
15 | /** @var int|null */ |
||
16 | 88 | private $duration; |
|
17 | |||
18 | 88 | /** @var int|null */ |
|
19 | 88 | private $memory; |
|
20 | |||
21 | public function __construct() |
||
22 | { |
||
23 | 88 | $this->startTime = new \DateTimeImmutable('now'); |
|
24 | } |
||
25 | 88 | ||
26 | abstract public function __toString(): string; |
||
27 | |||
28 | 78 | final public function getStartTime(): \DateTimeImmutable |
|
29 | { |
||
30 | 78 | return $this->startTime; |
|
31 | } |
||
32 | |||
33 | 13 | final public function hasRun(): bool |
|
34 | { |
||
35 | 13 | return null !== $this->memory; |
|
36 | } |
||
37 | 13 | ||
38 | final public function getDuration(): int |
||
39 | { |
||
40 | 13 | $this->ensureHasRun(); |
|
41 | |||
42 | 13 | return $this->duration; |
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
43 | } |
||
44 | |||
45 | 13 | final public function getFormattedDuration(): string |
|
46 | { |
||
47 | 13 | return Helper::formatTime($this->getDuration()); |
|
0 ignored issues
–
show
|
|||
48 | } |
||
49 | 13 | ||
50 | final public function getMemory(): int |
||
51 | { |
||
52 | 13 | $this->ensureHasRun(); |
|
53 | |||
54 | 13 | return $this->memory; |
|
0 ignored issues
–
show
|
|||
55 | } |
||
56 | |||
57 | 73 | final public function getFormattedMemory(): string |
|
58 | { |
||
59 | 73 | return Helper::formatMemory($this->getMemory()); |
|
60 | 73 | } |
|
61 | 73 | ||
62 | final protected function markAsRun(int $memory): void |
||
63 | { |
||
64 | $this->duration = \time() - $this->getStartTime()->getTimestamp(); |
||
65 | $this->memory = $memory; |
||
66 | 74 | } |
|
67 | |||
68 | 74 | /** |
|
69 | 2 | * @throws \LogicException if has not yet run |
|
70 | */ |
||
71 | 72 | final protected function ensureHasRun(): void |
|
72 | { |
||
73 | if (!$this->hasRun()) { |
||
74 | throw new \LogicException("\"{$this}\" has not yet run."); |
||
75 | } |
||
76 | } |
||
77 | } |
||
78 |