Passed
Push — master ( 99cab5...2782fc )
by Caen
04:06 queued 13s
created

CleanSiteDirectory::handle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 5
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Hyde\Framework\Actions\PreBuildTasks;
6
7
use Hyde\Hyde;
8
use Hyde\Facades\Site;
9
use Hyde\Framework\Features\BuildTasks\PreBuildTask;
10
use Illuminate\Support\Facades\File;
11
use function basename;
12
use function config;
13
use function in_array;
14
use function sprintf;
15
16
class CleanSiteDirectory extends PreBuildTask
17
{
18
    protected static string $message = 'Removing all files from build directory';
19
20
    public function handle(): void
21
    {
22
        if ($this->isItSafeToCleanOutputDirectory()) {
23
            array_map('unlink', glob(Hyde::sitePath('*.{html,json}'), GLOB_BRACE));
24
            File::cleanDirectory(Hyde::siteMediaPath());
25
        }
26
    }
27
28
    public function printFinishMessage(): void
29
    {
30
        $this->newLine();
31
    }
32
33
    protected function isItSafeToCleanOutputDirectory(): bool
34
    {
35
        if (! $this->isOutputDirectoryWhitelisted() && ! $this->askIfUnsafeDirectoryShouldBeEmptied()) {
36
            $this->info('Output directory will not be emptied.');
37
38
            return false;
39
        }
40
41
        return true;
42
    }
43
44
    protected function isOutputDirectoryWhitelisted(): bool
45
    {
46
        return in_array(basename(Hyde::sitePath()), $this->safeOutputDirectories());
47
    }
48
49
    protected function askIfUnsafeDirectoryShouldBeEmptied(): bool
50
    {
51
        return $this->confirm(sprintf(
52
            'The configured output directory (%s) is potentially unsafe to empty. '.
53
            'Are you sure you want to continue?',
54
            Site::getOutputDirectory()
55
        ));
56
    }
57
58
    protected function safeOutputDirectories(): array
59
    {
60
        return config('hyde.safe_output_directories', ['_site', 'docs', 'build']);
61
    }
62
}
63