phplibrary/src/Tales.php

90 lines
2.7 KiB
PHP

<?php
/**
* Расширения для PHPTAL для отображения времени и даты
*/
namespace ctiso;
use PHPTAL_Php_TalesInternal;
use ctiso\Controller\SiteInterface;
use ctiso\Controller\Component;
use ctiso\HttpRequest;
use PHPTAL_Tales;
use PHPTAL_TalesRegistry;
class Tales_DateTime implements PHPTAL_Tales
{
static public function date(string $expression, bool $nothrow = false): string
{
return "ctiso\\Tales::phptal_date(".PHPTAL_Php_TalesInternal::path($expression).")";
}
static public function time(string $expression, bool $nothrow = false): string
{
return "ctiso\\Tales::phptal_time(".PHPTAL_Php_TalesInternal::path($expression).")";
}
}
class Tales_Component implements PHPTAL_Tales
{
static public function component(string $expression, bool $nothrow = false): string
{
$s = PHPTAL_Php_TalesInternal::string($expression);
return "ctiso\\Tales::phptal_component(" . $s . ")";
}
}
class Tales_Assets implements PHPTAL_Tales
{
static public function assets(string $expression, bool $nothrow = false): string
{
$s = PHPTAL_Php_TalesInternal::string($expression);
return "ctiso\\Tales::phptal_asset(" . $s . ")";
}
}
class Tales {
/** @var ?SiteInterface */
static $site;
static function phptal_date (int $e): string {
return date("d.m.Y", $e);
}
static function phptal_time (int $e): string {
return date("H:i", $e);
}
static function phptal_asset(string $s): string {
self::$site->addStyleSheet($s);
return "";
}
/**
* Функция подключения компонента
* @param string $expression
* @return string
*/
static function phptal_component($expression): string {
$begin = floatval(microtime(true));
/** @var Component */
$component = self::$site->loadComponent($expression);
$req = new HttpRequest();
$result = $component->execute($req);
echo "<!-- ", $expression, ", ", round(floatval(microtime(true)) - $begin, 4), "sec -->";
return $result;
}
static function register(?SiteInterface $site): void {
self::$site = $site;
/* Регистрация нового префикса для подключения компонента */
$tales = PHPTAL_TalesRegistry::getInstance();
$tales->registerPrefix('component', [\ctiso\Tales_Component::class, 'component']);
$tales->registerPrefix('date', [\ctiso\Tales_DateTime::class, 'date']);
$tales->registerPrefix('time', [\ctiso\Tales_DateTime::class, 'time']);
$tales->registerPrefix('assets', [\ctiso\Tales_Assets::class, 'assets']);
}
}