backend/kernel/CgView.php

106 lines
2.2 KiB
PHP
Raw Permalink Normal View History

2024-07-24 17:22:59 +03:00
<?php
namespace kernel;
class CgView
{
public string $viewPath = '';
2024-09-03 16:29:44 +03:00
public string $layoutPath = '';
public array $varToLayout = [];
2024-07-24 17:22:59 +03:00
public bool|string $layout = false;
protected array $metaArr = [];
2024-07-24 17:22:59 +03:00
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;
}
2024-09-03 16:29:44 +03:00
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
2024-07-24 17:22:59 +03:00
{
ob_start();
$view = $this;
2024-09-03 16:29:44 +03:00
foreach ($data as $key => $datum) {
2024-07-24 17:22:59 +03:00
${"$key"} = $datum;
}
include($this->viewPath . $viewFile);
2024-07-24 17:22:59 +03:00
$content = ob_get_contents();
2024-09-03 16:29:44 +03:00
ob_end_clean();
2024-07-24 17:22:59 +03:00
ob_start();
2024-09-03 16:29:44 +03:00
2024-07-24 17:22:59 +03:00
$file_content = $content;
if (!isset($title)){
$title = "No Title";
}
2024-09-03 16:29:44 +03:00
$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);
2024-07-24 17:22:59 +03:00
$file_content = ob_get_contents();
}
}
2024-09-03 16:29:44 +03:00
ob_end_clean();
2024-07-24 17:22:59 +03:00
return $file_content;
}
}