web-base/Core/Elements/HtmlDocument.class.php

71 lines
1.7 KiB
PHP
Raw Normal View History

2021-12-08 16:53:43 +01:00
<?php
2022-11-18 18:06:46 +01:00
namespace Core\Elements;
2021-12-08 16:53:43 +01:00
2022-11-18 18:06:46 +01:00
use Core\Objects\Router\Router;
2021-12-08 16:53:43 +01:00
class HtmlDocument extends Document {
2022-08-20 22:17:17 +02:00
protected ?Head $head;
protected ?Body $body;
2021-12-08 16:53:43 +01:00
private ?string $activeView;
2022-06-01 12:28:50 +02:00
public function __construct(Router $router, $headClass, $bodyClass, ?string $view = NULL) {
parent::__construct($router);
2021-12-08 16:53:43 +01:00
$this->head = $headClass ? new $headClass($this) : null;
$this->body = $bodyClass ? new $bodyClass($this) : null;
$this->activeView = $view;
}
2022-08-20 22:17:17 +02:00
public function getHead(): ?Head { return $this->head; }
public function getBody(): ?Body { return $this->body; }
2021-12-08 16:53:43 +01:00
public function getView() : ?View {
if ($this->activeView === null) {
return null;
}
$view = parseClass($this->activeView);
$file = getClassPath($view);
if (!file_exists($file) || !is_subclass_of($view, View::class)) {
2021-12-08 16:53:43 +01:00
return null;
}
return new $view($this);
}
public function getRequestedView(): string {
return $this->activeView;
}
2022-06-01 12:28:50 +02:00
function getCode(array $params = []): string {
2021-12-08 16:53:43 +01:00
// generate body first, so we can modify head
$body = $this->body->getCode();
if ($this->isCSPEnabled()) {
foreach ($this->head->getSources() as $element) {
if ($element instanceof Script || $element instanceof Link) {
$element->setNonce($this->getCSPNonce());
}
}
}
$head = $this->head->getCode();
2022-06-20 19:52:31 +02:00
$lang = $this->getContext()->getLanguage();
2021-12-08 16:53:43 +01:00
$code = "<!DOCTYPE html>";
2022-06-20 19:52:31 +02:00
$code .= html_tag("html", ["lang" => $lang->getShortCode()], $head . $body, false);
return $code;
2021-12-08 16:53:43 +01:00
}
2022-08-20 22:17:17 +02:00
public function getTitle(): string {
if ($this->head !== null) {
return $this->head->getTitle();
}
return "Untitled Document";
}
2021-12-08 16:53:43 +01:00
}