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

StaticPageBuilder::save()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Hyde\Framework\Actions;
4
5
use Hyde\Framework\Concerns\AbstractPage;
6
use Hyde\Framework\Concerns\InteractsWithDirectories;
7
use Hyde\Framework\Contracts\PageContract;
8
use Hyde\Framework\Hyde;
9
10
/**
11
 * Converts a Page Model into a static HTML page.
12
 *
13
 * @see \Hyde\Framework\Testing\Feature\StaticPageBuilderTest
14
 */
15
class StaticPageBuilder
16
{
17
    use InteractsWithDirectories;
18
19
    /** @var string The absolute path to the output directory */
20
    public static string $outputPath;
21
22
    /**
23
     * Construct the class.
24
     *
25
     * @param  \Hyde\Framework\Concerns\AbstractPage|PageContract  $page  the Page to compile into HTML
26
     * @param  bool  $selfInvoke  if set to true the class will invoke when constructed
27
     */
28
    public function __construct(protected AbstractPage|PageContract $page, bool $selfInvoke = false)
29
    {
30
        if ($selfInvoke) {
31
            $this->__invoke();
32
        }
33
    }
34
35
    /**
36
     * Run the page builder.
37
     *
38
     * @return string
39
     */
40
    public function __invoke(): string
41
    {
42
        view()->share('page', $this->page);
43
        view()->share('currentPage', $this->page->getCurrentPagePath());
44
        view()->share('currentRoute', $this->page->getRoute());
45
46
        $this->needsDirectory(static::$outputPath);
47
        $this->needsDirectory(dirname(Hyde::getSiteOutputPath($this->page->getOutputPath())));
48
49
        return $this->save($this->page->compile());
50
    }
51
52
    /**
53
     * Save the compiled HTML to file.
54
     *
55
     * @param  string  $contents  to save to the file
56
     * @return string the path to the saved file (since v0.32.x)
57
     */
58
    protected function save(string $contents): string
59
    {
60
        $path = Hyde::getSiteOutputPath($this->page->getOutputPath());
61
62
        file_put_contents($path, $contents);
63
64
        return $path;
65
    }
66
}
67