igfs/kernel/CgView.php
2024-12-18 12:46:57 +03:00

106 lines
2.2 KiB
PHP

<?php
namespace kernel;
class CgView
{
public string $viewPath = '';
public string $layoutPath = '';
public array $varToLayout = [];
public bool|string $layout = false;
protected array $metaArr = [];
public function __construct()
{
}
public function render(string $view, array $data = []): void
{
$content = $this->createContent($view, $data);
echo $content;
}
public function fetch(string $view, array $data = []): false|string
{
$content = $this->createContent($view, $data);
return $content;
}
public function addVarToLayout($key, $value): void
{
$this->varToLayout[$key] = $value;
}
public function setTitle(string $title): void
{
$this->addVarToLayout('title', $title);
}
public function setMeta(array $meta): void
{
foreach ($meta as $key => $value){
$this->metaArr[$key] = $value;
}
}
public function getMeta(): string
{
$meta = "";
foreach ($this->metaArr as $key => $value){
$meta .= "<meta name='$key' content='$value'>";
}
return $meta;
}
private function createContent(string $viewFile, array $data = []): false|string
{
ob_start();
$view = $this;
foreach ($data as $key => $datum) {
${"$key"} = $datum;
}
include($this->viewPath . $viewFile);
$content = ob_get_contents();
ob_end_clean();
ob_start();
$file_content = $content;
if (!isset($title)){
$title = "No Title";
}
$layoutPath = $this->viewPath;
if ($this->layout) {
if ($this->layoutPath !== '') {
$layoutPath = $this->layoutPath;
}
if (file_exists($layoutPath . $this->layout)) {
if ($this->varToLayout){
foreach ($this->varToLayout as $key => $datum) {
${"$key"} = $datum;
}
}
include($layoutPath . $this->layout);
$file_content = ob_get_contents();
}
}
ob_end_clean();
return $file_content;
}
}