Passed
Push — master ( 1100a1...b83671 )
by Caen
03:15 queued 14s
created

AbstractBuildTask::withExecutionTime()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 5
rs 10
1
<?php
2
3
namespace Hyde\Framework\Contracts;
4
5
use Hyde\Framework\Hyde;
6
use Illuminate\Console\Concerns\InteractsWithIO;
7
use Illuminate\Console\OutputStyle;
8
9
/**
10
 * @see \Hyde\Framework\Testing\Feature\Services\BuildTaskServiceTest
11
 */
12
abstract class AbstractBuildTask implements BuildTaskContract
13
{
14
    use InteractsWithIO;
15
16
    protected static string $description = 'Generic build task';
17
18
    protected float $timeStart;
19
    protected ?int $exitCode = null;
20
21
    public function __construct(?OutputStyle $output = null)
22
    {
23
        $this->output = $output;
24
        $this->timeStart = microtime(true);
25
    }
26
27
    public function handle(): ?int
28
    {
29
        $this->write('<comment>'.$this->getDescription().'...</comment> ');
30
31
        try {
32
            $this->run();
33
            $this->then();
34
        } catch (\Throwable $exception) {
35
            $this->writeln('<error>Failed</error>');
36
            $this->writeln("<error>{$exception->getMessage()}</error>");
37
            $this->exitCode = $exception->getCode();
38
        }
39
40
        $this->write("\n");
41
42
        return $this->exitCode;
43
    }
44
45
    abstract public function run(): void;
46
47
    public function then(): void
48
    {
49
        $this->writeln('<fg=gray>Done in '.$this->getExecutionTime().'</>');
50
    }
51
52
    public function getDescription(): string
53
    {
54
        return static::$description;
55
    }
56
57
    public function getExecutionTime(): string
58
    {
59
        return number_format((microtime(true) - $this->timeStart) * 1000, 2).'ms';
60
    }
61
62
    public function write(string $message): void
63
    {
64
        $this->output?->write($message);
65
    }
66
67
    public function writeln(string $message): void
68
    {
69
        $this->output?->writeln($message);
70
    }
71
72
    public function createdSiteFile(string $path): static
73
    {
74
        $this->write(sprintf("\n > Created <info>%s</info>",
75
            str_replace('\\', '/', Hyde::pathToRelative($path))
76
        ));
77
78
        return $this;
79
    }
80
81
    public function withExecutionTime(): static
82
    {
83
        $this->write(" in {$this->getExecutionTime()}");
84
85
        return $this;
86
    }
87
}
88