Passed
Push — master ( c8fc2a...b4ea14 )
by Caen
03:10 queued 12s
created

AbstractBuildTask   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 74
rs 10
c 0
b 0
f 0
wmc 10

9 Methods

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