chore: Аннотации к типам

This commit is contained in:
origami11@yandex.ru 2025-10-23 15:54:14 +03:00
parent 530a3b931d
commit 730a608f9b
27 changed files with 491 additions and 134 deletions

View file

@ -3,27 +3,31 @@
namespace ctiso\Connection; namespace ctiso\Connection;
use ctiso\File; use ctiso\File;
class HttpRequest class HttpRequest
{ {
const POST = "POST"; const POST = "POST";
const GET = "GET"; const GET = "GET";
private $param = array(); // Параметры запроса private $param = []; // Параметры запроса
public $data = null; // Содержание public $data = null; // Содержание
public $url; // Адресс public $url; // Адресс
public $method; // Метод public $method; // Метод
/** @var int */
public $port = 80; public $port = 80;
/** @var string */
public $host = ""; public $host = "";
public $proxy_host = null; public $proxy_host = null;
public $proxy_port = null; public $proxy_port = null;
/** @var string */
public $http_version = 'HTTP/1.1'; public $http_version = 'HTTP/1.1';
function __construct() { function __construct() {
$this->method = self::GET; $this->method = self::GET;
} }
/** /**
* Возвращает заголовок соединения * Возвращает заголовок соединения
* @return string
*/ */
public function getHeader() public function getHeader()
{ {
@ -36,11 +40,11 @@ class HttpRequest
$result .= $this->data; $result .= $this->data;
return $result; return $result;
} }
/** /**
* Установка параметров запроса * Установка параметров запроса
* @parma string $name * @param string $name
* @parma string $value * @param string $value
*/ */
public function setParameter($name, $value) public function setParameter($name, $value)
{ {
@ -49,29 +53,35 @@ class HttpRequest
/** /**
* Метод запроса GET или POST * Метод запроса GET или POST
* @param string $method
*/ */
public function setMethod($method) public function setMethod($method): void
{ {
$this->method = $method; $this->method = $method;
} }
public function setUrl($url) /**
* Установка URL
* @param string $url
*/
public function setUrl($url): void
{ {
$this->url = $url; $this->url = $url;
$this->host = parse_url($this->url, PHP_URL_HOST); $this->host = parse_url($this->url, PHP_URL_HOST);
} }
public function getUrl() public function getUrl(): string
{ {
return $this->url; return $this->url;
} }
/** /**
* Содержание запроса * Содержание запроса
* @param string $data
*/ */
public function setContent($data) public function setContent($data): void
{ {
$this->setParameter ("Content-length", strlen($data)); $this->setParameter("Content-length", (string)strlen($data));
$this->data = $data; $this->data = $data;
} }
@ -99,6 +109,12 @@ class HttpRequest
return null; return null;
} }
/**
* Получение JSON
* @param string $url
* @param array $data
* @return array
*/
static function getJSON($url, $data) { static function getJSON($url, $data) {
$query = http_build_query($data); $query = http_build_query($data);
$q = $url . '?' . $query; $q = $url . '?' . $query;

View file

@ -8,7 +8,7 @@ namespace ctiso\Connection;
class HttpResponse class HttpResponse
{ {
private $offset; private $offset;
private $param = array (); private $param = [];
private $code; private $code;
public $response; public $response;
public $version; public $version;
@ -19,7 +19,7 @@ class HttpResponse
$this->offset = 0; $this->offset = 0;
$this->response = $response; $this->response = $response;
$this->parseMessage(); $this->parseMessage();
} }
/** /**
* Обработка HTTP ответа * Обработка HTTP ответа
@ -30,7 +30,7 @@ class HttpResponse
$this->version = $http[0]; $this->version = $http[0];
$this->code = $http[1]; $this->code = $http[1];
$line = $this->getLine(); $line = $this->getLine();
while ($offset = strpos($line, ":")) { while ($offset = strpos($line, ":")) {
$this->param[substr($line, 0, $offset)] = trim(substr($line, $offset + 1)); $this->param[substr($line, 0, $offset)] = trim(substr($line, $offset + 1));
$line = $this->getLine(); $line = $this->getLine();
@ -59,7 +59,7 @@ class HttpResponse
{ {
$begin = $this->offset; $begin = $this->offset;
$offset = strpos($this->response, "\r\n", $this->offset); $offset = strpos($this->response, "\r\n", $this->offset);
$result = substr($this->response, $begin, $offset - $begin); $result = substr($this->response, $begin, $offset - $begin);
$this->offset = $offset + 2; $this->offset = $offset + 2;
return $result; return $result;
} }
@ -67,20 +67,20 @@ class HttpResponse
/** /**
* Значение параметра HTTP ответа * Значение параметра HTTP ответа
*/ */
public function getParameter($name) public function getParameter($name)
{ {
return $this->param[$name]; return $this->param[$name];
} }
public function getData() public function getData()
{ {
return $this->data; return $this->data;
} }
/** /**
* Состояние * Состояние
*/ */
public function getCode() public function getCode()
{ {
return $this->code; return $this->code;
} }

View file

@ -61,6 +61,11 @@ class Action implements ActionInterface
public function setUp() { public function setUp() {
} }
/**
* Загрузка файла настроек
* @param string $name
* @return array
*/
public function loadConfig($name) { public function loadConfig($name) {
$basePath = $this->config->get('site', 'path'); $basePath = $this->config->get('site', 'path');
@ -74,17 +79,27 @@ class Action implements ActionInterface
return $settings; return $settings;
} }
public function getConnection() public function getConnection(): Database
{ {
return $this->db; return $this->db;
} }
/**
* Путь к установке модуля
* @param string $name
* @return string
*/
public function installPath($name) public function installPath($name)
{ {
$basePath = $this->config->get('system', 'path'); $basePath = $this->config->get('system', 'path');
return Path::join($basePath, "modules", $name); return Path::join($basePath, "modules", $name);
} }
/**
* Добавляет подсказки
* @param View $view
* @param string $name
*/
public function addSuggest(View $view, $name) { public function addSuggest(View $view, $name) {
$suggest = []; $suggest = [];
$file = Path::join($this->modulePath, 'help', $name . '.suggest'); $file = Path::join($this->modulePath, 'help', $name . '.suggest');
@ -93,6 +108,12 @@ class Action implements ActionInterface
} }
} }
/**
* Поиск иконки
* @param string $icon
* @param int $size
* @return string Путь к иконке
*/
function findIcon($icon, $size) { function findIcon($icon, $size) {
$webPath = $this->config->get('site', 'web'); $webPath = $this->config->get('site', 'web');
return Path::join($webPath, 'icons', $size . 'x' . $size, $icon . '.png'); return Path::join($webPath, 'icons', $size . 'x' . $size, $icon . '.png');
@ -192,6 +213,12 @@ class Action implements ActionInterface
return $text; return $text;
} }
/**
* Перенаправление на другой контроллер
* @param string $action
* @param HttpRequest $args
* @return mixed
*/
public function forward($action, HttpRequest $args) { public function forward($action, HttpRequest $args) {
$value = call_user_func([$this, $action], $args); $value = call_user_func([$this, $action], $args);
return $value; return $value;
@ -199,12 +226,19 @@ class Action implements ActionInterface
/** /**
* Страница по умолчанию * Страница по умолчанию
* @param HttpRequest $request
* @return string|\ctiso\View\View
*/ */
public function actionIndex(HttpRequest $request) { public function actionIndex(HttpRequest $request) {
return ""; return "";
} }
public function addUrlPart($key, $value) { /**
* Добавление части ссылки
* @param string $key
* @param string $value
*/
public function addUrlPart($key, $value): void {
$this->part->addQueryParam($key, $value); $this->part->addQueryParam($key, $value);
} }
@ -277,6 +311,10 @@ class Action implements ActionInterface
/** /**
* Загрузка файла класса * Загрузка файла класса
* @deprecated
* @param string $path
* @param mixed $setup
* @param string $prefix
*/ */
public function loadClass($path, $setup = null, $prefix = '') public function loadClass($path, $setup = null, $prefix = '')
{ {
@ -288,6 +326,11 @@ class Action implements ActionInterface
throw new Exception("NO CLASS $path"); throw new Exception("NO CLASS $path");
} }
/**
* Загрузка настроек
* @param $path
* @return array
*/
public function loadSettings($path) public function loadSettings($path)
{ {
$result = new Settings($path); $result = new Settings($path);
@ -295,7 +338,7 @@ class Action implements ActionInterface
return $result->export(); return $result->export();
} }
public function setView($name) public function setView($name): void
{ {
$this->view = $this->getView($name); $this->view = $this->getView($name);
} }
@ -303,7 +346,7 @@ class Action implements ActionInterface
/** /**
* Установка заголовка для отображения * Установка заголовка для отображения
*/ */
public function setTitle($title) public function setTitle($title): void
{ {
$this->view->setTitle($title); $this->view->setTitle($title);
} }
@ -311,12 +354,12 @@ class Action implements ActionInterface
/** /**
* Добавление widget к отображению * Добавление widget к отображению
*/ */
public function addChild($section, $node) public function addChild($section, $node): void
{ {
$this->childNodes[$section] = $node; $this->childNodes[$section] = $node;
} }
public function setValue($name, $value) public function setValue($name, $value): void
{ {
$this->ctrlValues[$name] = $value; $this->ctrlValues[$name] = $value;
} }
@ -324,7 +367,7 @@ class Action implements ActionInterface
/** /**
* Добавление дочернего отображения к текущему отображению * Добавление дочернего отображения к текущему отображению
*/ */
public function addView($section, $node) public function addView($section, $node): void
{ {
$this->childViews[$section] = $node; $this->childViews[$section] = $node;
} }
@ -353,12 +396,21 @@ class Action implements ActionInterface
return $this->view; return $this->view;
} }
/**
* Установка идентификатора страницы
* @return int
*/
function getPageId(HttpRequest $request) { function getPageId(HttpRequest $request) {
$pageId = time(); $pageId = time();
$request->session()->set('page', $pageId); $request->session()->set('page', $pageId);
return $pageId; return $pageId;
} }
/**
* Проверка идентификатора страницы
* @param $page int Идентификатор страницы
* @return bool
*/
function checkPageId(HttpRequest $request, $page) function checkPageId(HttpRequest $request, $page)
{ {
if ($request->get('__forced__')) { if ($request->get('__forced__')) {

View file

@ -1,11 +1,21 @@
<?php <?php
namespace ctiso\Controller; namespace ctiso\Controller;
use ctiso\Database;
use ctiso\HttpRequest; use ctiso\HttpRequest;
interface ActionInterface { interface ActionInterface {
function execute(HttpRequest $request); function execute(HttpRequest $request);
function getConnection(); function getConnection(): Database;
/**
* @param string $name
* @param class-string<\ctiso\View\View> $class
*/
function getView($name, $class); function getView($name, $class);
/**
* @param string $key
* @param string $value
*/
function addUrlPart($key, $value); function addUrlPart($key, $value);
} }

View file

@ -38,13 +38,18 @@ class FakeTemplate {
*/ */
class Component class Component
{ {
/** @var string[] */
public $viewPath = []; public $viewPath = [];
/** @var string[] */
public $webPath = []; public $webPath = [];
/** @var ?string */
public $template = null; public $template = null;
public string $templatePath; public string $templatePath;
/** @var string */
public $component_id; public $component_id;
/** @var string */
public $component_title; public $component_title;
public $COMPONENTS_WEB; public $COMPONENTS_WEB;
@ -53,9 +58,12 @@ class Component
public Database $db; public Database $db;
public Collection $parameter; public Collection $parameter;
/** @var string */
public $output = 'html'; public $output = 'html';
/** @var string */
public $module; public $module;
/** @var string */
public $item_module; public $item_module;
/** /**
@ -66,12 +74,22 @@ class Component
function before() { function before() {
} }
/**
* @param string $match
* @return string
*/
static function replaceContent($match) { static function replaceContent($match) {
return \ctiso\Tales::phptal_component(htmlspecialchars_decode($match[3])); return \ctiso\Tales::phptal_component(htmlspecialchars_decode($match[3]));
} }
/**
* @param string $text
* @return string
*/
static function applyComponents($text) { static function applyComponents($text) {
return preg_replace_callback('/<(\w+)(\s+[a-zA-Z\-]+=\"[^\"]*\")*\s+tal:replace="structure\s+component:([^\"]*)"[^>]*>/u', 'ctiso\\Controller\\Component::replaceContent', $text); $callback = fn($x) => self::replaceContent($x);
return preg_replace_callback('/<(\w+)(\s+[a-zA-Z\-]+=\"[^\"]*\")*\s+tal:replace="structure\s+component:([^\"]*)"[^>]*>/u',
$callback, $text);
} }
function execute(HttpRequest $request, $has_id = true) { function execute(HttpRequest $request, $has_id = true) {
@ -101,13 +119,18 @@ class Component
? $_COOKIE['with_template'] : ($_registry ? $_registry->get('site', 'template') : 'modern'); ? $_COOKIE['with_template'] : ($_registry ? $_registry->get('site', 'template') : 'modern');
} }
/**
* Получить шаблон
* @param string $name
* @return PHPTAL|FakeTemplate
*/
public function getView($name) public function getView($name)
{ {
if ($this->output === 'json') { if ($this->output === 'json') {
return new FakeTemplate($name); return new FakeTemplate($name);
} }
/* @var Registry $config */ /** @var Registry $config */
$config = $this->config; $config = $this->config;
$default = $config->get('site', 'template'); $default = $config->get('site', 'template');
$template = ($this->template) ? $this->template : $this->getTemplateName($config); $template = ($this->template) ? $this->template : $this->getTemplateName($config);
@ -152,10 +175,19 @@ class Component
return $tpl; return $tpl;
} }
/**
* Возвращает путь к шаблону по умолчанию
* @return string
*/
function _getDefaultPath() { function _getDefaultPath() {
return $this->viewPath[count($this->viewPath) - 1]; return $this->viewPath[count($this->viewPath) - 1];
} }
/**
* Возвращает путь к шаблону
* @param string $name
* @return string
*/
public function getTemplatePath($name) { public function getTemplatePath($name) {
$registry = $this->config; $registry = $this->config;
// Брать настройки из куков если есть // Брать настройки из куков если есть
@ -169,6 +201,10 @@ class Component
return Path::join($this->viewPath[count($this->viewPath) - 1], 'templates', 'modern', $name); return Path::join($this->viewPath[count($this->viewPath) - 1], 'templates', 'modern', $name);
} }
/**
* Возвращает путь к шаблонам
* @return string
*/
public function getTemplateWebPath() public function getTemplateWebPath()
{ {
return Path::join($this->webPath[count($this->webPath) - 1], 'templates', 'modern'); return Path::join($this->webPath[count($this->webPath) - 1], 'templates', 'modern');
@ -201,6 +237,11 @@ class Component
return $result; return $result;
} }
/**
* @param array $list
* @param bool $selected
* @return array
*/
public function optionsPair(array $list, $selected = false) { public function optionsPair(array $list, $selected = false) {
$result = []; $result = [];
foreach ($list as $key => $value) { foreach ($list as $key => $value) {
@ -371,12 +412,16 @@ class Component
return $component; return $component;
} }
/**
* @return ?array{name: string, url: string}
*/
function getEditUrl() { function getEditUrl() {
return null; return null;
} }
/** /**
* @param ComponentRequest $request * @param ComponentRequest $request
* @return array
*/ */
function raw_query($request) function raw_query($request)
{ {
@ -403,6 +448,8 @@ class Component
/** /**
* @param ComponentRequest $request * @param ComponentRequest $request
* @param array $list
* @return string
*/ */
function query($request, $list) function query($request, $list)
{ {
@ -416,7 +463,12 @@ class Component
return '?' . http_build_query($arr); return '?' . http_build_query($arr);
} }
function addRequireJsPath($name, $path, $shim = null) { /**
* @param string $name
* @param string $path
* @param array $shim
*/
function addRequireJsPath($name, $path, $shim = null): void {
$this->site->addRequireJsPath($name, $path, $shim); $this->site->addRequireJsPath($name, $path, $shim);
} }

View file

@ -5,16 +5,16 @@
* @package system.controller * @package system.controller
*/ */
namespace ctiso\Controller; namespace ctiso\Controller;
use ctiso\Controller\Action,
ctiso\Registry, use ctiso\Controller\Action;
ctiso\Database, use ctiso\Registry;
ctiso\Collection, use ctiso\Database;
ctiso\Filter\ActionAccess, use ctiso\Filter\ActionAccess;
ctiso\Filter\ActionLogger, use ctiso\Filter\ActionLogger;
ctiso\Path, use ctiso\Path;
ctiso\UserMessageException, use ctiso\UserMessageException;
ctiso\HttpRequest, use ctiso\HttpRequest;
ctiso\Role\User; use ctiso\Role\User;
class Front extends Action class Front extends Action
{ {
@ -22,7 +22,7 @@ class Front extends Action
protected $_param; // Параметр по которому выбирается модуль protected $_param; // Параметр по которому выбирается модуль
protected $default; // Значение параметра по умолчанию protected $default; // Значение параметра по умолчанию
protected $modules = array(); protected $modules = [];
public function __construct(Database $db, Registry $config, User $user, $default) { public function __construct(Database $db, Registry $config, User $user, $default) {
parent::__construct(); parent::__construct();

View file

@ -1,38 +1,64 @@
<?php <?php
namespace ctiso\Controller; namespace ctiso\Controller;
use ctiso\Settings,
ctiso\Path,
ctiso\Database\JsonInstall;
class Installer use ctiso\Settings;
use ctiso\Path;
use ctiso\Database\JsonInstall;
use ctiso\Database\Manager;
class Installer
{ {
/** @var Manager */
protected $db_manager; protected $db_manager;
/** @var callable */
protected $installPath; protected $installPath;
/** @var Settings */
public $_registry; public $_registry;
public function __construct(Settings $_registry) public function __construct(Settings $_registry)
{ {
$this->_registry = $_registry; $this->_registry = $_registry;
} }
/**
* Устанавливает параметры
* @param Manager $db_manager
* @param callable $installPath
*/
public function setUp($db_manager, $installPath) public function setUp($db_manager, $installPath)
{ {
$this->db_manager = $db_manager; $this->db_manager = $db_manager;
$this->installPath = $installPath; $this->installPath = $installPath;
} }
/**
* Получение пути к файлу install.json
* @param string $name
* @return string
*/
function getSetupFile($name) function getSetupFile($name)
{ {
$setup = Path::join(call_user_func($this->installPath, $name), "install.json"); $setup = Path::join(call_user_func($this->installPath, $name), "install.json");
return $setup; return $setup;
} }
function getUninstallFile($name) { /**
* Получение пути к файлу unisntall.json
* @param string $name
* @return string
*/
function getUninstallFile($name)
{
return Path::join(call_user_func($this->installPath, $name), "sql", "uninstall.json"); return Path::join(call_user_func($this->installPath, $name), "sql", "uninstall.json");
} }
// Проверка версии обновления /**
* Проверка версии обновления
* @param string $name
* @return bool
*/
function isChanged($name) // Информация о модулях function isChanged($name) // Информация о модулях
{ {
$item = $this->_registry->get($name); $item = $this->_registry->get($name);
@ -46,6 +72,14 @@ class Installer
return true; return true;
} }
/**
* Устанавливает SQL
* @param array $sql
* @param string $version_new
* @param string $version_old
* @param string $name
* @return array
*/
function installSQL(array $sql, $version_new, $version_old, $name) function installSQL(array $sql, $version_new, $version_old, $name)
{ {
$result = []; $result = [];
@ -60,18 +94,28 @@ class Installer
return $result; return $result;
} }
function uninstall($name){ /**
* @param string $name
* @return void
*/
function uninstall($name): void
{
$uninstall = $this->getUninstallFile($name); $uninstall = $this->getUninstallFile($name);
if (file_exists($uninstall)) { if (file_exists($uninstall)) {
$json_installer = new JsonInstall($this->db_manager); $json_installer = new JsonInstall($this->db_manager);
$json_installer->install($uninstall,null); $json_installer->install($uninstall, null);
} }
$this->_registry->removeKey($name); $this->_registry->removeKey($name);
$this->_registry->write(); $this->_registry->write();
} }
// Устанавливает обновления если есть /**
function doUpdates($name, $force = false) // Установка модуля * Устанавливает обновления если есть
* @param string $name
* @param bool $force
* @return array
*/
function doUpdates($name, $force = false)
{ {
$result = []; $result = [];
$setup = $this->getSetupFile($name); $setup = $this->getSetupFile($name);
@ -86,7 +130,7 @@ class Installer
$version_new = $settings->get('version'); $version_new = $settings->get('version');
if ($item) { if ($item) {
$version_old = $item['version']; $version_old = $item['version'];
} else { } else {
$version_old = "0.0"; $version_old = "0.0";
$registry->writeKey([$name], []); $registry->writeKey([$name], []);
@ -96,15 +140,15 @@ class Installer
if (is_array($sql)) { if (is_array($sql)) {
$res = $this->installSQL($sql, $version_new, $version_old, $name); $res = $this->installSQL($sql, $version_new, $version_old, $name);
if ($res) { if ($res) {
$result[]=$res; $result[] = $res;
} }
} }
} }
// Обновление версии меню // Обновление версии меню
$registry->removeKey($name); $registry->removeKey($name);
$registry->set($name, [ $registry->set($name, [
'version' => $version_new, 'version' => $version_new,
'time' => filemtime($setup) 'time' => filemtime($setup)
]); ]);
// $registry->writeKey([$name], $settings->export()); // $registry->writeKey([$name], $settings->export());
@ -114,7 +158,13 @@ class Installer
return $result; return $result;
} }
function install($dbinit_path, $dbfill_path = null) { /**
* Устанавливает базу данных
* @param string $dbinit_path
* @param string|null $dbfill_path
*/
function install($dbinit_path, $dbfill_path = null)
{
$json_installer = new JsonInstall($this->db_manager); $json_installer = new JsonInstall($this->db_manager);
$json_installer->install($dbinit_path, $dbfill_path); $json_installer->install($dbinit_path, $dbfill_path);
} }

View file

@ -4,17 +4,25 @@ namespace ctiso\Controller;
use ctiso\HttpRequest; use ctiso\HttpRequest;
class Request { class Request {
/** @var HttpRequest */
public $r; public $r;
/** @var string */
public $id; public $id;
/** /**
* @param HttpRequest $request * @param HttpRequest $request
* @param string $id
*/ */
function __construct($request, $id) { function __construct($request, $id) {
$this->r = $request; $this->r = $request;
$this->id = $id; $this->id = $id;
} }
/**
* @param string $name
* @param mixed $def
* @return mixed
*/
function get($name, $def = null) { function get($name, $def = null) {
$v = $this->r->get($name); $v = $this->r->get($name);
$id = $this->id; $id = $this->id;

View file

@ -4,29 +4,42 @@
* Класс сервиса = Упрощенный компонент * Класс сервиса = Упрощенный компонент
*/ */
namespace ctiso\Controller; namespace ctiso\Controller;
use ctiso\Path,
ctiso\Model\BaseMapper, use ctiso\Path;
ctiso\File, use ctiso\Model\BaseMapper;
ctiso\Registry, use ctiso\File;
ctiso\Database\PDOStatement; use ctiso\Registry;
use ctiso\Database\PDOStatement;
use ctiso\Database;
class Service class Service
{ {
/** @var array */
public $viewPath = []; public $viewPath = [];
/** @var array */
public $webPath = []; public $webPath = [];
/** @var Registry */ /** @var Registry */
public $config; public $config;
public $template; public $template;
public $templatePath; public $templatePath;
public $COMPONENTS_WEB; public $COMPONENTS_WEB;
/** @var Database */
public $db; public $db;
/**
* Возвращает путь к шаблонам
* @param string $name Имя шаблона
* @return string
*/
public function getTemplatePath($name) public function getTemplatePath($name)
{ {
return Path::join($this->viewPath[0], 'templates', 'modern', $name); return Path::join($this->viewPath[0], 'templates', 'modern', $name);
} }
/**
* Возвращает путь к шаблонам
* @return string
*/
public function getTemplateWebPath() public function getTemplateWebPath()
{ {
return Path::join($this->webPath[0], strtolower(get_class($this)), 'templates', 'modern'); return Path::join($this->webPath[0], strtolower(get_class($this)), 'templates', 'modern');
@ -58,6 +71,7 @@ class Service
* @param string $key * @param string $key
* @param string $val * @param string $val
* @param PDOStatement $res * @param PDOStatement $res
* @return array
*/ */
public function options($key, $val, $res) { public function options($key, $val, $res) {
$result = []; $result = [];
@ -67,6 +81,11 @@ class Service
return $result; return $result;
} }
/**
* @param array $list
* @param bool $selected
* @return array
*/
public function optionsPair($list, $selected = false) { public function optionsPair($list, $selected = false) {
$result = []; $result = [];
foreach ($list as $key => $value) { foreach ($list as $key => $value) {

View file

@ -9,18 +9,28 @@ namespace {
} }
namespace ctiso { namespace ctiso {
use PDO,
ctiso\Database\Statement, use PDO;
ctiso\Database\PDOStatement, use ctiso\Database\Statement;
ctiso\Database\IdGenerator; use ctiso\Database\PDOStatement;
use ctiso\Database\IdGenerator;
/** /**
* Класс оболочка для PDO для замены Creole * Класс оболочка для PDO для замены Creole
* @phpstan-type DSN = array{phptype: string, hostspec: string, database: string, username: string, password: string}
*/ */
class Database extends PDO class Database extends PDO
{ {
/** @var DSN */
public $dsn; public $dsn;
/**
* Создает соединение с базой данных
* @param string $dsn - DSN
* @param string|null $username - имя пользователя
* @param string|null $password - пароль
*/
public function __construct($dsn, $username = null, $password = null) public function __construct($dsn, $username = null, $password = null)
{ {
parent::__construct($dsn, $username, $password); parent::__construct($dsn, $username, $password);
@ -36,16 +46,27 @@ namespace ctiso {
return $result; return $result;
} }
/**
* Возвращает DSN
* @return DSN
*/
public function getDSN() public function getDSN()
{ {
return $this->dsn; return $this->dsn;
} }
/**
* Возвращает true, если база данных Postgres
* @return bool
*/
public function isPostgres() public function isPostgres()
{ {
return ($this->dsn["phptype"] == "pgsql"); return ($this->dsn["phptype"] == "pgsql");
} }
/** /**
* Создает соединение с базой данных * Создает соединение с базой данных
* @param array $dsn - DSN
* @return Database|null
*/ */
static function getConnection(array $dsn) static function getConnection(array $dsn)
{ {
@ -76,6 +97,11 @@ namespace ctiso {
return $connection; return $connection;
} }
/**
* Выполняет запрос к базе данных
* @param string $query - запрос
* @param array $values - значения
*/
public function executeQuery($query, $values = null): PDOStatement|bool public function executeQuery($query, $values = null): PDOStatement|bool
{ {
$stmt = $this->prepare($query); $stmt = $this->prepare($query);
@ -85,14 +111,20 @@ namespace ctiso {
return $stmt; return $stmt;
} }
/**
* Создает подготовленный запрос
* @param string $query - запрос
*/
public function prepareStatement($query) public function prepareStatement($query)
{ {
return new Statement($query, $this); return new Statement($query, $this);
} }
// Для совместимости со старым представлением баз данных CIS
/** /**
* Извлекает из базы все элементы по запросу * Извлекает из базы все элементы по запросу (Для совместимости со старым представлением баз данных CIS)
* @param string $query - запрос
* @param array $values - значения
* @return array
*/ */
public function fetchAllArray($query, $values = null) public function fetchAllArray($query, $values = null)
{ {
@ -104,6 +136,9 @@ namespace ctiso {
/** /**
* Извлекает из базы первый элемент по запросу * Извлекает из базы первый элемент по запросу
* @param string $query - запрос
* @param array $values - значения
* @return array|false
*/ */
public function fetchOneArray($query, $values = null) public function fetchOneArray($query, $values = null)
{ {
@ -113,6 +148,11 @@ namespace ctiso {
return $sth->fetch(PDO::FETCH_ASSOC); return $sth->fetch(PDO::FETCH_ASSOC);
} }
/**
* Преобразует значения в подготовленные значения
* @param array $values - значения
* @return ?array<string, string>
*/
private function prepareValues($values) private function prepareValues($values)
{ {
if (!$values) { if (!$values) {
@ -135,8 +175,14 @@ namespace ctiso {
} }
return $prep; return $prep;
} }
/** /**
* Создает INSERT запрос * Создает INSERT запрос
* @param string $table - таблица
* @param array $values - значения
* @param bool $return_id - возвращать id
* @param string $index - индекс
* @return int|mixed
*/ */
function insertQuery($table, array $values, $return_id = false, $index = null) function insertQuery($table, array $values, $return_id = false, $index = null)
{ {
@ -165,6 +211,9 @@ namespace ctiso {
/** /**
* Создает UPDATE запрос * Создает UPDATE запрос
* @param string $table - таблица
* @param array $values - значения
* @param string $cond - условие
*/ */
function updateQuery($table, array $values, $cond) function updateQuery($table, array $values, $cond)
{ {
@ -180,6 +229,10 @@ namespace ctiso {
$stmt->execute($prep); $stmt->execute($prep);
} }
/**
* Создает генератор идентификаторов
* @return IdGenerator
*/
function getIdGenerator() function getIdGenerator()
{ {
return new IdGenerator($this); return new IdGenerator($this);
@ -196,9 +249,11 @@ namespace ctiso {
return $result['nextval']; return $result['nextval'];
} }
function close() /**
* Закрывает соединение с базой данных
*/
function close(): void
{ {
return null;
} }
} }
} }

View file

@ -240,7 +240,7 @@ class Manager
* @param array $fields * @param array $fields
* @param array|string|null $constraints * @param array|string|null $constraints
*/ */
public function createTableQuery($table, $fields, $constraints) public function createTableQuery($table, $fields, $constraints): void
{ {
$pg = $this->db->isPostgres(); $pg = $this->db->isPostgres();
if ($constraints) { if ($constraints) {

View file

@ -9,8 +9,11 @@ use TheSeer\Tokenizer\Exception;
class PDOStatement extends \PDOStatement implements \IteratorAggregate class PDOStatement extends \PDOStatement implements \IteratorAggregate
{ {
/** @var int */
protected $cursorPos = 0; protected $cursorPos = 0;
public $cache = array(); /** @var array */
public $cache = [];
/** @var ?array */
public $fields; public $fields;
function getIterator(): \Iterator { function getIterator(): \Iterator {
@ -20,11 +23,15 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate
protected function __construct() { protected function __construct() {
} }
function rewind() { function rewind(): void {
$this->cursorPos = 0; $this->cursorPos = 0;
} }
public function seek($rownum) { /**
* @param int $rownum
* @return bool
*/
public function seek($rownum): bool {
if ($rownum < 0) { if ($rownum < 0) {
return false; return false;
} }
@ -35,17 +42,17 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate
return true; return true;
} }
function valid() { function valid(): bool {
return true; return true;
} }
public function first() { public function first() {
if($this->cursorPos !== 0) { $this->seek(0); } if ($this->cursorPos !== 0) { $this->seek(0); }
return $this->next(); return $this->next();
} }
function next() { function next(): bool{
if ($this->getRecordCount() > $this->cursorPos) { if ($this->getRecordCount() > $this->cursorPos) {
if (!isset($this->cache[$this->cursorPos])) { if (!isset($this->cache[$this->cursorPos])) {
$this->cache[$this->cursorPos] = $this->fetch(PDO::FETCH_ASSOC); $this->cache[$this->cursorPos] = $this->fetch(PDO::FETCH_ASSOC);
@ -60,10 +67,13 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate
} }
} }
function key() { function key(): int {
return $this->cursorPos; return $this->cursorPos;
} }
/**
* @return mixed
*/
function current() { function current() {
return $this->cache[$this->cursorPos]; return $this->cache[$this->cursorPos];
} }
@ -72,37 +82,68 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate
return $this->fields; return $this->fields;
} }
function getInt($name) { /**
* @param string $name
* @return int
*/
function getInt($name): int {
if (!$this->fields) { if (!$this->fields) {
throw new \Exception('no fields'); throw new \Exception('no fields');
} }
return (int)$this->fields[$name]; return (int)$this->fields[$name];
} }
/**
* @param string $name
* @return string
*/
function getBlob($name) { function getBlob($name) {
return $this->fields[$name]; return $this->fields[$name];
} }
/**
* @param string $name
* @return string
*/
function getString($name) { function getString($name) {
return $this->fields[$name] ?? null; return $this->fields[$name] ?? null;
} }
/**
* @param string $name
* @return bool
*/
function getBoolean($name) { function getBoolean($name) {
return (bool)$this->fields[$name]; return (bool)$this->fields[$name];
} }
/**
* @param string $name
* @return mixed
*/
function get($name) { function get($name) {
return $this->fields[$name]; return $this->fields[$name];
} }
/**
* @param string $name
* @return array
*/
function getArray($name) { function getArray($name) {
return StringUtil::strToArray($this->fields[$name]); return StringUtil::strToArray($this->fields[$name]);
} }
/**
* @return int
*/
function getRecordCount() { function getRecordCount() {
return count($this->cache); return count($this->cache);
} }
/**
* @param array $args
* @return bool
*/
function execute($args = null): bool { function execute($args = null): bool {
$result = parent::execute($args); $result = parent::execute($args);
return $result; return $result;

View file

@ -9,10 +9,15 @@ use XMLWriter,
class Document { class Document {
static $ns = "urn:schemas-microsoft-com:office:spreadsheet"; static $ns = "urn:schemas-microsoft-com:office:spreadsheet";
private $table = array (); /** @var list<Table|callable> */
protected $styles = array(); private $table = [];
protected $styles = [];
function addTable($table) { /**
* Добавление таблицы в документ
* @param Table|callable $table Таблица или функция, возвращающая таблицу
*/
function addTable($table): void {
$this->table [] = $table; $this->table [] = $table;
} }

View file

@ -4,16 +4,17 @@ namespace ctiso\Excel;
class Number class Number
{ {
/** @var int */
public $value; public $value;
function __construct($value) function __construct($value)
{ {
$this->value = (int)($value); $this->value = (int)($value);
} }
function getString() function getString(): string
{ {
return $this->value; return (string) $this->value;
} }
} }

View file

@ -26,6 +26,7 @@ class TableCell
class TableRow class TableRow
{ {
public $style = false; public $style = false;
/** @var TableCell[] */
public $cells = []; public $cells = [];
public $height = false; public $height = false;
@ -45,12 +46,16 @@ class TableRow
*/ */
class Table class Table
{ {
/** @var int */
static $index; static $index;
/** @var string */
private $name; private $name;
private $style; /** @var TableRow[] */
protected $rows = []; protected $rows = [];
/** @var int|false */
protected $_splitVertical = false; protected $_splitVertical = false;
/** @var int|false */
protected $_splitHorizontal = false; protected $_splitHorizontal = false;
function __construct() function __construct()
@ -61,7 +66,7 @@ class Table
/** /**
* Записать значение в клетку с заданными координатами * Записать значение в клетку с заданными координатами
*/ */
function setCell(int $x, int $y, $value) function setCell(int $x, int $y, $value): void
{ {
assert($x > 0); assert($x > 0);
assert($y > 0); assert($y > 0);
@ -69,7 +74,7 @@ class Table
if(! isset($this->rows[$x])) { if(! isset($this->rows[$x])) {
$this->rows[$x] = new TableRow(); $this->rows[$x] = new TableRow();
} }
/** @var TableRow $row */
$row = $this->rows[$x]; $row = $this->rows[$x];
$row->setCell($y, $value); $row->setCell($y, $value);
} }
@ -77,7 +82,7 @@ class Table
/** /**
* Заполняет ряд начиная с указанного столбца значениями из массива * Заполняет ряд начиная с указанного столбца значениями из массива
*/ */
function setRow(int $row, int $index, array $data) function setRow(int $row, int $index, array $data): void
{ {
assert($index > 0); assert($index > 0);
assert($row > 0); assert($row > 0);
@ -94,7 +99,7 @@ class Table
* @param int $row Номер ряда * @param int $row Номер ряда
* @param numeric $value Высота ряда * @param numeric $value Высота ряда
*/ */
function setRowHeight (int $row, $value) function setRowHeight (int $row, $value): void
{ {
assert($row > 0); assert($row > 0);
@ -106,7 +111,7 @@ class Table
* @param int $row Номер ряда * @param int $row Номер ряда
* @param string $name Имя стиля * @param string $name Имя стиля
*/ */
function setRowStyle(int $row, $name) function setRowStyle(int $row, $name): void
{ {
assert($row > 0); assert($row > 0);
@ -119,7 +124,7 @@ class Table
* @param $cell Номер столбца * @param $cell Номер столбца
* @param $merge Количество клеток для обьединения * @param $merge Количество клеток для обьединения
*/ */
function setCellMerge(int $x, int $cell, $merge) function setCellMerge(int $x, int $cell, $merge): void
{ {
assert($x > 0); assert($x > 0);
assert($cell > 0); assert($cell > 0);
@ -180,7 +185,7 @@ class Table
* Разделяет таблицу на две части по вертикали * Разделяет таблицу на две части по вертикали
* @param int $n Количество столбцов слева * @param int $n Количество столбцов слева
*/ */
function splitVertical($n) { function splitVertical($n): void {
$this->_splitVertical = $n; $this->_splitVertical = $n;
} }
@ -188,7 +193,7 @@ class Table
* Разделяет таблицу на две части по горизонтали * Разделяет таблицу на две части по горизонтали
* @param int $n Количество столбцов сверху * @param int $n Количество столбцов сверху
*/ */
function splitHorizontal($n) { function splitHorizontal($n): void {
$this->_splitHorizontal = $n; $this->_splitHorizontal = $n;
} }
@ -312,17 +317,17 @@ class Table
$doc->writeElement('FrozenNoSplit'); $doc->writeElement('FrozenNoSplit');
if ($this->_splitVertical) { if ($this->_splitVertical) {
$doc->writeElement('SplitVertical', $this->_splitVertical); $doc->writeElement('SplitVertical', (string) $this->_splitVertical);
$doc->writeElement('LeftColumnRightPane', $this->_splitVertical); $doc->writeElement('LeftColumnRightPane', (string) $this->_splitVertical);
} }
if ($this->_splitHorizontal) { if ($this->_splitHorizontal) {
$doc->writeElement('SplitHorizontal', $this->_splitHorizontal); $doc->writeElement('SplitHorizontal', (string) $this->_splitHorizontal);
$doc->writeElement('TopRowBottomPane', $this->_splitHorizontal); $doc->writeElement('TopRowBottomPane', (string) $this->_splitHorizontal);
} }
if ($this->_splitHorizontal && $this->_splitVertical) { if ($this->_splitHorizontal && $this->_splitVertical) {
$doc->writeElement('ActivePane', (string)0); $doc->writeElement('ActivePane', (string) 0);
} else if($this->_splitHorizontal) { } else if($this->_splitHorizontal) {
$doc->writeElement('ActivePane', (string)2); $doc->writeElement('ActivePane', (string) 2);
} }
$doc->endElement(); $doc->endElement();
} }

View file

@ -4,6 +4,11 @@ namespace ctiso;
use Exception; use Exception;
class File { class File {
/**
* @param string $filename
* @return string
* @throws Exception
*/
static function getContents($filename) { static function getContents($filename) {
$buffer = @file_get_contents($filename); $buffer = @file_get_contents($filename);
if ($buffer !== false) { if ($buffer !== false) {

View file

@ -7,10 +7,15 @@ use ctiso\Role\UserInterface,
/* Переделать формат Логов на список json */ /* Переделать формат Логов на список json */
class ActionLogger implements FilterInterface class ActionLogger implements FilterInterface
{ {
public $before = array(); /** @var array */
public $before = [];
/** @var resource */
public $file; public $file;
/** @var UserInterface */
public $user; public $user;
/** @var string */
public $action; public $action;
/** @var \ctiso\Controller\ActionInterface */
public $processor; public $processor;
/** /**

View file

@ -18,7 +18,7 @@ class Authorization {
/** /**
* @param string $group * @param string $group
*/ */
static function isLogged($group = 'access') { static function isLogged($group = 'access'): bool {
// echo session_status(); // echo session_status();
if (session_status() == PHP_SESSION_NONE) { if (session_status() == PHP_SESSION_NONE) {
session_start(); session_start();
@ -40,7 +40,7 @@ class Authorization {
* @param int $id * @param int $id
* @param string $group * @param string $group
*/ */
static function enter($id, $group = 'access') { static function enter($id, $group = 'access'): void {
// $db->executeQuery("UPDATE visitor SET sid = '' WHERE id_visitor = " . $result->getInt('id_user')); // $db->executeQuery("UPDATE visitor SET sid = '' WHERE id_visitor = " . $result->getInt('id_user'));
// session_register("access"); // session_register("access");
// session_register("time"); // session_register("time");

View file

@ -5,7 +5,7 @@
*/ */
namespace ctiso\Filter; namespace ctiso\Filter;
use ctiso\Controller\Action; use ctiso\Database;
use ctiso\HttpRequest; use ctiso\HttpRequest;
class Filter implements \ctiso\Controller\ActionInterface class Filter implements \ctiso\Controller\ActionInterface
@ -26,12 +26,17 @@ class Filter implements \ctiso\Controller\ActionInterface
return $this->processor->execute($request); return $this->processor->execute($request);
} }
/**
* @param string $name
* @param class-string<\ctiso\View\View> $class
* @return \ctiso\View\View
*/
public function getView($name, $class = \ctiso\View\Top::class) public function getView($name, $class = \ctiso\View\Top::class)
{ {
return $this->processor->getView($name, $class); return $this->processor->getView($name, $class);
} }
public function getConnection() public function getConnection(): Database
{ {
return $this->processor->getConnection(); return $this->processor->getConnection();
} }

View file

@ -19,7 +19,9 @@ class Field
/** @var ?string */ /** @var ?string */
public $error_msg = null; public $error_msg = null;
public $default = null; public $default = null;
/** @var bool */
public $error = false; public $error = false;
/** @var bool */
public $require = false; public $require = false;
public $hint = null; public $hint = null;
/** @var ?int */ /** @var ?int */

View file

@ -39,7 +39,9 @@ class left {
define('__', '_ARGUMENT_PLACE_'); define('__', '_ARGUMENT_PLACE_');
class partial { class partial {
/** @var array<mixed> */
protected $params; protected $params;
/** @var callable */
protected $fn; protected $fn;
public function __construct($params) { public function __construct($params) {
@ -354,33 +356,37 @@ class Functions {
/** /**
* Поиск элемента в массиве * Поиск элемента в массиве
* @param mixed $cb сравнение с элементом массива * @param callable $cb сравнение с элементом массива
* @param array $hs массив в котором ищется значение * @param array $hs массив в котором ищется значение
* *
* @return int|string|null ключ найденого элемента в массиве * @return int|string|null ключ найденого элемента в массиве
*/ */
static function array_usearch($cb, array $hs, $strict = false) { static function array_usearch($cb, array $hs, $strict = false) {
foreach($hs as $key => $value) { foreach($hs as $key => $value) {
if (call_user_func_array($cb, [$value, $key, $strict])) return $key; if (call_user_func_array($cb, [$value, $key, $strict])) {
return $key;
}
} }
return null; return null;
} }
/** /**
* Выбирает все сроки из таблицы с уникальными значениями ключа * Выбирает все сроки из таблицы с уникальными значениями ключа
* @param string $name Имя ключа
* @param array $table Двухмерный массив
* @example * @example
* key_unique_values ('name', array (array ('name' => 1), array ('name' => 2), array ('name' => 1))) * key_unique_values ('name', array (array ('name' => 1), array ('name' => 2), array ('name' => 1)))
* => array (1, 2) * => array (1, 2)
* @end example *
* @param string $name Имя ключа
* @param array $table Двухмерный массив
* @return array Массив с уникальными значениями ключа
*/ */
static function key_unique_values ($name, $table) { static function key_unique_values ($name, $table) {
// Ищем уникальные значения для заданного ключа // Ищем уникальные значения для заданного ключа
$keys = []; $keys = [];
foreach ($table as $row) { foreach ($table as $row) {
if (!in_array ($row[$name], $keys)) if (!in_array ($row[$name], $keys)) {
$keys[] = $row[$name]; $keys[] = $row[$name];
}
} }
return $keys; return $keys;
} }

View file

@ -42,6 +42,10 @@ class HttpRequest extends Collection
parent::set('files', $data); parent::set('files', $data);
} }
/**
* @param string $key
* @return Collection
*/
function _get($key) function _get($key)
{ {
return parent::get($key); return parent::get($key);
@ -49,6 +53,7 @@ class HttpRequest extends Collection
/** /**
* @param string $key * @param string $key
* @param mixed $default
* @return mixed * @return mixed
*/ */
function get($key, $default = null) function get($key, $default = null)
@ -135,6 +140,9 @@ class HttpRequest extends Collection
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'); return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
} }
/**
* @param string $url
*/
public function redirect($url): void { public function redirect($url): void {
header('location: ' . $url); header('location: ' . $url);
exit(); exit();

View file

@ -93,7 +93,7 @@ class Settings
/** /**
* Обновляет массив в соответствии со значением * Обновляет массив в соответствии со значением
*/ */
protected function merge(array &$data, $value) protected function merge(array &$data, $value): void
{ {
foreach ($value as $key => $subvalue) { foreach ($value as $key => $subvalue) {
if (is_array($subvalue)) { if (is_array($subvalue)) {

View file

@ -4,26 +4,29 @@
* Преобразование дерева из модели Plain в массив массивов (Adjacency List) * Преобразование дерева из модели Plain в массив массивов (Adjacency List)
*/ */
/**
* Обходит таблицу как дерево
* $fn ($name, $index, $rows, $cc)
* $name Ключ уровня
* $index Значение ключа уровня
* $rows Все столбцы текущго уровня
* $cc Столбцы более низкого уровня
*
* @param Array $level Уровни вложенности
* @param array $table Таблица
* @param Function $fn Функция которая применяется к каждой ветке дерева
*/
namespace ctiso; namespace ctiso;
use ctiso\Functions; use ctiso\Functions;
class TableTree { class TableTree {
/**
* Обходит таблицу как дерево
* $fn ($name, $index, $rows, $cc)
* $name Ключ уровня
* $index Значение ключа уровня
* $rows Все столбцы текущго уровня
* $cc Столбцы более низкого уровня
*
* @param array $level Уровни вложенности
* @param array $table Таблица
* @param callable $fn Функция которая применяется к каждой ветке дерева
* @return array
*/
static function walk($level, $table, $fn) { static function walk($level, $table, $fn) {
if (empty ($level)) return $table; if (empty ($level)) {
return $table;
}
$name = array_shift ($level); $name = array_shift ($level);
$keys = Functions::key_unique_values($name, $table); $keys = Functions::key_unique_values($name, $table);
$data = []; $data = [];
foreach ($keys as $index) { foreach ($keys as $index) {

View file

@ -60,7 +60,7 @@ class Drawing
$max_height, $max_height,
$align, $align,
$valign $valign
) { ): float {
// echo $left,"\n", $top, "\n"; // echo $left,"\n", $top, "\n";
// echo $max_width,"\n", $max_height, "\n"; // echo $max_width,"\n", $max_height, "\n";
// self::drawrectnagle($image, $left, $top, $max_width, $max_height, array(0xFF,0,0)); // self::drawrectnagle($image, $left, $top, $max_width, $max_height, array(0xFF,0,0));
@ -136,7 +136,7 @@ class Drawing
return $largest_line_height * count($lines); return $largest_line_height * count($lines);
} }
function imagettftextSp(GdImage $image, float $size, float $angle, int $x, int $y, int $color, string $font, string $text, int $spacing = 0) function imagettftextSp(GdImage $image, float $size, float $angle, int $x, int $y, int $color, string $font, string $text, int $spacing = 0): void
{ {
if ($spacing == 0) { if ($spacing == 0) {
imagettftext($image, $size, $angle, $x, $y, $color, $font, $text); imagettftext($image, $size, $angle, $x, $y, $color, $font, $text);

View file

@ -9,7 +9,9 @@ use GdImage;
class TemplateImage class TemplateImage
{ {
/** @var array<string, string> */
static array $listfiles = array('jpg' => 'jpeg', 'gif' => 'gif', 'png' => 'png', 'bmp' => 'wbmp'); static array $listfiles = array('jpg' => 'jpeg', 'gif' => 'gif', 'png' => 'png', 'bmp' => 'wbmp');
/** @var array<string, string> */
static array $listfonts = array( static array $listfonts = array(
'georgia' => 'georgia.ttf', 'georgia' => 'georgia.ttf',
'georgiabd' => 'georgiab.ttf', 'georgiabd' => 'georgiab.ttf',
@ -68,7 +70,7 @@ class TemplateImage
$this->base = $path; $this->base = $path;
} }
function set(string $name, $value) function set(string $name, $value): void
{ {
$this->context['['.$name.']'] = $value; $this->context['['.$name.']'] = $value;
} }
@ -79,6 +81,11 @@ class TemplateImage
$this->image = $this->imagefromfile($name); $this->image = $this->imagefromfile($name);
} }
/**
* Создает пустое изображение
* @param int $width
* @param int $height
*/
function setEmptyImage($width, $height): void function setEmptyImage($width, $height): void
{ {
$this->image = imagecreatetruecolor($width, $height); $this->image = imagecreatetruecolor($width, $height);
@ -86,6 +93,8 @@ class TemplateImage
/** /**
* Создает изображение из файла * Создает изображение из файла
* @param string $file
* @return GdImage|null
*/ */
function imagefromfile(string $file) function imagefromfile(string $file)
{ {

View file

@ -23,14 +23,14 @@ class Composite extends View
// $this->tal->addPreFilter(new PHPTAL_PreFilter_Normalize()); // $this->tal->addPreFilter(new PHPTAL_PreFilter_Normalize());
} }
function set(string $key, mixed $val) { function set(string $key, mixed $val): void {
if ($key == 'title') { if ($key == 'title') {
$this->setTitle($val); $this->setTitle($val);
} }
$this->tal->set($key, $val); $this->tal->set($key, $val);
} }
function __set(string $key, mixed $val) { function __set(string $key, mixed $val): void {
$this->tal->set($key, $val); $this->tal->set($key, $val);
} }