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

This commit is contained in:
origami11@yandex.ru 2025-10-22 17:48:37 +03:00
parent e2ba6bd46e
commit e5713e9015
28 changed files with 305 additions and 110 deletions

View file

@ -4,16 +4,23 @@
* Класс оболочка для PDOStatement для замены Creole * Класс оболочка для PDOStatement для замены Creole
*/ */
namespace ctiso\Database; namespace ctiso\Database;
use PDO,
ctiso\Database; use PDO;
use ctiso\Database;
class Statement class Statement
{ {
/** @var ?int */
protected $limit = null; protected $limit = null;
/** @var ?int */
protected $offset = null; protected $offset = null;
/** @var never */
protected $statement = null; protected $statement = null;
protected $binds = array(); /** @var array{int|string, mixed, int}[] */
protected $binds = [];
/** @var Database */
protected $conn; protected $conn;
/** @var string */
protected $query; protected $query;
/** /**
@ -37,14 +44,23 @@ class Statement
$this->binds [] = [$n, $value, PDO::PARAM_LOB]; $this->binds [] = [$n, $value, PDO::PARAM_LOB];
} }
/**
* @param int $limit
*/
function setLimit($limit) { function setLimit($limit) {
$this->limit = $limit; $this->limit = $limit;
} }
/**
* @param int $offset
*/
function setOffset($offset) { function setOffset($offset) {
$this->offset = $offset; $this->offset = $offset;
} }
/**
* @return ?PDOStatement
*/
function executeQuery() { function executeQuery() {
if ($this->limit) { if ($this->limit) {
$this->query .= " LIMIT {$this->limit} OFFSET {$this->offset}"; $this->query .= " LIMIT {$this->limit} OFFSET {$this->offset}";

View file

@ -26,7 +26,7 @@ class TableCell
class TableRow class TableRow
{ {
public $style = false; public $style = false;
public $cells = array(); public $cells = [];
public $height = false; public $height = false;
function setCell($y, $value) function setCell($y, $value)
@ -48,7 +48,7 @@ class Table
static $index; static $index;
private $name; private $name;
private $style; private $style;
protected $rows = array(); protected $rows = [];
protected $_splitVertical = false; protected $_splitVertical = false;
protected $_splitHorizontal = false; protected $_splitHorizontal = false;
@ -106,9 +106,9 @@ class Table
* @param int $row Номер ряда * @param int $row Номер ряда
* @param string $name Имя стиля * @param string $name Имя стиля
*/ */
function setRowStyle ($row, $name) function setRowStyle(int $row, $name)
{ {
assert(is_numeric($row) && $row > 0); assert($row > 0);
$this->rows[$row]->style = $name; $this->rows[$row]->style = $name;
} }

View file

@ -5,12 +5,19 @@ namespace ctiso\Filter;
class Authorization { class Authorization {
const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#'; const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#';
const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign';
/** @var string */
public $group; public $group;
/**
* @param string $group
*/
function __construct($group) { function __construct($group) {
$this->group = $group; $this->group = $group;
} }
/**
* @param string $group
*/
static function isLogged($group = 'access') { static function isLogged($group = 'access') {
// echo session_status(); // echo session_status();
if (session_status() == PHP_SESSION_NONE) { if (session_status() == PHP_SESSION_NONE) {
@ -29,6 +36,10 @@ class Authorization {
return false; return false;
} }
/**
* @param int $id
* @param string $group
*/
static function enter($id, $group = 'access') { static function enter($id, $group = 'access') {
// $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");
@ -40,7 +51,7 @@ class Authorization {
$_SESSION ["time"] = time(); $_SESSION ["time"] = time();
} }
static function getRawSign() static function getRawSign(): string
{ {
$rawSign = self::SESSION_BROWSER_SIGN_SECRET; $rawSign = self::SESSION_BROWSER_SIGN_SECRET;
$signParts = ['HTTP_USER_AGENT']; $signParts = ['HTTP_USER_AGENT'];
@ -48,17 +59,16 @@ class Authorization {
foreach ($signParts as $signPart) { foreach ($signParts as $signPart) {
$rawSign .= '::' . ($_SERVER[$signPart] ?? 'none'); $rawSign .= '::' . ($_SERVER[$signPart] ?? 'none');
} }
return $rawSign; return $rawSign;
} }
static function getBrowserSign() static function getBrowserSign(): string
{ {
return md5(self::getRawSign()); return md5(self::getRawSign());
} }
function logout() { function logout(): void {
session_destroy(); session_destroy();
} }
} }

View file

@ -5,8 +5,9 @@ use ctiso\Form\Field;
class CheckBox extends Field class CheckBox extends Field
{ {
/** @var bool */
public $checked = false; public $checked = false;
function setValue($value) function setValue($value): void
{ {
$this->value = $value; $this->value = $value;
$this->checked = $value; $this->checked = $value;

View file

@ -6,22 +6,31 @@ namespace ctiso\Form;
class Field class Field
{ {
/** @var bool */
public $hidden = false; public $hidden = false;
/** @var string */
public $name; public $name;
/** @var string */
public $label; // Метка поля public $label; // Метка поля
public $value; // Значение поля public $value; // Значение поля
/** @var string */
public $type = ""; // Каждому типу элемента соответствует макрос TAL public $type = ""; // Каждому типу элемента соответствует макрос TAL
/** @var ?string */
public $error_msg = null; public $error_msg = null;
public $default = null; public $default = null;
public $error = false; public $error = false;
public $require = false; public $require = false;
public $hint = null; public $hint = null;
/** @var ?int */
public $maxlength = null; public $maxlength = null;
public $fieldset = null; public $fieldset = null;
// Блоки (Убрать в отдельный класс!!!) // Блоки (Убрать в отдельный класс!!!)
public $_title = array(); public $_title = [];
/** @var string */
public $description = ""; public $description = "";
public $alias = array(); /** @var array */
public $alias = [];
/** @phpstan-ignore-next-line */ /** @phpstan-ignore-next-line */
public function __construct ($input = [], $factory = null) public function __construct ($input = [], $factory = null)
@ -44,12 +53,12 @@ class Field
/** /**
* @param mixed $value * @param mixed $value
*/ */
function setValue($value) function setValue($value): void
{ {
$this->value = $value; $this->value = $value;
} }
function getId() function getId(): string
{ {
return $this->name . '_label'; return $this->name . '_label';
} }

View file

@ -16,18 +16,26 @@ use ctiso\Form\Field,
* Форма для ввода * Форма для ввода
*/ */
class Form { class Form {
/** @var array */
public $field = []; //Поля формы public $field = []; //Поля формы
/** @var array */
public $fieldsets = []; //Группы полей (fieldset). Некоторые поля могут не принадлежать никаким группам public $fieldsets = []; //Группы полей (fieldset). Некоторые поля могут не принадлежать никаким группам
/** @var string */
public $action = ""; public $action = "";
/** @var string */
public $method = 'post'; public $method = 'post';
/** @var string */
public $header; public $header;
protected $replace; protected $replace;
protected $before; protected $before;
/** @var array */
public $_title = []; public $_title = [];
/** @var array */
public $alias = []; public $alias = [];
/** @var class-string<Field>[] */
private $constructor = []; private $constructor = [];
/** /**
@ -119,7 +127,6 @@ class Form {
/** /**
* Добавление массива fieldset на форму * Добавление массива fieldset на форму
*/ */
public function addFieldSetList(array $list) public function addFieldSetList(array $list)
{ {
foreach ($list as $fieldset) { foreach ($list as $fieldset) {
@ -150,6 +157,11 @@ class Form {
} }
} }
/**
* Устанавливает ошибку для поля
* @param string $name
* @param string $message
*/
function setFieldError($name, $message) function setFieldError($name, $message)
{ {
$this->field[$name]->error = true; $this->field[$name]->error = true;

View file

@ -4,5 +4,6 @@ namespace ctiso\Form;
use ctiso\Form\Input; use ctiso\Form\Input;
class Hidden extends Input { class Hidden extends Input {
/** @var bool */
public $hidden = true; public $hidden = true;
} }

View file

@ -5,7 +5,7 @@ use ctiso\Form\Select;
class QuestionType extends Select class QuestionType extends Select
{ {
function setValue($value) function setValue($value): void
{ {
// Установить selected у options // Установить selected у options
$this->value = $value; $this->value = $value;

View file

@ -5,7 +5,7 @@ use ctiso\Form\Select;
class SelectMany extends Select class SelectMany extends Select
{ {
function setValue($value) function setValue(mixed $value): void
{ {
// Установить selected у options // Установить selected у options
if (!is_array($value)) { $value = [$value]; } if (!is_array($value)) { $value = [$value]; }

View file

@ -8,7 +8,7 @@ use ctiso\Form\Select;
class SelectOne extends Select class SelectOne extends Select
{ {
function setValue($value) function setValue($value): void
{ {
// Установить selected у options // Установить selected у options
$this->value = $value; $this->value = $value;

View file

@ -1,13 +1,13 @@
<?php <?php
/** /**
* Текстовое поле * Текстовое поле
*/ */
namespace ctiso\Form; namespace ctiso\Form;
use ctiso\Form\Field; use ctiso\Form\Field;
class TextArea extends Field { class TextArea extends Field {
function setValue($value) function setValue($value): void
{ {
$this->value = $value; $this->value = $value;
} }

View file

@ -1,6 +1,6 @@
<?php <?php
/** /**
* http://www.alternateinterior.com/2006/09/a-viewstate-for-php.html * http://www.alternateinterior.com/2006/09/a-viewstate-for-php.html
* Управление состоянием между страницами * Управление состоянием между страницами
*/ */
@ -8,14 +8,20 @@ namespace ctiso\Form;
class ViewState // extends Collection class ViewState // extends Collection
{ {
private $values = array(); /** @var array */
private $values = [];
function set($name, $value) /**
* Устанавливает значение
* @param string $name
* @param mixed $value
*/
function set($name, $value): void
{ {
$this->values[$name] = $value; $this->values[$name] = $value;
} }
function get($_rest) function get($_rest)
{ {
$args = func_get_args(); $args = func_get_args();
$result = $this->values; $result = $this->values;
@ -28,7 +34,7 @@ class ViewState // extends Collection
return $result; return $result;
} }
function saveState() function saveState(): string
{ {
return base64_encode(serialize($this->values)); return base64_encode(serialize($this->values));
} }

View file

@ -1,15 +1,10 @@
<?php <?php
/** namespace ctiso;
* Функциональное программирование в PHP
* package functional
*/
/** /**
* Эмуляция каррированой функции * Эмуляция каррированой функции
*/ */
namespace ctiso;
class right { class right {
protected $params; protected $params;
protected $fn; protected $fn;

View file

@ -1,9 +1,10 @@
<?php <?php
namespace ctiso\Model; namespace ctiso\Model;
use ctiso\Registry,
ctiso\Database, use ctiso\Registry;
ctiso\Role\User; use ctiso\Database;
use ctiso\Role\User;
class Factory class Factory
{ {

View file

@ -160,6 +160,10 @@ class Path
return false; return false;
} }
/**
* Преобразует путь в строку
* @param array{ host?: string, path?: string, query?: string, fragment?: string, scheme?: string, user?: string, pass?: string, port?: int} $path Путь
*/
public static function makeUrl($path): string public static function makeUrl($path): string
{ {
$slash = (isset($path['host']) && (strlen($path['path']) > 0) && ($path['path'][0] != '/')) ? '/' : ''; $slash = (isset($path['host']) && (strlen($path['path']) > 0) && ($path['path'][0] != '/')) ? '/' : '';
@ -231,7 +235,12 @@ class Path
return $path->__toString(); return $path->__toString();
} }
// Вычисляет относительный путь в виде строки /**
* Вычисляет относительный путь в виде строки
* @param string $rpath Путь относительно которого вычисляется относительный путь
* @param string $lpath Путь к которому вычисляется относительный путь
* @return string Относительный путь
*/
static function relative($rpath, $lpath) { static function relative($rpath, $lpath) {
// Нужно проверять диск!! // Нужно проверять диск!!
$self = new Path($rpath); $self = new Path($rpath);
@ -259,6 +268,7 @@ class Path
/** /**
* @param string $path * @param string $path
* @return string
*/ */
public function append($path) public function append($path)
{ {
@ -300,12 +310,12 @@ class Path
} }
// Проверка структуры имени файла // Проверка структуры имени файла
static function checkName(string $name, string $extension) static function checkName(string $name, string $extension): bool
{ {
return (strlen(pathinfo($name, PATHINFO_FILENAME)) > 0) && (pathinfo($name, PATHINFO_EXTENSION) == $extension); return (strlen(pathinfo($name, PATHINFO_FILENAME)) > 0) && (pathinfo($name, PATHINFO_EXTENSION) == $extension);
} }
static function isCharName(string $char) static function isCharName(string $char): bool
{ {
$ch = ord($char); $ch = ord($char);
return ((($ch >= ord('a')) && ($ch <= ord('z'))) || (strpos('-._', $char) !== false) || (($ch >= ord('0')) && ($ch <= ord('9')))); return ((($ch >= ord('a')) && ($ch <= ord('z'))) || (strpos('-._', $char) !== false) || (($ch >= ord('0')) && ($ch <= ord('9'))));
@ -354,10 +364,10 @@ class Path
/** /**
* Список файлов в директории * Список файлов в директории
* *
* @param ?array $allow массив расширений для файлов * @param ?string[] $allow массив расширений для файлов
* @param array $ignore массив имен пааок которые не нужно обрабатывать * @param string[] $ignore массив имен пааок которые не нужно обрабатывать
* *
* @returnarray * @return string[]
*/ */
public function getContent(?array $allow = null, array $ignore = []) public function getContent(?array $allow = null, array $ignore = [])
{ {
@ -368,10 +378,10 @@ class Path
/** /**
* Обьединяет строки в путь соединяя необходимым разделителем * Обьединяет строки в путь соединяя необходимым разделителем
* *
* @param ?array $allow массив расширений разрешеных для файлов * @param ?string[] $allow массив расширений разрешеных для файлов
* @param array $ignore массив имен пааок которые не нужно обрабатывать * @param string[] $ignore массив имен папок которые не нужно обрабатывать
* *
* @return array * @return string[]
*/ */
function getContentRec(?array $allow = null, array $ignore = []) function getContentRec(?array $allow = null, array $ignore = [])
{ {
@ -381,7 +391,15 @@ class Path
return $result; return $result;
} }
// Использовать SPL ??? /**
* Список файлов в директории
*
* @param string $base Базовый путь
* @param ?string[] $allow массив расширений для файлов
* @param string[] $ignore массив имен папок которые не нужно обрабатывать
*
* @return string[]
*/
protected static function fileList(string $base, ?array &$allow, array &$ignore): array protected static function fileList(string $base, ?array &$allow, array &$ignore): array
{ {
if ($base == '') $base = '.'; if ($base == '') $base = '.';
@ -407,7 +425,7 @@ class Path
return $result; return $result;
} }
protected static function fileListAll(array &$result, string $base, ?array &$allow, array &$ignore) protected static function fileListAll(array &$result, string $base, ?array &$allow, array &$ignore): void
{ {
$files = self::fileList($base, $allow, $ignore); $files = self::fileList($base, $allow, $ignore);
foreach ($files as $name) { foreach ($files as $name) {

View file

@ -3,7 +3,6 @@
/** /**
* Преобразование типов !!! Пересмотреть использование классов!! * Преобразование типов !!! Пересмотреть использование классов!!
* Класс преобразования типа значения поля класса в тип поля таблицы * Класс преобразования типа значения поля класса в тип поля таблицы
* @package system
*/ */
namespace ctiso; namespace ctiso;

View file

@ -5,8 +5,7 @@ use ctiso\File,
Exception; Exception;
class Registry { class Registry {
public array $namespace = []; private array $namespace = [];
public $data;
function importFile(string $namespace, ?string $filePath = null) { function importFile(string $namespace, ?string $filePath = null) {
$data = json_decode(File::getContents($filePath), true); $data = json_decode(File::getContents($filePath), true);

View file

@ -1,8 +1,10 @@
<?php <?php
namespace ctiso\Role; namespace ctiso\Role;
use ctiso\Database,
ctiso\Database\Statement; use ctiso\Database;
use ctiso\Database\Statement;
use ctiso\Database\PDOStatement;
// Класс должен быть в библиотеке приложения // Класс должен быть в библиотеке приложения
class User implements UserInterface class User implements UserInterface
@ -11,8 +13,10 @@ class User implements UserInterface
public string $fullname; public string $fullname;
public string $name; public string $name;
/** @var string */
public $access; public $access;
public string $password; public string $password;
/** @var int */
public $id; public $id;
public Database $db; public Database $db;
public array $groups; public array $groups;
@ -34,8 +38,7 @@ class User implements UserInterface
return \ctiso\Filter\Authorization::isLogged(); return \ctiso\Filter\Authorization::isLogged();
} }
public function getUserByQuery(Statement $stmt): ?PDOStatement
public function getUserByQuery(Statement $stmt)
{ {
$result = $stmt->executeQuery(); $result = $stmt->executeQuery();
if ($result->next()) { if ($result->next()) {
@ -56,7 +59,7 @@ class User implements UserInterface
return $result->get('password'); return $result->get('password');
} }
public function getUserByLogin(string $login) public function getUserByLogin(string $login): ?PDOStatement
{ {
$stmt = $this->db->prepareStatement("SELECT * FROM users WHERE login = ?"); $stmt = $this->db->prepareStatement("SELECT * FROM users WHERE login = ?");
$stmt->setString(1, $login); $stmt->setString(1, $login);
@ -69,7 +72,7 @@ class User implements UserInterface
return $result; return $result;
} }
public function getUserById(int $id) public function getUserById(int $id): ?PDOStatement
{ {
$stmt = $this->db->prepareStatement("SELECT * FROM users WHERE id_user = ?"); $stmt = $this->db->prepareStatement("SELECT * FROM users WHERE id_user = ?");
$stmt->setInt(1, $_SESSION ['access']); $stmt->setInt(1, $_SESSION ['access']);

View file

@ -199,10 +199,20 @@ class Settings
file_put_contents (($file) ? $file : $this->file, $result); file_put_contents (($file) ? $file : $this->file, $result);
} }
public function set($key, $value) { /**
* Установка значения ключа
* @param string $key Ключ
* @param mixed $value Значение
*/
public function set($key, $value): void {
$this->data[$key] = $value; $this->data[$key] = $value;
} }
/**
* Получение значения ключа
* @param string $key Ключ
* @return mixed
*/
public function get($key, $default = null) public function get($key, $default = null)
{ {
return isset($this->data[$key]) && $this->data[$key] != '' ? $this->data[$key] : $default; return isset($this->data[$key]) && $this->data[$key] != '' ? $this->data[$key] : $default;
@ -218,6 +228,7 @@ class Settings
/** /**
* Список модулей/ключей * Список модулей/ключей
* @return array
*/ */
public function getKeys() public function getKeys()
{ {
@ -226,6 +237,8 @@ class Settings
/** /**
* Проверка наличия ключа * Проверка наличия ключа
* @param string $name Ключ
* @return bool
*/ */
public function hasKey($name) public function hasKey($name)
{ {

View file

@ -13,28 +13,44 @@ use ctiso\Path;
use SimpleXMLElement; use SimpleXMLElement;
class FakeZipArchive { class FakeZipArchive {
/** @var string */
public $base; public $base;
function open($path) {
function open(string $path) {
$this->base = $path; $this->base = $path;
} }
/**
* Возвращает содержимое файла
* @param string $file
* @return string
*/
function getFromName($file) { function getFromName($file) {
return file_get_contents(Path::join($this->base, $file)); return file_get_contents(Path::join($this->base, $file));
} }
} }
class Setup class Setup
{ {
protected $actions = array(); /** @var array */
public $context = array(); protected $actions = [];
/** @var array */
public $context = [];
/** @var string */
protected $file; protected $file;
/** @var string */
protected $action; protected $action;
/** @var SimpleXMLElement */
protected $node; protected $node;
protected $stack = array(); /** @var array */
protected $stack = [];
/** @var FakeZipArchive */
public $zip; public $zip;
/** @var string */
public $target; public $target;
/** @var string */
public $source; public $source;
public function __construct($file) public function __construct($file)
@ -58,14 +74,18 @@ class Setup
/** /**
* Регистрация новых действия для установки * Регистрация новых действия для установки
* @param string $name
* @param callable $action
*/ */
public function registerAction(string $name, $action) public function registerAction(string $name, $action): void
{ {
$this->actions[$name] = $action; $this->actions[$name] = $action;
} }
/** /**
* Установка переменных для шаблона * Установка переменных для шаблона
* @param string $name
* @param mixed $value
*/ */
public function set(string $name, $value) public function set(string $name, $value)
{ {
@ -188,7 +208,7 @@ class Setup
$setup->executeActions(); $setup->executeActions();
} }
function targetPath($s) { function targetPath(string $s): string {
return $this->target . '/' . $s; return $this->target . '/' . $s;
} }
@ -198,7 +218,7 @@ class Setup
* *
* @param array{dst:string} $attributes * @param array{dst:string} $attributes
*/ */
public function makeDirectory(array $attributes) public function makeDirectory(array $attributes): void
{ {
$path = $this->targetPath($attributes['dst']); $path = $this->targetPath($attributes['dst']);
if (!file_exists($path)) { if (!file_exists($path)) {
@ -206,7 +226,7 @@ class Setup
} }
} }
function testWhen(array $attributes) function testWhen(array $attributes): void
{ {
if (!isset($attributes['test']) || $attributes['test'] == $this->action) { if (!isset($attributes['test']) || $attributes['test'] == $this->action) {
$this->executeActions($this->action); $this->executeActions($this->action);
@ -218,7 +238,7 @@ class Setup
* @param Database $conn * @param Database $conn
* @param string $file * @param string $file
*/ */
function batchSQLZip($conn, $file) function batchSQLZip($conn, $file): void
{ {
$stmtList = SQLStatementExtractor::extract($this->zip->getFromName($file)); $stmtList = SQLStatementExtractor::extract($this->zip->getFromName($file));
foreach ($stmtList as $stmt) { foreach ($stmtList as $stmt) {
@ -231,7 +251,7 @@ class Setup
* @param Database $conn * @param Database $conn
* @param string $file * @param string $file
*/ */
static function batchSQL($conn, $file) static function batchSQL($conn, $file): void
{ {
$stmtList = SQLStatementExtractor::extractFile($file); $stmtList = SQLStatementExtractor::extractFile($file);
foreach ($stmtList as $stmt) { foreach ($stmtList as $stmt) {

View file

@ -13,12 +13,12 @@ use PHPTAL_Php_TalesInternal,
class Tales_DateTime implements PHPTAL_Tales class Tales_DateTime implements PHPTAL_Tales
{ {
static public function date(string $expression, $nothrow = false): string static public function date(string $expression, bool $nothrow = false): string
{ {
return "ctiso\\Tales::phptal_date(".PHPTAL_Php_TalesInternal::path($expression).")"; return "ctiso\\Tales::phptal_date(".PHPTAL_Php_TalesInternal::path($expression).")";
} }
static public function time(string $expression, $nothrow = false): string static public function time(string $expression, bool $nothrow = false): string
{ {
return "ctiso\\Tales::phptal_time(".PHPTAL_Php_TalesInternal::path($expression).")"; return "ctiso\\Tales::phptal_time(".PHPTAL_Php_TalesInternal::path($expression).")";
} }
@ -26,7 +26,7 @@ class Tales_DateTime implements PHPTAL_Tales
class Tales_Component implements PHPTAL_Tales class Tales_Component implements PHPTAL_Tales
{ {
static public function component(string $expression, $nothrow = false): string static public function component(string $expression, bool $nothrow = false): string
{ {
$s = PHPTAL_Php_TalesInternal::string($expression); $s = PHPTAL_Php_TalesInternal::string($expression);
return "ctiso\\Tales::phptal_component(" . $s . ")"; return "ctiso\\Tales::phptal_component(" . $s . ")";
@ -35,7 +35,7 @@ class Tales_Component implements PHPTAL_Tales
class Tales_Assets implements PHPTAL_Tales class Tales_Assets implements PHPTAL_Tales
{ {
static public function assets(string $expression, $nothrow = false): string static public function assets(string $expression, bool $nothrow = false): string
{ {
$s = PHPTAL_Php_TalesInternal::string($expression); $s = PHPTAL_Php_TalesInternal::string($expression);
return "ctiso\\Tales::phptal_asset(" . $s . ")"; return "ctiso\\Tales::phptal_asset(" . $s . ")";

View file

@ -12,7 +12,15 @@ class Drawing
const ALIGN_CENTER = "center"; const ALIGN_CENTER = "center";
const ALIGN_RIGHT = "right"; const ALIGN_RIGHT = "right";
static function drawrectnagle(GdImage &$image, int $left, int $top, int $width, int $height, array $rgb): void /**
* @param GdImage $image
* @param int $left
* @param int $top
* @param int $width
* @param int $height
* @param array $rgb
*/
static function drawRectangle(GdImage &$image, int $left, int $top, int $width, int $height, array $rgb): void
{ {
$color = imagecolorallocate($image, $rgb[0], $rgb[1], $rgb[2]); $color = imagecolorallocate($image, $rgb[0], $rgb[1], $rgb[2]);
$right = $left + $width; $right = $left + $width;
@ -25,6 +33,19 @@ class Drawing
/** /**
* http://ru2.php.net/imagettftext * http://ru2.php.net/imagettftext
*
* @param GdImage $image
* @param int $size
* @param float $angle
* @param int $left
* @param int $top
* @param int $color
* @param string $font
* @param string $text
* @param int $max_width
* @param int $max_height
* @param string $align
* @param string $valign
*/ */
static function imagettftextbox( static function imagettftextbox(
GdImage &$image, GdImage &$image,
@ -115,7 +136,6 @@ 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)
{ {
if ($spacing == 0) { if ($spacing == 0) {

View file

@ -7,7 +7,7 @@ use GdImage;
class Image class Image
{ {
/** /**
* @param $uri * @param string $uri
* @return GdImage|false * @return GdImage|false
*/ */
static function load($uri): GdImage|false static function load($uri): GdImage|false

View file

@ -2,10 +2,16 @@
namespace ctiso\Tools; namespace ctiso\Tools;
class StringUtil { class StringUtil
{
// from creole /**
static function strToArray(string $str): array { * Преобразует строку в массив
* @param string $str
* @return array
*/
static function strToArray(string $str): array
{
$str = substr($str, 1, -1); // remove { } $str = substr($str, 1, -1); // remove { }
$res = []; $res = [];
@ -13,7 +19,7 @@ class StringUtil {
$in_subarr = 0; $in_subarr = 0;
$toks = explode(',', $str); $toks = explode(',', $str);
foreach($toks as $tok) { foreach ($toks as $tok) {
if ($in_subarr > 0) { // already in sub-array? if ($in_subarr > 0) { // already in sub-array?
$subarr[$in_subarr][] = $tok; $subarr[$in_subarr][] = $tok;
if ('}' === substr($tok, -1, 1)) { // check to see if we just added last component if ('}' === substr($tok, -1, 1)) { // check to see if we just added last component
@ -21,7 +27,7 @@ class StringUtil {
$in_subarr--; $in_subarr--;
} }
} elseif ($tok[0] === '{') { // we're inside a new sub-array } elseif ($tok[0] === '{') { // we're inside a new sub-array
if ('}' !== substr($tok, -1, 1)) { if ('}' !== substr($tok, -1, 1)) {
$in_subarr++; $in_subarr++;
// if sub-array has more than one element // if sub-array has more than one element
$subarr[$in_subarr] = []; $subarr[$in_subarr] = [];
@ -32,26 +38,37 @@ class StringUtil {
} else { // not sub-array } else { // not sub-array
$val = trim($tok, '"'); // remove " (surrounding strings) $val = trim($tok, '"'); // remove " (surrounding strings)
// perform type castng here? // perform type castng here?
$res[] = $val; $res[] = $val;
} }
} }
return $res; return $res;
} }
//Нормализация строк на русском /**
static function normalizeRussian(string $str): string { * Нормализация строк на русском
$result = preg_replace('/\s+/',' ', $str); * @param string $str
* @return string
*/
static function normalizeRussian(string $str): string
{
$result = preg_replace('/\s+/', ' ', $str);
if (is_string($result)) { if (is_string($result)) {
$result = trim($result); //Замена длинных пробелов на одинарные, пробелы по краям $result = trim($result); //Замена длинных пробелов на одинарные, пробелы по краям
$result = mb_strtolower($result); $result = mb_strtolower($result);
$result = preg_replace('/ё/','е', $str); //е на ё $result = preg_replace('/ё/', 'е', $str); //е на ё
} }
return $result; return $result;
} }
//Проверка равенства двух строк на русском языке. /**
static function equalRussianCheck($str1,$str2): bool { * Проверка равенства двух строк на русском языке.
* @param string $str1
* @param string $str2
* @return bool
*/
static function equalRussianCheck($str1, $str2): bool
{
return self::normalizeRussian($str1) == self::normalizeRussian($str2); return self::normalizeRussian($str1) == self::normalizeRussian($str2);
} }
@ -61,33 +78,52 @@ class StringUtil {
* output: true * output: true
* input: $str="foo" $variants="foo1|foo2|foo3" * input: $str="foo" $variants="foo1|foo2|foo3"
* output: false * output: false
*/ *
static function compare_string_to_variants($str, string $variants){ * @param string $str
* @param string $variants
* @return bool
*/
static function compare_string_to_variants($str, string $variants)
{
$variants_array = explode('|', $variants); $variants_array = explode('|', $variants);
$founded = false; $founded = false;
foreach ($variants_array as $variant) { foreach ($variants_array as $variant) {
$founded = $founded || self::equalRussianCheck($variant, $str); $founded = $founded || self::equalRussianCheck($variant, $str);
} }
return $founded; return $founded;
} }
static function mb_str_split(string $str): array|false { /**
* Разбивает строку на массив символов
* @param string $str
* @return array|false
*/
static function mb_str_split(string $str): array|false
{
return preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY); return preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY);
} }
static function mb_strtr($str, $from, $to) { /**
* Заменяет символы в строке на символы из другой строки
* @param string $str
* @param string $from
* @param string $to
* @return string
*/
static function mb_strtr($str, $from, $to)
{
return str_replace(self::mb_str_split($from), self::mb_str_split($to), $str); return str_replace(self::mb_str_split($from), self::mb_str_split($to), $str);
} }
static function encodestring(string $st): string static function encodestring(string $st): string
{ {
$st = self::mb_strtr($st,"абвгдеёзийклмнопрстуфхъыэ !+()", "abvgdeeziyklmnoprstufh_ie_____"); $st = self::mb_strtr($st, "абвгдеёзийклмнопрстуфхъыэ !+()", "abvgdeeziyklmnoprstufh_ie_____");
$st = self::mb_strtr($st,"АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ", "ABVGDEEZIYKLMNOPRSTUFH_IE"); $st = self::mb_strtr($st, "АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ", "ABVGDEEZIYKLMNOPRSTUFH_IE");
$st = strtr($st, [ $st = strtr($st, [
" " => '_', " " => '_',
"." => '_', "." => '_',
"," => '_', "," => '_',
"?" => '_', "?" => '_',
"\"" => '_', "\"" => '_',
"'" => '_', "'" => '_',
"/" => '_', "/" => '_',
@ -95,18 +131,38 @@ class StringUtil {
"%" => '_', "%" => '_',
"#" => '_', "#" => '_',
"*" => '_', "*" => '_',
"ж"=>"zh", "ц"=>"ts", "ч"=>"ch", "ш"=>"sh", "ж" => "zh",
"щ"=>"shch","ь"=>"", "ю"=>"yu", "я"=>"ya", "ц" => "ts",
"Ж"=>"ZH", "Ц"=>"TS", "Ч"=>"CH", "Ш"=>"SH", "ч" => "ch",
"Щ"=>"SHCH","Ь"=>"", "Ю"=>"YU", "Я"=>"YA", "ш" => "sh",
"Й"=>"i", "й"=>"ie", "ё"=>"Ye", "щ" => "shch",
""=>"N" "ь" => "",
"ю" => "yu",
"я" => "ya",
"Ж" => "ZH",
"Ц" => "TS",
"Ч" => "CH",
"Ш" => "SH",
"Щ" => "SHCH",
"Ь" => "",
"Ю" => "YU",
"Я" => "YA",
"Й" => "i",
"й" => "ie",
"ё" => "Ye",
"" => "N"
]); ]);
return strtolower($st); return strtolower($st);
} }
static function validate_encoded_string(string $st): int|false { /**
* Проверяет, является ли строка кодированной
* @param string $st
* @return int|false
*/
static function validate_encoded_string(string $st): int|false
{
$enc_st = self::encodestring($st); $enc_st = self::encodestring($st);
return preg_match('/^[\w_-]+(\.[\w_-]+)?$/', $enc_st); return preg_match('/^[\w_-]+(\.[\w_-]+)?$/', $enc_st);
} }
} }

View file

@ -8,6 +8,13 @@ use Exception,
ctiso\Validator\Rule\AbstractRule, ctiso\Validator\Rule\AbstractRule,
ctiso\Collection; ctiso\Collection;
/**
* @phpstan-type Rule array{
* validate:string, // Описание правила см. формат правила ниже
* name:string, // Имя переменой для проверки
* context?:object
* }
*/
class Validator class Validator
{ {
/** @var AbstractRule[] */ /** @var AbstractRule[] */
@ -36,6 +43,9 @@ class Validator
'reg' => Rule\PregMatch::class, 'reg' => Rule\PregMatch::class,
]; ];
/**
* @param Rule[] $rules
*/
function __construct($rules = []) { function __construct($rules = []) {
$this->addRuleList($rules); $this->addRuleList($rules);
} }
@ -51,9 +61,7 @@ class Validator
/** /**
* Добавление списка правил в специальном формате * Добавление списка правил в специальном формате
* array(array('name' => fieldname, 'validate' => ruletext), ...) * @param Rule[] $input
* fieldname - Имя переменой для проверки
* ruletext - Описание правила см. формат правила ниже
*/ */
public function addRuleList(array $input): void public function addRuleList(array $input): void
{ {

View file

@ -3,6 +3,7 @@
namespace ctiso\View; namespace ctiso\View;
use ctiso\View\View, use ctiso\View\View,
PHPTAL; PHPTAL;
use PHPTAL_TranslationService;
class Composite extends View class Composite extends View
{ {
@ -39,7 +40,7 @@ class Composite extends View
return $this->tal->execute(); return $this->tal->execute();
} }
function setTranslator($t): void { function setTranslator(PHPTAL_TranslationService $t): void {
$this->tal->setTranslator($t); $this->tal->setTranslator($t);
} }
} }

View file

@ -8,10 +8,13 @@ class Top extends Composite
{ {
/** /**
* Общая строка заголовка * Общая строка заголовка
* @var int
*/ */
public $mid = 0; public $mid = 0;
public $require = array(); /** @var array */
public $deps = array(); public $require = [];
/** @var array */
public $deps = [];
/** /**
* Заголовок страницы * Заголовок страницы

View file

@ -22,10 +22,14 @@ class View extends \stdClass
public ?string $active_module = null; public ?string $active_module = null;
public string $module_action; public string $module_action;
/** @var string[] */
public array $prefix; public array $prefix;
/** @var string[] */
public array $suggestions = []; //подсказки public array $suggestions = []; //подсказки
/** @var string[] $alias */
public array $alias = []; public array $alias = [];
public $codeGenerator = null; public $codeGenerator = null;
public $parent_view = null; public $parent_view = null;