feat: Удаление магических методов в шаблонах

This commit is contained in:
origami11@yandex.ru 2025-12-02 19:43:10 +03:00
parent 18cc1cad01
commit 61b5bc1c0f
13 changed files with 148 additions and 111 deletions

View file

@ -111,7 +111,7 @@ class Action implements ActionInterface
* @param int $size
* @return string Путь к иконке
*/
function findIcon($icon, $size) {
function findIcon($icon, $size): string {
$webPath = $this->config->get('site', 'web');
return Path::join($webPath, 'icons', $size . 'x' . $size, $icon . '.png');
}
@ -119,8 +119,8 @@ class Action implements ActionInterface
/**
* Создает представление
* @param string $name
* @param class-string $viewClass
* @return Composite
* @param class-string<Composite> $viewClass
* @return View
*/
public function getView($name, $viewClass = Composite::class)
{
@ -143,7 +143,7 @@ class Action implements ActionInterface
/** @var \ctiso\View\Composite */
$tpl = new $viewClass($template);
$tpl->config = $this->config;
$tpl->set('config', $this->config);
$stylePath = Path::join($webPath, "assets", "css");
$iconsPath = Path::join($webPath, 'icons');

View file

@ -2,6 +2,7 @@
namespace ctiso\Controller;
use ctiso\View\Template;
use ctiso\Database;
use ctiso\HttpRequest;
@ -10,14 +11,14 @@ interface ActionInterface {
* Действие может вернуть Шаблон или строку
*
* @param HttpRequest $request
* @return \ctiso\View\View|string|false
* @return Template|string|false
*/
function execute(HttpRequest $request);
function getConnection(): Database;
/**
* @param string $name
* @param class-string<\ctiso\View\View> $class
* @return \ctiso\View\View
* @param class-string<Template> $class
* @return Template
*/
function getView($name, $class);
/**

View file

@ -8,15 +8,17 @@ use ctiso\Arr;
use ctiso\Path;
use ctiso\File;
use ctiso\Form\Form;
use ctiso\View\Composite;
use ctiso\View\View;
use ctiso\Database;
use ctiso\Collection;
use ctiso\Registry;
use ctiso\Controller\SiteInterface;
use ctiso\Database\PDOStatement;
use ctiso\View\Json;
use PHPTAL;
use PHPTAL_PreFilter_Normalize;
use ctiso\View\FakeTemplate;
use ctiso\View\Template;
use ctiso\View\TalView;
/**
* Класс компонента
@ -117,12 +119,12 @@ class Component
/**
* Получить шаблон
* @param string $name
* @return PHPTAL|FakeTemplate
* @return Template
*/
public function getView($name)
{
if ($this->output === 'json') {
return new FakeTemplate($name);
return new Json($name);
}
/** @var Registry $config */
@ -136,8 +138,7 @@ class Component
// Загружать шаблон по умолчанию если не найден текущий
$dir = Path::join($this->viewPath[$index], 'templates', $template);
if(is_dir($dir)) {
$tpl = new PHPTAL(Path::join($this->viewPath[$index], 'templates', $template, $name));
$tpl->setPhpCodeDestination(PHPTAL_PHP_CODE_DESTINATION);
$tpl = new TalView(Path::join($this->viewPath[$index], 'templates', $template, $name));
$selected = $index;
break;
}
@ -146,13 +147,11 @@ class Component
if ($selected === null) {
// Последний вариант viewPath, путь к папке компонента
$selected = count($this->viewPath) - 1;
$tpl = new PHPTAL(Path::join($this->viewPath[$selected], 'templates', 'modern', $name));
$tpl->setPhpCodeDestination(PHPTAL_PHP_CODE_DESTINATION);
$tpl = new TalView(Path::join($this->viewPath[$selected], 'templates', 'modern', $name));
$template = 'modern';
}
$tpl->stripComments(true);
$tpl->addPreFilter(new \PHPTAL_PreFilter_Normalize());
// $tpl->addPreFilter(new \PHPTAL_PreFilter_Normalize());
$tpl->set('common', Path::join($this->config->get('system', 'web'), '../', 'common'));
$tpl->set('script', Path::join($this->config->get('system', 'web'), 'js'));
@ -280,19 +279,19 @@ class Component
/**
* Генерация интерфейса для выбора галлереи фотографии
* @param Composite $view
* @param View $view
* @param ?\ctiso\Form\OptionsFactory $options
*/
public function setParameters(Composite $view, $options = null): void
public function setParameters(View $view, $options = null): void
{
$form = new Form();
$settings = $this->getInfo();
$form->addFieldList($settings['parameter'], $options);
$view->form = $form;
$view->component = $settings['component'];
$view->component_title = $settings['title'];
$view->set('form', $form);
$view->set('component', $settings['component']);
$view->set('component_title', $settings['title']);
}
/**

View file

@ -23,11 +23,13 @@ namespace ctiso {
* Класс оболочка для PDO для замены Creole
* @phpstan-type DSN = array{phptype: string, hostspec: string, database: string, username: string, password: string}
*/
class Database extends PDO
class Database
{
/** @var DSN */
public $dsn;
/** @var PDO */
public $db;
/**
* Создает соединение с базой данных
@ -37,10 +39,10 @@ namespace ctiso {
*/
public function __construct($dsn, $username = null, $password = null)
{
parent::__construct($dsn, $username, $password);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, [PDOStatement::class, []]);
$this->db = new PDO($dsn, $username, $password);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->db->setAttribute(PDO::ATTR_STATEMENT_CLASS, [PDOStatement::class, []]);
}
/**
@ -49,7 +51,38 @@ namespace ctiso {
function prepare(string $sql, array $options = []): PDOStatement
{
/** @var PDOStatement */
$result = parent::prepare($sql, $options);
$result = $this->db->prepare($sql, $options);
return $result;
}
function lastInsertId(?string $name = null): string|false {
return $this->db->lastInsertId($name);
}
function beginTransaction(): bool {
return $this->db->beginTransaction();
}
function commit(): bool {
return $this->db->commit();
}
function rollBack(): bool {
return $this->db->rollBack();
}
function quote(string $string, int $type = PDO::PARAM_STR): bool|string {
return $this->db->quote($string, $type);
}
/**
* query возвращает только PDOStatement т.к установлен PDO::ERRMODE_EXCEPTION
* @param string $query
* @return PDOStatement
*/
function query($query): PDOStatement {
/** @var PDOStatement */
$result = $this->db->query($query);
return $result;
}
@ -70,6 +103,10 @@ namespace ctiso {
{
return ($this->dsn["phptype"] == "pgsql");
}
function sqliteCreateFunction(string $function_name, ?callable $callback = null, int $num_args = -1): void {
$this->db->sqliteCreateFunction($function_name, $callback, $num_args);
}
/**
* Создает соединение с базой данных
* @param array $dsn - DSN
@ -95,7 +132,7 @@ namespace ctiso {
$connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1);
} elseif ($dsn['phptype'] == 'sqlite') {
$connection = new self("{$dsn['phptype']}:{$dsn['database']}");
$connection->setAttribute(PDO::ATTR_TIMEOUT, 5);
$connection->db->setAttribute(PDO::ATTR_TIMEOUT, 5);
$mode = defined('SQLITE_JOURNAL_MODE') ? \SQLITE_JOURNAL_MODE : 'WAL';
$connection->query("PRAGMA journal_mode=$mode");
$connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1);

View file

@ -8,6 +8,7 @@ namespace ctiso\Filter;
use ctiso\Database;
use ctiso\HttpRequest;
use ctiso\Controller\ActionInterface;
use ctiso\View\Template;
class Filter implements ActionInterface
{
@ -29,8 +30,8 @@ class Filter implements ActionInterface
/**
* @param string $name
* @param class-string<\ctiso\View\View> $class
* @return \ctiso\View\View
* @param class-string<Template> $class
* @return Template
*/
public function getView($name, $class = \ctiso\View\Top::class)
{

View file

@ -24,18 +24,10 @@ class Composite extends View
}
function set(string $key, mixed $val): void {
if ($key == 'title') {
$this->setTitle($val);
}
$this->tal->set($key, $val);
}
function __set(string $key, mixed $val): void {
$this->tal->set($key, $val);
}
function execute(): string
{
function execute(): string {
$this->processChild();
return $this->tal->execute();
}

View file

@ -1,32 +0,0 @@
<?php
namespace ctiso\View;
class FakeTemplate extends \stdClass {
/** @var array */
public $_data = [];
/** @var string */
public $_name = '';
/**
* @param string $name
*/
function __construct($name) {
$this->_name = $name;
}
/**
* @param string $key
* @param mixed $value
*/
function __set($key, $value): void {
$this->_data[$key] = $value;
}
/**
* @return string
*/
function execute() {
return json_encode($this->_data) ?: '';
}
}

33
src/View/Json.php Normal file
View file

@ -0,0 +1,33 @@
<?php
namespace ctiso\View;
class Json implements Template {
/** @var array */
private $_data = [];
/** @var string */
private $_file;
/**
* @param string $_file
*/
function __construct($_file) {
$this->_file = $_file;
}
function getFile(): string {
return $this->_file;
}
/**
* @param string $key
* @param mixed $value
*/
function set($key, $value): void {
$this->_data[$key] = $value;
}
function execute(): string {
return json_encode($this->_data) ?: '';
}
}

View file

@ -5,7 +5,7 @@ namespace ctiso\View;
/**
* Шаблон для PHP
*/
class Plain extends \stdClass
class Plain implements Template
{
/** @var string */
protected $document;
@ -40,23 +40,13 @@ class Plain extends \stdClass
$this->values = array_merge($this->values, $list);
}
/**
* @param string $key ключ
* @param mixed $value значение
*/
public function __set($key, $value): void
{
$this->set($key, $value);
}
/**
* Выполнение шаблона
* @return string
*/
public function execute()
public function execute(): string
{
$result = $this->values;
return self::getTemplateContent ($this->document, $result);
return self::getTemplateContent($this->document, $result);
}
/**

27
src/View/TalView.php Normal file
View file

@ -0,0 +1,27 @@
<?php
namespace ctiso\View;
use PHPTAL;
class TalView implements Template {
private PHPTAL $tal;
function __construct(string $file)
{
$this->tal = new PHPTAL($file);
$this->tal->setPhpCodeDestination(PHPTAL_PHP_CODE_DESTINATION);
$this->tal->setEncoding(PHPTAL_DEFAULT_ENCODING);
$this->tal->setTemplateRepository(PHPTAL_TEMPLATE_REPOSITORY);
$this->tal->setOutputMode(PHPTAL::HTML5);
$this->tal->stripComments(true);
}
function set(string $key, mixed $val): void {
$this->tal->set($key, $val);
}
function execute(): string {
return $this->tal->execute();
}
}

10
src/View/Template.php Normal file
View file

@ -0,0 +1,10 @@
<?php
namespace ctiso\View;
interface Template {
/** Установка значений шаблона */
function set(string $key, mixed $value): void;
/** Преобразование шаблона в строку */
function execute(): string;
}

View file

@ -6,15 +6,10 @@ use ctiso\View\Composite;
class Top extends Composite
{
/**
* Общая строка заголовка
* @var int
*/
public $mid = 0;
/** @var int Счетчик для идентификторов */
private $mid = 0;
/** @var array */
public $require = [];
/** @var array */
public $deps = [];
/** @var \ctiso\Registry */
public $config;
@ -57,7 +52,6 @@ class Top extends Composite
$this->set('stylesheet', array_unique($this->getStyleSheet()));
$this->require = ['admin' => 'ma'];
$this->deps = [];
$startup = [];
foreach ($this->_section as $s) {
@ -83,23 +77,9 @@ class Top extends Composite
foreach ($s->_values as $key => $v) {
$script .= $value . "." . $key . " = " . json_encode($v /*, JSON_PRETTY_PRINT*/) . ";\n";
}
$init = [];
/** @var View $item */
foreach ($s->_section as $key => $item) {
if ($item->codeGenerator !== null) {
// функцию которая вычисляет а не результат
$part = call_user_func($item->codeGenerator, $this, $key, $value);
$init[] = $part;
}
}
$script .= $value . ".execute('" . $s->module_action . "', " . json_encode($init) . ");\n";
$startup[] = $script;
}
$this->set('startup', implode("", $startup) . $this->getScriptStartup());
$this->set('require', implode(",", array_map(function ($x) {
return "'$x'"; }, array_keys($this->require))));

View file

@ -3,7 +3,7 @@
namespace ctiso\View;
use Exception;
class View extends \stdClass
class View implements Template
{
/** @var array<View|string> Вложенные шаблоны */
protected array $_section = [];
@ -32,7 +32,7 @@ class View extends \stdClass
/** @var array<string, string|array<string, string>> */
public array $alias = [];
// public $codeGenerator = null;
/** @var View|null */
public $parent_view = null;
@ -130,8 +130,7 @@ class View extends \stdClass
}
*/
/*abstract*/ public function set(string $key, mixed $value): void
public function set(string $key, mixed $value): void
{
}