Passed
Push — master ( 08eef1...8a66fd )
by Caen
03:23 queued 13s
created

BuildTask::getDescription()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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