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

This commit is contained in:
origami11@yandex.ru 2025-10-28 16:32:00 +03:00
parent 386a927254
commit 245b5c6c19
18 changed files with 191 additions and 104 deletions

View file

@ -30,7 +30,7 @@ class HttpResponse
/** /**
* Обработка HTTP ответа * Обработка HTTP ответа
*/ */
private function parseMessage() private function parseMessage(): void
{ {
$http = explode(" ", $this->getLine()); $http = explode(" ", $this->getLine());
$this->version = $http[0]; $this->version = $http[0];
@ -72,6 +72,7 @@ class HttpResponse
/** /**
* Значение параметра HTTP ответа * Значение параметра HTTP ответа
* @param string $name Имя параметра
*/ */
public function getParameter($name): string public function getParameter($name): string
{ {

View file

@ -1,16 +1,18 @@
<?php <?php
namespace ctiso\Controller; namespace ctiso\Controller;
use Exception,
ctiso\Path, use Exception;
ctiso\Url, use ctiso\Path;
ctiso\Model\Factory, use ctiso\Url;
ctiso\HttpRequest, use ctiso\Model\Factory;
ctiso\Settings, use ctiso\HttpRequest;
ctiso\Database, use ctiso\Settings;
ctiso\View\Composite, use ctiso\Database;
ctiso\View\View, use ctiso\View\Composite;
App\Controller\State; use ctiso\View\View;
use App\Controller\State;
/** /**
* Контроллер страниц * Контроллер страниц
*/ */
@ -37,6 +39,7 @@ class Action implements ActionInterface
// Фильтры // Фильтры
/** @var ?\ctiso\Filter\ActionAccess */ /** @var ?\ctiso\Filter\ActionAccess */
public $access = null; // Обьект хранит параметры доступа public $access = null; // Обьект хранит параметры доступа
/** @var ?\ctiso\Filter\ActionLogger */
public $logger = null; // Обьект для ведения лога public $logger = null; // Обьект для ведения лога
private $factory = null; // Ссылка на обьект создания модели private $factory = null; // Ссылка на обьект создания модели
@ -100,7 +103,7 @@ class Action implements ActionInterface
* @param View $view * @param View $view
* @param string $name * @param string $name
*/ */
public function addSuggest(View $view, $name) { public function addSuggest(View $view, $name): void {
$suggest = []; $suggest = [];
$file = Path::join($this->modulePath, 'help', $name . '.suggest'); $file = Path::join($this->modulePath, 'help', $name . '.suggest');
if (file_exists($file)) { if (file_exists($file)) {
@ -188,6 +191,7 @@ class Action implements ActionInterface
* 1. Можно переопределить действия * 1. Можно переопределить действия
* 2. Использовать наследование чтобы добавить к старому обработчику новое поведение * 2. Использовать наследование чтобы добавить к старому обработчику новое поведение
* @param HttpRequest $request запроса * @param HttpRequest $request запроса
* @return View|string
*/ */
public function preProcess(HttpRequest $request) public function preProcess(HttpRequest $request)
{ {
@ -203,6 +207,11 @@ class Action implements ActionInterface
return $view; return $view;
} }
/**
* Выполнение действия
* @param HttpRequest $request
* @return View|string
*/
public function execute(HttpRequest $request) public function execute(HttpRequest $request)
{ {
$result = $this->preProcess($request); $result = $this->preProcess($request);
@ -227,7 +236,7 @@ class Action implements ActionInterface
/** /**
* Страница по умолчанию * Страница по умолчанию
* @param HttpRequest $request * @param HttpRequest $request
* @return string|\ctiso\View\View * @return View|string
*/ */
public function actionIndex(HttpRequest $request) { public function actionIndex(HttpRequest $request) {
return ""; return "";
@ -355,14 +364,19 @@ class Action implements ActionInterface
/** /**
* Добавление widget к отображению * Добавление widget к отображению
* @param $section * @param string $section
* @param $node * @param View $node
*/ */
public function addChild($section, $node): void public function addChild($section, $node): void
{ {
$this->childNodes[$section] = $node; $this->childNodes[$section] = $node;
} }
/**
* Установка значения контроллера
* @param string $name
* @param mixed $value
*/
public function setValue($name, $value): void public function setValue($name, $value): void
{ {
$this->ctrlValues[$name] = $value; $this->ctrlValues[$name] = $value;
@ -370,6 +384,8 @@ class Action implements ActionInterface
/** /**
* Добавление дочернего отображения к текущему отображению * Добавление дочернего отображения к текущему отображению
* @param string $section
* @param View $node
*/ */
public function addView($section, $node): void public function addView($section, $node): void
{ {
@ -379,6 +395,7 @@ class Action implements ActionInterface
/** /**
* Генерация содержания * Генерация содержания
* Путаница c execute и render * Путаница c execute и render
* @return View|string
*/ */
public function render() public function render()
{ {
@ -426,16 +443,14 @@ class Action implements ActionInterface
return $result; return $result;
} }
/**
* @return State
*/
function _getActionPath() { function _getActionPath() {
return new State('index'); return new State('index');
} }
// Тоже убрать в метод Controller_Model function redirect(string $action): void {
function getActionPath(HttpRequest $request, $action = null) {
$this->_getActionPath()->getPath($this, ($action) ? $action : $request->getAction());
}
function redirect(string $action) {
header('location: ' . $action); header('location: ' . $action);
exit(); exit();
} }

View file

@ -29,10 +29,17 @@ class FakeTemplate {
$this->_name = $name; $this->_name = $name;
} }
function __set($key, $value) { /**
* @param string $key
* @param mixed $value
*/
function __set($key, $value): void {
$this->_data[$key] = $value; $this->_data[$key] = $value;
} }
/**
* @return string
*/
function execute() { function execute() {
return json_encode($this->_data); return json_encode($this->_data);
} }
@ -56,7 +63,7 @@ class Component
public $component_id; public $component_id;
/** @var string */ /** @var string */
public $component_title; public $component_title;
/** @var string */
public $COMPONENTS_WEB; public $COMPONENTS_WEB;
public Registry $config; public Registry $config;

View file

@ -20,8 +20,11 @@ class Service
public $webPath = []; public $webPath = [];
/** @var Registry */ /** @var Registry */
public $config; public $config;
/** @var string */
public $template; public $template;
/** @var string */
public $templatePath; public $templatePath;
/** @var string */
public $COMPONENTS_WEB; public $COMPONENTS_WEB;
/** @var Database */ /** @var Database */
public $db; public $db;

View file

@ -4,15 +4,22 @@ namespace ctiso\Controller;
interface SiteInterface { interface SiteInterface {
function getResource(); function getResource();
/**
* @return \ctiso\Database
*/
function getDatabase(); function getDatabase();
function getConfig(); function getConfig();
function getTheme(); function getTheme();
function addComponentConfig($config); function addComponentConfig($config): void;
function addRequireJsPath(string $name, string $path, ?array $shim = null); function addRequireJsPath(string $name, string $path, ?array $shim = null): void;
function addStyleSheet(string $url); function addStyleSheet(string $url): void;
/**
* @param string $expression
* @return ?Component
*/
function loadComponent(string $expression); function loadComponent(string $expression);
function findTemplate(string $name); function findTemplate(string $name);
function replaceImg(string $src, int $width, int $height); function replaceImg(string $src, int $width, int $height);
function updatePageTime(int $time); function updatePageTime(int $time): void;
} }

View file

@ -124,8 +124,8 @@ namespace ctiso {
/** /**
* Извлекает из базы все элементы по запросу (Для совместимости со старым представлением баз данных CIS) * Извлекает из базы все элементы по запросу (Для совместимости со старым представлением баз данных CIS)
* @param string $query - запрос * @param string $query - запрос
* @param array $values - значения * @param array<string, mixed> $values - значения
* @return array * @return list<array<string, mixed>>
*/ */
public function fetchAllArray($query, $values = null) public function fetchAllArray($query, $values = null)
{ {
@ -138,8 +138,8 @@ namespace ctiso {
/** /**
* Извлекает из базы первый элемент по запросу * Извлекает из базы первый элемент по запросу
* @param string $query - запрос * @param string $query - запрос
* @param array $values - значения * @param array<string, mixed> $values - значения
* @return array|false * @return array<string, mixed>|false
*/ */
public function fetchOneArray($query, $values = null) public function fetchOneArray($query, $values = null)
{ {

View file

@ -294,7 +294,7 @@ class Manager
/** /**
* Возвращает все имена таблиц * Возвращает все имена таблиц
* @return array * @return list<string>
*/ */
public function getAllTableNames() public function getAllTableNames()
{ {

View file

@ -3,5 +3,5 @@
namespace ctiso\Form; namespace ctiso\Form;
interface OptionsFactory { interface OptionsFactory {
function create(Select $field, array $options); function create(Select $field, array $options): void;
} }

View file

@ -217,15 +217,29 @@ class Functions {
return ($a[$key] < $b[$key]) ? -1 : 1; return ($a[$key] < $b[$key]) ? -1 : 1;
} }
/**
* @deprecated
* @param string $name Метод
* @param object $o
*
* @return mixed
*/
static function __self($name, $o) { static function __self($name, $o) {
return call_user_func([$o, $name]); return call_user_func([$o, $name]);
} }
static function concat(/* $args ...*/) { /**
$args = func_get_args(); * @param string ...$args
* @return string
*/
static function concat(...$args) {
return implode("", $args); return implode("", $args);
} }
/**
* @param mixed $x
* @return bool
*/
static function __empty($x) { static function __empty($x) {
return empty($x); return empty($x);
} }
@ -235,7 +249,7 @@ class Functions {
* @example key_values('a', array(1 => array('a' => 1, 'b' => 2))) => array(1) * @example key_values('a', array(1 => array('a' => 1, 'b' => 2))) => array(1)
* *
* @param string $key * @param string $key
* @param array|\ArrayIterator $array * @param list<array>|\ArrayIterator $array
* @return mixed * @return mixed
*/ */
static function key_values($key, $array) { static function key_values($key, $array) {
@ -249,7 +263,7 @@ class Functions {
/** /**
* @param string $key * @param string $key
* @param array|\ArrayIterator $array * @param list<object>|\ArrayIterator $array
*/ */
static function key_values_object($key, $array) { static function key_values_object($key, $array) {
$result = []; $result = [];

View file

@ -34,6 +34,9 @@ class User implements UserInterface
return $this->name; return $this->name;
} }
/**
* @return bool
*/
function isLogged() { function isLogged() {
return \ctiso\Filter\Authorization::isLogged(); return \ctiso\Filter\Authorization::isLogged();
} }
@ -55,6 +58,10 @@ class User implements UserInterface
return null; return null;
} }
/**
* @param PDOStatement $result
* @return string
*/
function getUserPassword($result) { function getUserPassword($result) {
return $result->get('password'); return $result->get('password');
} }

View file

@ -121,6 +121,8 @@ class Setup
/** /**
* Заменяет переменные на их значения в строке * Заменяет переменные на их значения в строке
* @param list<string> $match массив совпадения
* @return string
*/ */
function replaceVariable(array $match) function replaceVariable(array $match)
{ {
@ -132,6 +134,8 @@ class Setup
/** /**
* Для всех аттрибутов заменяет переменные на их значения * Для всех аттрибутов заменяет переменные на их значения
* @param SimpleXMLElement $attributes аттрибуты
* @return array<string, string>
*/ */
function resolve(SimpleXMLElement $attributes): array function resolve(SimpleXMLElement $attributes): array
{ {

View file

@ -4,12 +4,13 @@
* Расширения для PHPTAL для отображения времени и даты * Расширения для PHPTAL для отображения времени и даты
*/ */
namespace ctiso; namespace ctiso;
use PHPTAL_Php_TalesInternal,
ctiso\Controller\SiteInterface, use PHPTAL_Php_TalesInternal;
ctiso\Controller\Component, use ctiso\Controller\SiteInterface;
ctiso\HttpRequest, use ctiso\Controller\Component;
PHPTAL_Tales, use ctiso\HttpRequest;
PHPTAL_TalesRegistry; use PHPTAL_Tales;
use PHPTAL_TalesRegistry;
class Tales_DateTime implements PHPTAL_Tales class Tales_DateTime implements PHPTAL_Tales
{ {
@ -61,8 +62,10 @@ class Tales {
/** /**
* Функция подключения компонента * Функция подключения компонента
* @param string $expression
* @return string
*/ */
static function phptal_component($expression) { static function phptal_component($expression): string {
$begin = floatval(microtime(true)); $begin = floatval(microtime(true));
/** @var Component */ /** @var Component */
$component = self::$site->loadComponent($expression); $component = self::$site->loadComponent($expression);
@ -74,14 +77,14 @@ class Tales {
} }
static function register(?SiteInterface $site) { static function register(?SiteInterface $site): void {
self::$site = $site; self::$site = $site;
/* Регистрация нового префикса для подключения компонента */ /* Регистрация нового префикса для подключения компонента */
$tales = PHPTAL_TalesRegistry::getInstance(); $tales = PHPTAL_TalesRegistry::getInstance();
$tales->registerPrefix('component', ['ctiso\\Tales_Component', 'component']); $tales->registerPrefix('component', [\ctiso\Tales_Component::class, 'component']);
$tales->registerPrefix('date', ['ctiso\\Tales_DateTime', 'date']); $tales->registerPrefix('date', [\ctiso\Tales_DateTime::class, 'date']);
$tales->registerPrefix('time', ['ctiso\\Tales_DateTime', 'time']); $tales->registerPrefix('time', [\ctiso\Tales_DateTime::class, 'time']);
$tales->registerPrefix('assets', ['ctiso\\Tales_Assets', 'assets']); $tales->registerPrefix('assets', [\ctiso\Tales_Assets::class, 'assets']);
} }
} }

View file

@ -18,7 +18,7 @@ class Drawing
* @param int $top * @param int $top
* @param int $width * @param int $width
* @param int $height * @param int $height
* @param array $rgb * @param list<int> $rgb
*/ */
static function drawRectangle(GdImage &$image, int $left, int $top, int $width, int $height, array $rgb): void static function drawRectangle(GdImage &$image, int $left, int $top, int $width, int $height, array $rgb): void
{ {

View file

@ -26,10 +26,13 @@
* @version $Revision: 1.5 $ * @version $Revision: 1.5 $
* @package creole.util.sql * @package creole.util.sql
*/ */
namespace ctiso\Tools; namespace ctiso\Tools;
use Exception; use Exception;
class SQLStatementExtractor { class SQLStatementExtractor
{
protected static $delimiter = ';'; protected static $delimiter = ';';
@ -39,7 +42,8 @@ class SQLStatementExtractor {
* @param string $filename Path to file to read. * @param string $filename Path to file to read.
* @return array SQL statements * @return array SQL statements
*/ */
public static function extractFile($filename) { public static function extractFile($filename)
{
$buffer = file_get_contents($filename); $buffer = file_get_contents($filename);
if ($buffer !== false) { if ($buffer !== false) {
return self::extractStatements(self::getLines($buffer)); return self::extractStatements(self::getLines($buffer));
@ -53,28 +57,31 @@ class SQLStatementExtractor {
* @param string $buffer * @param string $buffer
* @return array * @return array
*/ */
public static function extract($buffer) { public static function extract($buffer)
{
return self::extractStatements(self::getLines($buffer)); return self::extractStatements(self::getLines($buffer));
} }
/** /**
* Extract SQL statements from array of lines. * Extract SQL statements from array of lines.
* *
* @param array $lines Lines of the read-in file. * @param list<string> $lines Lines of the read-in file.
* @return array * @return list<string>
*/ */
protected static function extractStatements($lines) { protected static function extractStatements($lines)
{
$statements = []; $statements = [];
$sql = ""; $sql = "";
foreach ($lines as $line) { foreach ($lines as $line) {
$line = trim($line); $line = trim($line);
if (self::startsWith("//", $line) || if (
self::startsWith("//", $line) ||
self::startsWith("--", $line) || self::startsWith("--", $line) ||
self::startsWith("#", $line)) { self::startsWith("#", $line)
) {
continue; continue;
} }
@ -110,7 +117,8 @@ class SQLStatementExtractor {
* @param string $string The string to check in (haystack). * @param string $string The string to check in (haystack).
* @return boolean True if $string starts with $check, or they are equal, or $check is empty. * @return boolean True if $string starts with $check, or they are equal, or $check is empty.
*/ */
protected static function startsWith($check, $string) { protected static function startsWith($check, $string)
{
if ($check === "" || $check === $string) { if ($check === "" || $check === $string) {
return true; return true;
} else { } else {
@ -124,7 +132,8 @@ class SQLStatementExtractor {
* @param string $string The string to check in (haystack). * @param string $string The string to check in (haystack).
* @return boolean True if $string ends with $check, or they are equal, or $check is empty. * @return boolean True if $string ends with $check, or they are equal, or $check is empty.
*/ */
protected static function endsWith(string $check, string $string) { protected static function endsWith(string $check, string $string)
{
if ($check === "" || $check === $string) { if ($check === "" || $check === $string) {
return true; return true;
} else { } else {
@ -136,7 +145,8 @@ class SQLStatementExtractor {
* a natural way of getting a subtring, php's circular string buffer and strange * a natural way of getting a subtring, php's circular string buffer and strange
* return values suck if you want to program strict as of C or friends * return values suck if you want to program strict as of C or friends
*/ */
protected static function substring(string $string, int $startpos, int $endpos = -1) { protected static function substring(string $string, int $startpos, int $endpos = -1)
{
$len = strlen($string); $len = strlen($string);
$endpos = (int) (($endpos === -1) ? $len - 1 : $endpos); $endpos = (int) (($endpos === -1) ? $len - 1 : $endpos);
if ($startpos > $len - 1 || $startpos < 0) { if ($startpos > $len - 1 || $startpos < 0) {
@ -159,9 +169,9 @@ class SQLStatementExtractor {
* @param string $buffer * @param string $buffer
* @return string[] lines of file. * @return string[] lines of file.
*/ */
protected static function getLines(string $buffer): array { protected static function getLines(string $buffer): array
{
$lines = preg_split("/\r?\n|\r/", $buffer); $lines = preg_split("/\r?\n|\r/", $buffer);
return $lines; return $lines;
} }
} }

View file

@ -32,6 +32,11 @@ abstract class AbstractRule
return $this->errorMsg; return $this->errorMsg;
} }
/**
* @param Collection $container
* @param bool|null $status
* @return bool
*/
public function isValid(Collection $container, $status = null): bool public function isValid(Collection $container, $status = null): bool
{ {
return true; return true;

View file

@ -123,11 +123,17 @@ class Validator
$this->errorMsg = []; $this->errorMsg = [];
} }
public function validate(Collection $container, $rule = null, $status = null): bool /**
* @param Collection $container
* @param AbstractRule[]|null $rules
* @param bool|null $status
* @return bool
*/
public function validate(Collection $container, $rules = null, $status = null): bool
{ {
$fields = []; $fields = [];
if ($rule) { if ($rules) {
$this->chain = $rule; $this->chain = $rules;
} }
foreach ($this->chain as $rule) { foreach ($this->chain as $rule) {
@ -156,7 +162,10 @@ class Validator
return empty($this->errorMsg); return empty($this->errorMsg);
} }
public function getErrorMsg() /**
* @return array<string, string>
*/
public function getErrorMsg(): array
{ {
return $this->errorMsg; return $this->errorMsg;
} }

View file

@ -147,5 +147,4 @@ class Top extends Composite
{ {
return $this->doTree('_stylesheet'); return $this->doTree('_stylesheet');
} }
} }

View file

@ -32,6 +32,7 @@ class View extends \stdClass
/** @var string[] $alias */ /** @var string[] $alias */
public array $alias = []; public array $alias = [];
public $codeGenerator = null; public $codeGenerator = null;
/** @var View|null */
public $parent_view = null; public $parent_view = null;
function __construct() { function __construct() {
@ -191,6 +192,8 @@ class View extends \stdClass
/** /**
* @param string[][] $alias * @param string[][] $alias
* @param string[] $list
* @return string[]
*/ */
public function resolveAllNames($alias, array $list): array { public function resolveAllNames($alias, array $list): array {
$result = []; $result = [];