Passed
Push — master ( 974934...e1eba7 )
by Caen
05:38 queued 14s
created

LiveEditController::handle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
rs 10
c 4
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Hyde\RealtimeCompiler\Http;
6
7
use Hyde\Hyde;
8
use Hyde\Support\Models\Route;
9
use Hyde\Support\Models\Redirect;
10
use Hyde\Markdown\Models\Markdown;
11
use Illuminate\Support\Facades\Blade;
12
use Hyde\Pages\Concerns\BaseMarkdownPage;
13
14
/**
15
 * @internal This class is not intended to be edited outside the Hyde Realtime Compiler.
16
 */
17
class LiveEditController extends BaseController
18
{
19
    protected bool $withConsoleOutput = true;
20
    protected bool $withSession = true;
21
22
    public function handle(): HtmlResponse
23
    {
24
        $this->authorizePostRequest();
25
26
        return $this->handleRequest();
27
    }
28
29
    protected function handleRequest(): HtmlResponse
30
    {
31
        $pagePath = $this->request->data['page'] ?? $this->abort(400, 'Must provide page path');
32
        $content = $this->request->data['markdown'] ?? $this->abort(400, 'Must provide content');
33
34
        $page = Hyde::pages()->getPage($pagePath);
35
36
        if (! $page instanceof BaseMarkdownPage) {
37
            $this->abort(400, 'Page is not a markdown page');
38
        }
39
40
        $page->markdown = new Markdown($content);
41
        $page->save();
42
43
        $this->writeToConsole("Updated file '$pagePath'", 'hyde@live-edit');
44
45
        return $this->redirectToPage($page->getRoute());
46
    }
47
48
    public static function enabled(): bool
49
    {
50
        return config('hyde.server.live_edit', true);
51
    }
52
53
    public static function injectLiveEditScript(string $html): string
54
    {
55
        session_start();
56
57
        return str_replace('</body>', sprintf('%s</body>', Blade::render(file_get_contents(__DIR__.'/../../resources/live-edit.blade.php'), [
58
            'styles' => file_get_contents(__DIR__.'/../../resources/live-edit.css'),
59
            'scripts' => file_get_contents(__DIR__.'/../../resources/live-edit.js'),
60
            'csrfToken' => self::generateCSRFToken(),
61
        ])), $html);
62
    }
63
64
    protected function redirectToPage(Route $route): HtmlResponse
65
    {
66
        $redirectPage = new Redirect($this->request->path, "../$route");
67
        Hyde::shareViewData($redirectPage);
68
69
        return (new HtmlResponse(303, 'See Other', [
70
            'body' => $redirectPage->compile(),
71
        ]))->withHeaders([
72
            'Location' => $route,
73
        ]);
74
    }
75
}
76