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

@ -8,14 +8,17 @@ class HttpRequest
const POST = "POST";
const GET = "GET";
private $param = array(); // Параметры запроса
private $param = []; // Параметры запроса
public $data = null; // Содержание
public $url; // Адресс
public $method; // Метод
/** @var int */
public $port = 80;
/** @var string */
public $host = "";
public $proxy_host = null;
public $proxy_port = null;
/** @var string */
public $http_version = 'HTTP/1.1';
function __construct() {
@ -24,6 +27,7 @@ class HttpRequest
/**
* Возвращает заголовок соединения
* @return string
*/
public function getHeader()
{
@ -39,8 +43,8 @@ class HttpRequest
/**
* Установка параметров запроса
* @parma string $name
* @parma string $value
* @param string $name
* @param string $value
*/
public function setParameter($name, $value)
{
@ -49,29 +53,35 @@ class HttpRequest
/**
* Метод запроса GET или POST
* @param string $method
*/
public function setMethod($method)
public function setMethod($method): void
{
$this->method = $method;
}
public function setUrl($url)
/**
* Установка URL
* @param string $url
*/
public function setUrl($url): void
{
$this->url = $url;
$this->host = parse_url($this->url, PHP_URL_HOST);
}
public function getUrl()
public function getUrl(): string
{
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;
}
@ -99,6 +109,12 @@ class HttpRequest
return null;
}
/**
* Получение JSON
* @param string $url
* @param array $data
* @return array
*/
static function getJSON($url, $data) {
$query = http_build_query($data);
$q = $url . '?' . $query;

View file

@ -8,7 +8,7 @@ namespace ctiso\Connection;
class HttpResponse
{
private $offset;
private $param = array ();
private $param = [];
private $code;
public $response;
public $version;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -18,7 +18,7 @@ class Authorization {
/**
* @param string $group
*/
static function isLogged($group = 'access') {
static function isLogged($group = 'access'): bool {
// echo session_status();
if (session_status() == PHP_SESSION_NONE) {
session_start();
@ -40,7 +40,7 @@ class Authorization {
* @param int $id
* @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'));
// session_register("access");
// session_register("time");

View file

@ -5,7 +5,7 @@
*/
namespace ctiso\Filter;
use ctiso\Controller\Action;
use ctiso\Database;
use ctiso\HttpRequest;
class Filter implements \ctiso\Controller\ActionInterface
@ -26,12 +26,17 @@ class Filter implements \ctiso\Controller\ActionInterface
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)
{
return $this->processor->getView($name, $class);
}
public function getConnection()
public function getConnection(): Database
{
return $this->processor->getConnection();
}

View file

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

View file

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

View file

@ -42,6 +42,10 @@ class HttpRequest extends Collection
parent::set('files', $data);
}
/**
* @param string $key
* @return Collection
*/
function _get($key)
{
return parent::get($key);
@ -49,6 +53,7 @@ class HttpRequest extends Collection
/**
* @param string $key
* @param mixed $default
* @return mixed
*/
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');
}
/**
* @param string $url
*/
public function redirect($url): void {
header('location: ' . $url);
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) {
if (is_array($subvalue)) {

View file

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

View file

@ -60,7 +60,7 @@ class Drawing
$max_height,
$align,
$valign
) {
): float {
// echo $left,"\n", $top, "\n";
// echo $max_width,"\n", $max_height, "\n";
// 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);
}
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) {
imagettftext($image, $size, $angle, $x, $y, $color, $font, $text);

View file

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

View file

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