diff --git a/src/Connection/HttpRequest.php b/src/Connection/HttpRequest.php index 006cc63..0e2fcf3 100644 --- a/src/Connection/HttpRequest.php +++ b/src/Connection/HttpRequest.php @@ -3,27 +3,31 @@ namespace ctiso\Connection; use ctiso\File; -class HttpRequest +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() { $this->method = self::GET; } - + /** * Возвращает заголовок соединения + * @return string */ public function getHeader() { @@ -36,11 +40,11 @@ class HttpRequest $result .= $this->data; return $result; } - + /** * Установка параметров запроса - * @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; diff --git a/src/Connection/HttpResponse.php b/src/Connection/HttpResponse.php index 1da2036..745091a 100644 --- a/src/Connection/HttpResponse.php +++ b/src/Connection/HttpResponse.php @@ -8,7 +8,7 @@ namespace ctiso\Connection; class HttpResponse { private $offset; - private $param = array (); + private $param = []; private $code; public $response; public $version; @@ -19,7 +19,7 @@ class HttpResponse $this->offset = 0; $this->response = $response; $this->parseMessage(); - } + } /** * Обработка HTTP ответа @@ -30,7 +30,7 @@ class HttpResponse $this->version = $http[0]; $this->code = $http[1]; - $line = $this->getLine(); + $line = $this->getLine(); while ($offset = strpos($line, ":")) { $this->param[substr($line, 0, $offset)] = trim(substr($line, $offset + 1)); $line = $this->getLine(); @@ -59,7 +59,7 @@ class HttpResponse { $begin = $this->offset; $offset = strpos($this->response, "\r\n", $this->offset); - $result = substr($this->response, $begin, $offset - $begin); + $result = substr($this->response, $begin, $offset - $begin); $this->offset = $offset + 2; return $result; } @@ -67,20 +67,20 @@ class HttpResponse /** * Значение параметра HTTP ответа */ - public function getParameter($name) + public function getParameter($name) { return $this->param[$name]; } - public function getData() + public function getData() { return $this->data; } /** - * Состояние + * Состояние */ - public function getCode() + public function getCode() { return $this->code; } diff --git a/src/Controller/Action.php b/src/Controller/Action.php index b4b7957..480eb86 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -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__')) { diff --git a/src/Controller/ActionInterface.php b/src/Controller/ActionInterface.php index e932c97..d0113b4 100644 --- a/src/Controller/ActionInterface.php +++ b/src/Controller/ActionInterface.php @@ -1,11 +1,21 @@ $class + */ function getView($name, $class); + /** + * @param string $key + * @param string $value + */ function addUrlPart($key, $value); } \ No newline at end of file diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 993521b..d9a3a84 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -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); } diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 132b560..e640c13 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -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(); diff --git a/src/Controller/Installer.php b/src/Controller/Installer.php index e00b705..f925697 100644 --- a/src/Controller/Installer.php +++ b/src/Controller/Installer.php @@ -1,38 +1,64 @@ _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; + 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); @@ -86,7 +130,7 @@ class Installer $version_new = $settings->get('version'); if ($item) { - $version_old = $item['version']; + $version_old = $item['version']; } else { $version_old = "0.0"; $registry->writeKey([$name], []); @@ -96,15 +140,15 @@ class Installer if (is_array($sql)) { $res = $this->installSQL($sql, $version_new, $version_old, $name); if ($res) { - $result[]=$res; + $result[] = $res; } } - } + } // Обновление версии меню $registry->removeKey($name); $registry->set($name, [ - 'version' => $version_new, + 'version' => $version_new, 'time' => filemtime($setup) ]); // $registry->writeKey([$name], $settings->export()); @@ -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); } diff --git a/src/Controller/Request.php b/src/Controller/Request.php index 6bfd653..4a4293e 100644 --- a/src/Controller/Request.php +++ b/src/Controller/Request.php @@ -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; diff --git a/src/Controller/Service.php b/src/Controller/Service.php index b12c807..1c572aa 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -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) { diff --git a/src/Database.php b/src/Database.php index 5206c08..37d6bc1 100644 --- a/src/Database.php +++ b/src/Database.php @@ -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 + */ 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; } } } diff --git a/src/Database/Manager.php b/src/Database/Manager.php index 31d589b..d31527f 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -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) { diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index 2a6a834..a8b42d8 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -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; diff --git a/src/Excel/Document.php b/src/Excel/Document.php index d4d033e..4b11eec 100644 --- a/src/Excel/Document.php +++ b/src/Excel/Document.php @@ -9,10 +9,15 @@ use XMLWriter, class Document { static $ns = "urn:schemas-microsoft-com:office:spreadsheet"; - private $table = array (); - protected $styles = array(); + /** @var list */ + private $table = []; + protected $styles = []; - function addTable($table) { + /** + * Добавление таблицы в документ + * @param Table|callable $table Таблица или функция, возвращающая таблицу + */ + function addTable($table): void { $this->table [] = $table; } diff --git a/src/Excel/Number.php b/src/Excel/Number.php index 8ed12b4..080fb74 100644 --- a/src/Excel/Number.php +++ b/src/Excel/Number.php @@ -4,16 +4,17 @@ namespace ctiso\Excel; class Number { + /** @var int */ public $value; - function __construct($value) + function __construct($value) { $this->value = (int)($value); } - function getString() + function getString(): string { - return $this->value; - } + return (string) $this->value; + } } diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 726a1dc..95ab5db 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -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(); } diff --git a/src/File.php b/src/File.php index c523cf6..8ee2eae 100644 --- a/src/File.php +++ b/src/File.php @@ -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) { diff --git a/src/Filter/ActionLogger.php b/src/Filter/ActionLogger.php index 73ea856..ee94839 100644 --- a/src/Filter/ActionLogger.php +++ b/src/Filter/ActionLogger.php @@ -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; /** diff --git a/src/Filter/Authorization.php b/src/Filter/Authorization.php index 5521f72..2421212 100644 --- a/src/Filter/Authorization.php +++ b/src/Filter/Authorization.php @@ -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"); diff --git a/src/Filter/Filter.php b/src/Filter/Filter.php index a419e99..7aac567 100644 --- a/src/Filter/Filter.php +++ b/src/Filter/Filter.php @@ -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(); } diff --git a/src/Form/Field.php b/src/Form/Field.php index cda2068..30daf90 100644 --- a/src/Form/Field.php +++ b/src/Form/Field.php @@ -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 */ diff --git a/src/Functions.php b/src/Functions.php index 2dc407c..a681669 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -39,7 +39,9 @@ class left { define('__', '_ARGUMENT_PLACE_'); class partial { + /** @var array */ protected $params; + /** @var callable */ protected $fn; public function __construct($params) { @@ -354,33 +356,37 @@ 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; } diff --git a/src/HttpRequest.php b/src/HttpRequest.php index b5a9970..21ea3d2 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -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(); diff --git a/src/Settings.php b/src/Settings.php index b9b67fa..e99bb98 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -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)) { diff --git a/src/TableTree.php b/src/TableTree.php index ba0ec60..d09eac3 100644 --- a/src/TableTree.php +++ b/src/TableTree.php @@ -4,26 +4,29 @@ * Преобразование дерева из модели Plain в массив массивов (Adjacency List) */ -/** - * Обходит таблицу как дерево - * $fn ($name, $index, $rows, $cc) - * $name Ключ уровня - * $index Значение ключа уровня - * $rows Все столбцы текущго уровня - * $cc Столбцы более низкого уровня - * - * @param Array $level Уровни вложенности - * @param array $table Таблица - * @param Function $fn Функция которая применяется к каждой ветке дерева - */ namespace ctiso; use ctiso\Functions; class TableTree { + /** + * Обходит таблицу как дерево + * $fn ($name, $index, $rows, $cc) + * $name Ключ уровня + * $index Значение ключа уровня + * $rows Все столбцы текущго уровня + * $cc Столбцы более низкого уровня + * + * @param array $level Уровни вложенности + * @param array $table Таблица + * @param callable $fn Функция которая применяется к каждой ветке дерева + * @return array + */ static function walk($level, $table, $fn) { - if (empty ($level)) return $table; + if (empty ($level)) { + return $table; + } $name = array_shift ($level); - + $keys = Functions::key_unique_values($name, $table); $data = []; foreach ($keys as $index) { diff --git a/src/Tools/Drawing.php b/src/Tools/Drawing.php index 80bb92d..dbfcd8a 100644 --- a/src/Tools/Drawing.php +++ b/src/Tools/Drawing.php @@ -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); diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index 62c8e9c..5d5bb06 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -9,7 +9,9 @@ use GdImage; class TemplateImage { + /** @var array */ static array $listfiles = array('jpg' => 'jpeg', 'gif' => 'gif', 'png' => 'png', 'bmp' => 'wbmp'); + /** @var array */ 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) { diff --git a/src/View/Composite.php b/src/View/Composite.php index 3953c42..278f798 100644 --- a/src/View/Composite.php +++ b/src/View/Composite.php @@ -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); }