From 530a3b931d1290bedd10de98601fd1ac8fcd776b Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 23 Oct 2025 11:24:33 +0300 Subject: [PATCH] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Collection.php | 2 +- src/Database/IdGenerator.php | 25 +++-- src/Database/JsonInstall.php | 33 ++++++- src/Database/Manager.php | 146 ++++++++++++++++++++++------- src/Database/Statement.php | 22 ++++- src/Database/StatementIterator.php | 8 +- src/Excel/DataTime.php | 10 +- src/Excel/Table.php | 17 +++- src/Filter/ActionAccess.php | 6 +- src/Filter/Filter.php | 4 +- src/Filter/Login.php | 6 +- src/Form/Form.php | 39 ++++---- src/Form/Select.php | 11 ++- src/Functions.php | 58 ++++++++++-- src/HttpRequest.php | 10 +- src/Layout/Manager.php | 39 ++++---- src/Model/Factory.php | 3 + src/Path.php | 8 +- src/Primitive.php | 56 +++++++++-- src/Url.php | 3 + src/UserMessageException.php | 4 + src/View/View.php | 9 +- 22 files changed, 388 insertions(+), 131 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index b15f3c0..58b725e 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -78,7 +78,7 @@ class Collection implements \ArrayAccess return (($result > 0) ? $result : $default); } - public function clear() + public function clear(): void { $this->data = []; } diff --git a/src/Database/IdGenerator.php b/src/Database/IdGenerator.php index 5ae4664..4cd3d3d 100644 --- a/src/Database/IdGenerator.php +++ b/src/Database/IdGenerator.php @@ -4,26 +4,37 @@ namespace ctiso\Database; use ctiso\Database; class IdGenerator { + /** @var Database */ private $db; function __construct(Database $db) { $this->db = $db; } + /** + * @return bool + */ function isBeforeInsert() { - return false; - } - - function isAfterInsert() { - return true; + return false; } - + + /** + * @return bool + */ + function isAfterInsert() { + return true; + } + + /** + * @param string $seq + * @return int + */ function getId($seq) { if ($this->db->isPostgres()) { $result = $this->db->fetchOneArray("SELECT nextval('$seq') AS nextval"); } else { $result = $this->db->fetchOneArray("SELECT last_insert_rowid() AS nextval"); - } + } return (int)$result['nextval']; } } diff --git a/src/Database/JsonInstall.php b/src/Database/JsonInstall.php index e6f384f..5dcfbd1 100644 --- a/src/Database/JsonInstall.php +++ b/src/Database/JsonInstall.php @@ -5,13 +5,20 @@ namespace ctiso\Database; use ctiso\Database\Manager; class JsonInstall { + /** @var Manager */ public $db_manager; + /** @var array */ public $serialColumns; public function __construct(Manager $db_manager) { $this->db_manager = $db_manager; } + /** + * Установить базу данных + * @param string $dbinit_path + * @param ?string $dbfill_path + */ function install($dbinit_path, $dbfill_path = null) { $dbinit_file = file_get_contents($dbinit_path); if (is_string($dbinit_file)) { @@ -32,6 +39,11 @@ class JsonInstall { $this->makeConstraints($initActions); } + /** + * Получить список таблиц, которые не существуют в базе данных + * @param array $tables + * @return array + */ function missingTables($tables) { $actual_tables = $this->db_manager->getAllTableNames(); $missingTables = []; @@ -42,7 +54,12 @@ class JsonInstall { return $missingTables; } - // Создать таблицы + /** + * Создать таблицы + * @param array $initActions + * @param string $dbinit_path + * @return void + */ function initDataBase(array $initActions, $dbinit_path) { $pg = $this->db_manager->db->isPostgres(); if (!$pg) { @@ -73,7 +90,7 @@ class JsonInstall { } } if ($action["type"] != "alterReference") { - $this->db_manager->ExecuteAction($action, $dbinit_path); + $this->db_manager->executeAction($action, $dbinit_path); } } @@ -95,7 +112,11 @@ class JsonInstall { } } - //Заполнить данными + /** + * Заполнить данными + * @param string $dbfill_file_path + * @return void + */ function fillDataBase($dbfill_file_path) { $dbfill_file = file_get_contents($dbfill_file_path); if (is_string($dbfill_file)) { @@ -128,7 +149,11 @@ class JsonInstall { } } - //Обновить ключи serial и создать ограничения + /** + * Обновить ключи serial и создать ограничения + * @param array $initActions + * @return void + */ function makeConstraints($initActions) { $pg = $this->db_manager->db->isPostgres(); if ($pg) { diff --git a/src/Database/Manager.php b/src/Database/Manager.php index ee58fbf..31d589b 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -17,9 +17,15 @@ class Manager $this->db = $db; } - public function executeAction(array $action, $db_file = "") + /** + * Выполняет действие + * @param array $action + * @param string $db_file + * @throws Exception + */ + public function executeAction(array $action, $db_file = ""): void { - switch($action["type"]) { + switch ($action["type"]) { case "dropTable": $this->dropTableQuery($action["table_name"], true); break; @@ -56,59 +62,85 @@ class Manager break; default: - throw new Exception("unknown action ". $action["type"] . PHP_EOL); + throw new Exception("unknown action " . $action["type"] . PHP_EOL); } } - //Дропает и создаёт SQL VIEW - public function recreateView($viewName, $selectStatement) + /** + * Дропает и создаёт SQL VIEW + * @param string $viewName + * @param string $selectStatement + */ + public function recreateView($viewName, $selectStatement): void { - $this->db->query("DROP VIEW ".$viewName); - $this->db->query("CREATE VIEW ".$viewName." AS ".$selectStatement); + $this->db->query("DROP VIEW " . $viewName); + $this->db->query("CREATE VIEW " . $viewName . " AS " . $selectStatement); } - public function dropTableQuery($table, $cascade=false) + /** + * Дропает таблицу + * @param string $table + * @param bool $cascade + */ + public function dropTableQuery($table, $cascade = false): void { - $statement = "DROP TABLE IF EXISTS ".$table; - if ($this->db->isPostgres()&&$cascade) { + $statement = "DROP TABLE IF EXISTS " . $table; + if ($this->db->isPostgres() && $cascade) { $statement .= " CASCADE"; } $this->db->query($statement); } - public function alterReference($table, $column, $refTable, $refColumn) + /** + * Добавляет ссылку на другую таблицу + * @param string $table + * @param string $column + * @param string $refTable + * @param string $refColumn + */ + public function alterReference($table, $column, $refTable, $refColumn): void { - $this->db->query("ALTER TABLE ".$table." ADD CONSTRAINT ".$table."_".$column."fk"." FOREIGN KEY (".$column.") REFERENCES ".$refTable." (".$refColumn.")"); + $this->db->query("ALTER TABLE " . $table . " ADD CONSTRAINT " . $table . "_" . $column . "fk" . " FOREIGN KEY (" . $column . ") REFERENCES " . $refTable . " (" . $refColumn . ") ON DELETE CASCADE ON UPDATE CASCADE"); } - //Извлечение информации о полях таблицы + /** + * Извлечение информации о полях таблицы + * @param string $table + * @return array{type:string,not_null:bool,constraint:?string}[]|null + */ public function tableInfo($table) { $pg = $this->db->isPostgres(); if ($pg) { throw new Exception("Not implemented for postgres"); } else { - $results = $this->db->fetchAllArray("PRAGMA table_info(".$table.");"); + $results = $this->db->fetchAllArray("PRAGMA table_info(" . $table . ");"); if (empty($results)) { return null; } $fields = []; foreach ($results as $result) { $fields[$result["name"]] = [ - "type"=> $result["type"], - "not_null"=> boolval($result["notnull"]), - "constraint"=> ((bool) $result["pk"]) ? "PRIMARY KEY" : null + "type" => $result["type"], + "not_null" => boolval($result["notnull"]), + "constraint" => ((bool) $result["pk"]) ? "PRIMARY KEY" : null ]; } return $fields; } } - public function renameColumn($table, $old_name, $new_name) + /** + * Переименование столбца в таблице + * @param string $table + * @param string $old_name + * @param string $new_name + */ + public function renameColumn($table, $old_name, $new_name): void { $pg = $this->db->isPostgres(); if ($pg) { - $this->db->query("ALTER TABLE ".$table." RENAME COLUMN ".$old_name." TO ".$new_name); + $this->db->query("ALTER TABLE " . $table . " RENAME COLUMN " . $old_name . " TO " . $new_name); } else { $tmp_table = "tmp_" . $table; $this->dropTableQuery($tmp_table); @@ -120,7 +152,7 @@ class Manager $data = $this->dumpTable($table); - $this->db->query("ALTER TABLE ".$table." RENAME TO ".$tmp_table.";"); + $this->db->query("ALTER TABLE " . $table . " RENAME TO " . $tmp_table . ";"); $table_info[$new_name] = $table_info[$old_name]; unset($table_info[$old_name]); $this->createTableQuery($table, $table_info, null); @@ -135,41 +167,63 @@ class Manager } } - //Обновление ключа serial после ручной вставки - public function updateSerial($table, $column) + /** + * Обновление ключа serial после ручной вставки + * @param string $table + * @param string $column + */ + public function updateSerial($table, $column): void { - $this->db->query("SELECT setval(pg_get_serial_sequence('".$table."', '".$column."'), coalesce(max(".$column."),0) + 1, false) FROM ".$table); + $this->db->query("SELECT setval(pg_get_serial_sequence('" . $table . "', '" . $column . "'), coalesce(max(" . $column . "),0) + 1, false) FROM " . $table); } + /** + * Возвращает определение столбца + * @param string $name + * @param array $data + * @param bool $pg + * @return string + */ public function columnDefinition($name, $data, $pg) { - $constraint = isset($data['constraint']) ? " ".$data['constraint'] : ""; + $constraint = isset($data['constraint']) ? " " . $data['constraint'] : ""; $references = ""; if (isset($data['references'])) { - $references = " REFERENCES " . $data['references']['refTable'] . '(' .$data['references']['refColumn'] . ')'; + $references = " REFERENCES " . $data['references']['refTable'] . '(' . $data['references']['refColumn'] . ')'; } if (isset($data["not_null"]) && $data["not_null"]) { - $constraint .=" NOT NULL"; + $constraint .= " NOT NULL"; } $type = $data['type']; if (!$pg) { - if (strtolower($type)=="serial") { + if (strtolower($type) == "serial") { $type = "integer"; } //if (strtolower($type)=="boolean") // $type = "integer"; } - return $name." ".$type.$references.$constraint; + return $name . " " . $type . $references . $constraint; } - public function addColumn($table_name, $column_name, $field) + /** + * Добавляет столбец в таблицу + * @param string $table_name + * @param string $column_name + * @param array $field + */ + public function addColumn($table_name, $column_name, $field): void { $pg = $this->db->isPostgres(); - $q = "ALTER TABLE ".$table_name." ADD COLUMN ". - $this->columnDefinition($column_name, $field, $pg); + $q = "ALTER TABLE " . $table_name . " ADD COLUMN " . + $this->columnDefinition($column_name, $field, $pg); $this->db->query($q); } + /** + * Возвращает определение ограничения + * @param array{fields: string[], type: string} $c + * @return string + */ public function getConstraintDef(array $c) { if ($c['type'] == 'unique') { @@ -178,7 +232,14 @@ class Manager return ""; } - //CreateTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']]) + + /** + * Создает таблицу + * @example createTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']]) + * @param string $table + * @param array $fields + * @param array|string|null $constraints + */ public function createTableQuery($table, $fields, $constraints) { $pg = $this->db->isPostgres(); @@ -198,12 +259,17 @@ class Manager $this->db->query($statement); } + /** + * Возвращает дамп таблицы + * @param string $table_name + * @return array + */ public function dumpTable($table_name) { $pg = $this->db->isPostgres(); $result = []; - $data = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); + $data = $this->db->fetchAllArray("SELECT * FROM " . $table_name . ";"); if (!$pg) { $table_fields = $this->tableInfo($table_name); @@ -220,14 +286,18 @@ class Manager } foreach ($data as $r) { $result[] = [ - "type" => "insert", - "table_name" => $table_name, - "values" => $r + "type" => "insert", + "table_name" => $table_name, + "values" => $r ]; } return $result; } + /** + * Возвращает все имена таблиц + * @return array + */ public function getAllTableNames() { $result = []; @@ -243,6 +313,10 @@ class Manager return $result; } + /** + * Возвращает дамп всех таблиц + * @return array + */ public function dumpInserts() { $table_names = $this->getAllTableNames(); diff --git a/src/Database/Statement.php b/src/Database/Statement.php index 132b305..90b6619 100644 --- a/src/Database/Statement.php +++ b/src/Database/Statement.php @@ -32,29 +32,41 @@ class Statement $this->conn = $conn; } - function setInt($n, $value) { + /** + * @param int|string $n + * @param int $value + */ + function setInt($n, $value): void { $this->binds [] = [$n, $value, PDO::PARAM_INT]; } - function setString($n, $value) { + /** + * @param int|string $n + * @param string $value + */ + function setString($n, $value): void { $this->binds [] = [$n, $value, PDO::PARAM_STR]; } - function setBlob($n, $value) { + /** + * @param int|string $n + * @param mixed $value + */ + function setBlob($n, $value): void { $this->binds [] = [$n, $value, PDO::PARAM_LOB]; } /** * @param int $limit */ - function setLimit($limit) { + function setLimit($limit): void { $this->limit = $limit; } /** * @param int $offset */ - function setOffset($offset) { + function setOffset($offset): void { $this->offset = $offset; } diff --git a/src/Database/StatementIterator.php b/src/Database/StatementIterator.php index 70413fe..8d0945b 100644 --- a/src/Database/StatementIterator.php +++ b/src/Database/StatementIterator.php @@ -7,7 +7,9 @@ class StatementIterator implements \Iterator { private $result; + /** @var int */ private $pos = 0; + /** @var int */ private $row_count; /** @@ -37,15 +39,15 @@ class StatementIterator implements \Iterator return $this->result->cache[$this->pos]; } - function next(): void{ + function next(): void { $this->pos++; } - function seek($index) { + function seek($index): void { $this->pos = $index; } - function count() { + function count(): int { return $this->row_count; } } diff --git a/src/Excel/DataTime.php b/src/Excel/DataTime.php index 877546d..7a910df 100644 --- a/src/Excel/DataTime.php +++ b/src/Excel/DataTime.php @@ -4,15 +4,19 @@ namespace ctiso\Excel; class DateTime { + /** @var int */ public $value; - function __construct($value) + /** + * @param int $value + */ + function __construct($value) { $this->value = (int)$value; } - function getString() + function getString(): string { return date('Y-m-d\TH:i:s.u', $this->value); - } + } } diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 26d9354..726a1dc 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -202,6 +202,12 @@ class Table return max(array_map([$this, 'getRowCells'], $this->rows)); } + /** + * Кодирование строки + * @deprecated + * @param string $s Строка + * @return string + */ function encode($s) { return $s; @@ -209,6 +215,11 @@ class Table /** * Генерация клетки таблицы (Переработать) + * @param TableCell $ncell Клетка таблицы + * @param XMLWriter $doc XMLWriter + * @param int $j Индекс клетки + * @param mixed $value Значение клетки + * @param bool $setIndex Устанавливать индекс клетки в атрибут ss:Index */ function createCell (TableCell $ncell, XMLWriter $doc, $j, mixed $value, $setIndex) { $doc->startElement("Cell"); @@ -222,7 +233,7 @@ class Table } if ($setIndex) { - $doc->writeAttribute('ss:Index', $j); + $doc->writeAttribute('ss:Index', (string)$j); } $doc->startElement("Data"); @@ -247,7 +258,7 @@ class Table /** * Генерация таблицы */ - public function createTable (XMLWriter $doc) { + public function createTable (XMLWriter $doc): void { $doc->startElement('Worksheet'); $doc->writeAttribute('ss:Name', $this->name); @@ -295,7 +306,7 @@ class Table $doc->endElement(); } - protected function splitPane (XMLWriter $doc) { + protected function splitPane (XMLWriter $doc): void { $doc->startElement('WorksheetOptions'); $doc->writeAttribute('xmlns', 'urn:schemas-microsoft-com:office:excel'); diff --git a/src/Filter/ActionAccess.php b/src/Filter/ActionAccess.php index 706efc1..89f7326 100644 --- a/src/Filter/ActionAccess.php +++ b/src/Filter/ActionAccess.php @@ -10,13 +10,14 @@ use ctiso\Filter\UserAccess, class ActionAccess { - public $access = array(); + public $access = []; public $processor; /** @var User */ public $user; /** * @param FilterInterface $processor + * @param User $user */ function __construct($processor, $user) { $this->processor = $processor; @@ -27,6 +28,9 @@ class ActionAccess * Проверка доступных действий для пользователя * !! Реализация класса проверки действий не должна быть внутри Контроллера!!! * Информация о доступе может быть в файле, базе данных и т.д. + * + * @param string $action + * @return bool */ function checkAction($action) { // Импликация !! http://ru.wikipedia.org/wiki/Импликация diff --git a/src/Filter/Filter.php b/src/Filter/Filter.php index da34f8e..a419e99 100644 --- a/src/Filter/Filter.php +++ b/src/Filter/Filter.php @@ -5,8 +5,8 @@ */ namespace ctiso\Filter; -use ctiso\Controller\Action, - ctiso\HttpRequest; +use ctiso\Controller\Action; +use ctiso\HttpRequest; class Filter implements \ctiso\Controller\ActionInterface { diff --git a/src/Filter/Login.php b/src/Filter/Login.php index c3c7b32..d8b6fd1 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -125,7 +125,7 @@ class Login extends Filter return false; } - private function enter($result) + private function enter($result): void { $this->user = $result; $random = rand(0, 1024 * 1024); @@ -138,7 +138,7 @@ class Login extends Filter $_SESSION["time"] = time(); } - public function execute(HttpRequest $request) + public function execute(HttpRequest $request): string { $logged = $this->isLoggin($request); if ($request->get('action') == 'user_access') { @@ -187,7 +187,7 @@ class Login extends Filter /** * Проверка на попадание реквеста в белый список */ - public function requestIsWhite(Collection $request) { + public function requestIsWhite(Collection $request): bool { $module = $request->get('module'); $action = $request->get('action'); diff --git a/src/Form/Form.php b/src/Form/Form.php index 8d38943..153f831 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -5,12 +5,12 @@ */ namespace ctiso\Form; -use ctiso\Form\Field, - ctiso\Form\Select, - ctiso\Form\Input, - ctiso\View\View, - ctiso\Validator\Validator, - ctiso\HttpRequest; + +use ctiso\Form\Field; +use ctiso\Form\Select; +use ctiso\Form\Input; +use ctiso\Validator\Validator; +use ctiso\HttpRequest; /** * Форма для ввода @@ -76,7 +76,7 @@ class Form { } - function getId() + function getId(): string { return '_form_edit'; } @@ -85,18 +85,16 @@ class Form { * Добавление конструкторя для поля формы * @param string $name Краткое название поля * @param class-string $class - * @return void */ - public function addFieldClass($name, $class) + public function addFieldClass($name, $class): void { $this->constructor [$name] = $class; } /** * Добавляет одно поле ввода на форму - * @return Field */ - public function addField(array $init, $factory = null) + public function addField(array $init, $factory = null): Field { assert(isset($init['type'])); assert(isset($init['name'])); @@ -118,8 +116,7 @@ class Form { /** * Добавление fieldset на форму */ - - public function addFieldSet(array $fieldset) + public function addFieldSet(array $fieldset): void { $this->fieldsets[$fieldset['name']] = $fieldset; } @@ -127,7 +124,7 @@ class Form { /** * Добавление массива fieldset на форму */ - public function addFieldSetList(array $list) + public function addFieldSetList(array $list): void { foreach ($list as $fieldset) { $this->addFieldSet($fieldset); @@ -138,7 +135,7 @@ class Form { * Добавляет список полей для формы * @param array $list */ - public function addFieldList(array $list, $factory = null) + public function addFieldList(array $list, $factory = null): void { foreach ($list as $init) { $this->addField($init, $factory); @@ -148,7 +145,7 @@ class Form { /** * Устанавливает ошибки после проверки */ - function setError(Validator $validator) + function setError(Validator $validator): void { foreach ($validator->getErrorMsg() as $name => $error) { @@ -162,7 +159,7 @@ class Form { * @param string $name * @param string $message */ - function setFieldError($name, $message) + function setFieldError($name, $message): void { $this->field[$name]->error = true; $this->field[$name]->error_msg = $message; @@ -171,7 +168,7 @@ class Form { /** * Устанавливает значения из масива */ - function setValues(HttpRequest $request) { + function setValues(HttpRequest $request): void { foreach ($this->field as $key => $_) { $value = $request->getRawData($this->method, $key); $this->field[$key]->setValue($value); @@ -183,7 +180,7 @@ class Form { * @param object $data * @param array $schema Связь между элементами формы и свойствами обьекта */ - public function fill($data, array $schema) + public function fill($data, array $schema): void { foreach ($schema as $key => $conv) { list($value, $type) = $conv; @@ -191,12 +188,12 @@ class Form { } } - public function set($name, $value) + public function set($name, $value): void { $this->field[$name]->setValue($value); } - function execute() + function execute(): self { return $this; } diff --git a/src/Form/Select.php b/src/Form/Select.php index 79fc2f4..333691a 100644 --- a/src/Form/Select.php +++ b/src/Form/Select.php @@ -3,12 +3,16 @@ namespace ctiso\Form; use ctiso\Form\Field; +/** + * @phpstan-type Option = array{value: string, name: string, selected: bool, class?: string|false} + */ class Select extends Field { + /** @var Option[] */ public $options = []; /** - * @param array $input + * @param array{ options?: Option[], 'options.pair'?: array } $input * @param OptionsFactory $factory */ public function __construct ($input, $factory) { @@ -28,6 +32,11 @@ class Select extends Field } } + /** + * @param string[] $list + * @param bool $selected + * @return Option[] + */ public function optionsPair($list, $selected = false) { $result = []; foreach ($list as $key => $value) { diff --git a/src/Functions.php b/src/Functions.php index dc98a18..2dc407c 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -160,7 +160,7 @@ class Functions { } /** - * @deprecated + * @deprecated use fn and <=> operator * @param array $a * @param array $b * @param $key @@ -174,6 +174,14 @@ class Functions { return ($a[$key] > $b[$key]) ? -1 : 1; } + /** + * @deprecated use fn and <=> operator + * @param array $a + * @param array $b + * @param $key + * + * @return int + */ static function __cmp_less($a, $b, $key) { if ($a[$key] == $b[$key]) { return 0; @@ -224,6 +232,11 @@ class Functions { return $result; } + /** + * @param string $key + * @param string $value + * @param array|\ArrayIterator $array + */ static function assoc_key_values($key, $value, $array) { $result = []; foreach ($array as $item) { @@ -232,6 +245,10 @@ class Functions { return $result; } + /** + * @param string $key + * @param array|\ArrayIterator $array + */ static function assoc_key($key, $array) { $result = []; foreach ($array as $item) { @@ -241,6 +258,7 @@ class Functions { } /** + * Возвращает значение по ключу * @param string $key * @param mixed $value * @param array $array @@ -248,14 +266,25 @@ class Functions { */ static function _get($key, $value, $array) { foreach ($array as $item) { - if ($item[$key] == $value) return $item; + if ($item[$key] == $value) { + return $item; + } } return null; } + /** + * Возвращает ключ по значению + * @param string $key + * @param mixed $value + * @param array $array + * @return mixed + */ static function _get_key($key, $value, $array) { foreach ($array as $name => $item) { - if ($item[$key] == $value) return $name; + if ($item[$key] == $value) { + return $name; + } } return null; } @@ -279,7 +308,6 @@ class Functions { * @return mixed */ static function some(array $array, callable $callback) { - foreach ($array as $key => $value) { if (call_user_func($callback, $value) === true) { return $key; @@ -288,8 +316,14 @@ class Functions { return false; } + /** + * Разбивает массив на массивы определенной длины + * @template T + * @param int $length Длина массива + * @param T[] $array Массив + * @return T[][] + */ static function span(int $length, array $array) { - $result = []; $count = count($array); for($i = 0; $i < $count; $i += $length) { @@ -298,12 +332,22 @@ class Functions { return $result; } + /** + * Возвращает значение массива + * @param array $data Массив + * @param string|int $n Ключ + * @return mixed + */ static function array_ref(array $data, string|int $n) { return $data[$n]; } - static function call() { - $args = func_get_args(); + /** + * Вызывает функцию с аргументами + * @param mixed ...$args Аргументы + * @return mixed + */ + static function call(...$args) { $name = array_shift($args); return call_user_func_array($name, $args); } diff --git a/src/HttpRequest.php b/src/HttpRequest.php index b3fb8a3..b5a9970 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -61,7 +61,7 @@ class HttpRequest extends Collection return parent::get('data')->getString($key, $default); } - function session(?Session $value = null) + function session(?Session $value = null): ?Session { if ($value) { $this->_session = $value; @@ -69,7 +69,7 @@ class HttpRequest extends Collection return $this->_session; } - function set(string $key, mixed $value) + function set(string $key, mixed $value): void { parent::get('data')->set($key, $value); } @@ -79,9 +79,11 @@ class HttpRequest extends Collection return parent::get($key)->export(); } - function clear() + function clear(): void { - return parent::get('data')->clear(); + /** @var Collection */ + $collection = parent::get('data'); + $collection->clear(); } /** diff --git a/src/Layout/Manager.php b/src/Layout/Manager.php index 9c0256c..a3f9b26 100644 --- a/src/Layout/Manager.php +++ b/src/Layout/Manager.php @@ -5,34 +5,34 @@ * Выбор оформления страницы осуществляется если было совпадение с каким либо условием */ namespace ctiso\Layout; -use ctiso\Filter\Filter, - ctiso\Functions, - ctiso\HttpRequest; + +use ctiso\Filter\Filter; +use ctiso\HttpRequest; class Manager extends Filter { - // Массив условий с их макетами - protected $condition = array(); + /** + * Массив условий с их макетами + * @var list + */ + protected $condition = []; /** * Функция которая добавляет условие для проверки параметров $_GET - * @param $get array() | true Ассоциативный массив ключей и значений для $_GET - * - * @example - * addConditionGet(array('module' => 'personal'), 'personal') - * addConditionGet(array('module' => 'login'), 'login') + * @param array|true $get Ассоциативный массив ключей и значений для $_GET + * @param Filter $layout Макет */ - public function addConditionGet($get, Filter $layout) + public function addConditionGet($get, Filter $layout): void { - $this->addCondition(Functions::rcurry([$this, 'checkGet'], $get), $layout); + $this->addCondition(fn(HttpRequest $request) => $this->checkGet($request, $get), $layout); } /** * Условие для аякс запросов. Тоже самое что и addConditionGet но еще проверяется является ли запрос ajax */ - public function addConditionXHR($get, Filter $layout) + public function addConditionXHR($get, Filter $layout): void { - $this->addCondition(Functions::rcurry([$this, 'checkXHR'], $get), $layout); + $this->addCondition(fn(HttpRequest $request) => $this->checkXHR($request, $get), $layout); } /** @@ -57,17 +57,17 @@ class Manager extends Filter * @param array $get * @return bool */ - public function checkXHR($request, $get) + public function checkXHR($request, $get): bool { return $request->isAjax() && $this->checkGet($request, $get); } /** * Добавляет условие в общем виде - * @parma $get function(HttpRequest) Функция - * @parma $layout Layout Макет + * @param callable $get Функция + * @param Filter $layout Макет */ - public function addCondition($get, Filter $layout) + public function addCondition($get, Filter $layout): void { $this->condition [] = [$get, $layout]; } @@ -75,7 +75,7 @@ class Manager extends Filter /** * Выбирает и применяет макет для страницы */ - public function execute(HttpRequest $request) + public function execute(HttpRequest $request): string { foreach ($this->condition as $condition) { if (call_user_func($condition[0], $request)) { @@ -88,6 +88,7 @@ class Manager extends Filter } } } + return ''; } } diff --git a/src/Model/Factory.php b/src/Model/Factory.php index 948d006..6f6e840 100644 --- a/src/Model/Factory.php +++ b/src/Model/Factory.php @@ -8,8 +8,11 @@ use ctiso\Role\User; class Factory { + /** @var Database */ public $db; + /** @var ?Registry */ public $config; + /** @var ?User */ public $user; public function __construct(Database $db, ?Registry $config = null, ?User $user = null) diff --git a/src/Path.php b/src/Path.php index 45fa946..787e2c7 100644 --- a/src/Path.php +++ b/src/Path.php @@ -75,6 +75,12 @@ class Path return pathinfo($fileName, PATHINFO_EXTENSION); } + /** + * Проверяет расширение файла + * @param string $fileName Полное имя файла + * @param string|array $extension Расширение файла + * @return bool + */ static function isType($fileName, $extension) { if (is_array($extension)) { @@ -101,7 +107,6 @@ class Path * Возвращает имя файла без расширения * * @param string $fileName Полное имя файла - * * @return string */ static function getFileName(string $fileName) @@ -344,7 +349,6 @@ class Path * Подбирает новое временное имя для файла * * @param string $dst Предпологаемое имя файла - * * @return string Новое имя файла */ static function resolveFile($dst) diff --git a/src/Primitive.php b/src/Primitive.php index 8a5a10d..7f0f92a 100644 --- a/src/Primitive.php +++ b/src/Primitive.php @@ -20,7 +20,7 @@ class Primitive { } // int - public static function to_bool($value) + public static function to_bool($value): bool { return filter_var($value, FILTER_VALIDATE_BOOLEAN);//(int)((bool) $value); } @@ -41,8 +41,12 @@ class Primitive { return ((string) $value); } - // date - public static function to_date($value) + /** + * Преобразование даты dd/mm/yy в unix timestamp + * @param string $value + * @return int + */ + public static function to_date($value): int { $result = 0; $tmp = explode("/", $value ?? '', 3); @@ -66,7 +70,12 @@ class Primitive { return $result; } - public static function to_datetime($value) + /** + * Преобразование даты ISO 8601 в unix timestamp + * @param string $value + * @return int + */ + public static function to_datetime($value): int { $result = 0; @@ -79,7 +88,12 @@ class Primitive { return $result; } - public static function from_date($value) + /** + * Преобразование даты в формат dd/mm/yyyy + * @param int $value + * @return string + */ + public static function from_date($value): string { if ($value > 0) { return date("d/m/Y", $value); @@ -87,7 +101,12 @@ class Primitive { return ''; } - public static function from_datetime($value) + /** + * Преобразование даты в формат ISO 8601 + * @param int $value + * @return string + */ + public static function from_datetime($value): string { if ($value > 0) { return date("Y-m-d\TH:i\Z", $value); @@ -96,24 +115,45 @@ class Primitive { } - // secure + /** + * @deprecated + * @template T + * @param T $value + * @return T + */ public static function to_secure($value) { // Значение приабразуется во время сохранения в базе данных return $value; } + /** + * @deprecated + * @template T + * @param T $value + * @return T + */ public static function from_secure($value) { return $value; } - // array + /** + * Преобразование значения в массив + * @param mixed $value + * @return array + */ public static function to_array($value) { return (is_array($value)) ? $value : []; } + /** + * @deprecated + * @template T + * @param T $value + * @return T + */ public static function from_array($value) { return $value; diff --git a/src/Url.php b/src/Url.php index 7759fcc..83ce86b 100644 --- a/src/Url.php +++ b/src/Url.php @@ -7,6 +7,9 @@ class Url { public array $parts = []; public ?Url $parent; + /** + * @param Url|null $parent + */ function setParent($parent): void { $this->parent = $parent; } diff --git a/src/UserMessageException.php b/src/UserMessageException.php index 226eb75..1638288 100644 --- a/src/UserMessageException.php +++ b/src/UserMessageException.php @@ -6,7 +6,11 @@ namespace ctiso; class UserMessageException extends \Exception { + /** @var string */ public $userMessage; + /** + * @param string $message + */ public function __construct($message) { parent::__construct($message); $this->userMessage = $message; diff --git a/src/View/View.php b/src/View/View.php index dcdb8df..5ecfe7f 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -169,7 +169,11 @@ class View extends \stdClass throw new Exception("file not found: $file"); } - // FIXME: Префикс, конфликтует с протоколом + + /** + * FIXME: Префикс, конфликтует с протоколом + * @param string[]|string[][] $alias + */ function resolveName($alias, string $file): string { list($type, $filename) = explode(":", $file, 2); @@ -185,6 +189,9 @@ class View extends \stdClass return $file; } + /** + * @param string[][] $alias + */ public function resolveAllNames($alias, array $list): array { $result = []; foreach($list as $item) {