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

BuildTaskService::run()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Hyde\Framework\Services;
4
5
use Hyde\Framework\Contracts\BuildTaskContract;
6
use Hyde\Framework\Hyde;
7
use Illuminate\Console\OutputStyle;
8
9
/**
10
 * This service manages the build tasks that are called after the site has been compiled using the build command.
11
 *
12
 * @see \Hyde\Framework\Testing\Feature\Services\BuildTaskServiceTest
13
 */
14
class BuildTaskService
15
{
16
    /**
17
     * Information for package developers: This offers a hook for packages to add custom build tasks.
18
     * Make sure to add the fully qualified class name to the array and doing so by merging the array, not overwriting it.
19
     */
20
    public static array $postBuildTasks = [];
21
22
    protected ?OutputStyle $output;
23
24
    public function __construct(?OutputStyle $output = null)
25
    {
26
        $this->output = $output;
27
    }
28
29
    public function runPostBuildTasks(): void
30
    {
31
        foreach ($this->getPostBuildTasks() as $task) {
32
            $this->run($task);
33
        }
34
    }
35
36
    public function getPostBuildTasks(): array
37
    {
38
        return array_unique(
39
            array_merge(
40
                config('hyde.post_build_tasks', []),
41
                static::findTasksInAppDirectory(),
42
                static::$postBuildTasks
43
            )
44
        );
45
    }
46
47
    public static function findTasksInAppDirectory(): array
48
    {
49
        $tasks = [];
50
51
        foreach (glob(Hyde::path('app/Actions/*BuildTask.php')) as $file) {
52
            $tasks[] = str_replace(
53
                [Hyde::path('app'), '.php', '/'],
54
                ['App', '', '\\'],
55
                $file
56
            );
57
        }
58
59
        return $tasks;
60
    }
61
62
    public function run(string $task): static
63
    {
64
        $this->runTask(new $task($this->output));
65
66
        return $this;
67
    }
68
69
    public function runIf(string $task, callable|bool $condition): static
70
    {
71
        if (is_bool($condition) ? $condition : $condition()) {
72
            $this->run($task);
73
        }
74
75
        return $this;
76
    }
77
78
    protected function runTask(BuildTaskContract $task): static
79
    {
80
        $task->handle();
81
82
        return $this;
83
    }
84
}
85