Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
6 / 6
CRAP
100.00% covered (success)
100.00%
1 / 1
CleanSiteDirectory
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
6 / 6
9
100.00% covered (success)
100.00%
1 / 1
 handle
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 printFinishMessage
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isItSafeToCleanOutputDirectory
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 isOutputDirectoryWhitelisted
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 askIfUnsafeDirectoryShouldBeEmptied
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 safeOutputDirectories
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Hyde\Framework\Actions\PreBuildTasks;
6
7use Hyde\Hyde;
8use Hyde\Facades\Config;
9use Hyde\Facades\Filesystem;
10use Hyde\Framework\Features\BuildTasks\PreBuildTask;
11
12use function basename;
13use function in_array;
14use function sprintf;
15
16class 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            Filesystem::unlink(Filesystem::findFiles(Hyde::sitePath(), ['html', 'json'])->all());
24            Filesystem::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            Hyde::getOutputDirectory()
55        ));
56    }
57
58    /** @return array<string> */
59    protected function safeOutputDirectories(): array
60    {
61        /** @var array<string> $directories */
62        $directories = Config::getArray('hyde.safe_output_directories', ['_site', 'docs', 'build']);
63
64        return $directories;
65    }
66}