From 0f4b2fb722662a897d8fc48e4d775740f3507402 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Fri, 23 Mar 2018 12:35:10 +0300 Subject: [PATCH 001/138] =?UTF-8?q?=D0=9E=D0=BF=D1=82=D0=B8=D0=BC=D0=B8?= =?UTF-8?q?=D0=B7=D0=B0=D1=86=D0=B8=D0=B8=20=D0=B8=20=D0=B8=D1=81=D0=BF?= =?UTF-8?q?=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D1=82=D0=BE?= =?UTF-8?q?=D0=BF=D0=BE=D0=B2.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Collection.php | 6 ++--- src/Connection/HttpResponse.php | 10 ++++---- src/Controller/Component.php | 38 ++++++++++++++++++++++++++--- src/Controller/Front.php | 6 ++--- src/Controller/Request.php | 8 ++++-- src/Controller/Service.php | 5 +++- src/Database/IdGenerator.php | 2 +- src/Database/PDOStatement.php | 2 +- src/Excel/DataTime.php | 2 +- src/Excel/Number.php | 2 +- src/Excel/Table.php | 4 +-- src/Filter/Login.php | 1 + src/Functions.php | 9 ++++--- src/Numbers.php | 3 ++- src/Path.php | 19 +++++++++------ src/Primitive.php | 6 ++--- src/Tools/Drawing.php | 3 ++- src/Tools/SQLStatementExtractor.php | 4 +-- src/Tools/String.php | 4 +-- src/Tools/TemplateImage.php | 19 +++++++++------ src/Validator/Rule/Code.php | 3 ++- src/Validator/Rule/Count.php | 2 +- src/Validator/Rule/Date.php | 1 + src/Validator/Rule/Time.php | 2 +- src/config.php | 1 + 25 files changed, 109 insertions(+), 53 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index 467175e..e56b2d1 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -58,17 +58,17 @@ class Collection implements ArrayAccess public function getInt($key, $default = 0) { - return intval($this->get($key, $default)); + return (int)$this->get($key, $default); } public function getString($key, $default = '') { - return ((string) $this->get($key, $default)); + return (string)$this->get($key, $default); } public function getNat($key, $default = 1) { - $result = intval($this->get($key, $default)); + $result = (int)$this->get($key, $default); return (($result > 0) ? $result : $default); } diff --git a/src/Connection/HttpResponse.php b/src/Connection/HttpResponse.php index 9e94c9f..df08cbc 100644 --- a/src/Connection/HttpResponse.php +++ b/src/Connection/HttpResponse.php @@ -36,12 +36,12 @@ class Connection_HttpResponse if (isset($this->param['Transfer-Encoding']) && $this->param['Transfer-Encoding'] == 'chunked') { //$this->data = substr($this->response, $this->offset); - $line = hexdec($this->getLine()); + $index = hexdec($this->getLine()); $chunk = array(); - while ($line > 0) { - $chunk [] = substr($this->response, $this->offset, $line); - $this->offset += $line; - $line = hexdec($this->getLine()); + while ($index > 0) { + $chunk [] = substr($this->response, $this->offset, $index); + $this->offset += $index; + $index = hexdec($this->getLine()); } $this->data = implode("", $chunk); diff --git a/src/Controller/Component.php b/src/Controller/Component.php index efc3cdf..dce2076 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -38,6 +38,23 @@ class ComponentRequest { } } +class FakeTemplate { + public $_data = []; + public $_name = ''; + + function __construct($name) { + $this->_name = $name; + } + + function __set($key, $value) { + $this->_data[$key] = $value; + } + + function execute() { + return $this->_data; + } +} + /** * Класс компонента */ @@ -56,6 +73,7 @@ class Controller_Component public /*.Settings.*/$registry; public /*.Database.*/$db; public /*.Collection.*/$parameter; + public $output = 'html'; public $module; public $item_module; @@ -86,6 +104,10 @@ class Controller_Component public function getView($name) { + if ($this->output == 'json') { + return new FakeTemplate($name); + } + // /*.Settings.*/$registry = $this->registry; $template = ($this->template) ? $this->template : $registry->readKey(array('system', 'template')); @@ -164,8 +186,18 @@ class Controller_Component return $result; } + function findFile($pathList, $name) { + foreach($pathList as $item) { + $filename = Path::join($item, $name); + if (file_exists($filename)) { + return $filename; + } + } + return null; + } + function getInfo() { - $filename = Path::join($this->viewPath[0], 'install.json'); + $filename = $this->findFile($this->viewPath, 'install.json'); if (file_exists($filename)) { $settings = json_decode(File::getContents($filename), true); return $settings; @@ -262,13 +294,13 @@ class Controller_Component } $params = new Collection(); - $params->import(array_merge($_GET, $arguments)); + $params->import($arguments); $component->parameter = $params; $component->template = $params->get('template', false); $editor = $component->getEditUrl(); if ($editor) { - if(class_exists("Controller_Site")){ //Если мы в CMS2 + if(class_exists("Controller_Site")) { //Если мы в CMS2 $instance = Controller_Site::getInstance(); $instance->componentsConfig[] = $editor; } else { diff --git a/src/Controller/Front.php b/src/Controller/Front.php index af064ad..772d177 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -40,7 +40,7 @@ class Controller_Front extends Controller_Action * @param request $request Имя модуля * @return string */ - public function loadModule($name, Collection $request, $controller = false) + public function loadModule($name, Collection $request, $controller = null) { if ($this->isLoaded($name)) { $module = $this->modules[$name]; @@ -93,13 +93,13 @@ class Controller_Front extends Controller_Action $this->default = $name; } - public function execute(HTTPRequest $request) + public function execute(HttpRequest $request) { $name = explode("_", $request->get($this->_param, $this->default)); if (count($name) >= 2) { $controller = $name[1]; } else { - $controller = false; + $controller = null; } try{ return $this->loadModule($name[0], $request, $controller); diff --git a/src/Controller/Request.php b/src/Controller/Request.php index 01822e1..1ac7be4 100644 --- a/src/Controller/Request.php +++ b/src/Controller/Request.php @@ -1,13 +1,17 @@ r = $request; $this->id = $id; } - function get($name) { + function get($name, $def) { $v = $this->r->get($name); + $id = $this->id; if ($id && is_array($v)) { return isset($v[$id]) ? $v[$id] : $def; } diff --git a/src/Controller/Service.php b/src/Controller/Service.php index 46f96aa..64b8a59 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -5,12 +5,15 @@ */ class Controller_Service { - public $viewPath = array(); + public $viewPath = []; + public $webPath = []; public $registry; // Registry->getInstance public $template; public $templatePath; public $COMPONENTS_WEB; + public $db; + public function getTemplatePath($name) { return Path::join($this->viewPath[0], 'templates', 'modern', $name); diff --git a/src/Database/IdGenerator.php b/src/Database/IdGenerator.php index 045ec86..41ee235 100644 --- a/src/Database/IdGenerator.php +++ b/src/Database/IdGenerator.php @@ -21,6 +21,6 @@ class Database_IdGenerator { } else { $result = $this->db->fetchOneArray("SELECT last_insert_rowid() AS nextval"); } - return intval($result['nextval']); + return (int)$result['nextval']; } } diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index 1274e6e..e74a244 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -66,7 +66,7 @@ class Database_PDOStatement extends PDOStatement implements IteratorAggregate } function getInt($name) { - return intval($this->fields[$name]); + return (int)$this->fields[$name]; } function getBlob($name) { diff --git a/src/Excel/DataTime.php b/src/Excel/DataTime.php index 0536cbd..8e590d0 100644 --- a/src/Excel/DataTime.php +++ b/src/Excel/DataTime.php @@ -6,7 +6,7 @@ class Excel_DateTime function __construct($value) { - $this->value = intval($value); + $this->value = (int)$value; } function getString() diff --git a/src/Excel/Number.php b/src/Excel/Number.php index 66dd6b6..5d212fe 100644 --- a/src/Excel/Number.php +++ b/src/Excel/Number.php @@ -6,7 +6,7 @@ class Excel_Number function __construct($value) { - $this->value = intval($value); + $this->value = (int)$value; } function getString() diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 162c823..63e2f80 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -50,7 +50,7 @@ class Excel_Table function __construct() { - $this->name = "Page " . intval(self::$index ++); + $this->name = "Page " . ((int)self::$index ++); } /** @@ -230,7 +230,7 @@ class Excel_Table } else { $doc->writeAttribute('ss:Type', "Number"); } - $doc->writeCData($this->encode($value)); + $doc->writeCdata($this->encode($value)); } $doc->endElement(); $doc->endElement(); diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 70ad01d..df3476d 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -13,6 +13,7 @@ class Filter_Login extends Filter_Filter const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#'; const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; public $mode = 'ajax'; + public $user; //AJAX-Реквесты для которых не требуется авторизация, потребовалось для сбора статистики public $whiteRequestList = [['module' => "requiredcontent", "action" => "getcount"], diff --git a/src/Functions.php b/src/Functions.php index 3f888e7..61b9123 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -53,7 +53,8 @@ class __partial { function apply() { $params = func_get_args(); $result = array(); - for($i = 0, $j = 0; $i < count($this->params); $i++) { + $count = count($this->params); + for($i = 0, $j = 0; $i < $count; $i++) { if ($this->params[$i] == __) { $result [] = $params[$j]; $j++; @@ -77,7 +78,8 @@ class __compose { function apply () { $params = func_get_args (); $result = call_user_func_array($this->fns[0], $params); - for ($i = 1; $i < count($this->fns); $i++) { + $count = count($this->fns); + for ($i = 1; $i < $count; $i++) { $result = call_user_func($this->fns[$i], $result); } return $result; @@ -306,7 +308,8 @@ class Functions { assert(is_int($length)); $result = array(); - for($i = 0; $i < count($array); $i += $length) { + $count = count($array); + for($i = 0; $i < $count; $i += $length) { $result [] = array_slice($array, $i, $length); } return $result; diff --git a/src/Numbers.php b/src/Numbers.php index c0a39c7..9001e4a 100644 --- a/src/Numbers.php +++ b/src/Numbers.php @@ -15,7 +15,8 @@ class Numbers static function prefix($prefix, array $array, $key = false) { $result = array(); - for ($i = 0; $i < count($array); $i++) { + $count = count($array); + for ($i = 0; $i < $count; $i++) { $result [] = call_user_func($prefix, $i + 1) . '. ' . $array[$i]; } return $result; diff --git a/src/Path.php b/src/Path.php index ba78789..1116448 100644 --- a/src/Path.php +++ b/src/Path.php @@ -160,8 +160,9 @@ class Path // Сравнение двух путей на равентство public function equal(/*.Path.*/ $path) { - if (count($this->path) == count($path->path)) { - for ($i = 0; $i < count($this->path); $i++) { + $count = count($this->path); + if ($count == count($path->path)) { + for ($i = 0; $i < $count; $i++) { if ($this->path[$i] != $path->path[$i]) { return false; } @@ -207,8 +208,9 @@ class Path if (isset($this->url['host']) && isset($path->url['host']) && ($this->url['host'] != $path->url['host'])) return false; - if (count($path->path) > count($this->path)) { - for ($i = 0; $i < count($this->path); $i++) { + $count = count($this->path); + if (count($path->path) > $count) { + for ($i = 0; $i < $count; $i++) { if ($path->path[$i] != $this->path[$i]) { return false; } @@ -252,15 +254,18 @@ class Path $list_path = $list->getParts(); $result = array(); - for ($i = 0; $i < count($list_path); $i++) { + $count = count($list_path); + for ($i = 0; $i < $count; $i++) { if (($i >= count($self_path)) || $list_path[$i] != $self_path[$i]) { break; } } - for($j = $i; $j < count($list_path); $j++) { + $list_count = count($list_path); + for($j = $i; $j < $list_count; $j++) { array_push($result, '..'); } - for($j = $i; $j < count($self_path); $j++) { + $self_count = count($self_path); + for($j = $i; $j < $self_count; $j++) { array_push($result, $self_path[$j]); } return implode("/", $result); diff --git a/src/Primitive.php b/src/Primitive.php index aec45fd..e911916 100644 --- a/src/Primitive.php +++ b/src/Primitive.php @@ -48,9 +48,9 @@ class Primitive { if (!empty($tmp)) { if (count($tmp) != 3) return $result; - $year = intval($tmp[2]); - $month = intval($tmp[1]); - $day = intval($tmp[0]); + $year = (int)$tmp[2]; + $month = (int)$tmp[1]; + $day = (int)$tmp[0]; if ($month != 0 && $day != 0 && $year != 0) { if (checkdate($month, $day, $year)) { diff --git a/src/Tools/Drawing.php b/src/Tools/Drawing.php index e13a323..e3dc6b0 100644 --- a/src/Tools/Drawing.php +++ b/src/Tools/Drawing.php @@ -40,7 +40,8 @@ class Tools_Drawing $first_word = true; $last_width = 0; - for ($i = 0; $i < count($words); $i++) { + $count = count($words); + for ($i = 0; $i < $count; $i++) { $item = $words[$i]; $dimensions = imagettfbbox($size, $angle, $font, $current_line . ($first_word ? '' : ' ') . $item); $line_width = $dimensions[2] - $dimensions[0]; diff --git a/src/Tools/SQLStatementExtractor.php b/src/Tools/SQLStatementExtractor.php index 739f6c7..61a54a3 100644 --- a/src/Tools/SQLStatementExtractor.php +++ b/src/Tools/SQLStatementExtractor.php @@ -111,7 +111,7 @@ class Tools_SQLStatementExtractor { if ($check === "" || $check === $string) { return true; } else { - return (strpos($string, $check) === 0) ? true : false; + return (strpos($string, $check) === 0); } } @@ -125,7 +125,7 @@ class Tools_SQLStatementExtractor { if ($check === "" || $check === $string) { return true; } else { - return (strpos(strrev($string), strrev($check)) === 0) ? true : false; + return (strpos(strrev($string), strrev($check)) === 0); } } diff --git a/src/Tools/String.php b/src/Tools/String.php index bd6c2de..ab3bab5 100644 --- a/src/Tools/String.php +++ b/src/Tools/String.php @@ -15,7 +15,7 @@ class Tools_String { if ($in_subarr > 0) { // already in sub-array? $subarr[$in_subarr][] = $tok; if ('}' === substr($tok, -1, 1)) { // check to see if we just added last component - $res[] = strToArray(implode(',', $subarr[$in_subarr])); + $res[] = self::strToArray(implode(',', $subarr[$in_subarr])); $in_subarr--; } } elseif ($tok{0} === '{') { // we're inside a new sub-array @@ -25,7 +25,7 @@ class Tools_String { $subarr[$in_subarr] = array(); $subarr[$in_subarr][] = $tok; } else { - $res[] = strToArray($tok); + $res[] = self::strToArray($tok); } } else { // not sub-array $val = trim($tok, '"'); // remove " (surrounding strings) diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index 6ce9a33..f6509ca 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -33,13 +33,16 @@ class Tools_TemplateImage protected $data = array(); protected $base = "c:\\windows\\fonts\\"; protected $image; - protected $prepare = true; + protected $_prepare = true; public $debug = false; - function __construct ($template = false) + public $resource; + public $filename; + + function __construct ($template = null) { // assert(is_string($src)); - if($template) { + if ($template) { $this->data = $template; } } @@ -116,7 +119,7 @@ class Tools_TemplateImage return ""; } - function imageText($text, $value) + function imageText($text, /*.stdClass.*/$value) { assert(is_string($text)); @@ -134,7 +137,7 @@ class Tools_TemplateImage } if ($value->valign[0]) { - $valign = Drawing::ALIGN_TOP; + $valign = Tools_Drawing::ALIGN_TOP; } elseif ($value->valign[1]) { $valign = Tools_Drawing::ALIGN_CENTER; } else { @@ -159,7 +162,7 @@ class Tools_TemplateImage { $width = imagesx($this->image); $height = imagesy($this->image); - if($new_height == false) { + if ($new_height == null) { $new_height = ceil($height * $new_width / $width); } @@ -171,8 +174,8 @@ class Tools_TemplateImage } function prepare() { - if($this->prepare) { - $this->prepare = false; + if($this->_prepare) { + $this->_prepare = false; foreach ($this->data as $value) { $this->imageText($value->text, $value); // break; } diff --git a/src/Validator/Rule/Code.php b/src/Validator/Rule/Code.php index 2bcfbf8..1928685 100644 --- a/src/Validator/Rule/Code.php +++ b/src/Validator/Rule/Code.php @@ -25,7 +25,8 @@ class Validator_Rule_Code extends Validator_Rule_Abstract $name = $this->field; if (is_array($_POST[$name . '_code_genre'])) { - for($n = 0; $n < count($_POST[$name . '_code_genre']); $n++) { + $count = count($_POST[$name . '_code_genre']); + for($n = 0; $n < $count; $n++) { $code = array( $_POST[$name . '_code_genre'][$n], $_POST[$name . '_code_f'][$n], diff --git a/src/Validator/Rule/Count.php b/src/Validator/Rule/Count.php index 2afd612..47686b8 100644 --- a/src/Validator/Rule/Count.php +++ b/src/Validator/Rule/Count.php @@ -6,7 +6,7 @@ class Validator_Rule_Count extends Validator_Rule_Abstract { public $size = 1; - public $max = false; + public $max = null; public function getErrorMsg() { diff --git a/src/Validator/Rule/Date.php b/src/Validator/Rule/Date.php index be8e17e..166907a 100644 --- a/src/Validator/Rule/Date.php +++ b/src/Validator/Rule/Date.php @@ -15,6 +15,7 @@ class Validator_Rule_Date extends Validator_Rule_Abstract public function isValid(Collection $container, $status = null) { $pattern = "/^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/"; + $matches = []; return (preg_match($pattern, $container->get($this->field), $matches) && checkdate($matches[2], $matches[1], $matches[3])); } diff --git a/src/Validator/Rule/Time.php b/src/Validator/Rule/Time.php index 05a7a46..a64655c 100644 --- a/src/Validator/Rule/Time.php +++ b/src/Validator/Rule/Time.php @@ -23,7 +23,7 @@ class Validator_Rule_Time extends Validator_Rule_Abstract { $tmp = explode($this->split, $container->get($this->field), 2); if ($tmp) { - if (self::checktime ($tmp[0], $tmp[1])) { + if (self::checktime ((int)$tmp[0], (int)$tmp[1])) { return true; } } diff --git a/src/config.php b/src/config.php index 3bbc19a..86c7dfb 100644 --- a/src/config.php +++ b/src/config.php @@ -1,6 +1,7 @@ Date: Tue, 27 Mar 2018 12:23:58 +0300 Subject: [PATCH 002/138] =?UTF-8?q?=D0=98=D0=B7=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D1=8F=D0=B5=D0=BC=D1=81=D1=8F=20=D0=BE=D1=82=20=D1=81=D1=82?= =?UTF-8?q?=D0=B0=D1=82=D0=B8=D1=87=D0=B5=D1=81=D0=BA=D0=B8=D1=85=20=D0=BA?= =?UTF-8?q?=D0=BB=D0=B0=D1=81=D1=81=D0=BE=D0=B2=20=D0=B8=20=D1=81=D0=B8?= =?UTF-8?q?=D0=BD=D0=B3=D0=BB=D1=82=D0=BE=D0=BD=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 4 +-- src/Controller/Front.php | 53 +++++++++------------------- src/Filter/Login.php | 46 +++++++++---------------- src/Filter/UserAccess.php | 69 ------------------------------------- src/Registry.php | 24 ------------- src/Role/User.php | 69 +++++++++++++++++++++++++++++++++++++ src/Settings.php | 4 +-- src/Shortcut.php | 66 ----------------------------------- src/Tales.php | 72 +++++++++++++++++++++++++++++++++++++++ src/config.php | 8 ----- src/tales.php | 71 -------------------------------------- 11 files changed, 177 insertions(+), 309 deletions(-) delete mode 100644 src/Filter/UserAccess.php delete mode 100644 src/Registry.php create mode 100644 src/Role/User.php delete mode 100644 src/Shortcut.php create mode 100644 src/Tales.php delete mode 100644 src/config.php delete mode 100644 src/tales.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 6045d5b..f67f515 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -304,12 +304,12 @@ class Controller_Action /** * Добавление widget к отображению */ - public function addChild(/*Widget*/ $section, $node) + public function addChild(/*Widgets_Widget*/ $section, $node) { $this->childNodes[$section] = $node; } - public function setValue(/*Widget*/ $name, $value) + public function setValue(/*Widgets_Widget*/ $name, $value) { $this->ctrlValues[$name] = $value; } diff --git a/src/Controller/Front.php b/src/Controller/Front.php index af064ad..d88b8f8 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -18,15 +18,12 @@ class Controller_Front extends Controller_Action * @param Settings $_registry * @param Shortcut $_shortcut */ - public function __construct(Settings $_registry, $_shortcut) // $db, $installer, $shortcut + public function __construct($db, $settings, $default) // $db, $installer, $shortcut { parent::__construct(); - $registry = $_registry; - $this->_registry = $_registry; - $this->_shortcut = $_shortcut; // $cc->newShortcut(); - - $dsn = $registry->readKey(array('system', 'dsn')); - $this->db = Database::getConnection($dsn); // $cc->newConnection(); + $this->settings = $settings; + $this->db = $db; + $this->default = $default; } public function isLoaded($name) @@ -47,34 +44,24 @@ class Controller_Front extends Controller_Action return $module->access->execute($request); } - if ($controller) { - $moduleFile = Shortcut::getUrl($this->shortcut, $name, $controller); // ModuleLoader (2) - } else { - $moduleFile = Shortcut::getUrl($this->shortcut, $name, $name); // ModuleLoader (2) - } + $basePath = $this->settings['system']->readKey(['path', 'modules']); + $moduleFile = Path::join($basePath, $name, 'classes', $controller ? $controller : $name); $module = $this->loadClass($moduleFile, null, 'Module_'); if ($module) { // Инициализация модуля - $module->viewPath = Shortcut::getUrl('modulepath', $name); + $modPath = Path::join($basePath, $name); + $module->viewPath = $modPath; $module->name = $name; - - $module->param = $this->param; // - $module->_registry = $this->_registry; - $module->_shortcut = $this->_shortcut; - - $module->iconPath = $this->iconPath; // -> Registry - $module->themePath = $this->themePath; // -> Registry - $module->jsPath = $this->jsPath; // -> Registry + $module->settings = $this->settings; $module->db = $this->db; - // Не для всех приложений нужно вести лог действий // Ведение лога - $logger = $this->loadClass(__DIR__ . '/../Filter/ActionLogger.php', $module, 'Filter_'); - $logger->before = $this->loadSettings(Shortcut::getUrl('logger', $name)); + $logger = new Filter_ActionLogger($module); + $logger->before = $this->loadSettings(Path::join($modPath, 'filter', 'logger.php')); // Управление доступом - $module->access = $this->loadClass(__DIR__ . '/../Filter/ActionAccess.php', $logger, 'Filter_'); - $module->access->access = $this->loadSettings(Shortcut::getUrl('access', $name)); + $module->access = new Filter_ActionAccess($logger); + $module->access->access = $this->loadSettings(Path::join($modPath, 'filter', 'access.php')); $module->setUp(); @@ -85,27 +72,19 @@ class Controller_Front extends Controller_Action return null; // throw new FileNotFoundException(); } - public function setParameter($shortcut, $param, $name) - { - $this->shortcut = $shortcut; - // Параметр - $this->_param = $param; - $this->default = $name; - } - public function execute(HTTPRequest $request) { - $name = explode("_", $request->get($this->_param, $this->default)); + $name = explode("_", $request->get('module', $this->default)); if (count($name) >= 2) { $controller = $name[1]; } else { $controller = false; } - try{ + try { return $this->loadModule($name[0], $request, $controller); } catch (UserMessageException $ex) { //Исключение с понятным пользователю сообщением $mode = $request->get('mode'); - if($mode == 'ajax' || $mode == 'json'){ + if($mode == 'ajax' || $mode == 'json') { return json_encode(['result'=>'fail', 'message'=> $ex->userMessage]); } else { return $ex->userMessage; diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 70ad01d..4f3b294 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -14,11 +14,11 @@ class Filter_Login extends Filter_Filter const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; public $mode = 'ajax'; - //AJAX-Реквесты для которых не требуется авторизация, потребовалось для сбора статистики - public $whiteRequestList = [['module' => "requiredcontent", "action" => "getcount"], - ['module' => "requiredcontent", "action" => "teststructure"], - ['module' => "requiredcontent", "action" => "specialdump"] - ]; + function __construct($processor, $role, $whitelist = []) { + parent::__construct($processor); + $this->role = $role; + $this->whitelist = $whitelist; + } /** * Проверка авторизации * @return Boolean Авторизовани пользователь или нет @@ -27,29 +27,18 @@ class Filter_Login extends Filter_Filter { // Авторизация session_start(); - $db = $this->getConnection(); - Filter_UserAccess::setUp($db); // Соединение switch ($request->getAction()) { // Авторизация по постоянному паролю case 'login': $login = $request->get('login'); $password = $request->get('password'); - $result = Filter_UserAccess::getUserByLogin($login); // Поиск по логину + $result = $this->role->getUserByLogin($login); // Поиск по логину if ($result) { - $userPassword = $result->getString('password'); - if (Filter_UserAccess::$access == 'site_root' && defined('PARENT_PATH')) { - $s = new Settings(PARENT_PATH . '/settings.json'); - $s->read(); - $dsn = $s->readKey(array('system', 'dsn')); - - $db = Database::getConnection($dsn); - $user = $db->fetchOneArray("SELECT * FROM users WHERE login = :login", ['login' => $login]); - $userPassword = $user['password']; - } + $userPassword = $this->role->getUserPassword($result); // Извлечнеие пользователя из родительской CMS, для проверки пароля if (md5($password) == $userPassword) { // password - $this->enter($db, $result); + $this->enter($result); return true; } } @@ -62,7 +51,7 @@ class Filter_Login extends Filter_Filter case 'enter': $login = $request->get('login'); $password = $request->get('sid'); - $result = Filter_UserAccess::getUserByLogin($login); // Поиск по логину + $result = $this->role->getUserByLogin($login); // Поиск по логину if ($result) { $temp = md5($result->getString('password') . $result->getString('login') . $result->getString('sid')); if ($password == $temp) { @@ -76,7 +65,7 @@ class Filter_Login extends Filter_Filter // Если $hash не совпадает $_SESSION['hash'] то удаляем сессию if (isset($_SESSION ['access']) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { if ($hash == $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME]) { - $this->user = $user = Filter_UserAccess::getUserById($_SESSION['access']); // Поиск по идентификатору + $this->user = $user = $role->getUserById($_SESSION['access']); // Поиск по идентификатору if ($user && isset($_SESSION['random']) && ($user->get('sid') == $_SESSION['random'])) { return true; } @@ -89,8 +78,7 @@ class Filter_Login extends Filter_Filter return false; } - private function getBrowserSign() - { + private function getBrowserSign() { $rawSign = self::SESSION_BROWSER_SIGN_SECRET; //$signParts = array('HTTP_USER_AGENT', 'HTTP_ACCEPT_ENCODING'); $signParts = array(); @@ -101,15 +89,15 @@ class Filter_Login extends Filter_Filter return md5($rawSign); } - private function enter($db, $result) + private function enter($result) { $this->user = $result; $random = rand(0, 1024 * 1024); - $db->executeQuery("UPDATE users SET sid = '$random' WHERE id_user = " . $result->getInt('id_user')); + $this->role->setSID($random, $result); - $_SESSION["group"] = $result->getInt('access'); - $_SESSION["access"] = $result->getInt('id_user'); // id_user - $_SESSION["random"] = $random; // id_user + // $_SESSION["group"] = $result->getInt('access'); + $_SESSION["access"] = $result->getInt('id_user'); + $_SESSION["random"] = $random; $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME] = $this->getBrowserSign(); $_SESSION["time"] = time(); } @@ -122,7 +110,6 @@ class Filter_Login extends Filter_Filter $result = array(); $result['fullname'] = $this->user->getString('patronymic') . " " . $this->user->getString('firstname'); $result['email'] = $this->user->getString('email'); - $result['site'] = 187; $result['hash'] = sha1(self::SESSION_BROWSER_SIGN_SECRET . $this->user->getString('email')); return json_encode($result); } else { @@ -164,7 +151,6 @@ class Filter_Login extends Filter_Filter /* --------------------- * Проверка на попадание реквеста в белый список */ - public function requestIsWhite(Collection $request, $whiteRequestList){ $module = $request->get('module'); $action = $request->get('action'); diff --git a/src/Filter/UserAccess.php b/src/Filter/UserAccess.php deleted file mode 100644 index ce27a66..0000000 --- a/src/Filter/UserAccess.php +++ /dev/null @@ -1,69 +0,0 @@ -executeQuery(); - if ($result->next()) { - self::$access = $GROUPS[$result->getString('access')]; - self::$name = $result->getString('login'); - self::$id = $result->getInt('id_user'); - self::$password = $result->getString('password'); - self::$fullname = implode(' ', array( - $result->getString('surname'), - $result->getString('firstname'), - $result->getString('patronymic'))); - return $result; - } - return null; - } - - public static function getUserByLogin($login) - { - $stmt = self::$db->prepareStatement("SELECT * FROM users WHERE login = ?"); - $stmt->setString(1, $login); - $result = self::getUserByQuery($stmt); - if ($result) { - $time = time(); - $id = self::$id; - self::$db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время входа - } - return $result; - } - - public static function getUserById($id) - { - $stmt = self::$db->prepareStatement("SELECT * FROM users WHERE id_user = ?"); - $stmt->setInt(1, $_SESSION ['access']); - $result = self::getUserByQuery($stmt); - if ($result) { - $lasttime = $result->getInt('lasttime'); - $time = time(); - if ($time - $lasttime > self::LIFE_TIME) return null; // Вышло время сессии - $id = self::$id; - self::$db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время последнего обращения входа - } - return $result; - } -} diff --git a/src/Registry.php b/src/Registry.php deleted file mode 100644 index 5a2d871..0000000 --- a/src/Registry.php +++ /dev/null @@ -1,24 +0,0 @@ - - -/** - * http://www.patternsforphp.com/wiki/Registry - * http://www.patternsforphp.com/wiki/Singleton - * http://www.phppatterns.com/docs/design/the_registry?s=registry - */ - -class Registry extends Settings -{ - static $instance = null; - - /** - */ - static public function getInstance () - { - if (self::$instance == null) { - self::$instance = new Registry(); - } - return self::$instance; - } -} diff --git a/src/Role/User.php b/src/Role/User.php new file mode 100644 index 0000000..18f229b --- /dev/null +++ b/src/Role/User.php @@ -0,0 +1,69 @@ +db = $db; + } + + public function getUserByQuery(Database_Statement $stmt) + { + global $GROUPS; + $result = $stmt->executeQuery(); + if ($result->next()) { + $this->access = $GROUPS[$result->getString('access')]; + $this->name = $result->getString('login'); + $this->id = $result->getInt('id_user'); + $this->password = $result->getString('password'); + $this->fullname = implode(' ', array( + $result->getString('surname'), + $result->getString('firstname'), + $result->getString('patronymic'))); + return $result; + } + return null; + } + + public static function getUserByLogin($login) + { + $stmt = $this->$db->prepareStatement("SELECT * FROM users WHERE login = ?"); + $stmt->setString(1, $login); + $result = $this->getUserByQuery($stmt); + if ($result) { + $time = time(); + $id = $this->id; + $this->$db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время входа + } + return $result; + } + + public static function getUserById($id) + { + $stmt = $this->$db->prepareStatement("SELECT * FROM users WHERE id_user = ?"); + $stmt->setInt(1, $_SESSION ['access']); + $result = $this->getUserByQuery($stmt); + if ($result) { + $lasttime = $result->getInt('lasttime'); + $time = time(); + if ($time - $lasttime > $this->LIFE_TIME) return null; // Вышло время сессии + $id = $this->$id; + $this->db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время последнего обращения входа + } + return $result; + } +} diff --git a/src/Settings.php b/src/Settings.php index 661cbb2..cbbf9fa 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -34,7 +34,7 @@ class Settings extends Collection if ($this->format == 'json') { $settings = json_decode(File::getContents($this->file), true); } else { - include ($this->file); + $settings = include ($this->file); } if (!is_array($settings)) { @@ -165,7 +165,7 @@ class Settings extends Collection $result = json_encode($this->data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); } else { $result = var_export($this->data, true); - $result = ""; + $result = ""; } file_put_contents (($file) ? $file : $this->file, $result); } diff --git a/src/Shortcut.php b/src/Shortcut.php deleted file mode 100644 index 4e24046..0000000 --- a/src/Shortcut.php +++ /dev/null @@ -1,66 +0,0 @@ -list[$prefix] = $path; - } - - /** - * - */ - public function addVar($name, $value) - { - $this->variables['$' . $name] = $value; - } - - /** - * Возвращает путь по имени ярлыка - */ - static function getUrl($prefix, $name = null, $name1 = null) - { - $shortcut = self::getInstance(); - - $names = $shortcut->variables; - if ($name) { - $names['$name'] = $name; - } - if ($name1) { - $names['$name1'] = $name1; - } - - if (isset($shortcut->list[$prefix])) { - return strtr($shortcut->list[$prefix], $names); - } - return null; - } - - static function expand($path) - { - $shortcut = self::getInstance(); - $names = $shortcut->variables; - return strtr($path, $names); - } - -} diff --git a/src/Tales.php b/src/Tales.php new file mode 100644 index 0000000..fb919b6 --- /dev/null +++ b/src/Tales.php @@ -0,0 +1,72 @@ +execute($req); + + echo ""; + return $result; + } + + + static function register() { + /* Регистрация нового префикса для подключения компонента */ + $tales = PHPTAL_TalesRegistry::getInstance(); + $tales->registerPrefix('component', array('Component_Tales', 'component')); + $tales->registerPrefix('date', array('DateTime_Tales', 'date')); + $tales->registerPrefix('time', array('DateTime_Tales', 'time')); + } +} diff --git a/src/config.php b/src/config.php deleted file mode 100644 index 3bbc19a..0000000 --- a/src/config.php +++ /dev/null @@ -1,8 +0,0 @@ -execute($req); - - echo ""; - return $result; -} - - -/* Регистрация нового префикса для подключения компонента */ -$tales = PHPTAL_TalesRegistry::getInstance(); -$tales->registerPrefix('component', array('Component_Tales', 'component')); -$tales->registerPrefix('date', array('DateTime_Tales', 'date')); -$tales->registerPrefix('time', array('DateTime_Tales', 'time')); - From e9f7c239902a2b8320a670bfbbd5f24e2fd0c416 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Tue, 27 Mar 2018 17:31:49 +0300 Subject: [PATCH 003/138] =?UTF-8?q?=D0=9C=D0=BE=D0=B4=D1=83=D0=BB=D0=B8=20?= =?UTF-8?q?c=20namespace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Adapter.php | 2 + src/Arr.php | 2 + src/Collection.php | 2 + src/Controller/Front.php | 4 +- src/Controller/Service.php | 2 +- src/Database.php | 2 +- src/Database/PDOStatement.php | 7 +++- src/Functions.php | 4 +- src/Layout/Manager.php | 4 +- src/Tales.php | 72 +++++++++++++++++++++++++++++++++++ src/tales.php | 71 ---------------------------------- 11 files changed, 92 insertions(+), 80 deletions(-) create mode 100644 src/Tales.php delete mode 100644 src/tales.php diff --git a/src/Adapter.php b/src/Adapter.php index 42bd4ab..5af0d7b 100644 --- a/src/Adapter.php +++ b/src/Adapter.php @@ -1,5 +1,7 @@ shortcut, $name, $name); // ModuleLoader (2) } - $module = $this->loadClass($moduleFile, null, 'Module_'); + $ucname = ucfirst($name); + $moduleClass = "Module\\$ucname\\$ucname"; + $module = new $moduleClass();//$this->loadClass($moduleFile, null, 'Module\\'); if ($module) { // Инициализация модуля $module->viewPath = Shortcut::getUrl('modulepath', $name); diff --git a/src/Controller/Service.php b/src/Controller/Service.php index 64b8a59..43f0802 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -46,7 +46,7 @@ class Controller_Service return $model; } - public function options($key, $val, $res) { + public function options($key, $val, /*.Database_PDOStatement.*/$res) { $result = array(); while($res->next()) { $result[] = array('value' => $res->getInt($key), 'name' => $res->getString($val)); diff --git a/src/Database.php b/src/Database.php index 415619d..2d5e8ad 100644 --- a/src/Database.php +++ b/src/Database.php @@ -1,6 +1,6 @@ -require_once "Database/PDOStatement.php"; +namespace ctiso; /** * Класс оболочка для PDO для замены Creole diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index e74a244..b780ae3 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -1,13 +1,16 @@ addCondition(Functions::rcurry(array($this, 'checkXHR'), $get), $layout); } - public function checkGet($request, $get) + public function checkGet(/*.HttpRequest.*/$request, $get) { if (is_array($get)) { foreach ($get as $key => $value) { @@ -42,7 +42,7 @@ class Layout_Manager extends Filter_Filter return true; } - public function checkXHR($request, $get) + public function checkXHR(/*.HttpRequest.*/$request, $get) { return $request->isAjax() && $this->checkGet($request, $get); } diff --git a/src/Tales.php b/src/Tales.php new file mode 100644 index 0000000..fb919b6 --- /dev/null +++ b/src/Tales.php @@ -0,0 +1,72 @@ +execute($req); + + echo ""; + return $result; + } + + + static function register() { + /* Регистрация нового префикса для подключения компонента */ + $tales = PHPTAL_TalesRegistry::getInstance(); + $tales->registerPrefix('component', array('Component_Tales', 'component')); + $tales->registerPrefix('date', array('DateTime_Tales', 'date')); + $tales->registerPrefix('time', array('DateTime_Tales', 'time')); + } +} diff --git a/src/tales.php b/src/tales.php deleted file mode 100644 index 2c9bc91..0000000 --- a/src/tales.php +++ /dev/null @@ -1,71 +0,0 @@ -execute($req); - - echo ""; - return $result; -} - - -/* Регистрация нового префикса для подключения компонента */ -$tales = PHPTAL_TalesRegistry::getInstance(); -$tales->registerPrefix('component', array('Component_Tales', 'component')); -$tales->registerPrefix('date', array('DateTime_Tales', 'date')); -$tales->registerPrefix('time', array('DateTime_Tales', 'time')); - From 32ec09a66ae5c3c84cb216347712f39ae46e1ca2 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Tue, 27 Mar 2018 17:40:33 +0300 Subject: [PATCH 004/138] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20namespace=20=D0=B8=20=D0=B7=D0=B0=D0=B2=D0=B8=D1=81?= =?UTF-8?q?=D0=B8=D0=BC=D0=BE=D1=81=D1=82=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Adapter.php | 1 + src/Arr.php | 1 + src/Collection.php | 3 ++- src/Connection/HttpRequest.php | 5 ++++- src/Connection/HttpResponse.php | 4 +++- src/Controller/Action.php | 19 +++++++++++++++---- src/Controller/Component.php | 23 ++++++++++++++++++----- src/Controller/Front.php | 10 +++++++++- src/Controller/Installer.php | 13 +++++++++---- src/Controller/Request.php | 4 +++- src/Controller/Service.php | 5 ++++- src/Controller/State.php | 11 +++++++---- src/Database.php | 8 ++++++-- src/Database/IdGenerator.php | 5 ++++- src/Database/JsonInstall.php | 7 +++++-- src/Database/Manager.php | 10 ++++++++-- src/Database/PDOStatement.php | 4 ++++ src/Database/Statement.php | 5 ++++- src/Database/StatementIterator.php | 5 ++++- src/Excel/DataTime.php | 4 +++- src/Excel/Document.php | 6 +++++- src/Excel/Number.php | 4 +++- src/Excel/Table.php | 4 +++- src/File.php | 3 +++ src/Filter/ActionAccess.php | 8 ++++++-- src/Filter/ActionLogger.php | 9 +++++++-- src/Filter/Authorization.php | 4 +++- src/Filter/Filter.php | 5 ++++- src/Filter/Login.php | 20 ++++++++++++++------ src/Filter/UserAccess.php | 8 ++++++-- src/Form/Color.php | 5 ++++- src/Form/Date.php | 5 ++++- src/Form/Field.php | 4 +++- src/Form/Form.php | 26 +++++++++++++++++--------- src/Form/Input.php | 5 ++++- src/Form/OptionFactory.php | 17 +++++++++++------ src/Form/Select.php | 5 ++++- src/Form/SelectMany.php | 5 ++++- src/Form/SelectOne.php | 5 ++++- src/Form/TextArea.php | 5 ++++- src/Form/ViewState.php | 4 +++- src/Functions.php | 18 ++++++++++-------- src/HttpRequest.php | 5 +++++ src/Layout/Empty.php | 6 +++++- src/Layout/Manager.php | 13 +++++++++---- src/Mail.php | 4 ++++ src/MailAlt.php | 3 +++ src/Model/Factory.php | 5 ++++- src/Numbers.php | 2 ++ src/Path.php | 2 ++ src/Primitive.php | 2 ++ src/Registry.php | 3 +++ src/Security.php | 2 ++ src/Session.php | 2 ++ src/Settings.php | 5 +++++ src/Setup.php | 8 ++++++-- src/Shortcut.php | 2 ++ src/SortRecord.php | 2 ++ src/Tales.php | 11 +++++++++-- src/Tools/Drawing.php | 4 +++- src/Tools/Image.php | 4 +++- src/Tools/SQLStatementExtractor.php | 5 ++++- src/Tools/String.php | 4 +++- src/Tools/TemplateImage.php | 19 +++++++++++-------- src/UTF8.php | 2 ++ src/UserMessageException.php | 3 +++ src/Validator/Rule/Abstract.php | 5 ++++- src/Validator/Rule/Alpha.php | 6 +++++- src/Validator/Rule/Code.php | 6 +++++- src/Validator/Rule/Count.php | 6 +++++- src/Validator/Rule/Date.php | 6 +++++- src/Validator/Rule/Email.php | 6 +++++- src/Validator/Rule/EmailList.php | 6 +++++- src/Validator/Rule/FileName.php | 7 ++++++- src/Validator/Rule/IsFile.php | 6 +++++- src/Validator/Rule/Match.php | 6 +++++- src/Validator/Rule/Notnull.php | 6 +++++- src/Validator/Rule/Numeric.php | 6 +++++- src/Validator/Rule/Time.php | 6 +++++- src/Validator/Rule/Unique.php | 6 +++++- src/Validator/Validator.php | 6 +++++- src/View/Composite.php | 6 +++++- src/View/List.php | 5 ++++- src/View/Page.php | 12 +++++++++--- src/View/Pages.php | 4 +++- src/View/Plain.php | 4 +++- src/View/Top.php | 5 ++++- src/View/View.php | 5 ++++- src/ZipFile.php | 3 +++ src/config.php | 3 +++ src/process.php | 2 ++ src/tabletree.php | 3 +++ 92 files changed, 454 insertions(+), 128 deletions(-) diff --git a/src/Adapter.php b/src/Adapter.php index 5af0d7b..2ba68f9 100644 --- a/src/Adapter.php +++ b/src/Adapter.php @@ -1,5 +1,6 @@ viewPath, 'help', $name . '.suggest'); @@ -141,7 +152,7 @@ class Controller_Action public function getModel($name) { if (!$this->factory) { - $this->factory = new Model_Factory($this->db, $this->_registry); + $this->factory = new Factory($this->db, $this->_registry); } return $this->factory->getModel($name); } @@ -364,7 +375,7 @@ class Controller_Action function _getActionPath() { - return new Controller_State('index'); + return new State('index'); } // Тоже убрать в метод Controller_Model diff --git a/src/Controller/Component.php b/src/Controller/Component.php index dce2076..830cd59 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -1,5 +1,18 @@ db, $this->registry); + $form = new Form(); + $options = new OptionFactory($this->db, $this->registry); $settings = $this->getInfo(); $form->addFieldList($settings['parameter'], $options); @@ -301,7 +314,7 @@ class Controller_Component $editor = $component->getEditUrl(); if ($editor) { if(class_exists("Controller_Site")) { //Если мы в CMS2 - $instance = Controller_Site::getInstance(); + $instance = Site::getInstance(); $instance->componentsConfig[] = $editor; } else { global $componentsConfig; @@ -356,7 +369,7 @@ class Controller_Component */ function addRequireJsPath($name, $path, $shim = null) { - Controller_Site::addRequireJsPath($name, $path, $shim); + Site::addRequireJsPath($name, $path, $shim); } function actionIndex(/*.ComponentRequest.*/ $request) { diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 8c4ee74..7d805a8 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -4,7 +4,15 @@ * Первичный контроллер контроллер страниц * @package system.controller */ -class Controller_Front extends Controller_Action +namespace ctiso\Controller; +use ctiso\Controller\Action, + ctiso\Settings, + ctiso\Database, + ctiso\Collection, + ctiso\Shortcut, + ctiso\HttpRequest; + +class Front extends Action { /** @var Shortcut */ diff --git a/src/Controller/Installer.php b/src/Controller/Installer.php index d20a93d..a5a55fa 100644 --- a/src/Controller/Installer.php +++ b/src/Controller/Installer.php @@ -1,6 +1,11 @@ db_manager); + $json_installer = new JsonInstall($this->db_manager); foreach ($sql as $version => $install) { if (version_compare($version, $version_new, "<=") && version_compare($version, $version_old, ">")) { $file = Path::join(call_user_func($this->installPath, $name), "sql", $install); @@ -58,7 +63,7 @@ class Controller_Installer function uninstall($name){ $uninstall = $this->getUninstallFile($name); if (file_exists($uninstall)) { - $json_installer = new Database_JsonInstall($this->db_manager); + $json_installer = new JsonInstall($this->db_manager); $json_installer->install($uninstall,null); } $this->_registry->removeKey($name); @@ -108,7 +113,7 @@ class Controller_Installer } function install($dbinit_path, $dbfill_path = null) { - $json_installer = new Database_JsonInstall($this->db_manager); + $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 1ac7be4..50a3039 100644 --- a/src/Controller/Request.php +++ b/src/Controller/Request.php @@ -1,6 +1,8 @@ states [$state->getAction()] = $state; return $this; @@ -49,7 +52,7 @@ class Controller_State return false; } - function makeTitle(Controller_Action $module) + function makeTitle(Action $module) { foreach ($this->titles as $item) { $module->path->addMenuItem($module->nUrl($this->action, $item[1]), $item[0]); diff --git a/src/Database.php b/src/Database.php index 2d5e8ad..f3d0800 100644 --- a/src/Database.php +++ b/src/Database.php @@ -1,6 +1,10 @@ + namespace ctiso; +use PDO, + ctiso\Database\Statement, + ctiso\Database\IdGenerator; /** * Класс оболочка для PDO для замены Creole @@ -64,7 +68,7 @@ class Database extends PDO public function prepareStatement($query) { - return new Database_Statement($query, $this); + return new Statement($query, $this); } // Для совместимости со старым представлением баз данных CIS @@ -161,7 +165,7 @@ class Database extends PDO } function getIdGenerator() { - return new Database_IdGenerator($this); + return new IdGenerator($this); } /** diff --git a/src/Database/IdGenerator.php b/src/Database/IdGenerator.php index 41ee235..5ae4664 100644 --- a/src/Database/IdGenerator.php +++ b/src/Database/IdGenerator.php @@ -1,6 +1,9 @@ db_manager = $db_manager; } diff --git a/src/Database/Manager.php b/src/Database/Manager.php index ec354c7..a0e46a5 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -1,6 +1,12 @@ db->executeQuery($stmt); } diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index b780ae3..c284683 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -1,6 +1,10 @@ access[$action]) || in_array(Filter_UserAccess::$access, $this->access[$action])); + return (!isset($this->access[$action]) || in_array(UserAccess::$access, $this->access[$action])); } function execute(HttpRequest $request) { diff --git a/src/Filter/ActionLogger.php b/src/Filter/ActionLogger.php index a71d5f5..b6da23c 100644 --- a/src/Filter/ActionLogger.php +++ b/src/Filter/ActionLogger.php @@ -1,6 +1,11 @@ getAction(); if(in_array($action, $this->before)) { - fwrite($this->file, "time: " . date("r", time()) . " query: ". json_encode(array_merge($_POST, $_GET)) . " by: " . Filter_UserAccess::$name . "\n"); + fwrite($this->file, "time: " . date("r", time()) . " query: ". json_encode(array_merge($_POST, $_GET)) . " by: " . UserAccess::$name . "\n"); } return $this->processor->execute($request); } diff --git a/src/Filter/Authorization.php b/src/Filter/Authorization.php index 5afd556..56ebc4d 100644 --- a/src/Filter/Authorization.php +++ b/src/Filter/Authorization.php @@ -1,6 +1,8 @@ getConnection(); - Filter_UserAccess::setUp($db); // Соединение + UserAccess::setUp($db); // Соединение switch ($request->getAction()) { // Авторизация по постоянному паролю case 'login': $login = $request->get('login'); $password = $request->get('password'); - $result = Filter_UserAccess::getUserByLogin($login); // Поиск по логину + $result = UserAccess::getUserByLogin($login); // Поиск по логину if ($result) { $userPassword = $result->getString('password'); - if (Filter_UserAccess::$access == 'site_root' && defined('PARENT_PATH')) { + if (UserAccess::$access == 'site_root' && defined('PARENT_PATH')) { $s = new Settings(PARENT_PATH . '/settings.json'); $s->read(); $dsn = $s->readKey(array('system', 'dsn')); @@ -63,7 +71,7 @@ class Filter_Login extends Filter_Filter case 'enter': $login = $request->get('login'); $password = $request->get('sid'); - $result = Filter_UserAccess::getUserByLogin($login); // Поиск по логину + $result = UserAccess::getUserByLogin($login); // Поиск по логину if ($result) { $temp = md5($result->getString('password') . $result->getString('login') . $result->getString('sid')); if ($password == $temp) { @@ -77,7 +85,7 @@ class Filter_Login extends Filter_Filter // Если $hash не совпадает $_SESSION['hash'] то удаляем сессию if (isset($_SESSION ['access']) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { if ($hash == $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME]) { - $this->user = $user = Filter_UserAccess::getUserById($_SESSION['access']); // Поиск по идентификатору + $this->user = $user = UserAccess::getUserById($_SESSION['access']); // Поиск по идентификатору if ($user && isset($_SESSION['random']) && ($user->get('sid') == $_SESSION['random'])) { return true; } diff --git a/src/Filter/UserAccess.php b/src/Filter/UserAccess.php index ce27a66..509b9b6 100644 --- a/src/Filter/UserAccess.php +++ b/src/Filter/UserAccess.php @@ -1,7 +1,11 @@ executeQuery(); diff --git a/src/Form/Color.php b/src/Form/Color.php index c7c0d2d..17a9caf 100644 --- a/src/Form/Color.php +++ b/src/Form/Color.php @@ -3,6 +3,9 @@ /** * Поле с цветом */ -class Form_Color extends Form_Field +namespace ctiso\Form; +use ctiso\Form\Field; + +class Color extends Field { } \ No newline at end of file diff --git a/src/Form/Date.php b/src/Form/Date.php index 42f8b00..3b1c526 100644 --- a/src/Form/Date.php +++ b/src/Form/Date.php @@ -2,5 +2,8 @@ /** * Поле с датой */ -class Form_Date extends Form_Field { +namespace ctiso\Form; +use ctiso\Form\Field; + +class Date extends Field { } \ No newline at end of file diff --git a/src/Form/Field.php b/src/Form/Field.php index bb756cb..1e1dd47 100644 --- a/src/Form/Field.php +++ b/src/Form/Field.php @@ -2,7 +2,9 @@ /** * Элемент формы */ -class Form_Field +namespace ctiso\Form; + +class Field { public $hidden = false; public $name; diff --git a/src/Form/Form.php b/src/Form/Form.php index 47a1854..02e6e7e 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -4,7 +4,15 @@ * При рендеринге каждому классу соответствует шаблон (см. themes/maxim/templates/macros.html) */ -class TCheckbox extends Form_Field +namespace ctiso\Form; +use ctiso\Form\Field, + ctiso\Form\Select, + ctiso\Form\Input, + ctiso\View\View, + ctiso\Validator\Validator, + ctiso\HttpRequest; + +class TCheckbox extends Field { public $checked = false; function setValue($value) @@ -14,7 +22,7 @@ class TCheckbox extends Form_Field } } -class TQuestionType extends Form_Select +class TQuestionType extends Select { function setValue($value) { @@ -26,29 +34,29 @@ class TQuestionType extends Form_Select } } -class TDateTime extends Form_Input { +class TDateTime extends Input { } /** * Поле для ввода пароля */ -class TSecret extends Form_Field { +class TSecret extends Field { } -class TUpload extends Form_Field { +class TUpload extends Field { } -class THidden extends Form_Input { +class THidden extends Input { public $hidden = true; } -class TComponentBrowserInput extends Form_Input { +class TComponentBrowserInput extends Input { } /** * Форма для ввода */ -class Form_Form extends View_View { +class Form extends View { public $field = array(); //Поля формы public $fieldsets = array(); //Группы полей (fieldset). Некоторые поля могут не принадлежать никаким группам @@ -163,7 +171,7 @@ class Form_Form extends View_View { /** * Устанавливает ошибки после проверки */ - function setError(Validator_Validator $validator) + function setError(Validator $validator) { foreach ($validator->getErrorMsg() as $name => $error) { diff --git a/src/Form/Input.php b/src/Form/Input.php index 855bec2..b2d4e68 100644 --- a/src/Form/Input.php +++ b/src/Form/Input.php @@ -3,5 +3,8 @@ /** * Поле ввода Input */ -class Form_Input extends Form_Field { +namespace ctiso\Form; +use ctiso\Form\Field; + +class Input extends Field { } \ No newline at end of file diff --git a/src/Form/OptionFactory.php b/src/Form/OptionFactory.php index 41a8447..70904bb 100644 --- a/src/Form/OptionFactory.php +++ b/src/Form/OptionFactory.php @@ -1,6 +1,11 @@ registry = $registry; } - function create(Form_Select $field, $input) { + function create(Select $field, $input) { if (isset($input['options.resid'])) { $type = $input['options.resid']; - $res = new Model_Resources($this->db); + $res = new Resources($this->db); $field->options = $this->optionsArray('id_section', 'title', $res->getSubsections('', $type)); } else if (isset($input['options.res'])) { $type = $input['options.res']; - $res = new Model_Resources($this->db); + $res = new Resources($this->db); $field->options = $this->optionsArray('path', 'title', $res->getSubsections('', $type)); } else if (isset($input['options.all_res'])) { $type = $input['options.all_res']; - $res = new Model_Resources($this->db); + $res = new Resources($this->db); $field->options = $this->optionsArray('id_resource', 'subtitle', $res->getAllResource($type)); } else if (isset($input['options.db'])) { @@ -39,7 +44,7 @@ class Form_OptionFactory { } elseif (isset($input['options.pair'])) { $field->options = $this->optionsPair($input['options.pair']); } elseif (isset($input['options.model'])) { - $factory = new Model_Factory($this->db, $this->registry); + $factory = new Factory($this->db, $this->registry); $model = $factory->getModel($input['options.model']); $field->options = $model->getAllAsOptions(); } else { diff --git a/src/Form/Select.php b/src/Form/Select.php index 6a3f7a1..3a4ec2c 100644 --- a/src/Form/Select.php +++ b/src/Form/Select.php @@ -1,6 +1,9 @@ value = $value; diff --git a/src/Form/ViewState.php b/src/Form/ViewState.php index 777618b..c9c6831 100644 --- a/src/Form/ViewState.php +++ b/src/Form/ViewState.php @@ -4,7 +4,9 @@ * http://www.alternateinterior.com/2006/09/a-viewstate-for-php.html * Управление состоянием между страницами */ -class Form_ViewState // extends Collection +namespace ctiso\Form; + +class ViewState // extends Collection { private $values = array(); diff --git a/src/Functions.php b/src/Functions.php index 63c131e..fc1d5a8 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -8,7 +8,9 @@ /** * Эмуляция каррированой функции */ -class __right { +namespace ctiso; + +class right { protected $params; protected $fn; @@ -24,7 +26,7 @@ class __right { } } -class __left { +class left { protected $params; protected $fn; @@ -41,7 +43,7 @@ class __left { } define('__', '_ARGUMENT_PLACE_'); -class __partial { +class partial { protected $params; protected $fn; @@ -69,7 +71,7 @@ class __partial { /** * Композиция функций */ -class __compose { +class compose { protected $fns; function __construct($list) { $this->fns = array_reverse($list); @@ -89,7 +91,7 @@ class __compose { class Functions { static function partial($_rest) { - $closure = new __partial(func_get_args()); + $closure = new partial(func_get_args()); return array($closure, 'apply'); } @@ -102,7 +104,7 @@ class Functions { * @return array[int]mixed */ static function compose($_rest) { - $closure = new __compose(func_get_args()); + $closure = new compose(func_get_args()); return array($closure, 'apply'); } @@ -112,7 +114,7 @@ class Functions { * @return array[int]mixed */ static function rcurry($_rest) { - $closure = new __right(func_get_args ()); + $closure = new right(func_get_args ()); return array($closure, 'apply'); } @@ -122,7 +124,7 @@ class Functions { * @return array[int]mixed */ static function lcurry($_rest) { - $closure = new __left(func_get_args ()); + $closure = new left(func_get_args ()); return array($closure, 'apply'); } diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 7693177..21efe01 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -3,6 +3,11 @@ /** * Неверный запрос */ +namespace ctiso; +use Exception, + ctiso\Collection, + ctiso\Session; + class WrongRequestException extends Exception { } diff --git a/src/Layout/Empty.php b/src/Layout/Empty.php index a7f99b8..202f0d2 100644 --- a/src/Layout/Empty.php +++ b/src/Layout/Empty.php @@ -3,7 +3,11 @@ /** * Самый простой макет */ -class Layout_Empty extends Filter_Filter +namespace ctiso\Layout; +use ctiso\Filter\Filter, + ctiso\HttpRequest; + +class Empty extends Filter { function execute(HttpRequest $request) { diff --git a/src/Layout/Manager.php b/src/Layout/Manager.php index 33b934a..63ccb0a 100644 --- a/src/Layout/Manager.php +++ b/src/Layout/Manager.php @@ -4,7 +4,12 @@ * Выбор макета страницы. * Выбор оформления страницы осуществляется если было совпадение с каким либо условием */ -class Layout_Manager extends Filter_Filter +namespace ctiso\Layout; +use ctiso\Filter\Filter, + ctiso\Functions, + ctiso\HttpRequest; + +class Manager extends Filter { // Массив условий с их макетами protected $condition = array(); @@ -17,7 +22,7 @@ class Layout_Manager extends Filter_Filter * addConditionGet(array('module' => 'personal'), 'personal') * addConditionGet(array('module' => 'login'), 'login') */ - public function addConditionGet($get, Filter_Filter $layout) + public function addConditionGet($get, Filter $layout) { $this->addCondition(Functions::rcurry(array($this, 'checkGet'), $get), $layout); } @@ -25,7 +30,7 @@ class Layout_Manager extends Filter_Filter /** * Условие для аякс запросов. Тоже самое что и addConditionGet но еще проверяется является ли запрос ajax */ - public function addConditionXHR($get, Filter_Filter $layout) + public function addConditionXHR($get, Filter $layout) { $this->addCondition(Functions::rcurry(array($this, 'checkXHR'), $get), $layout); } @@ -52,7 +57,7 @@ class Layout_Manager extends Filter_Filter * @parma $get function(HttpRequest) Функция * @parma $layout Layout Макет */ - public function addCondition($get, Filter_Filter $layout) + public function addCondition($get, Filter $layout) { $this->condition [] = array($get, $layout); } diff --git a/src/Mail.php b/src/Mail.php index 1f4eda4..20cdb7c 100644 --- a/src/Mail.php +++ b/src/Mail.php @@ -4,6 +4,10 @@ * Класс для работы с почтой * http://en.wikipedia.org/wiki/MIME */ +namespace ctiso; +use ctiso\Path, + Exception; + class Mail { public $_from; diff --git a/src/MailAlt.php b/src/MailAlt.php index 99b296d..138ae94 100644 --- a/src/MailAlt.php +++ b/src/MailAlt.php @@ -1,5 +1,8 @@ executeActions('install'); * */ +namespace ctiso; +use ZipArchive, + ctiso\Tools\SQLStatementExtractor; + class Setup { protected $actions = array(); @@ -198,7 +202,7 @@ class Setup */ function batchSQLZip(/*.Database.*/ $conn, $file) { - $stmtList = Tools_SQLStatementExtractor::extract($this->zip->getFromName($file)); + $stmtList = SQLStatementExtractor::extract($this->zip->getFromName($file)); foreach ($stmtList as $stmt) { $conn->executeQuery ($stmt); } @@ -206,7 +210,7 @@ class Setup static function batchSQL(/*.Database.*/ $conn, $file) { - $stmtList = Tools_SQLStatementExtractor::extractFile($file); + $stmtList = SQLStatementExtractor::extractFile($file); foreach ($stmtList as $stmt) { $conn->executeQuery ($stmt); } diff --git a/src/Shortcut.php b/src/Shortcut.php index 4e24046..09da63f 100644 --- a/src/Shortcut.php +++ b/src/Shortcut.php @@ -3,6 +3,8 @@ /** * Класс для короткого доступа к файлам / папкам */ +namespace ctiso; + class Shortcut { static $instance = null; diff --git a/src/SortRecord.php b/src/SortRecord.php index 24c054b..030bb52 100644 --- a/src/SortRecord.php +++ b/src/SortRecord.php @@ -1,5 +1,7 @@ 'jpeg', 'gif' => 'gif', 'png' => 'png', 'bmp' => 'wbmp'); static $listfonts = array( @@ -129,22 +132,22 @@ class Tools_TemplateImage $color = intval(substr($value->color, 1), 16); if ($value->align[0]) { - $align = Tools_Drawing::ALIGN_LEFT; + $align = Drawing::ALIGN_LEFT; } elseif ($value->align[2]) { - $align = Tools_Drawing::ALIGN_RIGHT; + $align = Drawing::ALIGN_RIGHT; } else { - $align = Tools_Drawing::ALIGN_CENTER; + $align = Drawing::ALIGN_CENTER; } if ($value->valign[0]) { - $valign = Tools_Drawing::ALIGN_TOP; + $valign = Drawing::ALIGN_TOP; } elseif ($value->valign[1]) { - $valign = Tools_Drawing::ALIGN_CENTER; + $valign = Drawing::ALIGN_CENTER; } else { - $valign = Tools_Drawing::ALIGN_BOTTOM; + $valign = Drawing::ALIGN_BOTTOM; } - Tools_Drawing::imagettftextbox($this->image, $size, 0, $value->left, $value->top, $color, $fontfile, $text, + Drawing::imagettftextbox($this->image, $size, 0, $value->left, $value->top, $color, $fontfile, $text, $value->width, $value->height, $align, $valign); } diff --git a/src/UTF8.php b/src/UTF8.php index 3cc68b8..fe97742 100644 --- a/src/UTF8.php +++ b/src/UTF8.php @@ -1,5 +1,7 @@ Date: Tue, 27 Mar 2018 18:10:46 +0300 Subject: [PATCH 005/138] =?UTF-8?q?=D0=9D=D0=B0=D1=81=D1=82=D1=80=D0=BE?= =?UTF-8?q?=D0=B9=D0=BA=D0=B0=20=D0=B4=D0=BB=D1=8F=20composer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- composer.json | 4 ++-- src/Controller/Front.php | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index de9a023..4c325c2 100644 --- a/composer.json +++ b/composer.json @@ -8,8 +8,8 @@ } ], "autoload": { - "psr-0": { - "": "src/" + "psr-4": { + "ctiso\\": "src/" } } } diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 7d805a8..9b5e718 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -111,11 +111,12 @@ class Front extends Action } else { $controller = null; } + try{ return $this->loadModule($name[0], $request, $controller); } catch (UserMessageException $ex) { //Исключение с понятным пользователю сообщением $mode = $request->get('mode'); - if($mode == 'ajax' || $mode == 'json'){ + if ($mode == 'ajax' || $mode == 'json') { return json_encode(['result'=>'fail', 'message'=> $ex->userMessage]); } else { return $ex->userMessage; From f0414885543232bf0f4e80fc5eb286f79f5cd9ae Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Wed, 28 Mar 2018 12:43:06 +0300 Subject: [PATCH 006/138] =?UTF-8?q?=D0=98=D0=B7=D0=B1=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D1=8F=D0=B5=D0=BC=D1=81=D1=8F=20=D0=BE=D1=82=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=BD=D1=81=D1=82=D0=B0=D0=BD=D1=82=20=D0=B8=20=D0=B3=D0=BB?= =?UTF-8?q?=D0=BE=D0=B1=D0=B0=D0=BB=D1=8C=D0=BD=D1=8B=D1=85=20=D0=BF=D0=B5?= =?UTF-8?q?=D1=80=D0=B5=D0=BC=D0=B5=D0=BD=D0=BD=D1=8B=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 21 +++++++++++++-------- src/Controller/Front.php | 23 ++++++++++++----------- src/Database.php | 2 +- src/Database/PDOStatement.php | 6 ++---- src/Filter/ActionLogger.php | 12 ++++++------ src/Filter/Filter.php | 2 +- src/Filter/Login.php | 2 +- src/HttpRequest.php | 1 + src/Layout/{Empty.php => Blank.php} | 2 +- src/Layout/Manager.php | 1 + 10 files changed, 39 insertions(+), 33 deletions(-) rename src/Layout/{Empty.php => Blank.php} (90%) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 300eb99..d833f55 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -52,7 +52,6 @@ class Action public $param = array(); // Параметры для ссылки public /*.Registry.*/$_registry; // Ссылка на реестр - public $_shortcut; public $modulePrefix = ''; public $iconPath = ''; @@ -69,10 +68,12 @@ class Action } public function loadConfig($name) { - $filename = Shortcut::getUrl('config', $name); + $basePath = $this->settings['base']; + + $filename = Path::join($basePath, 'modules', $name); $settings = []; if (file_exists($filename)) { - include($filename); + $settings = include($filename); } else { throw new Exception('Невозможно загрузить файл настроек ' . $name); } @@ -86,7 +87,8 @@ class Action public function installPath($name) { - return Path::join(CMS_PATH, "modules", $name); + $basePath = $this->settings['base']; + return Path::join($basePath, "modules", $name); } public function addSuggest(View $view, $name) @@ -110,13 +112,16 @@ class Action * @param $viewClass String * @return View_Composite */ - public function getView($name, $viewClass = 'View_Composite') + public function getView($name, $viewClass = 'ctiso\\View\\Composite') { $file = $name . self::TEMPLATE_EXTENSION; + $basePath = $this->settings['base']; + $webPath = $this->settings['web']; + $list = array( - Path::join($this->viewPath, TEMPLATES, $this->viewPathPrefix) => Path::join(WWW_PATH, "modules", $this->name, TEMPLATES, $this->viewPathPrefix), - Path::join(CMS_PATH, "templates") => Path::join(WWW_PATH, "templates") + Path::join($this->viewPath, 'templates', $this->viewPathPrefix) => Path::join($webPath, "modules", $this->name, 'templates', $this->viewPathPrefix), + Path::join($basePath, "templates") => Path::join($webPath, "templates") ); // Поиск файла для шаблона @@ -127,7 +132,7 @@ class Action /*.View_Composite.*/$tpl = new $viewClass($template); - $assets = Path::join(enableHttps(WWW_PATH), "assets", "css"); + $assets = Path::join($webPath, "assets", "css"); $tpl->set('icons', $this->iconPath); // Путь к файлам текущей темы $tpl->set('media', $this->themePath); // Путь к файлам текущей темы $tpl->set('assets', $assets); diff --git a/src/Controller/Front.php b/src/Controller/Front.php index f2ff867..5453892 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -11,28 +11,26 @@ use ctiso\Controller\Action, ctiso\Collection, ctiso\Filter\ActionAccess, ctiso\Filter\ActionLogger, - ctiso\Path; + ctiso\Path, ctiso\UserMessageException, ctiso\HttpRequest; class Front extends Action { - /** @var Shortcut */ - protected $shortcut; // Ярлык к модулю protected $_param; // Параметр по которому выбирается модуль protected $default; // Значение параметра по умолчанию protected $modules = array(); /** - * @param Settings $_registry - * @param Shortcut $_shortcut + * @param Settings $settings */ - public function __construct($db, $settings, $default) { + public function __construct($db, $settings, $user, $default) { parent::__construct(); $this->settings = $settings; $this->db = $db; + $this->user = $user; $this->default = $default; } @@ -52,23 +50,26 @@ class Front extends Action $module = $this->modules[$name]; return $module->access->execute($request); } + + $system = $this->settings['system']; - $basePath = $this->settings['system']->readKey(['path', 'modules']); - $moduleFile = Path::join($basePath, $name, 'classes', $controller ? $controller : $name); + $moulesPath = $system->readKey(['path', 'modules']); + $logPath = Path::join($this->settings['site'], $system->readKey(['path', 'access.log'])); + $moduleFile = Path::join($this->settings['base'], $moulesPath, $name, 'classes', $controller ? $controller : $name); $ucname = ucfirst($name); - $moduleClass = "Module\\$ucname\\$ucname"; + $moduleClass = "Modules\\$ucname\\$ucname"; $module = new $moduleClass(); if ($module) { // Инициализация модуля - $modPath = Path::join($basePath, $name); + $modPath = Path::join($moulesPath, $name); $module->viewPath = $modPath; $module->name = $name; // $module->settings = $this->settings; $module->db = $this->db; // Ведение лога - $logger = new ActionLogger($module); + $logger = new ActionLogger($module, $logPath, $this->user); $logger->before = $this->loadSettings(Path::join($modPath, 'filter', 'logger.php')); // Управление доступом $module->access = new ActionAccess($logger); diff --git a/src/Database.php b/src/Database.php index f3d0800..cd196f8 100644 --- a/src/Database.php +++ b/src/Database.php @@ -17,7 +17,7 @@ class Database extends PDO { parent::__construct($dsn, $username, $password); $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('Database_PDOStatement', array())); + $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('ctiso\\Database\\PDOStatement', array())); } public function getDSN() diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index c284683..48e591a 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -1,11 +1,9 @@ processor = $processor; - $this->file = fopen(Shortcut::getUrl('access.log'), "a"); + $this->user = $user; + $this->file = fopen($logPath, "a"); } function execute(HttpRequest $request) { $action = $request->getAction(); if(in_array($action, $this->before)) { - fwrite($this->file, "time: " . date("r", time()) . " query: ". json_encode(array_merge($_POST, $_GET)) . " by: " . UserAccess::$name . "\n"); + fwrite($this->file, "time: " . date("r", time()) . " query: ". json_encode(array_merge($_POST, $_GET)) . " by: " . $this->user->name . "\n"); } return $this->processor->execute($request); } diff --git a/src/Filter/Filter.php b/src/Filter/Filter.php index 233a9f3..b61b5c8 100644 --- a/src/Filter/Filter.php +++ b/src/Filter/Filter.php @@ -19,7 +19,7 @@ class Filter return $this->processor->execute($request); } - public function getView($name, $class = 'View_Top') + public function getView($name, $class = 'ctiso\\View\\Top') { return $this->processor->getView($name, $class); } diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 92f0b47..6e5f242 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -74,7 +74,7 @@ class Login extends Filter // Если $hash не совпадает $_SESSION['hash'] то удаляем сессию if (isset($_SESSION ['access']) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { if ($hash == $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME]) { - $this->user = $user = $role->getUserById($_SESSION['access']); // Поиск по идентификатору + $this->user = $user = $this->role->getUserById($_SESSION['access']); // Поиск по идентификатору if ($user && isset($_SESSION['random']) && ($user->get('sid') == $_SESSION['random'])) { return true; } diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 21efe01..f88fb0c 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -5,6 +5,7 @@ */ namespace ctiso; use Exception, + ArrayAccess, ctiso\Collection, ctiso\Session; diff --git a/src/Layout/Empty.php b/src/Layout/Blank.php similarity index 90% rename from src/Layout/Empty.php rename to src/Layout/Blank.php index 202f0d2..f731df3 100644 --- a/src/Layout/Empty.php +++ b/src/Layout/Blank.php @@ -7,7 +7,7 @@ namespace ctiso\Layout; use ctiso\Filter\Filter, ctiso\HttpRequest; -class Empty extends Filter +class Blank extends Filter { function execute(HttpRequest $request) { diff --git a/src/Layout/Manager.php b/src/Layout/Manager.php index 63ccb0a..884fb3b 100644 --- a/src/Layout/Manager.php +++ b/src/Layout/Manager.php @@ -67,6 +67,7 @@ class Manager extends Filter */ public function execute(HttpRequest $request) { +// print_r($request->get('mode')); foreach ($this->condition as $condition) { if (call_user_func($condition[0], $request)) { $layout = $condition[1]; From 0b66a724846f85fd10c73d5a07e0563b1f8da8c1 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Wed, 28 Mar 2018 17:02:20 +0300 Subject: [PATCH 007/138] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BD=D0=B0=D0=B7=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5?= =?UTF-8?q?=20=D0=BA=D0=BB=D0=B0=D1=81=D1=81=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Database.php | 19 +++++++++++-------- src/Role/User.php | 6 ++++-- src/Tales.php | 9 +++++---- 3 files changed, 20 insertions(+), 14 deletions(-) diff --git a/src/Database.php b/src/Database.php index cd196f8..0a8e103 100644 --- a/src/Database.php +++ b/src/Database.php @@ -1,7 +1,15 @@ -namespace ctiso; +namespace { + if(!function_exists('sqliteLower')){ + function sqliteLower($str) { + return mb_strtolower($str, 'UTF-8'); + } + } +} + +namespace ctiso { use PDO, ctiso\Database\Statement, ctiso\Database\IdGenerator; @@ -45,13 +53,7 @@ class Database extends PDO $connection->setAttribute(PDO::ATTR_TIMEOUT, 5); $mode = defined('SQLITE_JOURNAL_MODE') ? SQLITE_JOURNAL_MODE : 'WAL'; $connection->query("PRAGMA journal_mode=$mode"); - - if(!function_exists('sqliteLower')){ - function sqliteLower($str) { - return mb_strtolower($str, 'UTF-8'); - } - $connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1); - } + $connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1); } $connection->dsn = $dsn; return $connection; @@ -183,3 +185,4 @@ class Database extends PDO return null; } } +} \ No newline at end of file diff --git a/src/Role/User.php b/src/Role/User.php index 53dd441..d287543 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -1,6 +1,6 @@ db = $db; + $this->groups = $groups; } public function setDB(Database $db) { diff --git a/src/Tales.php b/src/Tales.php index 32b0533..c3f2155 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -8,9 +8,10 @@ use PHPTAL_Php_TalesInternal, ctiso\Controller\Site, ctiso\Controller\Component, ctiso\HttpRequest, + PHPTAL_Tales, PHPTAL_TalesRegistry; -class Tales_DateTime_ implements PHPTAL_Tales +class Tales_DateTime implements PHPTAL_Tales { static public function date($expression, $nothrow = false) { return "ctiso\\Tales::phptal_date(".PHPTAL_Php_TalesInternal::path ($expression).")"; @@ -68,8 +69,8 @@ class Tales { /* Регистрация нового префикса для подключения компонента */ $tales = PHPTAL_TalesRegistry::getInstance(); - $tales->registerPrefix('component', array('ctiso\\Component_Tales', 'component')); - $tales->registerPrefix('date', array('ctiso\\DateTime_Tales', 'date')); - $tales->registerPrefix('time', array('ctiso\\DateTime_Tales', 'time')); + $tales->registerPrefix('component', array('ctiso\\Tales_Component', 'component')); + $tales->registerPrefix('date', array('ctiso\\Tales_DateTime', 'date')); + $tales->registerPrefix('time', array('ctiso\\Tales_DateTime', 'time')); } } From bef71657770712200f364775aab62f083efdfc9f Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Wed, 28 Mar 2018 19:06:30 +0300 Subject: [PATCH 008/138] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=B8=D0=BD=D0=B8=D1=86=D0=B8=D0=B0=D0=BB=D0=B8?= =?UTF-8?q?=D0=B7=D0=B0=D1=86=D0=B8=D1=8E=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB?= =?UTF-8?q?=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 43 ++++++++++++++++++++------------------- src/Controller/Front.php | 7 ++++--- src/Filter/Login.php | 1 - src/Role/User.php | 21 ++++++++++++------- 4 files changed, 40 insertions(+), 32 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index d833f55..e549f9a 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -28,15 +28,14 @@ class Action const TEMPLATE_EXTENSION = ".html"; // Расширение для шаблонов const ACTION_PREFIX = "action"; // Префикс для функций действий - public $jsPath; // Глобальный путь к скриптам - public $themePath; // Глобальный путь к текущей теме - // Параметры устанавливаются при создании контроллера public $name = ''; // Имя модуля - public $viewPath = null; // Путь к шаблонам контроллера - public $viewPathPrefix = null; // Путь к шаблонам контроллера - public $moduleTitle = ""; + public $modulePath = null; // Путь к модулю + public $moduleTitle = ''; + public $modulePrefix = ''; + + public $viewPathPrefix = null; // Путь к шаблонам контроллера /** * Соединение с базой данных @@ -49,11 +48,10 @@ class Action private $factory = null; // Ссылка на обьект создания модели private $helpers = array(); // Помошники для действий - public $param = array(); // Параметры для ссылки + public $param = array(); // Параметры для ссылки - public /*.Registry.*/$_registry; // Ссылка на реестр - public $modulePrefix = ''; - public $iconPath = ''; + public /*.Settings.*/$settings; // Ссылка на настройки + public $user; // Обьект пользователя // Для Widgets public $view = null; @@ -94,7 +92,7 @@ class Action public function addSuggest(View $view, $name) { $suggest = array(); - $file = Path::join($this->viewPath, 'help', $name . '.suggest'); + $file = Path::join($this->modulePath, 'help', $name . '.suggest'); if (file_exists($file)) { include($file); $view->suggestions = $suggest; @@ -103,7 +101,8 @@ class Action function findIcon($icon, $size) { - return Path::join($this->iconPath, $size . 'x' . $size, $icon . '.png'); + $webPath = $this->settings['web']; + return Path::join($webPath, 'icons', $size . 'x' . $size, $icon . '.png'); } /** @@ -120,7 +119,7 @@ class Action $webPath = $this->settings['web']; $list = array( - Path::join($this->viewPath, 'templates', $this->viewPathPrefix) => Path::join($webPath, "modules", $this->name, 'templates', $this->viewPathPrefix), + Path::join($this->modulePath, 'templates', $this->viewPathPrefix) => Path::join($webPath, "modules", $this->name, 'templates', $this->viewPathPrefix), Path::join($basePath, "templates") => Path::join($webPath, "templates") ); @@ -132,17 +131,19 @@ class Action /*.View_Composite.*/$tpl = new $viewClass($template); - $assets = Path::join($webPath, "assets", "css"); - $tpl->set('icons', $this->iconPath); // Путь к файлам текущей темы - $tpl->set('media', $this->themePath); // Путь к файлам текущей темы - $tpl->set('assets', $assets); - $tpl->set('script', $this->jsPath); // Путь к файлам скриптов + $stylePath = Path::join($webPath, "assets", "css"); + $iconsPath = Path::join($webPath, 'icons'); + $scriptPath = Path::join($webPath, 'assets'); + + $tpl->set('icons', $iconsPath); // Путь к файлам текущей темы + $tpl->set('assets', $stylePath); + $tpl->set('script', $scriptPath); // Путь к файлам скриптов $tpl->set('template', $path); // Путь к файлам текущего шаблона $tpl->setAlias(array( - 'assets' => $assets, - 'icons' => $this->iconPath, - 'script' => $this->jsPath, + 'assets' => $stylePath, + 'icons' => $iconsPath, + 'script' => $scriptPath, // Для media и template поиск происходит как для файлов шаблонов 'media' => $list, 'template' => $list diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 5453892..b9fa014 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -53,9 +53,9 @@ class Front extends Action $system = $this->settings['system']; - $moulesPath = $system->readKey(['path', 'modules']); + $moulesPath = Path::join($this->settings['base'], $system->readKey(['path', 'modules'])); $logPath = Path::join($this->settings['site'], $system->readKey(['path', 'access.log'])); - $moduleFile = Path::join($this->settings['base'], $moulesPath, $name, 'classes', $controller ? $controller : $name); + $moduleFile = Path::join($moulesPath, $name, 'classes', $controller ? $controller : $name); $ucname = ucfirst($name); $moduleClass = "Modules\\$ucname\\$ucname"; @@ -63,11 +63,12 @@ class Front extends Action if ($module) { // Инициализация модуля $modPath = Path::join($moulesPath, $name); - $module->viewPath = $modPath; + $module->modulePath = $modPath; $module->name = $name; // $module->settings = $this->settings; $module->db = $this->db; + $module->user = $this->user; // Ведение лога $logger = new ActionLogger($module, $logPath, $this->user); $logger->before = $this->loadSettings(Path::join($modPath, 'filter', 'logger.php')); diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 6e5f242..eb94070 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -41,7 +41,6 @@ class Login extends Filter $login = $request->get('login'); $password = $request->get('password'); - $result = $this->role->getUserByLogin($login); // Поиск по логину if ($result) { $userPassword = $this->role->getUserPassword($result); diff --git a/src/Role/User.php b/src/Role/User.php index d287543..f199363 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -43,31 +43,38 @@ class User return null; } - public static function getUserByLogin($login) + function getUserPassword($result) { + return $result->get('password'); + } + + public function getUserByLogin($login) { - $stmt = $this->$db->prepareStatement("SELECT * FROM users WHERE login = ?"); + $stmt = $this->db->prepareStatement("SELECT * FROM users WHERE login = ?"); $stmt->setString(1, $login); $result = $this->getUserByQuery($stmt); if ($result) { $time = time(); $id = $this->id; - $this->$db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время входа + $this->db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время входа } return $result; } - public static function getUserById($id) + public function getUserById($id) { - $stmt = $this->$db->prepareStatement("SELECT * FROM users WHERE id_user = ?"); + $stmt = $this->db->prepareStatement("SELECT * FROM users WHERE id_user = ?"); $stmt->setInt(1, $_SESSION ['access']); $result = $this->getUserByQuery($stmt); if ($result) { $lasttime = $result->getInt('lasttime'); $time = time(); - if ($time - $lasttime > $this->LIFE_TIME) return null; // Вышло время сессии - $id = $this->$id; + if ($time - $lasttime > self::LIFE_TIME) return null; // Вышло время сессии + $id = $this->id; $this->db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время последнего обращения входа } return $result; } + + function setSID() { + } } From ee06f1febbe4d40b102d0a6e249fd99e3b26c32a Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Tue, 3 Apr 2018 14:35:20 +0300 Subject: [PATCH 009/138] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20namespace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 48 ++++++------------------ src/Model/Factory.php | 3 +- src/Tools/{String.php => StringUtil.php} | 2 +- src/Url.php | 13 +++++++ 4 files changed, 26 insertions(+), 40 deletions(-) rename src/Tools/{String.php => StringUtil.php} (99%) create mode 100644 src/Url.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index e549f9a..750b25e 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -4,6 +4,7 @@ namespace ctiso\Controller; use ctiso\Shortcut, Exception, ctiso\Path, + ctiso\Url, ctiso\View\View, ctiso\Model\Factory, ctiso\HttpRequest, @@ -11,14 +12,6 @@ use ctiso\Shortcut, ctiso\Settings, ctiso\Controller\State; -function forceUrl($name) -{ - if (is_callable($name)) { - return call_user_func($name); - } - return $name; -} - /** * Контроллер страниц */ @@ -158,7 +151,7 @@ class Action public function getModel($name) { if (!$this->factory) { - $this->factory = new Factory($this->db, $this->_registry); + $this->factory = new Factory($this->db, $this->settings['registry']); } return $this->factory->getModel($name); } @@ -170,7 +163,7 @@ class Action * 2. Использовать наследование чтобы добавить к старому обработчику новое поведение * @param $request Обьект запроса */ - public function preprocess(HttpRequest $request) + public function preProcess(HttpRequest $request) { $action = self::ACTION_PREFIX . ucfirst($request->getAction()); if (!method_exists($this, $action)) { @@ -186,7 +179,7 @@ class Action public function execute(HttpRequest $request) { - $result = $this->preprocess($request); + $result = $this->preProcess($request); if (!empty($result)) { $this->view = $result; } @@ -206,15 +199,6 @@ class Action return ""; } - public function postUrl($name, $param) - { - $uri = array_merge(array('module' => - strtr($this->modulePrefix . strtolower(get_class($this)), array('module_' => '')), "action" => $name), - $this->param, $param); - - return "?" . http_build_query($uri); - } - /** * Генерация ссылки c учетом прав пользователя на ссылки * @param string $name Действие @@ -227,24 +211,14 @@ class Action /*.Filter_ActionAccess.*/$access = $this->access; if ($access == null || $access->checkAction($name)) { - return Functions::lcurry(array($this, 'postUrl'), $name, $param); - } - return null; - } + $param = array_merge(array( + 'module' => strtr($this->modulePrefix . strtolower(get_class($this)), array('module_' => '')), + "action" => $name + ), $param); - public function fUrl($name, array $param = array()) - { - return forceUrl($this->nUrl($name, $param)); - } - - /** - * Добавляет параметр для всех ссылок создаваемых функцией nUrl, aUrl - */ - public function addParameter($name, $value) - { - if ($value) { - $this->param [$name] = $value; + return new Url($param); } + return new Url(); } /** @@ -259,7 +233,7 @@ class Action */ public function aUrl($name, array $param = array()) { - return $this->nUrl($name, array_merge(array('mode' => 'ajax'), $param)); // FIXME + return $this->nUrl($name, array_merge(array('mode' => 'ajax'), $param)); } /** diff --git a/src/Model/Factory.php b/src/Model/Factory.php index 38ed7b7..868da5a 100644 --- a/src/Model/Factory.php +++ b/src/Model/Factory.php @@ -8,7 +8,6 @@ class Factory static $shortcut = "model"; public $db; public $_registry; - public $_shortcut; public function __construct (/*.Database.*/ $db, Settings $_registry = null) { @@ -23,7 +22,7 @@ class Factory */ public function getModel ($name) { - $modelName = "Mapper_" . $name; + $modelName = "App\\Mapper\\" . $name; $model = new $modelName(); $model->db = $this->db; $model->factory = $this; diff --git a/src/Tools/String.php b/src/Tools/StringUtil.php similarity index 99% rename from src/Tools/String.php rename to src/Tools/StringUtil.php index bda7385..8d07048 100644 --- a/src/Tools/String.php +++ b/src/Tools/StringUtil.php @@ -2,7 +2,7 @@ namespace ctiso\Tools; -class String { +class StringUtil { // from creole static function strToArray($str) { diff --git a/src/Url.php b/src/Url.php new file mode 100644 index 0000000..3137d16 --- /dev/null +++ b/src/Url.php @@ -0,0 +1,13 @@ +parts = $parts; + } + + function toString() { + return '?' . http_build_query($this->parts); + } +} \ No newline at end of file From 524b27936a0d2febd01a32bd9dc7bdf5f098d2ba Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Fri, 13 Apr 2018 17:59:57 +0300 Subject: [PATCH 010/138] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20?= =?UTF-8?q?namespace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ComponentRequest.php | 35 ++++++++++++++ src/Controller/Action.php | 36 +++++++------- src/Controller/Component.php | 48 +++++-------------- src/Controller/Front.php | 2 +- src/Controller/Request.php | 1 + src/Controller/Service.php | 5 +- src/Database.php | 18 ++++--- src/Database/PDOStatement.php | 3 +- src/Database/Statement.php | 5 +- src/Database/StatementIterator.php | 4 +- src/Excel/Table.php | 2 +- src/Filter/ActionAccess.php | 4 +- src/Filter/ActionLogger.php | 2 +- src/Filter/Filter.php | 6 ++- src/Filter/Login.php | 5 +- src/Form/OptionFactory.php | 2 +- src/Model/Factory.php | 3 +- src/Setup.php | 2 +- src/Tales.php | 4 +- src/Tools/TemplateImage.php | 2 +- src/Url.php | 2 + .../Rule/{Abstract.php => AbstractRule.php} | 4 +- src/Validator/Rule/Alpha.php | 4 +- src/Validator/Rule/Code.php | 4 +- src/Validator/Rule/Count.php | 4 +- src/Validator/Rule/Date.php | 4 +- src/Validator/Rule/Email.php | 4 +- src/Validator/Rule/EmailList.php | 4 +- src/Validator/Rule/FileName.php | 4 +- src/Validator/Rule/IsFile.php | 4 +- src/Validator/Rule/Match.php | 4 +- src/Validator/Rule/Notnull.php | 4 +- src/Validator/Rule/Numeric.php | 4 +- src/Validator/Rule/Time.php | 4 +- src/Validator/Rule/Unique.php | 4 +- src/Validator/Validator.php | 3 +- src/View/{List.php => ListView.php} | 2 +- src/View/Page.php | 7 ++- src/View/Top.php | 2 +- 39 files changed, 141 insertions(+), 120 deletions(-) create mode 100644 src/ComponentRequest.php rename src/Validator/Rule/{Abstract.php => AbstractRule.php} (92%) rename src/View/{List.php => ListView.php} (89%) diff --git a/src/ComponentRequest.php b/src/ComponentRequest.php new file mode 100644 index 0000000..3d56041 --- /dev/null +++ b/src/ComponentRequest.php @@ -0,0 +1,35 @@ +component_id = $c; + $this->r = $r; + } + + function get($key, $default = null) { + if ($key == 'active_page') { + return $this->r->get($key); + } + if ($arr = $this->r->get($key)) { + if (is_array($arr)) { + return Arr::get($arr, $this->component_id, $default); + } else { + return $arr; + } + } + return $default; + } + + function getAction() { + return $this->r->getAction(); + } +} \ No newline at end of file diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 750b25e..ca3a547 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -10,6 +10,8 @@ use ctiso\Shortcut, ctiso\HttpRequest, ctiso\Functions, ctiso\Settings, + ctiso\View\Composite, + ctiso\View\View, ctiso\Controller\State; /** @@ -82,18 +84,15 @@ class Action return Path::join($basePath, "modules", $name); } - public function addSuggest(View $view, $name) - { + public function addSuggest(View $view, $name) { $suggest = array(); $file = Path::join($this->modulePath, 'help', $name . '.suggest'); if (file_exists($file)) { - include($file); - $view->suggestions = $suggest; + $view->suggestions = include($file); } } - function findIcon($icon, $size) - { + function findIcon($icon, $size) { $webPath = $this->settings['web']; return Path::join($webPath, 'icons', $size . 'x' . $size, $icon . '.png'); } @@ -122,7 +121,7 @@ class Action if(file_exists($template)) { break; } } - /*.View_Composite.*/$tpl = new $viewClass($template); + /*.Composite.*/$tpl = new $viewClass($template); $stylePath = Path::join($webPath, "assets", "css"); $iconsPath = Path::join($webPath, 'icons'); @@ -170,7 +169,7 @@ class Action $action = "actionIndex"; } $view = $this->forward($action, $request); - if ($view instanceof View_View) { + if ($view instanceof View) { $view->active_module = get_class($this); $view->module_action = $action; } @@ -208,7 +207,7 @@ class Action */ public function nUrl($name, array $param = array()) { - /*.Filter_ActionAccess.*/$access = $this->access; + /*.ActionAccess.*/$access = $this->access; if ($access == null || $access->checkAction($name)) { $param = array_merge(array( @@ -295,12 +294,12 @@ class Action /** * Добавление widget к отображению */ - public function addChild(/*Widgets_Widget*/ $section, $node) + public function addChild($section, $node) { $this->childNodes[$section] = $node; } - public function setValue(/*Widgets_Widget*/ $name, $value) + public function setValue($name, $value) { $this->ctrlValues[$name] = $value; } @@ -308,7 +307,7 @@ class Action /** * Добавление дочернего отображения к текущему отображению */ - public function addView(/*CompositeView*/ $section, $node) + public function addView($section, $node) { $this->childViews[$section] = $node; } @@ -322,7 +321,7 @@ class Action if ($this->view instanceof View_View) { $this->view->assignValues($this->ctrlValues); - /*.Widgets_Widget.*/$node = null; + /*.Composite.*/$node = null; foreach ($this->childNodes as $name => $node) { $node->make($this); $this->view->setView($name, $node->view); @@ -335,8 +334,7 @@ class Action return $this->view; } - function getPageId(HttpRequest $request) - { + function getPageId(HttpRequest $request) { $pageId = time(); $request->session()->set('page', $pageId); return $pageId; @@ -353,19 +351,17 @@ class Action return $result; } - function _getActionPath() - { + function _getActionPath() { return new State('index'); } // Тоже убрать в метод Controller_Model - function getActionPath(HttpRequest $request, $action = null) - { + function getActionPath(HttpRequest $request, $action = null) { $this->_getActionPath()->getPath($this, ($action) ? $action : $request->getAction()); } function redirect($action) { - header('location: ' . $this->fUrl($action)); + header('location: ' . $action->toString()); exit(); } } diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 1fcc8a8..1e94b27 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -2,16 +2,19 @@ namespace ctiso\Controller; use ctiso\HttpRequest, + ctiso\ComponentRequest, ctiso\Arr, ctiso\Path, - PHPTAL, - PHPTAL_PreFilter_Normalize, ctiso\File, ctiso\Form\Form, ctiso\Form\OptionFactory, ctiso\Database, + ctiso\Database\PDOStatement, ctiso\Collection, - ctiso\Controller\Site; + ctiso\Settings, + App\Controller\Site, + PHPTAL, + PHPTAL_PreFilter_Normalize; function replaceContent($match) { $result = Tales\Component::phptal_component(htmlspecialchars_decode($match[3])); @@ -22,35 +25,6 @@ function applyComponents($text) { return preg_replace_callback('/<(\w+)(\s+[a-zA-Z\-]+=\"[^\"]*\")*\s+tal:replace="structure\s+component:([^\"]*)"[^>]*>/u', 'replaceContent', $text); } -class ComponentRequest { - public $component_id; - public $component_title; - public $r; - - function __construct($c, HttpRequest $r) { - $this->component_id = $c; - $this->r = $r; - } - - function get($key, $default = null) { - if ($key == 'active_page') { - return $this->r->get($key); - } - if ($arr = $this->r->get($key)) { - if (is_array($arr)) { - return Arr::get($arr, $this->component_id, $default); - } else { - return $arr; - } - } - return $default; - } - - function getAction() { - return $this->r->getAction(); - } -} - class FakeTemplate { public $_data = []; public $_name = ''; @@ -183,7 +157,7 @@ class Component return $model; } - public function options($key, $val, /*.Database_PDOStatement.*/$res) { + public function options($key, $val, /*.PDOStatement.*/$res) { $result = array(); while($res->next()) { $result[] = array('value' => $res->getString($key), 'name' => $res->getString($val)); @@ -221,7 +195,7 @@ class Component /** * Генерация интерфейса для выбора галлереи фотографии */ - public function setParameters(/*.View_Composite.*/$view) + public function setParameters(/*.Composite.*/$view) { $form = new Form(); $options = new OptionFactory($this->db, $this->registry); @@ -234,7 +208,7 @@ class Component $view->component_title = $settings['title']; } - static function loadComponent($expression, Database $db, /*.Registry.*/ $registry) + static function loadComponent($expression, Database $db, /*.Settings.*/ $registry) { $expression = htmlspecialchars_decode($expression); @@ -254,7 +228,7 @@ class Component $path = Path::join (BASE_PATH, 'components', $name, $name . '.php'); $className = 'Component_' . $name; - /*.Controller_Component.*/$component = null; + /*.Component.*/$component = null; if (file_exists($path)) { require_once ($path); @@ -313,7 +287,7 @@ class Component $editor = $component->getEditUrl(); if ($editor) { - if(class_exists("Controller_Site")) { //Если мы в CMS2 + if (class_exists("Controller_Site")) { //Если мы в CMS2 $instance = Site::getInstance(); $instance->componentsConfig[] = $editor; } else { diff --git a/src/Controller/Front.php b/src/Controller/Front.php index b9fa014..9e55c82 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -98,7 +98,7 @@ class Front extends Action return $this->loadModule($name[0], $request, $controller); } catch (UserMessageException $ex) { //Исключение с понятным пользователю сообщением $mode = $request->get('mode'); - if($mode == 'ajax' || $mode == 'json') { + if ($mode == 'ajax' || $mode == 'json') { return json_encode(['result'=>'fail', 'message'=> $ex->userMessage]); } else { return $ex->userMessage; diff --git a/src/Controller/Request.php b/src/Controller/Request.php index 50a3039..e67ed7d 100644 --- a/src/Controller/Request.php +++ b/src/Controller/Request.php @@ -1,6 +1,7 @@ next()) { $result[] = array('value' => $res->getInt($key), 'name' => $res->getString($val)); diff --git a/src/Database.php b/src/Database.php index 0a8e103..bd013e0 100644 --- a/src/Database.php +++ b/src/Database.php @@ -12,6 +12,7 @@ namespace { namespace ctiso { use PDO, ctiso\Database\Statement, + ctiso\Database\PDOStatement, ctiso\Database\IdGenerator; /** @@ -61,7 +62,7 @@ class Database extends PDO public function executeQuery($query, $values=null) { - /*.Database_PDOStatement.*/$stmt = $this->prepare($query); + /*.PDOStatement.*/$stmt = $this->prepare($query); $stmt->execute($values); $stmt->cache = $stmt->fetchAll(PDO::FETCH_ASSOC); @@ -79,7 +80,7 @@ class Database extends PDO */ public function fetchAllArray($query, $values = null) { - /*.Database_PDOStatement.*/$sth = $this->prepare($query); + /*.PDOStatement.*/$sth = $this->prepare($query); $prep = $this->prepareValues($values); $sth->execute($prep); return $sth->fetchAll(PDO::FETCH_ASSOC); @@ -90,7 +91,7 @@ class Database extends PDO */ public function fetchOneArray($query, $values = null) { - /*.Database_PDOStatement.*/$sth = $this->prepare($query); + /*.PDOStatement.*/$sth = $this->prepare($query); $prep = $this->prepareValues($values); $sth->execute($prep); return $sth->fetch(PDO::FETCH_ASSOC); @@ -180,9 +181,12 @@ class Database extends PDO return $result['nextval']; } - function close() - { + function prepare($query) { + /*.PDOStatement.*/$result = $this->prepare($query); + return $result; + } + + function close() { return null; } -} -} \ No newline at end of file +}} diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index 48e591a..7d5b3fe 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -3,6 +3,7 @@ namespace ctiso\Database; use ctiso\Database\StatementIterator, + ctiso\Tools\StringUtil, PDO; class PDOStatement extends \PDOStatement implements \IteratorAggregate @@ -91,7 +92,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate } function getArray($name) { - return strToArray($this->fields[$name]); + return StringUtil::strToArray($this->fields[$name]); } function getRecordCount() { diff --git a/src/Database/Statement.php b/src/Database/Statement.php index 69d7cf2..f47278f 100644 --- a/src/Database/Statement.php +++ b/src/Database/Statement.php @@ -4,7 +4,8 @@ * Класс оболочка для PDOStatement для замены Creole */ namespace ctiso\Database; -use PDO; +use PDO, + ctiso\Database; class Statement { @@ -50,7 +51,7 @@ class Statement if ($this->limit) { $this->query .= " LIMIT {$this->limit} OFFSET {$this->offset}"; } - /*.Database_PDOStatement.*/$stmt = $this->conn->prepare($this->query); + /*.PDOStatement.*/$stmt = $this->conn->prepare($this->query); foreach ($this->binds as $bind) { list($n, $value, $type) = $bind; $stmt->bindValue($n, $value, (int) $type); diff --git a/src/Database/StatementIterator.php b/src/Database/StatementIterator.php index 02a5c3a..6286a6d 100644 --- a/src/Database/StatementIterator.php +++ b/src/Database/StatementIterator.php @@ -3,7 +3,7 @@ namespace ctiso\Database; use PDO; -class StatementIterator implements Iterator +class StatementIterator implements \Iterator { private $result; @@ -11,7 +11,7 @@ class StatementIterator implements Iterator private $fetchmode; private $row_count; - public function __construct(/*.Database_PDOStatement.*/ $rs) { + public function __construct(/*.PDOStatement.*/ $rs) { $this->result = $rs; $this->row_count = $rs->getRecordCount(); } diff --git a/src/Excel/Table.php b/src/Excel/Table.php index bb28499..1861a36 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -4,6 +4,7 @@ * Клетка таблицы */ namespace ctiso\Excel; +use XMLWriter; class TableCell { @@ -310,4 +311,3 @@ class Table $doc->endElement(); } } - diff --git a/src/Filter/ActionAccess.php b/src/Filter/ActionAccess.php index 0bb031c..da01325 100644 --- a/src/Filter/ActionAccess.php +++ b/src/Filter/ActionAccess.php @@ -12,7 +12,7 @@ class ActionAccess public $access = array(); public $processor; - function __construct(/*.Filter_Filter.*/$processor) { + function __construct(/*.Filter.*/$processor) { $this->processor = $processor; } @@ -23,7 +23,7 @@ class ActionAccess */ function checkAction($action) { // Импликация !! http://ru.wikipedia.org/wiki/Импликация - return (!isset($this->access[$action]) || in_array(UserAccess::$access, $this->access[$action])); + return (!isset($this->access[$action]) || in_array($this->user->access, $this->access[$action])); } function execute(HttpRequest $request) { diff --git a/src/Filter/ActionLogger.php b/src/Filter/ActionLogger.php index 4718da8..d7da199 100644 --- a/src/Filter/ActionLogger.php +++ b/src/Filter/ActionLogger.php @@ -11,7 +11,7 @@ class ActionLogger public $action; public $processor; - function __construct(/*.Filter_Filter.*/$processor, $logPath, $user) { + function __construct(/*.Filter.*/$processor, $logPath, $user) { $this->processor = $processor; $this->user = $user; $this->file = fopen($logPath, "a"); diff --git a/src/Filter/Filter.php b/src/Filter/Filter.php index b61b5c8..864e898 100644 --- a/src/Filter/Filter.php +++ b/src/Filter/Filter.php @@ -4,12 +4,14 @@ * Попытка реализовать фильтр для запросов */ namespace ctiso\Filter; -use ctiso\HttpRequest; + +use ctiso\Controller\Action, + ctiso\HttpRequest; class Filter { public $processor; - public function __construct(/*.Controller_Action.*/$processor) + public function __construct(/*.Action.*/$processor) { $this->processor = $processor; } diff --git a/src/Filter/Login.php b/src/Filter/Login.php index eb94070..851e966 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -19,8 +19,11 @@ class Login extends Filter { const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#'; const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; + public $mode = 'ajax'; public $user; + public $role; + public $whitelist; function __construct($processor, $role, $whitelist = []) { parent::__construct($processor); @@ -63,7 +66,7 @@ class Login extends Filter if ($result) { $temp = md5($result->getString('password') . $result->getString('login') . $result->getString('sid')); if ($password == $temp) { - $this->enter($db, $result); + $this->enter($result); return true; } } diff --git a/src/Form/OptionFactory.php b/src/Form/OptionFactory.php index 70904bb..42ae288 100644 --- a/src/Form/OptionFactory.php +++ b/src/Form/OptionFactory.php @@ -2,7 +2,7 @@ namespace ctiso\Form; use ctiso\Form\Select, - ctiso\Model\Resources, + App\Model\Resources, ctiso\Model\Factory; class OptionFactory { diff --git a/src/Model/Factory.php b/src/Model/Factory.php index 868da5a..2e57587 100644 --- a/src/Model/Factory.php +++ b/src/Model/Factory.php @@ -1,7 +1,8 @@ stack[count($this->stack) - 1]; + /*.\SimpleXMLElement.*/$item = $this->stack[count($this->stack) - 1]; $root = $item->children(); foreach ($root as $node) { diff --git a/src/Tales.php b/src/Tales.php index c3f2155..58a341d 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -5,7 +5,7 @@ */ namespace ctiso; use PHPTAL_Php_TalesInternal, - ctiso\Controller\Site, + App\Controller\Site, ctiso\Controller\Component, ctiso\HttpRequest, PHPTAL_Tales, @@ -48,7 +48,7 @@ class Tales { */ static function phptal_component ($expression) { $begin = floatval(microtime(true)); - /*.Controller_Component.*/$component = null; + /*.Component.*/$component = null; if (class_exists("ctiso\\Controller\\Site")) { //Если мы в CMS2 $component = Site::loadComponent($expression); diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index fbde7c1..fad2434 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -122,7 +122,7 @@ class TemplateImage return ""; } - function imageText($text, /*.stdClass.*/$value) + function imageText($text, /*.\stdClass.*/$value) { assert(is_string($text)); diff --git a/src/Url.php b/src/Url.php index 3137d16..f52baec 100644 --- a/src/Url.php +++ b/src/Url.php @@ -3,6 +3,8 @@ namespace ctiso; class Url { + public $parts; + function __construct($parts = []) { $this->parts = $parts; } diff --git a/src/Validator/Rule/Abstract.php b/src/Validator/Rule/AbstractRule.php similarity index 92% rename from src/Validator/Rule/Abstract.php rename to src/Validator/Rule/AbstractRule.php index 15e6cb9..4ab8307 100644 --- a/src/Validator/Rule/Abstract.php +++ b/src/Validator/Rule/AbstractRule.php @@ -1,9 +1,9 @@ Rule_Abstract + public function skip(/*.AbstractRule.*/$rule, /*.Collection.*/$container) // -> Rule_Abstract { if ($rule->skipEmpty()) { $data = $container->get($rule->field); diff --git a/src/View/List.php b/src/View/ListView.php similarity index 89% rename from src/View/List.php rename to src/View/ListView.php index 45ca726..16945ff 100644 --- a/src/View/List.php +++ b/src/View/ListView.php @@ -3,7 +3,7 @@ namespace ctiso\View; use ctiso\View\View; -class List extends View +class ListView extends View { function execute() { diff --git a/src/View/Page.php b/src/View/Page.php index 2c0a4ab..10e40ec 100644 --- a/src/View/Page.php +++ b/src/View/Page.php @@ -2,7 +2,7 @@ namespace ctiso\View; use ctiso\View\View, - ctiso\Controller\Site, + App\Controller\Site, ctiso\Controller\Component, ctiso\HttpRequest; @@ -54,10 +54,9 @@ class Page extends View function replaceContent($match, $offset) { //$result = phptal_component($match, $offset); - /*.Controller_Component.*/$component = null; + /*.Component.*/$component = null; - - if(class_exists("Controller_Site")){ //Если мы в CMS2 + if (class_exists("App\\Controller\\Site")) { //Если мы в CMS2 $component = Site::loadComponent($match); } else { global $db, $registry; // diff --git a/src/View/Top.php b/src/View/Top.php index 3c2ed6c..eb67c02 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -102,7 +102,7 @@ class Top extends Composite { $init = array(); foreach($s->_section as $key => $item) { - /*.View_View.*/$ss = $item; + /*.View.*/$ss = $item; if ($ss->codeGenerator !== null) { // функцию которая вычисляет а не результат $part = call_user_func($ss->codeGenerator, $this, $key, $value); From 40fad0e75b17bffb868ed5acf11b4431b6120524 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Wed, 18 Apr 2018 18:20:56 +0300 Subject: [PATCH 011/138] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=20=D0=BC=D0=B5=D1=85=D0=B0=D0=BD=D0=B8=D0=B7=D0=BC=20?= =?UTF-8?q?=D1=80=D0=B0=D1=81=D1=88=D0=B8=D1=80=D0=B5=D0=BD=D0=B8=D1=8F=20?= =?UTF-8?q?=D1=81=D1=81=D1=8B=D0=BB=D0=BE=D0=BA.=20=D0=98=D0=B7=D0=B1?= =?UTF-8?q?=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BE=D1=82=20?= =?UTF-8?q?=D0=B3=D0=BB=D0=BE=D0=B1=D0=B0=D0=BB=D1=8C=D0=BD=D1=8B=D1=85=20?= =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D0=BC=D0=B5=D0=BD=D0=BD=D1=8B=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 19 +++++++++++++----- src/Controller/Component.php | 36 ++++++++++++++--------------------- src/Controller/Front.php | 2 +- src/Database.php | 4 ++-- src/Filter/ActionLogger.php | 11 +++++++++-- src/Filter/Login.php | 2 +- src/HttpRequest.php | 8 ++++---- src/Tales.php | 18 ++++++------------ src/Url.php | 18 +++++++++++++++--- src/View/Page.php | 13 ++++--------- src/WrongRequestException.php | 7 +++++++ 11 files changed, 77 insertions(+), 61 deletions(-) create mode 100644 src/WrongRequestException.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index ca3a547..2078409 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -5,12 +5,12 @@ use ctiso\Shortcut, Exception, ctiso\Path, ctiso\Url, - ctiso\View\View, ctiso\Model\Factory, ctiso\HttpRequest, ctiso\Functions, ctiso\Settings, ctiso\View\Composite, + ctiso\Filter\ActionAccess, ctiso\View\View, ctiso\Controller\State; @@ -43,7 +43,7 @@ class Action private $factory = null; // Ссылка на обьект создания модели private $helpers = array(); // Помошники для действий - public $param = array(); // Параметры для ссылки + public $part = null; // Параметры для ссылки public /*.Settings.*/$settings; // Ссылка на настройки public $user; // Обьект пользователя @@ -55,6 +55,7 @@ class Action public $childViews = array(); function __construct() { + $this->part = new Url(); } public function setUp() { @@ -198,6 +199,10 @@ class Action return ""; } + public function addUrlPart($key, $value) { + $this->part->addQueryParam($key, $value); + } + /** * Генерация ссылки c учетом прав пользователя на ссылки * @param string $name Действие @@ -208,16 +213,20 @@ class Action public function nUrl($name, array $param = array()) { /*.ActionAccess.*/$access = $this->access; + $url = new Url(); if ($access == null || $access->checkAction($name)) { $param = array_merge(array( 'module' => strtr($this->modulePrefix . strtolower(get_class($this)), array('module_' => '')), "action" => $name + ), $param); - return new Url($param); + $url->setParent($this->part); + $url->setQuery($param); } - return new Url(); + + return $url; } /** @@ -318,7 +327,7 @@ class Action */ public function render() { - if ($this->view instanceof View_View) { + if ($this->view instanceof View) { $this->view->assignValues($this->ctrlValues); /*.Composite.*/$node = null; diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 1e94b27..c87cf59 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -8,6 +8,7 @@ use ctiso\HttpRequest, ctiso\File, ctiso\Form\Form, ctiso\Form\OptionFactory, + ctiso\View\Composite, ctiso\Database, ctiso\Database\PDOStatement, ctiso\Collection, @@ -38,7 +39,7 @@ class FakeTemplate { } function execute() { - return $this->_data; + return json_encode($this->_data); } } @@ -64,6 +65,7 @@ class Component public $module; public $item_module; + public $site; function before() { } @@ -95,7 +97,6 @@ class Component return new FakeTemplate($name); } - // /*.Settings.*/$registry = $this->registry; $template = ($this->template) ? $this->template : $registry->readKey(array('system', 'template')); @@ -195,7 +196,7 @@ class Component /** * Генерация интерфейса для выбора галлереи фотографии */ - public function setParameters(/*.Composite.*/$view) + public function setParameters(/*.Composite.*/ $view) { $form = new Form(); $options = new OptionFactory($this->db, $this->registry); @@ -208,7 +209,7 @@ class Component $view->component_title = $settings['title']; } - static function loadComponent($expression, Database $db, /*.Settings.*/ $registry) + static function loadComponent($expression, /*.Site.*/ $site) { $expression = htmlspecialchars_decode($expression); @@ -232,22 +233,16 @@ class Component if (file_exists($path)) { require_once ($path); - $component = new $className(); - $component->db = $db; - $component->registry = $registry; $component->viewPath = array(BASE_PATH . '/components/' . $name . '/'); $component->webPath = array(SITE_WWW_PATH . '/components/' . $name); - $component->COMPONENTS_WEB = SITE_WWW_PATH . '/components/'; } else { $path = Path::join (COMPONENTS, $name, $name . '.php'); require_once ($path); $component = new $className(); - $component->db = $db; - $component->registry = $registry; $component->viewPath = array(COMPONENTS . '/' . $name . '/', BASE_PATH . '/components/' . $name . '/'); if (defined('COMPONENTS_WEB')) { @@ -255,6 +250,12 @@ class Component $component->COMPONENTS_WEB = COMPONENTS_WEB; } } + + $db = $site->db; + + $component->db = $db; + $component->registry = $site->registry; + $component->site = $site; $stmt = $db->prepareStatement("SELECT * FROM component WHERE code = ?"); $stmt->setString(1, $expression); @@ -282,18 +283,13 @@ class Component $params = new Collection(); $params->import($arguments); + $component->parameter = $params; $component->template = $params->get('template', false); $editor = $component->getEditUrl(); if ($editor) { - if (class_exists("Controller_Site")) { //Если мы в CMS2 - $instance = Site::getInstance(); - $instance->componentsConfig[] = $editor; - } else { - global $componentsConfig; - $componentsConfig[] = $editor; - } + $site->componentsConfig[] = $editor; } return $component; @@ -338,12 +334,8 @@ class Component return '?' . http_build_query($arr); } - /** - * @deprecated В CMS2 перенесено в контроллер сайта! - */ - function addRequireJsPath($name, $path, $shim = null) { - Site::addRequireJsPath($name, $path, $shim); + $this->site->addRequireJsPath($name, $path, $shim); } function actionIndex(/*.ComponentRequest.*/ $request) { diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 9e55c82..5f243af 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -51,7 +51,7 @@ class Front extends Action return $module->access->execute($request); } - $system = $this->settings['system']; + /*.Settings.*/$system = $this->settings['system']; $moulesPath = Path::join($this->settings['base'], $system->readKey(['path', 'modules'])); $logPath = Path::join($this->settings['site'], $system->readKey(['path', 'access.log'])); diff --git a/src/Database.php b/src/Database.php index bd013e0..9ac4c6d 100644 --- a/src/Database.php +++ b/src/Database.php @@ -181,8 +181,8 @@ class Database extends PDO return $result['nextval']; } - function prepare($query) { - /*.PDOStatement.*/$result = $this->prepare($query); + function prepare($query, $options = NULL) { + /*.PDOStatement.*/$result = parent::prepare($query); return $result; } diff --git a/src/Filter/ActionLogger.php b/src/Filter/ActionLogger.php index d7da199..93c11e7 100644 --- a/src/Filter/ActionLogger.php +++ b/src/Filter/ActionLogger.php @@ -3,6 +3,7 @@ namespace ctiso\Filter; use ctiso\HttpRequest; +/* Переделать формат Логов на список json */ class ActionLogger { public $before = array(); @@ -14,13 +15,19 @@ class ActionLogger function __construct(/*.Filter.*/$processor, $logPath, $user) { $this->processor = $processor; $this->user = $user; - $this->file = fopen($logPath, "a"); + $file = fopen($logPath, "a"); + if (is_resource($file)) { + $this->file = $file; + } else { + throw new \Exception('Ошибка открытия файла ' . $logPath); + } } function execute(HttpRequest $request) { $action = $request->getAction(); if(in_array($action, $this->before)) { - fwrite($this->file, "time: " . date("r", time()) . " query: ". json_encode(array_merge($_POST, $_GET)) . " by: " . $this->user->name . "\n"); + $message = ["time" => date("r", time()), "query" => array_merge($_POST, $_GET), "user" => $this->user->name]; + fwrite($this->file, json_encode($message) . "\n"); } return $this->processor->execute($request); } diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 851e966..74f2259 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -162,7 +162,7 @@ class Login extends Filter /* --------------------- * Проверка на попадание реквеста в белый список */ - public function requestIsWhite(Collection $request, $whiteRequestList){ + public function requestIsWhite(HttpRequest $request, $whiteRequestList){ $module = $request->get('module'); $action = $request->get('action'); foreach ($whiteRequestList as $whiteRequest) { diff --git a/src/HttpRequest.php b/src/HttpRequest.php index f88fb0c..5e1b519 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -9,10 +9,6 @@ use Exception, ctiso\Collection, ctiso\Session; -class WrongRequestException extends Exception -{ -} - // HTTPRequest = ArrayAccess class HttpRequest extends Collection implements ArrayAccess { @@ -132,4 +128,8 @@ class HttpRequest extends Collection implements ArrayAccess public function offsetGet($key) { } + + static function getProtocol() { + return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; + } } diff --git a/src/Tales.php b/src/Tales.php index 58a341d..c0e09d4 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -14,11 +14,11 @@ use PHPTAL_Php_TalesInternal, class Tales_DateTime implements PHPTAL_Tales { static public function date($expression, $nothrow = false) { - return "ctiso\\Tales::phptal_date(".PHPTAL_Php_TalesInternal::path ($expression).")"; + return "ctiso\\Tales::phptal_date(".PHPTAL_Php_TalesInternal::path($expression).")"; } static public function time($expression, $nothrow = false) { - return "ctiso\\Tales::phptal_time(".PHPTAL_Php_TalesInternal::path ($expression).")"; + return "ctiso\\Tales::phptal_time(".PHPTAL_Php_TalesInternal::path($expression).")"; } } @@ -32,8 +32,7 @@ class Tales_Component implements PHPTAL_Tales } class Tales { - static $db; - static $registry; + static $site; static function phptal_date ($e) { return date("d.m.Y", $e); @@ -50,11 +49,7 @@ class Tales { $begin = floatval(microtime(true)); /*.Component.*/$component = null; - if (class_exists("ctiso\\Controller\\Site")) { //Если мы в CMS2 - $component = Site::loadComponent($expression); - } else { - $component = Component::loadComponent($expression, self::$db, self::$registry); - } + $component = self::$site->loadComponent($expression); $req = new HttpRequest(); $result = $component->execute($req); @@ -63,9 +58,8 @@ class Tales { } - static function register($db, $registry) { - self::$db = $db; - self::$registry = $registry; + static function register($site) { + self::$site = $site; /* Регистрация нового префикса для подключения компонента */ $tales = PHPTAL_TalesRegistry::getInstance(); diff --git a/src/Url.php b/src/Url.php index f52baec..3b879ef 100644 --- a/src/Url.php +++ b/src/Url.php @@ -3,13 +3,25 @@ namespace ctiso; class Url { - public $parts; + public $parts = []; + public $parent; - function __construct($parts = []) { + function __construct() { + } + + function setParent($parent) { + $this->parent = $parent; + } + + function setQuery($parts) { $this->parts = $parts; } + function addQueryParam($key, $value) { + $this->parts[$key] = $value; + } + function toString() { - return '?' . http_build_query($this->parts); + return '?' . http_build_query(array_merge($this->parts, $this->parent->parts)); } } \ No newline at end of file diff --git a/src/View/Page.php b/src/View/Page.php index 10e40ec..4ccb457 100644 --- a/src/View/Page.php +++ b/src/View/Page.php @@ -10,9 +10,11 @@ class Page extends View { private $counter; public $text; + public $site; - function __construct($data) + function __construct($data, $site) { + $this->site = $site; // Вставка компонентов на странице $pattern = '/<(\w+)(\s+[a-zA-Z\-]+=\"[^\"]*\")*\s+tal:replace="structure\s+component:([^\"]*)"[^>]*>/u'; $matches = array(); @@ -53,15 +55,8 @@ class Page extends View function replaceContent($match, $offset) { - //$result = phptal_component($match, $offset); /*.Component.*/$component = null; - - if (class_exists("App\\Controller\\Site")) { //Если мы в CMS2 - $component = Site::loadComponent($match); - } else { - global $db, $registry; // - $component = Component::loadComponent($match, $db, $registry); - } + $component = $this->site->loadComponent($match); $req = new HttpRequest(); unset($req['active_page']); diff --git a/src/WrongRequestException.php b/src/WrongRequestException.php new file mode 100644 index 0000000..6ebddfc --- /dev/null +++ b/src/WrongRequestException.php @@ -0,0 +1,7 @@ + Date: Fri, 20 Apr 2018 18:03:39 +0300 Subject: [PATCH 012/138] =?UTF-8?q?=D0=94=D1=80=D1=83=D0=B3=D0=B0=D1=8F=20?= =?UTF-8?q?=D0=B8=D0=BD=D1=82=D0=B5=D1=80=D0=BF=D1=80=D0=B5=D1=82=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8F=20=D1=80=D0=B5=D0=B5=D1=81=D1=82=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 25 ++++++++------- src/Controller/Component.php | 60 +++++++++++++++++------------------ src/Controller/Front.php | 14 ++++---- src/Controller/Installer.php | 9 +++--- src/Controller/Service.php | 5 +-- src/Controller/State.php | 3 +- src/Excel/Document.php | 2 +- src/Excel/Table.php | 4 ++- src/Filter/ActionAccess.php | 7 ++-- src/Filter/Authorization.php | 23 ++++++++------ src/Filter/Login.php | 5 +-- src/Form/OptionFactory.php | 2 +- src/Path.php | 2 +- src/Registry.php | 40 +++++++++++++++++++++++ src/Settings.php | 28 ++++++++++------ src/Tales.php | 2 +- src/Url.php | 2 +- src/Validator/Rule/Count.php | 2 +- src/View/Page.php | 7 ++-- src/View/Top.php | 4 +-- src/WrongRequestException.php | 2 +- 21 files changed, 156 insertions(+), 92 deletions(-) create mode 100644 src/Registry.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 2078409..be0dfb8 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -9,6 +9,8 @@ use ctiso\Shortcut, ctiso\HttpRequest, ctiso\Functions, ctiso\Settings, + ctiso\Registry, + ctiso\Role\User, ctiso\View\Composite, ctiso\Filter\ActionAccess, ctiso\View\View, @@ -45,8 +47,8 @@ class Action private $helpers = array(); // Помошники для действий public $part = null; // Параметры для ссылки - public /*.Settings.*/$settings; // Ссылка на настройки - public $user; // Обьект пользователя + public /*.Registry.*/$config; // Ссылка на настройки + public /*.User.*/$user; // Обьект пользователя // Для Widgets public $view = null; @@ -62,7 +64,7 @@ class Action } public function loadConfig($name) { - $basePath = $this->settings['base']; + $basePath = $this->config->get('site', 'path'); $filename = Path::join($basePath, 'modules', $name); $settings = []; @@ -81,7 +83,7 @@ class Action public function installPath($name) { - $basePath = $this->settings['base']; + $basePath = $this->config->get('site', 'path'); return Path::join($basePath, "modules", $name); } @@ -94,7 +96,7 @@ class Action } function findIcon($icon, $size) { - $webPath = $this->settings['web']; + $webPath = $this->config->get('site', 'web'); return Path::join($webPath, 'icons', $size . 'x' . $size, $icon . '.png'); } @@ -108,8 +110,8 @@ class Action { $file = $name . self::TEMPLATE_EXTENSION; - $basePath = $this->settings['base']; - $webPath = $this->settings['web']; + $basePath = $this->config->get('site', 'path'); + $webPath = $this->config->get('site', 'web'); $list = array( Path::join($this->modulePath, 'templates', $this->viewPathPrefix) => Path::join($webPath, "modules", $this->name, 'templates', $this->viewPathPrefix), @@ -151,7 +153,7 @@ class Action public function getModel($name) { if (!$this->factory) { - $this->factory = new Factory($this->db, $this->settings['registry']); + $this->factory = new Factory($this->db, $this->config); } return $this->factory->getModel($name); } @@ -327,7 +329,8 @@ class Action */ public function render() { - if ($this->view instanceof View) { + $view = $this->view; + if ($view instanceof View) { $this->view->assignValues($this->ctrlValues); /*.Composite.*/$node = null; @@ -369,8 +372,8 @@ class Action $this->_getActionPath()->getPath($this, ($action) ? $action : $request->getAction()); } - function redirect($action) { - header('location: ' . $action->toString()); + function redirect(/*.string.*/$action) { + header('location: ' . $action); exit(); } } diff --git a/src/Controller/Component.php b/src/Controller/Component.php index c87cf59..7210d32 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -12,20 +12,11 @@ use ctiso\HttpRequest, ctiso\Database, ctiso\Database\PDOStatement, ctiso\Collection, - ctiso\Settings, + ctiso\Registry, App\Controller\Site, PHPTAL, PHPTAL_PreFilter_Normalize; -function replaceContent($match) { - $result = Tales\Component::phptal_component(htmlspecialchars_decode($match[3])); - return $result; -} - -function applyComponents($text) { - return preg_replace_callback('/<(\w+)(\s+[a-zA-Z\-]+=\"[^\"]*\")*\s+tal:replace="structure\s+component:([^\"]*)"[^>]*>/u', 'replaceContent', $text); -} - class FakeTemplate { public $_data = []; public $_name = ''; @@ -56,11 +47,13 @@ class Component public $component_id; public $component_title; + public $COMPONENTS_WEB; - public /*.Settings.*/$registry; + public /*.Registry.*/$config; public /*.Database.*/$db; public /*.Collection.*/$parameter; + public $output = 'html'; public $module; @@ -70,7 +63,12 @@ class Component function before() { } - function get($request, $key, $default) { + static function replaceContent($match) { + return \ctiso\Tales::phptal_component(htmlspecialchars_decode($match[3])); + } + + 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); } function execute(HttpRequest $request, $has_id = true) { @@ -97,8 +95,9 @@ class Component return new FakeTemplate($name); } - /*.Settings.*/$registry = $this->registry; - $template = ($this->template) ? $this->template : $registry->readKey(array('system', 'template')); + /*.Registry.*/$config = $this->config; + $default = $config->get('site', 'template'); + $template = ($this->template) ? $this->template : $default; $selected = null; foreach ($this->viewPath as $index => $viewPath) { @@ -121,13 +120,14 @@ class Component $tpl->stripComments(true); $tpl->addPreFilter(new PHPTAL_PreFilter_Normalize()); - $tpl->set('common', Path::join(WWW_PATH, '../', 'common')); - $tpl->set('script', Path::join(WWW_PATH, 'js')); - $tpl->set('media', Path::join(TEMPLATE_WEB, $template)); - if ($registry) { - $tpl->set('site_template', SITE_WWW_PATH . '/templates' . $registry->readKey(array('system', 'template'))); + $tpl->set('common', Path::join($this->config->get('system', 'web'), '../', 'common')); + $tpl->set('script', Path::join($this->config->get('system', 'web'), 'js')); + $tpl->set('media', Path::join($this->config->get('system', 'templates_web'), $template)); + + if ($default) { + $tpl->set('site_template', $this->config->get('site', 'web') . '/templates/' . $default); } - $tpl->set('base', SITE_WWW_PATH); + $tpl->set('base', $this->config->get('site', 'web')); $tpl->set('component_base', $this->webPath[$selected]); $tpl->set('component', Path::join($this->webPath[$selected], 'templates', $template)); @@ -199,7 +199,7 @@ class Component public function setParameters(/*.Composite.*/ $view) { $form = new Form(); - $options = new OptionFactory($this->db, $this->registry); + $options = new OptionFactory($this->db, $this->config); $settings = $this->getInfo(); $form->addFieldList($settings['parameter'], $options); @@ -226,7 +226,7 @@ class Component } $name = $path; - $path = Path::join (BASE_PATH, 'components', $name, $name . '.php'); + $path = Path::join ($this->config->get('site', 'path'), 'components', $name, $name . '.php'); $className = 'Component_' . $name; /*.Component.*/$component = null; @@ -235,26 +235,26 @@ class Component require_once ($path); $component = new $className(); - $component->viewPath = array(BASE_PATH . '/components/' . $name . '/'); - $component->webPath = array(SITE_WWW_PATH . '/components/' . $name); - $component->COMPONENTS_WEB = SITE_WWW_PATH . '/components/'; + $component->viewPath = array($this->config->get('site', 'path') . '/components/' . $name . '/'); + $component->webPath = array($this->config->get('site', 'web') . '/components/' . $name); + $component->COMPONENTS_WEB = $this->config->get('site', 'web') . '/components/'; } else { - $path = Path::join (COMPONENTS, $name, $name . '.php'); + $path = Path::join ($this->config->get('system', 'components'), $name, $name . '.php'); require_once ($path); $component = new $className(); - $component->viewPath = array(COMPONENTS . '/' . $name . '/', BASE_PATH . '/components/' . $name . '/'); + $component->viewPath = array($this->config->get('system', 'components') . '/' . $name . '/', $this->config->get('site', 'path') . '/components/' . $name . '/'); if (defined('COMPONENTS_WEB')) { - $component->webPath = array(COMPONENTS_WEB . '/' . $name, SITE_WWW_PATH . '/components/' . $name); - $component->COMPONENTS_WEB = COMPONENTS_WEB; + $component->webPath = array($this->config->get('system', 'components_web') . '/' . $name, $this->config->get('site', 'web') . '/components/' . $name); + $component->COMPONENTS_WEB = $this->config->get('system', 'components_web'); } } $db = $site->db; $component->db = $db; - $component->registry = $site->registry; + $component->config = $site->config; $component->site = $site; $stmt = $db->prepareStatement("SELECT * FROM component WHERE code = ?"); diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 5f243af..bc4096c 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -26,9 +26,9 @@ class Front extends Action /** * @param Settings $settings */ - public function __construct($db, $settings, $user, $default) { + public function __construct($db, $config, $user, $default) { parent::__construct(); - $this->settings = $settings; + $this->config = $config; $this->db = $db; $this->user = $user; $this->default = $default; @@ -50,11 +50,11 @@ class Front extends Action $module = $this->modules[$name]; return $module->access->execute($request); } + $config = $this->config; - /*.Settings.*/$system = $this->settings['system']; + $moulesPath = Path::join($config->get('system', 'path'), 'modules'); + $logPath = Path::join($config->get('site', 'path'), $config->get('system', 'access.log')); - $moulesPath = Path::join($this->settings['base'], $system->readKey(['path', 'modules'])); - $logPath = Path::join($this->settings['site'], $system->readKey(['path', 'access.log'])); $moduleFile = Path::join($moulesPath, $name, 'classes', $controller ? $controller : $name); $ucname = ucfirst($name); @@ -66,14 +66,14 @@ class Front extends Action $module->modulePath = $modPath; $module->name = $name; // - $module->settings = $this->settings; + $module->config = $this->config; $module->db = $this->db; $module->user = $this->user; // Ведение лога $logger = new ActionLogger($module, $logPath, $this->user); $logger->before = $this->loadSettings(Path::join($modPath, 'filter', 'logger.php')); // Управление доступом - $module->access = new ActionAccess($logger); + $module->access = new ActionAccess($logger, $this->user); $module->access->access = $this->loadSettings(Path::join($modPath, 'filter', 'access.php')); $module->setUp(); diff --git a/src/Controller/Installer.php b/src/Controller/Installer.php index a5a55fa..e544921 100644 --- a/src/Controller/Installer.php +++ b/src/Controller/Installer.php @@ -35,7 +35,7 @@ class Installer // Проверка версии обновления function isChanged($name) // Информация о модулях { - $item = $this->_registry->readKey(array($name)); + $item = $this->_registry->get('system', $name); if ($item) { $setup = $this->getSetupFile($name); if (file_exists($setup) && (filemtime($setup) > $item['time'])) { @@ -81,7 +81,7 @@ class Installer $settings = new Settings($setup); $settings->read(); - $item = $registry->readKey(array($name)); + $item = $registry->get('system', $name); $version_new = $settings->get('version'); if ($item) { @@ -101,8 +101,9 @@ class Installer // Обновление версии меню $registry->removeKey($name); - $registry->writeKey(array($name), $settings->get('settings')); - $registry->writeKey(array($name), + + $registry->set($name, $settings->get('settings')); + $registry->set($name, array('version' => $version_new, 'time' => filemtime($setup))); } diff --git a/src/Controller/Service.php b/src/Controller/Service.php index 26c81cc..fbcbb69 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -5,13 +5,14 @@ */ namespace ctiso\Controller; use ctiso\Path, + ctiso\Registry, ctiso\Database\PDOStatement; class Service { public $viewPath = []; public $webPath = []; - public $registry; // Registry->getInstance + public /*.Registry.*/$config; public $template; public $templatePath; public $COMPONENTS_WEB; @@ -33,7 +34,7 @@ class Service */ private function getModelPath($name) { - return Path::join (CMS_PATH, "model", $name . ".php"); + return Path::join ($this->config->get('system', 'path'), "model", $name . ".php"); } /** diff --git a/src/Controller/State.php b/src/Controller/State.php index 481faaf..225de1a 100644 --- a/src/Controller/State.php +++ b/src/Controller/State.php @@ -1,7 +1,8 @@ createStyles($doc); foreach ($this->table as $table) { - if ($table instanceof Excel_Table) { + if ($table instanceof Table) { $table->createTable($doc); } else { $table_data = call_user_func($table); diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 1861a36..5a1786f 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -4,7 +4,9 @@ * Клетка таблицы */ namespace ctiso\Excel; -use XMLWriter; +use XMLWriter, + ctiso\Excel\DateTime as Excel_DateTime, + ctiso\Excel\Number as Excel_Number; class TableCell { diff --git a/src/Filter/ActionAccess.php b/src/Filter/ActionAccess.php index da01325..c27b1b2 100644 --- a/src/Filter/ActionAccess.php +++ b/src/Filter/ActionAccess.php @@ -5,15 +5,18 @@ */ namespace ctiso\Filter; use ctiso\Filter\UserAccess, - ctiso\HttpRequest; + ctiso\HttpRequest, + ctiso\Role\User; class ActionAccess { public $access = array(); public $processor; + public /*.User.*/$user; - function __construct(/*.Filter.*/$processor) { + function __construct(/*.Filter.*/$processor, $user) { $this->processor = $processor; + $this->user = $user; } /** diff --git a/src/Filter/Authorization.php b/src/Filter/Authorization.php index 56ebc4d..0538eb2 100644 --- a/src/Filter/Authorization.php +++ b/src/Filter/Authorization.php @@ -5,38 +5,41 @@ namespace ctiso\Filter; class Authorization { const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#'; const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; + public $group; - static function isLogged($group = 'access') { + function __construct($group) { + $this->group = $group; + } + + function isLogged() { // echo session_status(); if (session_status() == PHP_SESSION_NONE) { session_start(); } $hash = self::getBrowserSign(); // Если $hash не совпадает $_SESSION['hash'] то удаляем сессию - if (isset($_SESSION[$group]) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { + if (isset($_SESSION[$this->group]) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { if ($hash == $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME]) { // UserAccess::getUserById($_SESSION ['access']); // Поиск по идентификатору return true; } else { - return false; + return false; } } return false; } - static function enter($id, $group = 'access') - { + function enter($id) { // $db->executeQuery("UPDATE visitor SET sid = '' WHERE id_visitor = " . $result->getInt('id_user')); // session_register("access"); // session_register("time"); -// $_SESSION ["group"] = $result->getInt('access'); - $_SESSION [$group] = $id; // id_user + $_SESSION [$this->group] = $id; $_SESSION [self::SESSION_BROWSER_SIGN_KEYNAME] = self::getBrowserSign(); - $_SESSION ["time"] = time(); + $_SESSION ["time"] = time(); } - private static function getBrowserSign() + static function getBrowserSign() { $rawSign = self::SESSION_BROWSER_SIGN_SECRET; // $signParts = array('HTTP_USER_AGENT', 'HTTP_ACCEPT_ENCODING'); @@ -48,7 +51,7 @@ class Authorization { return md5($rawSign); } - static function logout() { + function logout() { session_destroy(); } } diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 74f2259..7d976bd 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -13,6 +13,7 @@ use ctiso\Filter\Filter, ctiso\HttpRequest, ctiso\Settings, ctiso\Database, + ctiso\Role\User, ctiso\Collection; class Login extends Filter @@ -22,7 +23,7 @@ class Login extends Filter public $mode = 'ajax'; public $user; - public $role; + public /*.User.*/$role; public $whitelist; function __construct($processor, $role, $whitelist = []) { @@ -140,7 +141,7 @@ class Login extends Filter // Параметры при неправильной авторизации // Действия по умолчанию !! Возможно переход на форму регистрации if ($request->get('mode') == 'ajax') { - if (!$this->requestIsWhite($request, $this->whiteRequestList)) { + if (!$this->requestIsWhite($request, $this->whitelist)) { return json_encode(array('result' => 'fail', 'message' =>"NOT_AUTHORIZED")); } } else { diff --git a/src/Form/OptionFactory.php b/src/Form/OptionFactory.php index 42ae288..d0fd9e8 100644 --- a/src/Form/OptionFactory.php +++ b/src/Form/OptionFactory.php @@ -38,7 +38,7 @@ class OptionFactory { try { $query_result = $this->db->executeQuery("SELECT * FROM $table"); $field->options = $this->optionsDB($key, $value, $query_result); - } catch(Exception $ex) { + } catch(\Exception $ex) { $field->options = []; } } elseif (isset($input['options.pair'])) { diff --git a/src/Path.php b/src/Path.php index 803952e..5234e73 100644 --- a/src/Path.php +++ b/src/Path.php @@ -372,7 +372,7 @@ class Path */ public function getContent($allow = null, $ignore = array()) { - $ignore = array_merge(array(".", ".."), $ignore); + $ignore = array_merge(array(".", ".."), $ignore); return self::fileList($this->__toString(), $allow, $ignore); } diff --git a/src/Registry.php b/src/Registry.php new file mode 100644 index 0000000..552c086 --- /dev/null +++ b/src/Registry.php @@ -0,0 +1,40 @@ +namespace[$namespace] = [ + 'path' => $filePath, + 'data' => $data + ]; + } + + function importArray($namespace, $data = []) { + if (isset($this->namespace[$namespace])) { + $data = array_merge($this->namespace[$namespace]['data'], $data); + } + $this->namespace[$namespace] = [ + 'path' => null, + 'data' => $data + ]; + } + + public function get($ns, $key) { + return $this->namespace[$ns]['data'][$key]; + } + + public function has($ns, $key) { + return isset($this->namespace[$ns]['data'][$key]); + } + + function set($ns, $key, $value) { + $this->namespace[$ns]['data'][$key] = $value; + } +} diff --git a/src/Settings.php b/src/Settings.php index 4a677a8..5ea6a52 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -10,12 +10,12 @@ * Имя необходимо чтобы потом легко было удалить ненужные ветки дерева */ namespace ctiso; -use ctiso\Collection, - ctiso\File, +use ctiso\File, Exception; -class Settings extends Collection +class Settings { + public $data; protected $file; protected $format = 'php'; @@ -45,7 +45,8 @@ class Settings extends Collection if (!is_array($settings)) { throw new Exception($this->file); } - return $this->import($settings); + + $this->data = $settings; } /** @@ -175,11 +176,20 @@ class Settings extends Collection file_put_contents (($file) ? $file : $this->file, $result); } - /** - * Список модулей - */ - public function getModules() + public function set($key, $value) { + $this->data[$key] = $value; + } + + public function get($key, $default = null) { - return array_keys($this->data); + return isset($this->data[$key]) && $this->data[$key] != '' ? $this->data[$key] : $default; + } + + function export() { + return $this->data; + } + + function import($data) { + $this->data = $data; } } diff --git a/src/Tales.php b/src/Tales.php index c0e09d4..55bffc6 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -32,7 +32,7 @@ class Tales_Component implements PHPTAL_Tales } class Tales { - static $site; + static /*.Site.*/$site; static function phptal_date ($e) { return date("d.m.Y", $e); diff --git a/src/Url.php b/src/Url.php index 3b879ef..a7b16fd 100644 --- a/src/Url.php +++ b/src/Url.php @@ -4,7 +4,7 @@ namespace ctiso; class Url { public $parts = []; - public $parent; + public /*.Url.*/$parent; function __construct() { } diff --git a/src/Validator/Rule/Count.php b/src/Validator/Rule/Count.php index 71d60a9..ff030a4 100644 --- a/src/Validator/Rule/Count.php +++ b/src/Validator/Rule/Count.php @@ -30,7 +30,7 @@ class Count extends AbstractRule $count = count(array_filter(array_map('trim', explode(";", $container->get($this->field))), array($this, 'not_empty'))); - return $count >= $this->size && $count <= $this->max; + return $count >= $this->size && $count <= ((int)$this->max); } } diff --git a/src/View/Page.php b/src/View/Page.php index 4ccb457..d224fc2 100644 --- a/src/View/Page.php +++ b/src/View/Page.php @@ -2,7 +2,7 @@ namespace ctiso\View; use ctiso\View\View, - App\Controller\Site, + App\Controller\Site, /* Нужно импортровать интерфейс */ ctiso\Controller\Component, ctiso\HttpRequest; @@ -10,7 +10,7 @@ class Page extends View { private $counter; public $text; - public $site; + public /*.Site.*/$site; function __construct($data, $site) { @@ -55,8 +55,7 @@ class Page extends View function replaceContent($match, $offset) { - /*.Component.*/$component = null; - $component = $this->site->loadComponent($match); + /*.Component.*/$component = $this->site->loadComponent($match); $req = new HttpRequest(); unset($req['active_page']); diff --git a/src/View/Top.php b/src/View/Top.php index eb67c02..47d1a2c 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -29,7 +29,7 @@ class Top extends Composite { private function groupFiles(array $list, $debugMode = true) { $debug = ($debugMode) ? 'debug=1' : ''; - $path = parse_url(WWW_PATH, PHP_URL_PATH); + $path = parse_url($this->config->get('system', 'web'), PHP_URL_PATH); $groups = array(); $use = array(); @@ -120,7 +120,7 @@ class Top extends Composite { $this->set('deps', implode(",", array_values($this->require))); $this->set('title', $this->getTitle()); - $this->set('jspath', enableHttps(WWW_PATH)); + $this->set('jspath', enableHttps($this->config->get('system', 'web'))); // return $this->execute(); // execute+phptal ?? } diff --git a/src/WrongRequestException.php b/src/WrongRequestException.php index 6ebddfc..34863be 100644 --- a/src/WrongRequestException.php +++ b/src/WrongRequestException.php @@ -2,6 +2,6 @@ namespace ctiso; -class WrongRequestException extends Exception +class WrongRequestException extends \Exception { } From c2b9254fd0b1bab0c1525cc86c782214b9b243b7 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Mon, 23 Apr 2018 11:18:53 +0300 Subject: [PATCH 013/138] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D1=85=D0=BE=D0=B6?= =?UTF-8?q?=D0=B4=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B0=D0=B2=D1=82=D1=80=D0=B8?= =?UTF-8?q?=D0=B7=D0=B0=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 5 +++-- src/File.php | 2 +- src/Filter/ActionLogger.php | 1 + src/Model/Factory.php | 10 +++++----- src/Settings.php | 2 +- src/Url.php | 2 +- src/View/Composite.php | 4 ++-- src/View/Top.php | 2 +- src/View/View.php | 2 +- 9 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index be0dfb8..34137af 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -110,8 +110,8 @@ class Action { $file = $name . self::TEMPLATE_EXTENSION; - $basePath = $this->config->get('site', 'path'); - $webPath = $this->config->get('site', 'web'); + $basePath = $this->config->get('system', 'path'); + $webPath = $this->config->get('system', 'web'); $list = array( Path::join($this->modulePath, 'templates', $this->viewPathPrefix) => Path::join($webPath, "modules", $this->name, 'templates', $this->viewPathPrefix), @@ -125,6 +125,7 @@ class Action } /*.Composite.*/$tpl = new $viewClass($template); + $tpl->config = $this->config; $stylePath = Path::join($webPath, "assets", "css"); $iconsPath = Path::join($webPath, 'icons'); diff --git a/src/File.php b/src/File.php index 5de7429..c523cf6 100644 --- a/src/File.php +++ b/src/File.php @@ -5,7 +5,7 @@ use Exception; class File { static function getContents($filename) { - $buffer = file_get_contents($filename); + $buffer = @file_get_contents($filename); if ($buffer !== false) { return $buffer; } diff --git a/src/Filter/ActionLogger.php b/src/Filter/ActionLogger.php index 93c11e7..403d3b0 100644 --- a/src/Filter/ActionLogger.php +++ b/src/Filter/ActionLogger.php @@ -15,6 +15,7 @@ class ActionLogger function __construct(/*.Filter.*/$processor, $logPath, $user) { $this->processor = $processor; $this->user = $user; + $file = fopen($logPath, "a"); if (is_resource($file)) { $this->file = $file; diff --git a/src/Model/Factory.php b/src/Model/Factory.php index 2e57587..577b826 100644 --- a/src/Model/Factory.php +++ b/src/Model/Factory.php @@ -1,19 +1,19 @@ db = $db; - $this->_registry = $_registry; + $this->config = $config; } /** @@ -27,7 +27,7 @@ class Factory $model = new $modelName(); $model->db = $this->db; $model->factory = $this; - $model->_registry = $this->_registry; + $model->config = $this->config; $model->setUp(); // return $model; diff --git a/src/Settings.php b/src/Settings.php index 5ea6a52..4bd7ee5 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -15,7 +15,7 @@ use ctiso\File, class Settings { - public $data; + public $data = []; protected $file; protected $format = 'php'; diff --git a/src/Url.php b/src/Url.php index a7b16fd..5c824ab 100644 --- a/src/Url.php +++ b/src/Url.php @@ -22,6 +22,6 @@ class Url { } function toString() { - return '?' . http_build_query(array_merge($this->parts, $this->parent->parts)); + return '?' . http_build_query(array_merge($this->parts, $this->parent ? $this->parent->parts : [])); } } \ No newline at end of file diff --git a/src/View/Composite.php b/src/View/Composite.php index 8be63fc..ff659ef 100644 --- a/src/View/Composite.php +++ b/src/View/Composite.php @@ -11,6 +11,7 @@ use ctiso\View\View, class Composite extends View { private $tal; + public $config; function __construct($file) { @@ -18,7 +19,7 @@ class Composite extends View $this->tal = new PHPTAL($file); $this->tal->setPhpCodeDestination(PHPTAL_PHP_CODE_DESTINATION); - $this->tal->setEncoding(PHPTAL_DEFAULT_ENCODING); // PHPTAL_DEFAULT_ENCODING !! + $this->tal->setEncoding(PHPTAL_DEFAULT_ENCODING); $this->tal->setTemplateRepository(PHPTAL_TEMPLATE_REPOSITORY); $this->tal->setOutputMode(PHPTAL::HTML5); $this->tal->stripComments(true); @@ -39,7 +40,6 @@ class Composite extends View function execute() { parent::execute(); - // postProcess return $this->tal->execute(); } diff --git a/src/View/Top.php b/src/View/Top.php index 47d1a2c..08051f0 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -120,7 +120,7 @@ class Top extends Composite { $this->set('deps', implode(",", array_values($this->require))); $this->set('title', $this->getTitle()); - $this->set('jspath', enableHttps($this->config->get('system', 'web'))); + $this->set('jspath', $this->config->get('system', 'web')); // return $this->execute(); // execute+phptal ?? } diff --git a/src/View/View.php b/src/View/View.php index 5955112..ab8aff9 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -205,4 +205,4 @@ class View } return $result; } -} \ No newline at end of file +} From df00756a412f597e29f29b76203f39eb54809266 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Wed, 25 Apr 2018 14:50:45 +0300 Subject: [PATCH 014/138] =?UTF-8?q?=D0=98=D0=BD=D1=82=D0=B5=D1=80=D1=84?= =?UTF-8?q?=D0=B5=D0=B9=D1=81=20=D0=B2=D0=BC=D0=B5=D1=81=D1=82=D0=BE=20?= =?UTF-8?q?=D0=BA=D0=BB=D0=B0=D1=81=D1=81=D0=B0=20Site?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 6 +++--- src/Controller/SiteInterface.php | 11 +++++++++++ src/Registry.php | 5 ++++- src/Tales.php | 4 ++-- src/View/Page.php | 4 ++-- 5 files changed, 22 insertions(+), 8 deletions(-) create mode 100644 src/Controller/SiteInterface.php diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 7210d32..2204da8 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -13,7 +13,7 @@ use ctiso\HttpRequest, ctiso\Database\PDOStatement, ctiso\Collection, ctiso\Registry, - App\Controller\Site, + ctiso\Controller\SiteInterface, PHPTAL, PHPTAL_PreFilter_Normalize; @@ -209,7 +209,7 @@ class Component $view->component_title = $settings['title']; } - static function loadComponent($expression, /*.Site.*/ $site) + static function loadComponent($expression, /*.SiteInterface.*/ $site) { $expression = htmlspecialchars_decode($expression); @@ -251,7 +251,7 @@ class Component } } - $db = $site->db; + $db = $site->getDatabase(); $component->db = $db; $component->config = $site->config; diff --git a/src/Controller/SiteInterface.php b/src/Controller/SiteInterface.php new file mode 100644 index 0000000..205e5ea --- /dev/null +++ b/src/Controller/SiteInterface.php @@ -0,0 +1,11 @@ +namespace[$ns]['data'][$key]; + if (isset($this->namespace[$ns]['data'][$key])) { + return $this->namespace[$ns]['data'][$key]; + } + throw new Exception('Unknown key ' . $ns . '::' . $key); } public function has($ns, $key) { diff --git a/src/Tales.php b/src/Tales.php index 55bffc6..b6fc45a 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -5,7 +5,7 @@ */ namespace ctiso; use PHPTAL_Php_TalesInternal, - App\Controller\Site, + ctiso\Controller\SiteInterface, ctiso\Controller\Component, ctiso\HttpRequest, PHPTAL_Tales, @@ -32,7 +32,7 @@ class Tales_Component implements PHPTAL_Tales } class Tales { - static /*.Site.*/$site; + static /*.SiteInterface.*/$site; static function phptal_date ($e) { return date("d.m.Y", $e); diff --git a/src/View/Page.php b/src/View/Page.php index d224fc2..3591abe 100644 --- a/src/View/Page.php +++ b/src/View/Page.php @@ -2,7 +2,7 @@ namespace ctiso\View; use ctiso\View\View, - App\Controller\Site, /* Нужно импортровать интерфейс */ + ctiso\Controller\SiteInterface, ctiso\Controller\Component, ctiso\HttpRequest; @@ -10,7 +10,7 @@ class Page extends View { private $counter; public $text; - public /*.Site.*/$site; + public /*.SiteInterface.*/$site; function __construct($data, $site) { From 8065253db0831ce2542fc9ba1e879a93b3e04373 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Thu, 26 Apr 2018 12:31:43 +0300 Subject: [PATCH 015/138] =?UTF-8?q?OptionFactory=20=D0=B2=D1=8B=D0=BD?= =?UTF-8?q?=D0=B5=D1=81=20=D0=B2=20cms?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 4 +- src/Form/OptionFactory.php | 78 ------------------------------------ 2 files changed, 1 insertion(+), 81 deletions(-) delete mode 100644 src/Form/OptionFactory.php diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 7210d32..b520f09 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -7,7 +7,6 @@ use ctiso\HttpRequest, ctiso\Path, ctiso\File, ctiso\Form\Form, - ctiso\Form\OptionFactory, ctiso\View\Composite, ctiso\Database, ctiso\Database\PDOStatement, @@ -196,10 +195,9 @@ class Component /** * Генерация интерфейса для выбора галлереи фотографии */ - public function setParameters(/*.Composite.*/ $view) + public function setParameters(/*.Composite.*/ $view, $options = null) { $form = new Form(); - $options = new OptionFactory($this->db, $this->config); $settings = $this->getInfo(); $form->addFieldList($settings['parameter'], $options); diff --git a/src/Form/OptionFactory.php b/src/Form/OptionFactory.php deleted file mode 100644 index d0fd9e8..0000000 --- a/src/Form/OptionFactory.php +++ /dev/null @@ -1,78 +0,0 @@ -db = $db; - $this->registry = $registry; - } - - function create(Select $field, $input) { - if (isset($input['options.resid'])) { - $type = $input['options.resid']; - - $res = new Resources($this->db); - $field->options = $this->optionsArray('id_section', 'title', $res->getSubsections('', $type)); - - } else if (isset($input['options.res'])) { - $type = $input['options.res']; - - $res = new Resources($this->db); - $field->options = $this->optionsArray('path', 'title', $res->getSubsections('', $type)); - - } else if (isset($input['options.all_res'])) { - $type = $input['options.all_res']; - - $res = new Resources($this->db); - $field->options = $this->optionsArray('id_resource', 'subtitle', $res->getAllResource($type)); - - } else if (isset($input['options.db'])) { - list($table, $keyvalue) = explode(":", $input['options.db']); - list($key, $value) = explode(",", $keyvalue); - try { - $query_result = $this->db->executeQuery("SELECT * FROM $table"); - $field->options = $this->optionsDB($key, $value, $query_result); - } catch(\Exception $ex) { - $field->options = []; - } - } elseif (isset($input['options.pair'])) { - $field->options = $this->optionsPair($input['options.pair']); - } elseif (isset($input['options.model'])) { - $factory = new Factory($this->db, $this->registry); - $model = $factory->getModel($input['options.model']); - $field->options = $model->getAllAsOptions(); - } else { - $field->options = $input['options']; - } - } - - public function optionsDB($key, $val, $res) { - $result = array(); - while($res->next()) { - $result[] = array('value' => $res->getInt($key), 'name' => $res->getString($val)); - } - return $result; - } - - public function optionsArray($key, $val, $res) { - $result = array(); - foreach($res as $item) { - $result[] = array('value' => $item->{$key}, 'name' => $item->{$val}); - } - return $result; - } - - public function optionsPair($list, $selected = false) { - $result = array(); - foreach ($list as $key => $value) { - $result [] = array('value' => $key, 'name' => $value, 'selected' => $key == $selected); - } - return $result; - } -} From 40f40a8d6ddeda416bc945022efeb30dae7d5257 Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Sat, 28 Apr 2018 14:13:19 +0300 Subject: [PATCH 016/138] =?UTF-8?q?=D0=9F=D0=BE=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BE=D0=BF=D1=80=D0=B5=D0=B4=D0=B5=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D0=BD=D0=B0=D0=B7=D0=B2=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 7 ++----- src/Form/BrowserInput.php | 6 ++++++ src/Form/Form.php | 31 ++++++++++++++----------------- 3 files changed, 22 insertions(+), 22 deletions(-) create mode 100644 src/Form/BrowserInput.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 34137af..a86511b 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -219,11 +219,8 @@ class Action $url = new Url(); if ($access == null || $access->checkAction($name)) { - $param = array_merge(array( - 'module' => strtr($this->modulePrefix . strtolower(get_class($this)), array('module_' => '')), - "action" => $name - - ), $param); + $moduleName = explode("\\", strtolower(get_class($this)), 2); + $param = array_merge(array('module' => $this->modulePrefix . $moduleName[1], "action" => $name), $param); $url->setParent($this->part); $url->setQuery($param); diff --git a/src/Form/BrowserInput.php b/src/Form/BrowserInput.php new file mode 100644 index 0000000..f6e1e69 --- /dev/null +++ b/src/Form/BrowserInput.php @@ -0,0 +1,6 @@ +constructor = array( - 'input' => 'Form_Input', - 'inputreq' => 'Form_Input', // input с проверкой на заполненность + 'input' => 'ctiso\\Form\\Input', + 'inputreq' => 'ctiso\\Form\\Input', // input с проверкой на заполненность - 'date' => 'Form_Date', - 'datereq' => 'Form_Date', + 'date' => 'ctiso\\Form\\Date', + 'datereq' => 'ctiso\\Form\\Date', 'datetime' => 'TDateTime', - 'color' => 'Form_Color', - 'textarea' => 'Form_TextArea', - 'text' => 'Form_TextArea', - 'multiselect' => 'Form_SelectMany', + 'color' => 'ctiso\\Form\\Color', + 'textarea' => 'ctiso\\Form\\TextArea', + 'text' => 'ctiso\\Form\\TextArea', + 'multiselect' => 'ctiso\\Form\\SelectMany', // 'selectmany' => 'TSelectMany', - 'select1' => 'Form_SelectOne', - 'select' => 'Form_SelectOne', + 'select1' => 'ctiso\\Form\\SelectOne', + 'select' => 'ctiso\\Form\\SelectOne', 'questiontype'=> 'TQuestionType', 'secret' => 'TSecret', 'upload' => 'TUpload', 'image' => 'TUpload', 'checkbox' => 'TCheckbox', - 'checkmany' => 'Form_SelectMany', + 'checkmany' => 'ctiso\\Form\\SelectMany', 'hidden' => 'THidden', - 'radio' => 'Form_SelectOne', - 'filebrowser' => 'TComponentBrowserInput', - 'documents' => 'TComponentBrowserInput', + 'radio' => 'ctiso\\Form\\SelectOne', + 'filebrowser' => 'ctiso\\Form\\BrowserInput', + 'documents' => 'ctiso\\Form\\BrowserInput', ); } From 11370eecc90b26913df208510f4d7434b6e4e72f Mon Sep 17 00:00:00 2001 From: "CORP\\phedor" Date: Fri, 4 May 2018 14:57:52 +0300 Subject: [PATCH 017/138] =?UTF-8?q?=D0=9F=D0=BE=D1=81=D1=82=D1=84=D0=B8?= =?UTF-8?q?=D0=BA=D1=81=D0=BD=D0=B0=D1=8F=20=D0=B7=D0=B0=D0=BF=D0=B8=D1=81?= =?UTF-8?q?=D1=8C=20=D1=82=D0=B8=D0=BF=D0=BE=D0=B2=20=D0=B2=D0=BC=D0=B5?= =?UTF-8?q?=D1=81=D1=82=D0=BE=20=D0=BF=D1=80=D0=B5=D1=84=D0=B8=D0=BA=D1=81?= =?UTF-8?q?=D0=BD=D0=BE=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Collection.php | 2 +- src/Controller/Action.php | 12 ++++++------ src/Controller/Component.php | 24 ++++++++++++------------ src/Controller/Request.php | 2 +- src/Controller/Service.php | 4 ++-- src/Database.php | 12 ++++++------ src/Database/JsonInstall.php | 2 +- src/Database/Manager.php | 14 +++++++------- src/Database/Statement.php | 4 ++-- src/Database/StatementIterator.php | 2 +- src/Excel/Document.php | 2 +- src/Excel/Table.php | 12 ++++++------ src/Filter/ActionAccess.php | 4 ++-- src/Filter/ActionLogger.php | 7 ++++--- src/Filter/Filter.php | 2 +- src/Filter/Login.php | 2 +- src/Form/Field.php | 2 +- src/Functions.php | 8 ++++---- src/HttpRequest.php | 2 +- src/Layout/Manager.php | 4 ++-- src/MailAlt.php | 2 +- src/Path.php | 4 ++-- src/Role/User.php | 6 +++++- src/Role/UserInterface.php | 11 +++++++++++ src/Setup.php | 6 +++--- src/Tales.php | 4 ++-- src/Tools/SQLStatementExtractor.php | 2 +- src/Tools/TemplateImage.php | 2 +- src/Url.php | 2 +- src/Validator/Validator.php | 4 ++-- src/View/Page.php | 4 ++-- src/View/Pages.php | 2 +- src/View/Top.php | 2 +- 33 files changed, 95 insertions(+), 79 deletions(-) create mode 100644 src/Role/UserInterface.php diff --git a/src/Collection.php b/src/Collection.php index 1f977ee..ccc60cf 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -42,7 +42,7 @@ class Collection implements \ArrayAccess * * @return void */ - public function set(/*.string.*/$key, /*.any.*/$value) + public function set($key/*: string*/, $value/*: any*/) { $this->data[$key] = $value; } diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 34137af..d365a49 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -47,8 +47,8 @@ class Action private $helpers = array(); // Помошники для действий public $part = null; // Параметры для ссылки - public /*.Registry.*/$config; // Ссылка на настройки - public /*.User.*/$user; // Обьект пользователя + public $config/*: Registry*/; // Ссылка на настройки + public $user/*: User*/; // Обьект пользователя // Для Widgets public $view = null; @@ -124,7 +124,7 @@ class Action if(file_exists($template)) { break; } } - /*.Composite.*/$tpl = new $viewClass($template); + $tpl/*: Composite*/ = new $viewClass($template); $tpl->config = $this->config; $stylePath = Path::join($webPath, "assets", "css"); @@ -215,7 +215,7 @@ class Action */ public function nUrl($name, array $param = array()) { - /*.ActionAccess.*/$access = $this->access; + $access/*: ActionAccess*/ = $this->access; $url = new Url(); if ($access == null || $access->checkAction($name)) { @@ -334,7 +334,7 @@ class Action if ($view instanceof View) { $this->view->assignValues($this->ctrlValues); - /*.Composite.*/$node = null; + $node/*: Composite*/ = null; foreach ($this->childNodes as $name => $node) { $node->make($this); $this->view->setView($name, $node->view); @@ -373,7 +373,7 @@ class Action $this->_getActionPath()->getPath($this, ($action) ? $action : $request->getAction()); } - function redirect(/*.string.*/$action) { + function redirect($action/*: string*/) { header('location: ' . $action); exit(); } diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 30d1904..655fbd5 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -49,9 +49,9 @@ class Component public $COMPONENTS_WEB; - public /*.Registry.*/$config; - public /*.Database.*/$db; - public /*.Collection.*/$parameter; + public $config/*: Registry*/; + public $db/*: Database*/; + public $parameter/*: Collection*/; public $output = 'html'; @@ -94,7 +94,7 @@ class Component return new FakeTemplate($name); } - /*.Registry.*/$config = $this->config; + $config/*: Registry*/ = $this->config; $default = $config->get('site', 'template'); $template = ($this->template) ? $this->template : $default; @@ -157,7 +157,7 @@ class Component return $model; } - public function options($key, $val, /*.PDOStatement.*/$res) { + public function options($key, $val, $res/*: PDOStatement*/) { $result = array(); while($res->next()) { $result[] = array('value' => $res->getString($key), 'name' => $res->getString($val)); @@ -195,7 +195,7 @@ class Component /** * Генерация интерфейса для выбора галлереи фотографии */ - public function setParameters(/*.Composite.*/ $view, $options = null) + public function setParameters($view/*: Composite*/, $options = null) { $form = new Form(); @@ -207,7 +207,7 @@ class Component $view->component_title = $settings['title']; } - static function loadComponent($expression, /*.SiteInterface.*/ $site) + static function loadComponent($expression, $site/*: SiteInterface*/) { $expression = htmlspecialchars_decode($expression); @@ -227,7 +227,7 @@ class Component $path = Path::join ($this->config->get('site', 'path'), 'components', $name, $name . '.php'); $className = 'Component_' . $name; - /*.Component.*/$component = null; + $component/*: Component*/ = null; if (file_exists($path)) { require_once ($path); @@ -297,12 +297,12 @@ class Component return null; } - function raw_query(/*.ComponentRequest.*/ $request) + function raw_query($request/*: ComponentRequest*/) { $arr = $request->r->export('get'); $param = array(); - /*.Collection.*/$parameter = $this->parameter; + $parameter/*: Collection*/ = $this->parameter; foreach($parameter->export() as $key => $value) { $param[$key] = $value; } @@ -320,7 +320,7 @@ class Component } - function query(/*.ComponentRequest.*/ $request, $list) + function query($request/*: ComponentRequest*/, $list) { $arr = $request->r->export('get'); @@ -336,6 +336,6 @@ class Component $this->site->addRequireJsPath($name, $path, $shim); } - function actionIndex(/*.ComponentRequest.*/ $request) { + function actionIndex($request/*: ComponentRequest*/) { } } diff --git a/src/Controller/Request.php b/src/Controller/Request.php index e67ed7d..b9e77e9 100644 --- a/src/Controller/Request.php +++ b/src/Controller/Request.php @@ -7,7 +7,7 @@ class Request { public $r; public $id; - function __construct(/*.HttpRequest.*/$request, $id) { + function __construct($request/*: HttpRequest*/, $id) { $this->r = $request; $this->id = $id; } diff --git a/src/Controller/Service.php b/src/Controller/Service.php index fbcbb69..4992e50 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -12,7 +12,7 @@ class Service { public $viewPath = []; public $webPath = []; - public /*.Registry.*/$config; + public $config/*: Registry*/; public $template; public $templatePath; public $COMPONENTS_WEB; @@ -51,7 +51,7 @@ class Service return $model; } - public function options($key, $val, /*.PDOStatement.*/$res) { + public function options($key, $val, $res/*: PDOStatement*/) { $result = array(); while($res->next()) { $result[] = array('value' => $res->getInt($key), 'name' => $res->getString($val)); diff --git a/src/Database.php b/src/Database.php index 9ac4c6d..ebf717c 100644 --- a/src/Database.php +++ b/src/Database.php @@ -44,13 +44,13 @@ class Database extends PDO if ($dsn['phptype'] == 'pgsql' || $dsn['phptype'] == 'mysql') { $port = (isset($dsn['port'])) ? "port={$dsn['port']};" : ""; - /*.Database.*/$connection = new static("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']); + $connection/*: Database*/ = new static("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']); if ($dsn['phptype'] == 'pgsql') { $connection->query('SET client_encoding="UTF-8"'); } } if ($dsn['phptype'] == 'sqlite') { - /*.Database.*/$connection = new static("{$dsn['phptype']}:{$dsn['database']}"); + $connection/*: Database*/ = new static("{$dsn['phptype']}:{$dsn['database']}"); $connection->setAttribute(PDO::ATTR_TIMEOUT, 5); $mode = defined('SQLITE_JOURNAL_MODE') ? SQLITE_JOURNAL_MODE : 'WAL'; $connection->query("PRAGMA journal_mode=$mode"); @@ -62,7 +62,7 @@ class Database extends PDO public function executeQuery($query, $values=null) { - /*.PDOStatement.*/$stmt = $this->prepare($query); + $stmt/*: PDOStatement*/ = $this->prepare($query); $stmt->execute($values); $stmt->cache = $stmt->fetchAll(PDO::FETCH_ASSOC); @@ -80,7 +80,7 @@ class Database extends PDO */ public function fetchAllArray($query, $values = null) { - /*.PDOStatement.*/$sth = $this->prepare($query); + $sth/*: PDOStatement*/ = $this->prepare($query); $prep = $this->prepareValues($values); $sth->execute($prep); return $sth->fetchAll(PDO::FETCH_ASSOC); @@ -91,7 +91,7 @@ class Database extends PDO */ public function fetchOneArray($query, $values = null) { - /*.PDOStatement.*/$sth = $this->prepare($query); + $sth/*: PDOStatement*/ = $this->prepare($query); $prep = $this->prepareValues($values); $sth->execute($prep); return $sth->fetch(PDO::FETCH_ASSOC); @@ -182,7 +182,7 @@ class Database extends PDO } function prepare($query, $options = NULL) { - /*.PDOStatement.*/$result = parent::prepare($query); + $result/*: PDOStatement*/ = parent::prepare($query); return $result; } diff --git a/src/Database/JsonInstall.php b/src/Database/JsonInstall.php index 0395427..6acb9b7 100644 --- a/src/Database/JsonInstall.php +++ b/src/Database/JsonInstall.php @@ -43,7 +43,7 @@ class JsonInstall { } //Создать таблицы - function initDataBase(/*.array.*/$initActions, $dbinit_path) { + function initDataBase($initActions/*: array*/, $dbinit_path) { $pg = $this->db_manager->db->isPostgres(); if (!$pg) { $refs = []; diff --git a/src/Database/Manager.php b/src/Database/Manager.php index a0e46a5..354a722 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -8,13 +8,13 @@ use ctiso\Database, class Manager { - public /*.Database.*/$db; + public $db/*: Database*/; function __construct(Database $db) { $this->db = $db; } - public function ExecuteAction(/*.array.*/$action, $db_file = "") { + public function ExecuteAction($action/*: array*/, $db_file = "") { switch($action["type"]) { case "dropTable": $this->DropTableQuery($action["table_name"], true); @@ -100,7 +100,7 @@ class Manager return; } - /*.array.*/$data = $this->DumpTable($table); + $data/*: array*/ = $this->DumpTable($table); $this->db->query("ALTER TABLE ".$table." RENAME TO ".$tmp_table.";"); $table_info[$new_name] = $table_info[$old_name]; @@ -147,7 +147,7 @@ class Manager $this->db->query($q); } - function getConstraintDef(/*.array.*/$c) { + function getConstraintDef($c/*: array*/) { if ($c['type'] == 'unique') { return "UNIQUE(" . implode(", ", $c['fields']) . ")"; } @@ -175,8 +175,8 @@ class Manager public function DumpTable($table_name) { $pg = $this->db->isPostgres(); - /*.array.*/$result = array(); - /*.array.*/$data = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); + $result/*: array*/ = array(); + $data/*: array*/ = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); if (!$pg) { $table_fields = $this->TableInfo($table_name); @@ -184,7 +184,7 @@ class Manager $type = strtolower($value['type']); if ($type == "boolean") { foreach ($data as &$row) { - /*.array.*/$row = $row; + $row/*: array*/ = $row; if (isset($row[$name])) { $row[$name] = boolval($row[$name]); } diff --git a/src/Database/Statement.php b/src/Database/Statement.php index f47278f..b25b008 100644 --- a/src/Database/Statement.php +++ b/src/Database/Statement.php @@ -16,7 +16,7 @@ class Statement protected $conn; protected $query; - function __construct($query, /*.Database.*/ $conn) { + function __construct($query, $conn/*: Database*/) { $this->query = $query; $this->conn = $conn; } @@ -51,7 +51,7 @@ class Statement if ($this->limit) { $this->query .= " LIMIT {$this->limit} OFFSET {$this->offset}"; } - /*.PDOStatement.*/$stmt = $this->conn->prepare($this->query); + $stmt/*: PDOStatement*/ = $this->conn->prepare($this->query); foreach ($this->binds as $bind) { list($n, $value, $type) = $bind; $stmt->bindValue($n, $value, (int) $type); diff --git a/src/Database/StatementIterator.php b/src/Database/StatementIterator.php index 6286a6d..aad0c90 100644 --- a/src/Database/StatementIterator.php +++ b/src/Database/StatementIterator.php @@ -11,7 +11,7 @@ class StatementIterator implements \Iterator private $fetchmode; private $row_count; - public function __construct(/*.PDOStatement.*/ $rs) { + public function __construct($rs/*: PDOStatement*/) { $this->result = $rs; $this->row_count = $rs->getRecordCount(); } diff --git a/src/Excel/Document.php b/src/Excel/Document.php index eba0654..dff1c3b 100644 --- a/src/Excel/Document.php +++ b/src/Excel/Document.php @@ -43,7 +43,7 @@ class Document { if ($type == 'Borders') { $doc->startElement('Borders'); foreach ($s as $border) { - /*.array.*/$border = $border; + $border/*: array*/ = $border; $doc->startElement('Border'); foreach ($border as $key => $value) { $doc->writeAttribute('ss:' . $key, $value); diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 5a1786f..7754aa1 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -69,7 +69,7 @@ class Table if(! isset($this->rows[$x])) { $this->rows[$x] = new TableRow(); } - /*.TableRow.*/$row = $this->rows[$x]; + $row/*: TableRow*/ = $this->rows[$x]; $row->setCell($y, $value); } @@ -123,7 +123,7 @@ class Table assert(is_numeric($x) && $x > 0); assert(is_numeric($cell) && $cell > 0); - /*.TableRow.*/$row = $this->rows[$x]; + $row/*: TableRow*/ = $this->rows[$x]; $row->cells[$cell]->merge = $merge; } @@ -158,7 +158,7 @@ class Table */ function getRows() { - /*.array.*/$keys = array_keys($this->rows); + $keys/*: array*/ = array_keys($this->rows); return max($keys); } @@ -169,7 +169,7 @@ class Table */ function getRowCells(TableRow $row) { - /*.array.*/$keys = array_keys($row->cells); + $keys/*: array*/ = array_keys($row->cells); return max($keys); } @@ -207,7 +207,7 @@ class Table /** * Генерация клетки таблицы (Переработать) */ - function createCell (TableCell $ncell, XMLWriter $doc, $j, /*.any.*/$value, $setIndex) { + function createCell (TableCell $ncell, XMLWriter $doc, $j, $value/*: any*/, $setIndex) { $doc->startElement("Cell"); if ($ncell->style) { @@ -267,7 +267,7 @@ class Table $doc->writeAttribute('ss:Height', $this->rows[$i]->height); } - /*.TableRow.*/$nrow = $this->rows[$i]; + $nrow/*: TableRow*/ = $this->rows[$i]; // Флаг индикатор подстановки номера столбца $setIndex = false; for ($j = 1; $j <= $columns; $j++) { diff --git a/src/Filter/ActionAccess.php b/src/Filter/ActionAccess.php index c27b1b2..4fabc60 100644 --- a/src/Filter/ActionAccess.php +++ b/src/Filter/ActionAccess.php @@ -12,9 +12,9 @@ class ActionAccess { public $access = array(); public $processor; - public /*.User.*/$user; + public $user/*: User*/; - function __construct(/*.Filter.*/$processor, $user) { + function __construct($processor/*: Filter*/, $user) { $this->processor = $processor; $this->user = $user; } diff --git a/src/Filter/ActionLogger.php b/src/Filter/ActionLogger.php index 403d3b0..09f497c 100644 --- a/src/Filter/ActionLogger.php +++ b/src/Filter/ActionLogger.php @@ -1,7 +1,8 @@ processor = $processor; $this->user = $user; @@ -27,7 +28,7 @@ class ActionLogger function execute(HttpRequest $request) { $action = $request->getAction(); if(in_array($action, $this->before)) { - $message = ["time" => date("r", time()), "query" => array_merge($_POST, $_GET), "user" => $this->user->name]; + $message = ["time" => date("r", time()), "query" => array_merge($_POST, $_GET), "user" => $this->user->getName()]; fwrite($this->file, json_encode($message) . "\n"); } return $this->processor->execute($request); diff --git a/src/Filter/Filter.php b/src/Filter/Filter.php index 864e898..156d4e0 100644 --- a/src/Filter/Filter.php +++ b/src/Filter/Filter.php @@ -11,7 +11,7 @@ use ctiso\Controller\Action, class Filter { public $processor; - public function __construct(/*.Action.*/$processor) + public function __construct($processor/*: Action*/) { $this->processor = $processor; } diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 7d976bd..4362bc7 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -23,7 +23,7 @@ class Login extends Filter public $mode = 'ajax'; public $user; - public /*.User.*/$role; + public $role/*: User*/; public $whitelist; function __construct($processor, $role, $whitelist = []) { diff --git a/src/Form/Field.php b/src/Form/Field.php index 1e1dd47..83a23ea 100644 --- a/src/Form/Field.php +++ b/src/Form/Field.php @@ -40,7 +40,7 @@ class Field } } - function setValue(/*.any.*/$value) + function setValue($value/*: any*/) { $this->value = $value; } diff --git a/src/Functions.php b/src/Functions.php index fc1d5a8..be161bc 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -226,7 +226,7 @@ class Functions { * * @return mixed */ - static function key_values($key, /*array|ArrayIterator*/ $array) { + static function key_values($key, $array/*: array|ArrayIterator*/) { $result = array(); foreach($array as $item) { @@ -235,7 +235,7 @@ class Functions { return $result; } - static function key_values_object($key, /*array|ArrayIterator*/ $array) { + static function key_values_object($key, $array/*: array|ArrayIterator*/) { $result = array(); foreach($array as $item) { @@ -260,7 +260,7 @@ class Functions { return $result; } - static function _get($key, /*.any.*/$value, /*.array.*/$array) { + static function _get($key, $value/*: any*/, $array/*: array*/) { foreach ($array as $item) { if ($item[$key] == $value) return $item; } @@ -373,7 +373,7 @@ class Functions { * Преобразует ключи элементов для многомерного массива * @return mixed */ - static function hash_key ($key_name,/*. array .*/ $array) { + static function hash_key ($key_name,$array/*: array */) { $result = array(); foreach($array as $value) { diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 5e1b519..05c435e 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -56,7 +56,7 @@ class HttpRequest extends Collection implements ArrayAccess return $this->_session; } - function set($key, /*.any.*/$value) + function set($key, $value/*: any*/) { return parent::get('data')->set($key, $value); } diff --git a/src/Layout/Manager.php b/src/Layout/Manager.php index 884fb3b..e843219 100644 --- a/src/Layout/Manager.php +++ b/src/Layout/Manager.php @@ -35,7 +35,7 @@ class Manager extends Filter $this->addCondition(Functions::rcurry(array($this, 'checkXHR'), $get), $layout); } - public function checkGet(/*.HttpRequest.*/$request, $get) + public function checkGet($request/*: HttpRequest*/, $get) { if (is_array($get)) { foreach ($get as $key => $value) { @@ -47,7 +47,7 @@ class Manager extends Filter return true; } - public function checkXHR(/*.HttpRequest.*/$request, $get) + public function checkXHR($request/*: HttpRequest*/, $get) { return $request->isAjax() && $this->checkGet($request, $get); } diff --git a/src/MailAlt.php b/src/MailAlt.php index 138ae94..753dedf 100644 --- a/src/MailAlt.php +++ b/src/MailAlt.php @@ -51,7 +51,7 @@ class MailAlt /** * Тема письма */ - function subject(/*.string.*/$subject) + function subject($subject/*: string*/) { $this->mailer->Subject = $subject; } diff --git a/src/Path.php b/src/Path.php index 5234e73..1918571 100644 --- a/src/Path.php +++ b/src/Path.php @@ -160,7 +160,7 @@ class Path } // Сравнение двух путей на равентство - public function equal(/*.Path.*/ $path) + public function equal($path/*: Path*/) { $count = count($this->path); if ($count == count($path->path)) { @@ -205,7 +205,7 @@ class Path * * @return boolean */ - public function isParent(/*.Path.*/ $path) + public function isParent($path/*: Path*/) { if (isset($this->url['host']) && isset($path->url['host']) && ($this->url['host'] != $path->url['host'])) return false; diff --git a/src/Role/User.php b/src/Role/User.php index f199363..8d3e892 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -5,7 +5,7 @@ use ctiso\Database, ctiso\Database\Statement; // Класс должен быть в библиотеке приложения -class User +class User implements UserInterface { const LIFE_TIME = 1800; // = 30min * 60sec; @@ -26,6 +26,10 @@ class User $this->db = $db; } + public function getName() { + return $this->name; + } + public function getUserByQuery(Statement $stmt) { $result = $stmt->executeQuery(); diff --git a/src/Role/UserInterface.php b/src/Role/UserInterface.php new file mode 100644 index 0000000..778394d --- /dev/null +++ b/src/Role/UserInterface.php @@ -0,0 +1,11 @@ +stack[count($this->stack) - 1]; + $item/*: \SimpleXMLElement*/ = $this->stack[count($this->stack) - 1]; $root = $item->children(); foreach ($root as $node) { @@ -200,7 +200,7 @@ class Setup /** * Выполнение Списка SQL команд */ - function batchSQLZip(/*.Database.*/ $conn, $file) + function batchSQLZip($conn/*: Database*/, $file) { $stmtList = SQLStatementExtractor::extract($this->zip->getFromName($file)); foreach ($stmtList as $stmt) { @@ -208,7 +208,7 @@ class Setup } } - static function batchSQL(/*.Database.*/ $conn, $file) + static function batchSQL($conn/*: Database*/, $file) { $stmtList = SQLStatementExtractor::extractFile($file); foreach ($stmtList as $stmt) { diff --git a/src/Tales.php b/src/Tales.php index b6fc45a..90ce298 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -32,7 +32,7 @@ class Tales_Component implements PHPTAL_Tales } class Tales { - static /*.SiteInterface.*/$site; + static $site/*: SiteInterface*/; static function phptal_date ($e) { return date("d.m.Y", $e); @@ -47,7 +47,7 @@ class Tales { */ static function phptal_component ($expression) { $begin = floatval(microtime(true)); - /*.Component.*/$component = null; + $component/*: Component*/ = null; $component = self::$site->loadComponent($expression); $req = new HttpRequest(); diff --git a/src/Tools/SQLStatementExtractor.php b/src/Tools/SQLStatementExtractor.php index dd4df20..d6acd15 100644 --- a/src/Tools/SQLStatementExtractor.php +++ b/src/Tools/SQLStatementExtractor.php @@ -124,7 +124,7 @@ class SQLStatementExtractor { * @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. */ - protected static function endsWith(/*.string.*/$check, $string) { + protected static function endsWith($check/*: string*/, $string) { if ($check === "" || $check === $string) { return true; } else { diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index fad2434..8dbb21e 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -122,7 +122,7 @@ class TemplateImage return ""; } - function imageText($text, /*.\stdClass.*/$value) + function imageText($text, $value/*: \stdClass*/) { assert(is_string($text)); diff --git a/src/Url.php b/src/Url.php index 5c824ab..f4393b0 100644 --- a/src/Url.php +++ b/src/Url.php @@ -4,7 +4,7 @@ namespace ctiso; class Url { public $parts = []; - public /*.Url.*/$parent; + public $parent/*: Url*/; function __construct() { } diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index ed36f7f..0529662 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -74,7 +74,7 @@ class Validator } } - public function addRule(/*.any.*/$rule) { + public function addRule($rule/*: any*/) { if (is_array($rule)) { $this->chain = array_merge($this->chain, $rule); } else { @@ -82,7 +82,7 @@ class Validator } } - public function skip(/*.AbstractRule.*/$rule, /*.Collection.*/$container) // -> Rule_Abstract + public function skip($rule/*: AbstractRule*/, $container/*: Collection*/) // -> Rule_Abstract { if ($rule->skipEmpty()) { $data = $container->get($rule->field); diff --git a/src/View/Page.php b/src/View/Page.php index 3591abe..ec6b8f8 100644 --- a/src/View/Page.php +++ b/src/View/Page.php @@ -10,7 +10,7 @@ class Page extends View { private $counter; public $text; - public /*.SiteInterface.*/$site; + public $site/*: SiteInterface*/; function __construct($data, $site) { @@ -55,7 +55,7 @@ class Page extends View function replaceContent($match, $offset) { - /*.Component.*/$component = $this->site->loadComponent($match); + $component/*: Component*/ = $this->site->loadComponent($match); $req = new HttpRequest(); unset($req['active_page']); diff --git a/src/View/Pages.php b/src/View/Pages.php index 8eb0767..1bba197 100644 --- a/src/View/Pages.php +++ b/src/View/Pages.php @@ -33,7 +33,7 @@ class Pages * @param $onpage int количество элем на странице * @return string */ - static function getLimit(/*.number.*/$page, /*.number.*/$onpage) { + static function getLimit($page/*: number*/, $onpage/*: number*/) { if ($page <= 0) { $page = 1; } return "LIMIT $onpage OFFSET " . ($page - 1) * $onpage; } diff --git a/src/View/Top.php b/src/View/Top.php index 08051f0..b3fd768 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -102,7 +102,7 @@ class Top extends Composite { $init = array(); foreach($s->_section as $key => $item) { - /*.View.*/$ss = $item; + $ss/*: View*/ = $item; if ($ss->codeGenerator !== null) { // функцию которая вычисляет а не результат $part = call_user_func($ss->codeGenerator, $this, $key, $value); From 6a9ef3534b4240c121542303cb2fadfee8459d83 Mon Sep 17 00:00:00 2001 From: anatoly Date: Tue, 28 Jun 2022 15:57:41 +0300 Subject: [PATCH 018/138] =?UTF-8?q?=D0=A2=D0=B5=D0=BF=D0=B5=D1=80=D1=8C=20?= =?UTF-8?q?=D0=BC=D0=BE=D0=B6=D0=BD=D0=BE=20=D0=B4=D0=B5=D0=BB=D0=B0=D1=82?= =?UTF-8?q?=D1=8C=20=D1=82=D0=B0=D0=BA:=20curl=20-d=20'login=3Dmanager&pas?= =?UTF-8?q?sword=3D1'=20-X=20POST=20http://10.1.1.1:8090/sites/demo/admin/?= =?UTF-8?q?=3Faction=3Dapi=5Fkey?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit С полученным ключом будут доступны команды, прописанные в json-ке как доступные с ключом --- src/Filter/Login.php | 114 +++++++++++++++++++++++++++++++++---------- src/Security.php | 6 ++- 2 files changed, 92 insertions(+), 28 deletions(-) diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 4a993a1..64529d1 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -14,10 +14,40 @@ class Filter_Login extends Filter_Filter const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; public $mode = 'ajax'; public $user; + /* + * Проверка пары логин/пароль + */ + public function checkLoginPasswordPair($db, $login, $password) + { + $result = Filter_UserAccess::getUserByLogin($login); // Поиск по логину + if ($result) { + $userPassword = $result->getString('password'); + if (Filter_UserAccess::$access == 'site_root' && defined('PARENT_PATH')) { + $s = new Settings(PARENT_PATH . '/settings.json'); + $s->read(); + $dsn = $s->readKey(array('system', 'dsn')); + $db = Database::getConnection($dsn); + $user = $db->fetchOneArray("SELECT * FROM users WHERE login = :login", ['login' => $login]); + $userPassword = $user['password']; + } /*else if (time() - $result->getInt('lastupdate') > 60*60*24*60) { + // Проверить давность пароля, 60 дней + $request->set('error', true); + $request->set('lastupdate', true); + return false; + }*/ + + // Извлечение пользователя из родительской CMS, для проверки пароля + if (md5($password) == $userPassword) { // password + $this->enter($db, $result); + return true; + } + } + return false; + } /** * Проверка авторизации - * @return Boolean Авторизовани пользователь или нет + * @return Boolean Авторизован пользователь или нет */ public function isLoggin(HttpRequest $request) { @@ -28,33 +58,12 @@ class Filter_Login extends Filter_Filter switch ($request->getAction()) { // Авторизация по постоянному паролю + case 'api_key': case 'login': $login = $request->get('login'); $password = $request->get('password'); - - $result = Filter_UserAccess::getUserByLogin($login); // Поиск по логину - if ($result) { - $userPassword = $result->getString('password'); - if (Filter_UserAccess::$access == 'site_root' && defined('PARENT_PATH')) { - $s = new Settings(PARENT_PATH . '/settings.json'); - $s->read(); - $dsn = $s->readKey(array('system', 'dsn')); - - $db = Database::getConnection($dsn); - $user = $db->fetchOneArray("SELECT * FROM users WHERE login = :login", ['login' => $login]); - $userPassword = $user['password']; - } /*else if (time() - $result->getInt('lastupdate') > 60*60*24*60) { - // Проверить давность пароля, 60 дней - $request->set('error', true); - $request->set('lastupdate', true); - return false; - }*/ - - // Извлечнеие пользователя из родительской CMS, для проверки пароля - if (md5($password) == $userPassword) { // password - $this->enter($db, $result); - return true; - } + if($this->checkLoginPasswordPair($db,$login,$password)==true){ + return true; } $request->set('error', true); break; @@ -121,7 +130,8 @@ class Filter_Login extends Filter_Filter public function execute(HttpRequest $request) { - $logged = $this->isLoggin($request); + $logged = $this->isLoggin($request); +// return json_encode(["logged"=>$logged]); if ($request->get('action') == 'user_access') { if ($logged) { $result = array(); @@ -135,6 +145,11 @@ class Filter_Login extends Filter_Filter } } + if($logged && ($request->get('action') == 'api_key')) { + $result['key'] = Security::generateAPIKey(strval(time())); + return json_encode($result); + } + if ($request->get('action') == 'relogin') { if ($logged) { return json_encode(array('result' => 'ok', 'message' => "Авторизация успешна")); @@ -147,7 +162,7 @@ class Filter_Login extends Filter_Filter // Параметры при неправильной авторизации // Действия по умолчанию !! Возможно переход на форму регистрации if ($request->get('mode') == 'ajax') { - if (!$this->requestIsWhite($request)) { + if ((!$this->requestIsWhite($request))&&(!$this->APIKeyCheck($request))) { return json_encode(array('result' => 'fail', 'message' =>"NOT_AUTHORIZED")); } } else { @@ -186,4 +201,49 @@ class Filter_Login extends Filter_Filter return false; } + + /* --------------------- + * Проверка на попадание реквеста в API_key_allowed и проверка ключа API + */ + + public function APIKeyCheck(Collection $request) { + $key = $request->get('api_key'); + if(!is_string($key)) { + return false; + } + $module = $request->get('module'); + $action = $request->get('action'); + + $moduleDir = explode('_',$module)[0]; + $file = Path::join(CMS_PATH, 'modules', $moduleDir, 'filters', 'api_key.json'); + if (file_exists($file)) { + $whiteList = json_decode(file_get_contents($file), true); + + if (in_array($action, $whiteList)) { + if($this->isValidAPIKey($key)) { + return true; + } + } + } + + return false; + } + /** + * ключ API имеет вид [unixTime]_[hash(unixTime,WWW_PATH)] + */ + public function isValidAPIKey(String $key) { + $parts = explode('_',$key,2); + if(count($parts)!=2) { + return false; + } + $timestamp = intval($parts[0]); + $timediff = time()-$timestamp; + if(($timediff<0)||($timediff>60*60*24)) { // key is valid for 24 hours + return false; + } + if($key != Security::generateAPIKey($timestamp)){ + return false; + } + return true; + } } diff --git a/src/Security.php b/src/Security.php index a42af31..8eb7057 100644 --- a/src/Security.php +++ b/src/Security.php @@ -16,7 +16,7 @@ class Security { if ($strength & 8) { $consonants .= '@#$%'; } - + $password = ''; $alt = time() % 2; for ($i = 0; $i < $length; $i++) { @@ -30,4 +30,8 @@ class Security { } return $password; } + + public static function generateAPIKey($timestamp){ + return $timestamp."_".md5(WWW_PATH.$timestamp."asjfgkg0o123rkdsdfl1023kwaf012kj10asdld"); + } } From 03cd37109582cdde4987d3c0c8df64a45e5679c6 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 20 Jul 2022 17:30:53 +0300 Subject: [PATCH 019/138] =?UTF-8?q?=D0=91=D0=B0=D0=B3=20=D0=B2=20=D1=81?= =?UTF-8?q?=D0=BE=D0=B7=D0=B4=D0=B0=D0=BD=D0=B8=D0=B8=20site=5Ftemplate?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 7077175..97315f4 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -120,7 +120,7 @@ class Controller_Component $tpl->set('script', Path::join(WWW_PATH, 'js')); $tpl->set('media', Path::join(TEMPLATE_WEB, $template)); if ($registry) { - $tpl->set('site_template', SITE_WWW_PATH . '/templates' . $registry->readKey(array('system', 'template'))); + $tpl->set('site_template', SITE_WWW_PATH . '/templates/' . $registry->readKey(array('system', 'template'))); } $tpl->set('base', SITE_WWW_PATH); From 95fc1b28c8a0ea60cf3c8aadc77d61feec985757 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 21 Sep 2022 18:11:58 +0300 Subject: [PATCH 020/138] =?UTF-8?q?=D0=9F=D0=BE=D0=B8=D1=81=D0=BA=20=D1=88?= =?UTF-8?q?=D0=B0=D0=B1=D0=BB=D0=BE=D0=BD=D0=B0=20=D0=BA=D0=BE=D0=BC=D0=BF?= =?UTF-8?q?=D0=BE=D0=BD=D0=B5=D0=BD=D1=82=D0=B0=20=D0=B2=20=D0=BF=D0=B0?= =?UTF-8?q?=D0=BF=D0=BA=D0=B5=20=D0=BE=D1=81=D0=BD=D0=BE=D0=B2=D0=BD=D0=BE?= =?UTF-8?q?=D0=B3=D0=BE=20=D1=88=D0=B0=D0=B1=D0=BB=D0=BE=D0=BD=D0=B0.=20?= =?UTF-8?q?=D0=94=D0=BB=D1=8F=20=D1=83=D0=BF=D1=80=D0=B0=D1=89=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=20=D1=80=D0=B0=D0=B7=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=BA=D0=B8=20=D0=BD=D0=BE=D0=B2=D0=BE=D0=B3=D0=BE=20=D1=88?= =?UTF-8?q?=D0=B0=D0=B1=D0=BB=D0=BE=D0=BD=D0=B0=20=D1=81=D0=BE=D0=B2=D0=BC?= =?UTF-8?q?=D0=B5=D1=81=D1=82=D0=BD=D0=BE=20=D1=81=20=D0=BA=D0=BE=D0=BC?= =?UTF-8?q?=D0=BF=D0=BE=D0=BD=D0=B5=D0=BD=D1=82=D0=B0=D0=BC=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Collection.php | 6 +++--- src/Controller/Component.php | 18 +++++++++++++++--- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index 1370be3..8a4ba7d 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -1,7 +1,7 @@ data[$key]) && $this->data[$key] != '' ? $this->data[$key] : $default; } - public function getInt($key, $default = 0) + public function getInt($key, $default = 0) { return (int)$this->get($key, $default); } @@ -69,7 +69,7 @@ class Collection implements ArrayAccess public function getNat($key, $default = 1) { $result = (int)$this->get($key, $default); - return (($result > 0) ? $result : $default); + return (($result > 0) ? $result : $default); } public function clear() diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 97315f4..bb8938f 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -244,14 +244,26 @@ class Controller_Component $component->db = $db; $component->registry = $registry; - $component->viewPath = array(COMPONENTS . '/' . $name . '/', BASE_PATH . '/components/' . $name . '/'); + $template = $component->getTemplateName($registry); + + $component->viewPath = array( + COMPONENTS . '/' . $name . '/', + BASE_PATH . '/components/' . $name . '/', + CMS_PATH . '/../templates/' . $template . '/_components/' . $name . '/', + BASE_PATH . '/templates/' . $template . '/_components/' . $name . '/' + ); if (defined('COMPONENTS_WEB')) { - $component->webPath = array(COMPONENTS_WEB . '/' . $name, SITE_WWW_PATH . '/components/' . $name); + $component->webPath = array( + COMPONENTS_WEB . '/' . $name, + SITE_WWW_PATH . '/components/' . $name, + TEMPLATE_WEB . '/' . $template . '/_components/' . $name, + SITE_WWW_PATH . '/templates/' . $template . '/_components/' . $name + ); $component->COMPONENTS_WEB = COMPONENTS_WEB; } else { $component->webPath = array('', SITE_WWW_PATH . '/components/' . $name, ''); } - } + } $stmt = $db->prepareStatement("SELECT * FROM component WHERE code = ?"); $stmt->setString(1, $expression); From 282fff8276478fc511c4aa91c331339321036c7c Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 30 Sep 2022 11:46:52 +0300 Subject: [PATCH 021/138] =?UTF-8?q?fix=20=D0=9E=D0=BF=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=D0=B5=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=88=D0=B0=D0=B1=D0=BB?= =?UTF-8?q?=D0=BE=D0=BD=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index bb8938f..3672a57 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -247,17 +247,21 @@ class Controller_Component $template = $component->getTemplateName($registry); $component->viewPath = array( - COMPONENTS . '/' . $name . '/', + // Сначало ищем локально + BASE_PATH . '/templates/' . $template . '/_components/' . $name . '/', BASE_PATH . '/components/' . $name . '/', - CMS_PATH . '/../templates/' . $template . '/_components/' . $name . '/', - BASE_PATH . '/templates/' . $template . '/_components/' . $name . '/' + // Потом в общем хранилище + CMS_PATH . '/../templates/' . $template . '/_components/' . $name . '/', + COMPONENTS . '/' . $name . '/', ); if (defined('COMPONENTS_WEB')) { $component->webPath = array( - COMPONENTS_WEB . '/' . $name, + // Сначало локально + SITE_WWW_PATH . '/templates/' . $template . '/_components/' . $name, SITE_WWW_PATH . '/components/' . $name, - TEMPLATE_WEB . '/' . $template . '/_components/' . $name, - SITE_WWW_PATH . '/templates/' . $template . '/_components/' . $name + // Потом в общем хранилище + TEMPLATE_WEB . '/' . $template . '/_components/' . $name, + COMPONENTS_WEB . '/' . $name, ); $component->COMPONENTS_WEB = COMPONENTS_WEB; } else { From fdc13fd6be2b55e78e08def91226f882095f3a67 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 30 Sep 2022 16:21:42 +0300 Subject: [PATCH 022/138] =?UTF-8?q?fix=20=D0=9E=D0=BF=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=D0=B5=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=88=D0=B0=D0=B1=D0=BB?= =?UTF-8?q?=D0=BE=D0=BD=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 3672a57..1f1e18e 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -98,7 +98,8 @@ class Controller_Component $selected = null; foreach ($this->viewPath as $index => $viewPath) { // Загружать шаблон по умолчанию если не найден текущий - if(is_dir(Path::join($this->viewPath[$index], 'templates', $template))) { + $dir = Path::join($this->viewPath[$index], 'templates', $template); + if(is_dir($dir)) { $tpl = new PHPTAL(Path::join($this->viewPath[$index], 'templates', $template, $name)); $tpl->setPhpCodeDestination(PHPTAL_PHP_CODE_DESTINATION); $selected = $index; @@ -107,10 +108,11 @@ class Controller_Component } if ($selected === null) { - $tpl = new PHPTAL(Path::join($this->viewPath[0], 'templates', 'modern', $name)); + // Последний вариант viewPath, путь к папке компонента + $selected = count($this->viewPath) - 1; + $tpl = new PHPTAL(Path::join($this->viewPath[$selected], 'templates', 'modern', $name)); $tpl->setPhpCodeDestination(PHPTAL_PHP_CODE_DESTINATION); $template = 'modern'; - $selected = 0; } $tpl->stripComments(true); From b60398acd79ca961900a130518b721a535b78bed Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Mon, 3 Oct 2022 17:26:18 +0300 Subject: [PATCH 023/138] =?UTF-8?q?fix=20=D0=9F=D1=83=D1=82=D1=8C=20=D0=BF?= =?UTF-8?q?=D0=BE=20=D1=83=D0=BC=D0=BE=D0=BB=D1=87=D0=B0=D0=BD=D0=B8=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 1f1e18e..a528190 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -133,6 +133,10 @@ class Controller_Component return $tpl; } + function _getDefaultPath() { + return $this->viewPath[count($this->viewPath) - 1]; + } + public function getTemplatePath($name) { $registry/*: Settings*/ = $this->registry; // Брать настройки из куков если есть @@ -143,12 +147,12 @@ class Controller_Component } } - return Path::join($this->viewPath[0], 'templates', 'modern', $name); + return Path::join($this->viewPath[count($this->viewPath) - 1], 'templates', 'modern', $name); } public function getTemplateWebPath() { - return Path::join($this->webPath[0], 'templates', 'modern'); + return Path::join($this->webPath[count($this->webPath) - 1], 'templates', 'modern'); } /** @@ -181,7 +185,7 @@ class Controller_Component } function getInfo() { - $filename = Path::join($this->viewPath[0], 'install.json'); + $filename = Path::join($this->viewPath[count($this->viewPath) - 1], 'install.json'); if (file_exists($filename)) { $settings = json_decode(File::getContents($filename), true); return $settings; From df08cfaa60bfc5afcf86e882624ef3a9f438fa6c Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 4 Oct 2022 14:43:36 +0300 Subject: [PATCH 024/138] =?UTF-8?q?=D0=A8=D0=B0=D0=B1=D0=BB=D0=BE=D0=BD=20?= =?UTF-8?q?=D0=BF=D0=BE=20=D1=83=D0=BC=D0=BE=D0=BB=D1=87=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index a528190..209d765 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -86,7 +86,8 @@ class Controller_Component } public function getTemplateName($_registry/*: Settings*/) { - return (isset($_COOKIE['with_template']) && preg_match('/^[\w\d-]{3,20}$/', $_COOKIE['with_template'])) ? $_COOKIE['with_template'] : $_registry->readKey(array('system', 'template')); + return (isset($_COOKIE['with_template']) && preg_match('/^[\w\d-]{3,20}$/', $_COOKIE['with_template'])) + ? $_COOKIE['with_template'] : ($_registry ? $_registry->readKey(array('system', 'template')) : 'modern'); } public function getView($name) From 08bc587126151a7dbb7e1925adf7ee453707f116 Mon Sep 17 00:00:00 2001 From: Daniil Date: Fri, 21 Oct 2022 17:33:20 +0300 Subject: [PATCH 025/138] =?UTF-8?q?=D1=84=D0=BE=D1=80=D0=BC=D0=B0=20=D0=B4?= =?UTF-8?q?=D0=BB=D1=8F=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=20=D0=B2=D0=B5=D1=80=D1=81=D1=82=D0=BA=D0=B8=20=20?= =?UTF-8?q?html?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Form/Form.php | 6 +++++- src/Settings.php | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/Form/Form.php b/src/Form/Form.php index 898e18d..f79be2c 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -45,6 +45,9 @@ class THidden extends Form_Input { class TComponentBrowserInput extends Form_Input { } +// вставка простого html +class Html_Text extends Form_Field { +} /** * Форма для ввода */ @@ -94,7 +97,8 @@ class Form_Form extends View_View { 'filebrowser' => 'TComponentBrowserInput', 'documents' => 'TComponentBrowserInput', 'chooser' => 'Form_Input', - 'select_chooser' => 'Form_SelectOne' + 'select_chooser' => 'Form_SelectOne', + 'html_text' => 'Html_Text' ); } diff --git a/src/Settings.php b/src/Settings.php index eca24eb..8bf59c4 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -47,7 +47,7 @@ class Settings extends Collection } /** - * Запись ключа в реестр (Реестр это могомерный массив) + * Запись ключа в реестр (Реестр это многомерный массив) */ public function writeKey(array $key, $value) { From 2cee29d7a0fba6d984f1ba114c6e88b7bc49c92d Mon Sep 17 00:00:00 2001 From: denis Date: Wed, 26 Oct 2022 17:46:00 +0300 Subject: [PATCH 026/138] =?UTF-8?q?=D0=9F=D0=BE=D0=B4=D1=81=D1=87=D0=B5?= =?UTF-8?q?=D1=82=20=D0=BA=D0=BE=D0=BB=D0=B8=D1=87=D0=B5=D1=81=D1=82=D0=B2?= =?UTF-8?q?=D0=B0=20=D0=BD=D0=B5=D1=83=D0=B4=D0=B0=D1=87=D0=BD=D1=8B=D1=85?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=BF=D1=8B=D1=82=D0=BE=D0=BA=20=D0=B0=D0=B2?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Filter/Login.php | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 4a993a1..6d724bc 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -12,6 +12,8 @@ class Filter_Login extends Filter_Filter { const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#'; const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; + const AUTH_MAX_ATTEMPT = 10; + const AUTH_LAST_ATTEMPT_TIMER = 600; public $mode = 'ajax'; public $user; @@ -42,18 +44,38 @@ class Filter_Login extends Filter_Filter $db = Database::getConnection($dsn); $user = $db->fetchOneArray("SELECT * FROM users WHERE login = :login", ['login' => $login]); - $userPassword = $user['password']; + $userPassword = $user['password']; } /*else if (time() - $result->getInt('lastupdate') > 60*60*24*60) { - // Проверить давность пароля, 60 дней + // Проверить давность пароля, 60 дней $request->set('error', true); $request->set('lastupdate', true); return false; }*/ - + // Проверка на количества попыток авторизации + $lastAttempt = $db->fetchOneArray( + "SELECT trie_count, trie_time FROM users WHERE login = :login", ['login' => $request->get('login')]); + if ($lastAttempt['trie_count'] >= self::AUTH_MAX_ATTEMPT /*&& time() - $lastAttempt['trie_time'] < self::AUTH_LAST_ATTEMPT_TIMER*/) { + if (time() - $lastAttempt['trie_time'] < self::AUTH_LAST_ATTEMPT_TIMER) { + $request->set('timeout_error', true); + break; + } else { + $db->executeQuery( + "UPDATE users SET trie_count = :count WHERE login = :login", + ['count' => 0, 'login' => $request->get('login')] + ); + } + } // Извлечнеие пользователя из родительской CMS, для проверки пароля if (md5($password) == $userPassword) { // password $this->enter($db, $result); return true; + } else { + // Обновление количества неудачных попыток входа + $user = $db->fetchOneArray("SELECT id_user, trie_count FROM users WHERE login = :login", ['login' => $login]); + $db->executeQuery( + "UPDATE users SET trie_time = :cur_time, trie_count = :count WHERE id_user = :id_user", + ['cur_time' => time(), 'count' => $user['trie_count']+=1, 'id_user' => $user['id_user']] + ); } } $request->set('error', true); @@ -110,7 +132,7 @@ class Filter_Login extends Filter_Filter { $this->user = $result; $random = rand(0, 1024 * 1024); - $db->executeQuery("UPDATE users SET sid = '$random' WHERE id_user = " . $result->getInt('id_user')); + $db->executeQuery("UPDATE users SET sid = '$random', trie_count = 0 WHERE id_user = " . $result->getInt('id_user')); $_SESSION["group"] = $result->getInt('access'); $_SESSION["access"] = $result->getInt('id_user'); // id_user From a09fc396d8d56c932a998a07f75ba84d46e30295 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 22 Nov 2022 12:46:15 +0300 Subject: [PATCH 027/138] fix --- src/Collection.php | 1 - src/ComponentRequest.php | 4 ++-- src/Controller/Action.php | 3 +-- src/Controller/Component.php | 10 ++++------ src/Filter/Authorization.php | 8 ++++---- src/Functions.php | 23 ++++++++++++----------- src/Role/User.php | 5 +++++ src/Role/UserInterface.php | 3 ++- src/View/View.php | 5 ----- 9 files changed, 30 insertions(+), 32 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index d2f662d..4eea3d1 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -1,6 +1,5 @@ r->getAction(); } -} \ No newline at end of file +} diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 4db58c5..cbfd202 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -1,8 +1,7 @@ set('common', Path::join($this->config->get('system', 'web'), '../', 'common')); $tpl->set('script', Path::join($this->config->get('system', 'web'), 'js')); - $tpl->set('media', Path::join($this->config->get('system', 'templates_web'), $template)); + $tpl->set('media', Path::join($this->config->get('system', 'web'), 'templates', $template)); if ($default) { $tpl->set('site_template', $this->config->get('site', 'web') . '/templates/' . $default); @@ -244,13 +244,13 @@ class Component } $name = $path; - $path = Path::join ($site->config->get('site', 'path'), 'components', $name, $name . '.php'); - $className = 'Component_' . $name; + $path = Path::join ($site->config->get('site', 'components'), $name, $name . '.php'); + $className = 'Components\\'. ucfirst($name). '\\' . $name; $component/*: Component*/ = null; if (file_exists($path)) { - require_once ($path); + // require_once ($path); $component = new $className(); $component->viewPath = array($site->config->get('site', 'path') . '/components/' . $name . '/'); @@ -258,8 +258,6 @@ class Component $component->COMPONENTS_WEB = $site->config->get('site', 'web') . '/components/'; } else { - $path = Path::join ($site->config->get('system', 'components'), $name, $name . '.php'); - require_once ($path); $component = new $className(); $template = $component->getTemplateName($registry); diff --git a/src/Filter/Authorization.php b/src/Filter/Authorization.php index 0538eb2..0df3e6f 100644 --- a/src/Filter/Authorization.php +++ b/src/Filter/Authorization.php @@ -11,14 +11,14 @@ class Authorization { $this->group = $group; } - function isLogged() { + static function isLogged($group = 'access') { // echo session_status(); if (session_status() == PHP_SESSION_NONE) { session_start(); } $hash = self::getBrowserSign(); // Если $hash не совпадает $_SESSION['hash'] то удаляем сессию - if (isset($_SESSION[$this->group]) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { + if (isset($_SESSION[$group]) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { if ($hash == $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME]) { // UserAccess::getUserById($_SESSION ['access']); // Поиск по идентификатору return true; @@ -29,12 +29,12 @@ class Authorization { return false; } - function enter($id) { + static function enter($id, $group = 'access') { // $db->executeQuery("UPDATE visitor SET sid = '' WHERE id_visitor = " . $result->getInt('id_user')); // session_register("access"); // session_register("time"); - $_SESSION [$this->group] = $id; + $_SESSION [$group] = $id; $_SESSION [self::SESSION_BROWSER_SIGN_KEYNAME] = self::getBrowserSign(); $_SESSION ["time"] = time(); } diff --git a/src/Functions.php b/src/Functions.php index be161bc..ec3032a 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -101,7 +101,7 @@ class Functions { * @param mixed $a * @param mixed $b * - * @return array[int]mixed + * @return mixed */ static function compose($_rest) { $closure = new compose(func_get_args()); @@ -111,7 +111,7 @@ class Functions { /** * Карирование справа * - * @return array[int]mixed + * @return mixed */ static function rcurry($_rest) { $closure = new right(func_get_args ()); @@ -121,7 +121,7 @@ class Functions { /** * Карирование слева * - * @return array[int]mixed + * @return mixed */ static function lcurry($_rest) { $closure = new left(func_get_args ()); @@ -133,7 +133,7 @@ class Functions { * @param mixed $pred Условие по которому разделяется массив * @param array $lst * - * @return array[int]mixed + * @return mixed */ static function partition($pred, $lst) { $left = array (); @@ -329,19 +329,20 @@ class Functions { /** * Поиск элемента в массиве - * @param function $cb сравнение с элементом массива - * @param array $hs массив в котором ищется значение + * @param mixed $cb сравнение с элементом массива + * @param Array $hs массив в котором ищется значение * * @return int|string ключ найденого элемента в массиве */ static function array_usearch($cb, array $hs, $strict = false) { foreach($hs as $key => $value) if (call_user_func_array($cb, array($value, $key, $strict))) return $key; + return null; } /** * Выбирает все сроки из таблицы с уникальными значениями ключа - * @param $name Имя ключа - * @param $table Двухмерный массив + * @param string $name Имя ключа + * @param Array $table Двухмерный массив * @example * key_unique_values ('name', array (array ('name' => 1), array ('name' => 2), array ('name' => 1))) => array (1, 2) @@ -359,9 +360,9 @@ class Functions { /** * Сортировка двумерного массива по заданному ключу - * @param $array Массив - * @param $key Имя ключа по значению которого будет идти сравнение - * @return Отсортированный массив + * @param Array $array Массив + * @param string $key Имя ключа по значению которого будет идти сравнение + * @return Array Отсортированный массив */ static function sortOn($array, $key, $fn = 'Functions::__cmp') { usort ($array, Functions::rcurry($fn, $key)); diff --git a/src/Role/User.php b/src/Role/User.php index d6b6671..a22cb13 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -30,6 +30,11 @@ class User implements UserInterface return $this->name; } + function isLogged() { + return \ctiso\Filter\Authorization::isLogged(); + } + + public function getUserByQuery(Statement $stmt) { $result = $stmt->executeQuery(); diff --git a/src/Role/UserInterface.php b/src/Role/UserInterface.php index 778394d..295e4ca 100644 --- a/src/Role/UserInterface.php +++ b/src/Role/UserInterface.php @@ -1,11 +1,12 @@ _values["suggestions"] = $this->suggestions; } - public function jGrowl($message, $args) - { - $this->addScriptRaw('$.jGrowl("' . $message . '", ' . json_encode($args) . ");\n", true); - } - public function setGlobal($name, $args) { $this->addScriptRaw("var " . $name . " = " . json_encode($args) . ";\n", false); From 28429039a44309e0c522a7791f93649a5b606328 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 24 Nov 2022 19:12:00 +0300 Subject: [PATCH 028/138] =?UTF-8?q?ref=20=D0=98=D1=81=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=82=D0=B8=D0=BF=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 8 ++-- src/Controller/Component.php | 4 +- src/Database/PDOStatement.php | 5 +- src/Form/OptionFactory.php | 87 ----------------------------------- src/Model/BaseMapper.php | 6 +++ src/Model/Factory.php | 2 +- src/Registry.php | 7 +++ src/UserMessageException.php | 3 +- 8 files changed, 24 insertions(+), 98 deletions(-) delete mode 100644 src/Form/OptionFactory.php create mode 100644 src/Model/BaseMapper.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index cbfd202..99391a6 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -101,9 +101,9 @@ class Action /** * Создает представление - * @param $name String - * @param $viewClass String - * @return View_Composite + * @param string + * @param string $viewClass + * @return Composite */ public function getView($name, $viewClass = 'ctiso\\View\\Composite') { @@ -163,7 +163,7 @@ class Action * Т.к действия являются методами класса то * 1. Можно переопределить действия * 2. Использовать наследование чтобы добавить к старому обработчику новое поведение - * @param $request Обьект запроса + * @param HttpRequest $request запроса */ public function preProcess(HttpRequest $request) { diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 630312d..4fb8fba 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -88,7 +88,7 @@ class Component } } - public function getTemplateName($_registry/*: Settings*/) { + public function getTemplateName($_registry/*: \ctiso\Settings*/) { return (isset($_COOKIE['with_template']) && preg_match('/^[\w\d-]{3,20}$/', $_COOKIE['with_template'])) ? $_COOKIE['with_template'] : ($_registry ? $_registry->get('site', 'template') : 'modern'); } @@ -147,7 +147,7 @@ class Component } public function getTemplatePath($name) { - $registry/*: Settings*/ = $this->config; + $registry/*: \ctiso\Settings*/ = $this->config; // Брать настройки из куков если есть $template = ($this->template) ? $this->template : $this->getTemplateName($registry); foreach ($this->viewPath as $index => $viewPath) { diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index d837669..af8c19f 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -5,6 +5,7 @@ namespace ctiso\Database; use ctiso\Database\StatementIterator, ctiso\Tools\StringUtil, PDO; +use TheSeer\Tokenizer\Exception; class PDOStatement extends \PDOStatement implements \IteratorAggregate { @@ -12,7 +13,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate public $cache = array(); public $fields; - function getIterator(): Iterator { + function getIterator(): \Iterator { return new StatementIterator($this); } @@ -73,7 +74,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate function getInt($name) { if (!$this->fields) { - throw new Error('no fields'); + throw new \Exception('no fields'); } return (int)$this->fields[$name]; } diff --git a/src/Form/OptionFactory.php b/src/Form/OptionFactory.php deleted file mode 100644 index 724b3e6..0000000 --- a/src/Form/OptionFactory.php +++ /dev/null @@ -1,87 +0,0 @@ -db = $db; - $this->registry = $registry; - } - - function create(Form_Select $field, $input) { - if (isset($input['options.resid'])) { - $type = $input['options.resid']; - - $res = new Model_Resources($this->db); - $field->options = $this->optionsArray('id_section', 'title', $res->getSubsections('', $type)); - - } else if (isset($input['options.res'])) { - $type = $input['options.res']; - - $res = new Model_Resources($this->db); - $field->options = $this->optionsArray('path', 'title', $res->getSubsections('', $type)); - - } else if (isset($input['options.all_res'])) { - $type = $input['options.all_res']; - - $res = new Model_Resources($this->db); - $field->options = $this->optionsArray('id_resource', 'subtitle', $res->getAllResource($type)); - - } else if (isset($input['options.db'])) { - list($table, $keyvalue) = explode(":", $input['options.db']); - list($key, $value) = explode(",", $keyvalue); - try { - $query_result = $this->db->executeQuery("SELECT * FROM $table"); - $field->options = $this->optionsDB($key, $value, $query_result); - } catch(Exception $ex) { - $field->options = []; - } - } elseif (isset($input['options.pair'])) { - $field->options = $this->optionsPair($input['options.pair']); - } elseif (isset($input['options.model'])) { - $factory = new Model_Factory($this->db, $this->registry); - $model = $factory->getModel($input['options.model']); - $field->options = $model->getAllAsOptions(); - } else { - $field->options = $input['options']; - } - if (isset($input['default'])) { - array_unshift($field->options, ['value' => 0, 'name' => $input['default']]); - } - - // Ставим корневой каталог в начало списка (скорее всего он будет в конце массива) - if ($field->options) - { - $root_elem = array_pop($field->options); - if ($root_elem['value'] == '/') - array_unshift($field->options, $root_elem); - else - array_push($field->options, $root_elem); - } - } - - public function optionsDB($key, $val, $res) { - $result = array(); - while($res->next()) { - $result[] = array('value' => $res->getInt($key), 'name' => $res->getString($val)); - } - return $result; - } - - public function optionsArray($key, $val, $res) { - $result = array(); - foreach($res as $item) { - $result[] = array('value' => $item->{$key}, 'name' => $item->{$val}); - } - return $result; - } - - public function optionsPair($list, $selected = false) { - $result = array(); - foreach ($list as $key => $value) { - $result [] = array('value' => $key, 'name' => $value, 'selected' => $key == $selected); - } - return $result; - } -} diff --git a/src/Model/BaseMapper.php b/src/Model/BaseMapper.php new file mode 100644 index 0000000..50cad30 --- /dev/null +++ b/src/Model/BaseMapper.php @@ -0,0 +1,6 @@ +namespace[$ns]['data'][$key])) { + return $this->namespace[$ns]['data'][$key]; + } + return null; + } + public function has($ns, $key) { return isset($this->namespace[$ns]['data'][$key]); } diff --git a/src/UserMessageException.php b/src/UserMessageException.php index 1049dc9..226eb75 100644 --- a/src/UserMessageException.php +++ b/src/UserMessageException.php @@ -4,9 +4,8 @@ * @see Controller_Front */ namespace ctiso; -use Exception; -class UserMessageException extends Exception { +class UserMessageException extends \Exception { public $userMessage; public function __construct($message) { parent::__construct($message); From 526262c80ba65fbf42eb3645d8d820457b0af033 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Mon, 28 Nov 2022 18:44:09 +0300 Subject: [PATCH 029/138] fix Validator --- src/Controller/Action.php | 1 + src/Controller/Component.php | 5 ++-- src/Controller/Front.php | 1 + src/Controller/SiteInterface.php | 1 + src/Registry.php | 16 ------------ src/Settings.php | 21 +++++++++++---- .../Rule/{Match.php => MatchRule.php} | 2 +- src/Validator/Validator.php | 26 +++++++++---------- src/View/View.php | 4 +-- 9 files changed, 38 insertions(+), 39 deletions(-) rename src/Validator/Rule/{Match.php => MatchRule.php} (92%) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 99391a6..998f735 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -26,6 +26,7 @@ class Action // Параметры устанавливаются при создании контроллера public $name = ''; // Имя модуля + public $front; public $modulePath = null; // Путь к модулю public $moduleTitle = ''; diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 4fb8fba..e4b54da 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -171,8 +171,9 @@ class Component */ public function getModel($name) { - $modelName = "Mapper_" . $name; + $modelName = "App\\Mapper\\" . $name; $model = new $modelName(); + $model->config = $this->config; $model->db = $this->db; return $model; } @@ -260,7 +261,7 @@ class Component } else { $component = new $className(); - $template = $component->getTemplateName($registry); + $template = $component->getTemplateName($site->config); $component->viewPath = array( // Сначало ищем локально diff --git a/src/Controller/Front.php b/src/Controller/Front.php index b8c3bae..2e1cc1d 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -67,6 +67,7 @@ class Front extends Action $module->config = $this->config; $module->db = $this->db; $module->user = $this->user; + $module->front = $this; // Ведение лога $logger = new ActionLogger($module, $logPath, $this->user); $logger->before = $this->loadSettings(Path::join($modPath, 'filter', 'logger.php')); diff --git a/src/Controller/SiteInterface.php b/src/Controller/SiteInterface.php index 205e5ea..1125601 100644 --- a/src/Controller/SiteInterface.php +++ b/src/Controller/SiteInterface.php @@ -3,6 +3,7 @@ namespace ctiso\Controller; interface SiteInterface { + function getResource(); function loadComponent($expression); function getDatabase(); function getConfig(); diff --git a/src/Registry.php b/src/Registry.php index c9c9fac..21e08eb 100644 --- a/src/Registry.php +++ b/src/Registry.php @@ -48,20 +48,4 @@ class Registry { function set($ns, $key, $value) { $this->namespace[$ns]['data'][$key] = $value; } - - /** - * Список модулей - */ - public function getModules() - { - return array_keys($this->data); - } - - /** - * Проверка наличия модуля - */ - public function hasModule($name) - { - return isset($this->data[$name]); - } } diff --git a/src/Settings.php b/src/Settings.php index c7c96b1..1325830 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -156,11 +156,6 @@ class Settings $name = array_shift($key); unset($data[$name]); } - - public function getOwner() - { - return array_keys($this->data); - } /** * Запись настроек в файл (Может переименовать в store) @@ -195,4 +190,20 @@ class Settings function import($data) { $this->data = $data; } + + /** + * Список модулей/ключей + */ + public function getKeys() + { + return array_keys($this->data); + } + + /** + * Проверка наличия ключа + */ + public function hasKey($name) + { + return isset($this->data[$name]); + } } diff --git a/src/Validator/Rule/Match.php b/src/Validator/Rule/MatchRule.php similarity index 92% rename from src/Validator/Rule/Match.php rename to src/Validator/Rule/MatchRule.php index 7f8b999..d54f448 100644 --- a/src/Validator/Rule/Match.php +++ b/src/Validator/Rule/MatchRule.php @@ -7,7 +7,7 @@ namespace ctiso\Validator\Rule; use ctiso\Validator\Rule\AbstractRule, ctiso\Collection; -class Match extends AbstractRule +class MatchRule extends AbstractRule { public $same; diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 0529662..88fd870 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -28,19 +28,19 @@ class Validator public function addRuleList(array $input) { $type = array( - 'date' => 'Validator_Rule_Date', - 'email' => 'Validator_Rule_Email', - 'emaillist'=> 'Validator_Rule_EmailList', - 'match' => 'Validator_Rule_Match', - 'time' => 'Validator_Rule_Time', - 'alpha' => 'Validator_Rule_Alpha', - 'require' => 'Validator_Rule_Notnull', - 'numeric' => 'Validator_Rule_Numeric', - 'unique' => 'Validator_Rule_Unique', - 'filename' => 'Validator_Rule_FileName', - 'count' => 'Validator_Rule_Count', - 'isfile' => 'Validator_Rule_IsFile', - 'code' => 'Validator_Rule_Code' + 'date' => 'ctiso\\Validator\\Rule\\Date', + 'email' => 'ctiso\\Validator\\Rule\\Email', + 'emaillist'=> 'ctiso\\Validator\\Rule\\EmailList', + 'match' => 'ctiso\\Validator\\Rule\\MatchRule', + 'time' => 'ctiso\\Validator\\Rule\\Time', + 'alpha' => 'ctiso\\Validator\\Rule\\Alpha', + 'require' => 'ctiso\\Validator\\Rule\\Notnull', + 'numeric' => 'ctiso\\Validator\\Rule\\Numeric', + 'unique' => 'ctiso\\Validator\\Rule\\Unique', + 'filename' => 'ctiso\\Validator\\Rule\\FileName', + 'count' => 'ctiso\\Validator\\Rule\\Count', + 'isfile' => 'ctiso\\Validator\\Rule\\IsFile', + 'code' => 'ctiso\\Validator\\Rule\\Code' ); // Разбор правила проверки diff --git a/src/View/View.php b/src/View/View.php index 54000d8..088cd43 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -31,9 +31,9 @@ class View * Связывет переменную с вложенным шаблоном * * @param string $section переменная шаблона - * @param CompositeView $view вложенный шаблон + * @param View|string $view вложенный шаблон */ - public function setView($section, /*View_View|string*/ $view) + public function setView($section, $view/*: View|string*/) { $this->_section [$section] = $view; if (is_object($view)) { From aaba3d758542fe967b511e55f428f219bb8a6b0b Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 29 Nov 2022 16:15:58 +0300 Subject: [PATCH 030/138] fix type --- src/Controller/Action.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 998f735..e40e3f1 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -211,7 +211,7 @@ class Action * @param string $name Действие * @param array $param Дополнительные параметры * 'mode' означает что элемент до отправки обрабатывается javascript - * @return array|null + * @return Url|null */ public function nUrl($name, array $param = array()) { From 7fd7c4fd123b0b2bc9e0f91e3dc8e195b3ce1fec Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 8 Dec 2022 18:40:00 +0300 Subject: [PATCH 031/138] =?UTF-8?q?fix=20=D0=9A=D0=BB=D0=B0=D1=81=D1=81?= =?UTF-8?q?=D1=8B=20=D0=B4=D0=BB=D1=8F=20=D0=BF=D0=BE=D0=BB=D0=B5=D0=B9=20?= =?UTF-8?q?=D1=84=D0=BE=D1=80=D0=BC=D1=8B=20=D0=B2=D1=8B=D0=BD=D0=B5=D1=81?= =?UTF-8?q?=D0=B5=D0=BD=D1=8B=20=D0=B2=20=D0=BE=D1=82=D0=B4=D0=B5=D0=BB?= =?UTF-8?q?=D1=8C=D0=BD=D1=8B=D0=B5=20=D1=84=D0=B0=D0=B9=D0=BB=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 2 +- src/Form/CheckBox.php | 14 ++++++++++ src/Form/DateTime.php | 7 +++++ src/Form/Form.php | 59 ++++++++------------------------------- src/Form/Hidden.php | 8 ++++++ src/Form/QuestionType.php | 16 +++++++++++ src/Form/Secret.php | 10 +++++++ src/Form/Upload.php | 7 +++++ 8 files changed, 74 insertions(+), 49 deletions(-) create mode 100644 src/Form/CheckBox.php create mode 100644 src/Form/DateTime.php create mode 100644 src/Form/Hidden.php create mode 100644 src/Form/QuestionType.php create mode 100644 src/Form/Secret.php create mode 100644 src/Form/Upload.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index e40e3f1..485bd3c 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -234,7 +234,7 @@ class Action * Ajax определяется автоматически mode = ajax используется для смены layout * @param $name * @param array $param - * @return array|null + * @return Url|null * * @example ?action=$name&mode=ajax * {$param[i].key = $param[i].value} diff --git a/src/Form/CheckBox.php b/src/Form/CheckBox.php new file mode 100644 index 0000000..ea5f880 --- /dev/null +++ b/src/Form/CheckBox.php @@ -0,0 +1,14 @@ +value = $value; + $this->checked = $value; + } +} diff --git a/src/Form/DateTime.php b/src/Form/DateTime.php new file mode 100644 index 0000000..4f995fb --- /dev/null +++ b/src/Form/DateTime.php @@ -0,0 +1,7 @@ +value = $value; - $this->checked = $value; - } -} - -class TQuestionType extends Select -{ - function setValue($value) - { - // Установить selected у options - $this->value = $value; - foreach ($this->options as &$option) { - $option['selected'] = ($option['value'] == $value); - } - } -} - -class TDateTime extends Input { -} - -/** - * Поле для ввода пароля - */ -class TSecret extends Field { -} - -class TUpload extends Field { -} - -class THidden extends Input { - public $hidden = true; -} - /** * Форма для ввода */ @@ -75,29 +37,30 @@ class Form extends View { { $this->constructor = array( 'input' => 'ctiso\\Form\\Input', - 'inputreq' => 'ctiso\\Form\\Input', // input с проверкой на заполненность + // input с проверкой на заполненность + 'inputreq' => 'ctiso\\Form\\Input', 'date' => 'ctiso\\Form\\Date', 'datereq' => 'ctiso\\Form\\Date', - 'datetime' => 'TDateTime', + 'datetime' => 'ctiso\\Form\\DateTime', 'color' => 'ctiso\\Form\\Color', 'textarea' => 'ctiso\\Form\\TextArea', 'text' => 'ctiso\\Form\\TextArea', 'multiselect' => 'ctiso\\Form\\SelectMany', -// 'selectmany' => 'TSelectMany', 'select1' => 'ctiso\\Form\\SelectOne', 'select' => 'ctiso\\Form\\SelectOne', - 'questiontype'=> 'TQuestionType', - 'secret' => 'TSecret', - 'upload' => 'TUpload', - 'image' => 'TUpload', - 'checkbox' => 'TCheckbox', + + 'questiontype'=> 'ctiso\\Form\\QuestionType', + 'secret' => 'ctiso\\Form\\Secret', + 'upload' => 'ctiso\\Form\\Upload', + 'image' => 'ctiso\\Form\\Upload', + 'checkbox' => 'ctiso\\Form\\CheckBox', 'checkmany' => 'ctiso\\Form\\SelectMany', - 'hidden' => 'THidden', + 'hidden' => 'ctiso\\Form\\Hidden', 'radio' => 'ctiso\\Form\\SelectOne', 'filebrowser' => 'ctiso\\Form\\BrowserInput', - 'documents' => 'ctiso\\Form\\BrowserInput', + 'documents' => 'ctiso\\Form\\BrowserInput', 'chooser' => 'ctiso\\Form\\Input', 'select_chooser' => 'ctiso\\Form\\SelectOne' ); diff --git a/src/Form/Hidden.php b/src/Form/Hidden.php new file mode 100644 index 0000000..535e21b --- /dev/null +++ b/src/Form/Hidden.php @@ -0,0 +1,8 @@ +value = $value; + foreach ($this->options as &$option) { + $option['selected'] = ($option['value'] == $value); + } + } +} diff --git a/src/Form/Secret.php b/src/Form/Secret.php new file mode 100644 index 0000000..ce0175a --- /dev/null +++ b/src/Form/Secret.php @@ -0,0 +1,10 @@ + Date: Fri, 9 Dec 2022 16:09:40 +0300 Subject: [PATCH 032/138] =?UTF-8?q?fix=20=D0=98=D1=81=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D0=BE=20=D0=BE=D0=BF=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=D0=B5=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B8=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 9 ++++++--- src/Layout/Manager.php | 6 ++---- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 485bd3c..241b3df 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -30,7 +30,6 @@ class Action public $modulePath = null; // Путь к модулю public $moduleTitle = ''; - public $modulePrefix = ''; public $viewPathPrefix = null; // Путь к шаблонам контроллера @@ -219,8 +218,12 @@ class Action $url = new Url(); if ($access == null || $access->checkAction($name)) { - $moduleName = explode("\\", strtolower(get_class($this)), 2); - $param = array_merge(array('module' => $this->modulePrefix . $moduleName[1], "action" => $name), $param); + $moduleName = explode("\\", strtolower(get_class($this))); + array_shift($moduleName); + if ($moduleName[0] == $moduleName[1]) { + array_shift($moduleName); + } + $param = array_merge(array('module' => implode("\\", $moduleName), "action" => $name), $param); $url->setParent($this->part); $url->setQuery($param); diff --git a/src/Layout/Manager.php b/src/Layout/Manager.php index e843219..d687113 100644 --- a/src/Layout/Manager.php +++ b/src/Layout/Manager.php @@ -67,17 +67,15 @@ class Manager extends Filter */ public function execute(HttpRequest $request) { -// print_r($request->get('mode')); foreach ($this->condition as $condition) { if (call_user_func($condition[0], $request)) { $layout = $condition[1]; $view = $layout->execute($request); if (is_object($view)) { - echo $view->render(); + return $view->render(); } else { - echo $view; + return $view; } - return null; } } } From 73112f5bf0b648380365bfa103a1b71ce958ad10 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 9 Dec 2022 17:39:23 +0300 Subject: [PATCH 033/138] =?UTF-8?q?fix=20=D0=9F=D0=B5=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=D0=B0=D1=87=D0=B0=20=D0=BE=D0=B1=D1=8C=D0=B5=D0=BA=D1=82=D0=B0?= =?UTF-8?q?=20=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D1=82=D0=B5?= =?UTF-8?q?=D0=BB=D1=8F=20=D0=B2=20=D0=BC=D0=BE=D0=B4=D0=B5=D0=BB=D1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 2 +- src/Database.php | 2 +- src/Model/Factory.php | 7 +++++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 241b3df..4309caf 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -153,7 +153,7 @@ class Action public function getModel($name) { if (!$this->factory) { - $this->factory = new Factory($this->db, $this->config); + $this->factory = new Factory($this->db, $this->config, $this->user); } return $this->factory->getModel($name); } diff --git a/src/Database.php b/src/Database.php index 3cb15b6..b2ac6ca 100644 --- a/src/Database.php +++ b/src/Database.php @@ -30,7 +30,7 @@ class Database/**/ extends PDO $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('ctiso\\Database\\PDOStatement', array())); } - function prepare($sql, $args = []) { + function prepare($sql, $args = []) { $result/*: PDOStatement*/ = parent::prepare($sql, $args); return $result; } diff --git a/src/Model/Factory.php b/src/Model/Factory.php index 031ce43..39d30ca 100644 --- a/src/Model/Factory.php +++ b/src/Model/Factory.php @@ -2,17 +2,19 @@ namespace ctiso\Model; use ctiso\Registry, - ctiso\Database; + ctiso\Database, + ctiso\Role\User; class Factory { public $db; public $config; - public function __construct (Database $db, Registry $config = null) + public function __construct (Database $db, Registry $config = null, User $user) { $this->db = $db; $this->config = $config; + $this->user = $user; } /** @@ -27,6 +29,7 @@ class Factory $model->db = $this->db; $model->factory = $this; $model->config = $this->config; + $model->user = $this->user; $model->setUp(); // return $model; From ab13ebd2897164326313e4e440fefb327fa0d3d4 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 15 Dec 2022 15:50:40 +0300 Subject: [PATCH 034/138] =?UTF-8?q?fix=20=D0=9E=D0=BF=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=D0=B5=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BF=D1=83=D1=82=D0=B8?= =?UTF-8?q?=20=D0=BA=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Front.php | 25 ++++++++++++++----------- src/Form/Form.php | 2 +- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 2e1cc1d..d5e6d12 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -44,23 +44,31 @@ class Front extends Action * @param Request $request Имя модуля * @return string */ - public function loadModule($name, Collection $request, $controller = null) + public function loadModule($name, Collection $request) { if ($this->isLoaded($name)) { $module = $this->modules[$name]; return $module->access->execute($request); } + + $parts = explode('\\', $name); + $config = $this->config; $moulesPath = Path::join($config->get('system', 'path'), 'modules'); $logPath = Path::join($config->get('site', 'path'), $config->get('system', 'access.log')); - $ucname = ucfirst($name); - $moduleClass = "Modules\\$ucname\\$ucname"; + $first = $parts[0]; + $second = (count($parts) >= 2) ? $parts[1] : $parts[0]; + + $ucname = ucfirst($first); + $ucpart = ucfirst($second); + + $moduleClass = "Modules\\$ucname\\$ucpart"; $module = new $moduleClass(); if ($module) { // Инициализация модуля - $modPath = Path::join($moulesPath, $name); + $modPath = Path::join($moulesPath, $first); $module->modulePath = $modPath; $module->name = $name; // @@ -87,14 +95,9 @@ class Front extends Action public function execute(HttpRequest $request) { - $name = explode("\\", $request->get('module', $this->default)); - if (count($name) >= 2) { - $controller = $name[1]; - } else { - $controller = null; - } + $name = $request->get('module', $this->default); try { - return $this->loadModule($name[0], $request, $controller); + return $this->loadModule($name, $request); } catch (UserMessageException $ex) { //Исключение с понятным пользователю сообщением $mode = $request->get('mode'); if ($mode == 'ajax' || $mode == 'json') { diff --git a/src/Form/Form.php b/src/Form/Form.php index f14360c..d5e7582 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -167,7 +167,7 @@ class Form extends View { { foreach ($schema as $key => $conv) { list($value, $type) = $conv; - $this->field [$key]->setValue(call_user_func(array('Primitive', 'from_' . $type), $data->$value)); + $this->field [$key]->setValue(call_user_func(array('ctiso\\Primitive', 'from_' . $type), $data->$value)); } } From 36b7d93a981e009e634c65db18bf7fa862c38073 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 15 Dec 2022 18:16:58 +0300 Subject: [PATCH 035/138] =?UTF-8?q?fix=20=D0=9F=D1=80=D0=B8=20=D1=83=D1=81?= =?UTF-8?q?=D1=82=D0=B0=D0=BD=D0=BE=D0=B2=D0=BA=D0=B5=20=D0=BC=D0=BE=D0=B4?= =?UTF-8?q?=D1=83=D0=BB=D1=8F=20=D0=BD=D0=B5=D0=BF=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=D1=8C=D0=BD=D0=BE=20=D0=B7=D0=B0=D0=BF=D0=B8=D1=81=D1=8B?= =?UTF-8?q?=D0=B2=D0=B0=D0=BB=D0=B8=D1=81=D1=8C=20=D0=BD=D0=B0=D1=81=D1=82?= =?UTF-8?q?=D1=80=D0=BE=D0=B9=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 2 +- src/Controller/Installer.php | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 4309caf..ee955f5 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -82,7 +82,7 @@ class Action public function installPath($name) { - $basePath = $this->config->get('site', 'path'); + $basePath = $this->config->get('system', 'path'); return Path::join($basePath, "modules", $name); } diff --git a/src/Controller/Installer.php b/src/Controller/Installer.php index e544921..2adff19 100644 --- a/src/Controller/Installer.php +++ b/src/Controller/Installer.php @@ -94,20 +94,20 @@ class Installer $sql = $settings->get('sql'); if (is_array($sql)) { $res = $this->installSQL($sql, $version_new, $version_old, $name); - if($res){ + if ($res) { $result[]=$res; } } - - // Обновление версии меню - $registry->removeKey($name); - - $registry->set($name, $settings->get('settings')); - $registry->set($name, - array('version' => $version_new, - 'time' => filemtime($setup))); } + // Обновление версии меню + $registry->removeKey($name); + $registry->set($name, [ + 'version' => $version_new, + 'time' => filemtime($setup) + ]); + $registry->writeKey([$name], $settings->get('settings')); + $registry->write(); } return $result; From d9b6faafc6c833e5b85e4ea9d20a395423b3f2bf Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 16 Dec 2022 12:38:01 +0300 Subject: [PATCH 036/138] =?UTF-8?q?fix=20=D0=94=D0=BE=D0=BF.=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B0=20=D0=B4=D0=BB=D1=8F?= =?UTF-8?q?=20=D0=B8=D0=BC=D0=B5=D0=BD=D0=B8=20=D0=BA=D0=BB=D0=B0=D1=81?= =?UTF-8?q?=D1=81=D0=B0=20=D0=B4=D0=BB=D1=8F=20=D0=BF=D1=80=D0=BE=D1=85?= =?UTF-8?q?=D0=BE=D0=B6=D0=B4=D0=B5=D0=BD=D0=B8=D1=8F=20=D1=82=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 7 ++++--- src/Database.php | 4 ++-- src/Settings.php | 2 +- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index ee955f5..2066995 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -14,7 +14,6 @@ use Exception, ctiso\Filter\ActionAccess, ctiso\View\View, ctiso\Controller\State; - /** * Контроллер страниц */ @@ -219,9 +218,11 @@ class Action if ($access == null || $access->checkAction($name)) { $moduleName = explode("\\", strtolower(get_class($this))); - array_shift($moduleName); - if ($moduleName[0] == $moduleName[1]) { + if (count($moduleName) > 2) { array_shift($moduleName); + if ($moduleName[0] == $moduleName[1]) { + array_shift($moduleName); + } } $param = array_merge(array('module' => implode("\\", $moduleName), "action" => $name), $param); diff --git a/src/Database.php b/src/Database.php index b2ac6ca..ad989d7 100644 --- a/src/Database.php +++ b/src/Database.php @@ -48,8 +48,8 @@ class Database/**/ extends PDO static function getConnection(array $dsn) { - if ($dsn['phptype'] == 'pgsql' || $dsn['phptype'] == 'mysql') { - $port = (isset($dsn['port'])) ? "port={$dsn['port']};" : ""; + if ($dsn['phptype'] == 'pgsql' || $dsn['phptype'] == 'mysql') { + $port = (isset($dsn['port'])) ? "port={$dsn['port']};" : ""; $connection/*: Database*/ = new static("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']); if ($dsn['phptype'] == 'pgsql') { $connection->query('SET client_encoding="UTF-8"'); diff --git a/src/Settings.php b/src/Settings.php index 1325830..d443681 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -46,7 +46,7 @@ class Settings } if (!is_array($settings)) { - throw new Exception($this->file); + throw new Exception('no data in ' . $this->file); } $this->data = $settings; From c912ceebb9d16ef9cfb45e640cf7967974a52396 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 16 Dec 2022 19:17:09 +0300 Subject: [PATCH 037/138] =?UTF-8?q?fix=20=D0=97=D0=B0=D0=BF=D1=8F=D1=82?= =?UTF-8?q?=D0=B0=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Form/Form.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Form/Form.php b/src/Form/Form.php index 8be991b..343f254 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -62,7 +62,7 @@ class Form extends View { 'filebrowser' => 'ctiso\\Form\\BrowserInput', 'documents' => 'ctiso\\Form\\BrowserInput', 'chooser' => 'ctiso\\Form\\Input', - 'select_chooser' => 'ctiso\\Form\\SelectOne' + 'select_chooser' => 'ctiso\\Form\\SelectOne', 'html_text' => 'ctiso\\Form\\HtmlText' ); From e4527ad94e73680ec18f7ead2b84a91e7366a574 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 26 Jan 2023 19:42:10 +0300 Subject: [PATCH 038/138] fix Component class name --- src/Controller/Component.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index e4b54da..badc2f0 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -246,7 +246,7 @@ class Component $name = $path; $path = Path::join ($site->config->get('site', 'components'), $name, $name . '.php'); - $className = 'Components\\'. ucfirst($name). '\\' . $name; + $className = 'Components\\'. ucfirst($name). '\\' . ucfirst($name); $component/*: Component*/ = null; From b3f6cfcbd7fe74b05b45de09106b9147a162d20e Mon Sep 17 00:00:00 2001 From: System Administrator Date: Mon, 30 Jan 2023 18:28:45 +0300 Subject: [PATCH 039/138] fix tabletree --- src/{process.php => Process.php} | 0 src/{tabletree.php => TableTree.php} | 26 ++++++++++++++------------ 2 files changed, 14 insertions(+), 12 deletions(-) rename src/{process.php => Process.php} (100%) rename src/{tabletree.php => TableTree.php} (50%) diff --git a/src/process.php b/src/Process.php similarity index 100% rename from src/process.php rename to src/Process.php diff --git a/src/tabletree.php b/src/TableTree.php similarity index 50% rename from src/tabletree.php rename to src/TableTree.php index 0d9203a..70b3cb6 100644 --- a/src/tabletree.php +++ b/src/TableTree.php @@ -19,17 +19,19 @@ namespace ctiso; use ctiso\Functions; -function tableTreeWalk($level, $table, $fn) { - if (empty ($level)) return $table; - $name = array_shift ($level); - - $keys = Functions::key_unique_values($name, $table); - $data = array (); - foreach ($keys as $index) { - list($rows, $table) = Functions::partition (Functions::lcurry(['Functions', '__index'], $index, $name), $table); -// $rows = array_filter ($table, lcurry('__index', intval($index), $name)); - //$rows = array_filter ($table, create_function ('$x', 'return __index ('.intval($index).', \''.$name.'\', $x);')); - $data[$index] = call_user_func ($fn, $name, $index, $rows, tableTreeWalk ($level, $rows, $fn)); +class TableTree { + static function walk($level, $table, $fn) { + if (empty ($level)) return $table; + $name = array_shift ($level); + + $keys = Functions::key_unique_values($name, $table); + $data = array (); + foreach ($keys as $index) { + list($rows, $table) = Functions::partition (Functions::lcurry(['\ctiso\Functions', '__index'], $index, $name), $table); + // $rows = array_filter ($table, lcurry('__index', intval($index), $name)); + //$rows = array_filter ($table, create_function ('$x', 'return __index ('.intval($index).', \''.$name.'\', $x);')); + $data[$index] = call_user_func ($fn, $name, $index, $rows, self::walk ($level, $rows, $fn)); + } + return $data; } - return $data; } From 0c3fba0d7e3d131f02efe61bc8c7e7bb226eb15f Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 31 Jan 2023 10:49:00 +0300 Subject: [PATCH 040/138] =?UTF-8?q?=D0=9C=D0=B5=D0=BB=D0=BA=D0=B8=D0=B5=20?= =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 8 +++++--- src/Model/Factory.php | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index badc2f0..f0c6647 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -208,9 +208,11 @@ class Component $filename = Path::join($this->viewPath[count($this->viewPath) - 1], 'install.json'); if (file_exists($filename)) { $settings = json_decode(File::getContents($filename), true); - return $settings; + if ($settings) { + return $settings; + } } - return array(); + return array('parameter' => []); } /** @@ -246,7 +248,7 @@ class Component $name = $path; $path = Path::join ($site->config->get('site', 'components'), $name, $name . '.php'); - $className = 'Components\\'. ucfirst($name). '\\' . ucfirst($name); + $className = implode("\\", ['Components', ucfirst($name), ucfirst($name)]); $component/*: Component*/ = null; diff --git a/src/Model/Factory.php b/src/Model/Factory.php index 39d30ca..dd99fd7 100644 --- a/src/Model/Factory.php +++ b/src/Model/Factory.php @@ -10,7 +10,7 @@ class Factory public $db; public $config; - public function __construct (Database $db, Registry $config = null, User $user) + public function __construct (Database $db, Registry $config = null, User $user = null) { $this->db = $db; $this->config = $config; From fff5b7b5c41890ce568b16d79af0f346cd517b21 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 1 Feb 2023 12:55:02 +0300 Subject: [PATCH 041/138] =?UTF-8?q?fix=20=D0=A0=D0=B0=D1=81=D1=87=D0=B5?= =?UTF-8?q?=D1=82=20=D0=BF=D1=83=D1=82=D0=B5=D0=B9=20=D0=B4=D0=BE=20=D1=88?= =?UTF-8?q?=D0=B0=D0=B1=D0=BB=D0=BE=D0=BD=D0=BE=D0=B2=20=D0=B8=20=D0=BA?= =?UTF-8?q?=D0=BE=D0=BC=D0=BF=D0=BE=D0=BD=D0=B5=D0=BD=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 37 ++++++++++++++++++------------------ src/Functions.php | 2 +- 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index f0c6647..02bdd9f 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -128,10 +128,10 @@ class Component $tpl->set('common', Path::join($this->config->get('system', 'web'), '../', 'common')); $tpl->set('script', Path::join($this->config->get('system', 'web'), 'js')); - $tpl->set('media', Path::join($this->config->get('system', 'web'), 'templates', $template)); + $tpl->set('media', Path::join($this->config->get('system', 'templates.web'), $template)); if ($default) { - $tpl->set('site_template', $this->config->get('site', 'web') . '/templates/' . $default); + $tpl->set('site_template', $this->config->get('site', 'templates.web') . $default); } $tpl->set('base', $this->config->get('site', 'web')); @@ -246,9 +246,11 @@ class Component parse_str($query, $arguments); } $name = $path; + $config = $site->config; - $path = Path::join ($site->config->get('site', 'components'), $name, $name . '.php'); - $className = implode("\\", ['Components', ucfirst($name), ucfirst($name)]); + $filename = ucfirst($name); + $path = Path::join ($config->get('site', 'components'), $name, $filename . '.php'); + $className = implode("\\", ['Components', ucfirst($name), $filename]); $component/*: Component*/ = null; @@ -256,35 +258,34 @@ class Component // require_once ($path); $component = new $className(); - $component->viewPath = array($site->config->get('site', 'path') . '/components/' . $name . '/'); - $component->webPath = array($site->config->get('site', 'web') . '/components/' . $name); - $component->COMPONENTS_WEB = $site->config->get('site', 'web') . '/components/'; + $component->viewPath = array($config->get('site', 'components') . '/' . $name . '/'); + $component->webPath = array($config->get('site', 'components.web') . '/' . $name); + $component->COMPONENTS_WEB = $config->get('site', 'web') . '/components/'; } else { $component = new $className(); - $template = $component->getTemplateName($site->config); $component->viewPath = array( // Сначало ищем локально - $site->config->get('site', 'path') . '/templates/' . $template . '/_components/' . $name . '/', - $site->config->get('site', 'path') . '/components/' . $name . '/', + $config->get('site', 'templates') . '/'. $template . '/_components/' . $name . '/', + $config->get('site', 'components') . '/' . $name . '/', // Потом в общем хранилище - CMS_PATH . '/../templates/' . $template . '/_components/' . $name . '/', - $site->config->get('system', 'components') . '/' . $name . '/', + $config->get('system', 'templates'). '/' . $template . '/_components/' . $name . '/', + $config->get('system', 'components') . '/' . $name . '/', ); if (defined('COMPONENTS_WEB')) { $component->webPath = array( // Сначало локально - $site->config->get('site', 'web') . '/templates/' . $template . '/_components/' . $name, - $site->config->get('site', 'web') . '/components/' . $name, + $config->get('site', 'templates.web') . '/' . $template . '/_components/' . $name, + $config->get('site', 'components.web') . '/' . $name, // Потом в общем хранилище - TEMPLATE_WEB . '/' . $template . '/_components/' . $name, - COMPONENTS_WEB . '/' . $name, + $config->get('system', 'templates.web') . '/' . $template . '/_components/' . $name, + $config->get('system', 'components.web') . '/' . $name, ); - $component->COMPONENTS_WEB = COMPONENTS_WEB; + $component->COMPONENTS_WEB = $config->get('system', 'components.web'); } else { - $component->webPath = array('', $site->config->get('site', 'web') . '/components/' . $name, ''); + $component->webPath = array('', $config->get('site', 'components.web') . '/' . $name, ''); } } diff --git a/src/Functions.php b/src/Functions.php index ec3032a..1c64ed1 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -364,7 +364,7 @@ class Functions { * @param string $key Имя ключа по значению которого будет идти сравнение * @return Array Отсортированный массив */ - static function sortOn($array, $key, $fn = 'Functions::__cmp') { + static function sortOn($array, $key, $fn = '\\ctiso\\Functions::__cmp') { usort ($array, Functions::rcurry($fn, $key)); //usort ($array, create_function ('$x,$y', 'return __cmp ($x, $y, "'.$key.'");')); return $array; From 8321ec244f6a93937590de8626f2cb529962128c Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 16 Feb 2023 16:18:29 +0300 Subject: [PATCH 042/138] =?UTF-8?q?fix=20=D0=9D=D0=B5=20=D0=B7=D0=B0=D0=BF?= =?UTF-8?q?=D0=B8=D1=81=D1=8B=D0=B2=D0=B0=D1=82=D1=8C=20=D1=84=D0=B0=D0=B9?= =?UTF-8?q?=D0=BB=20=D0=B5=D1=81=D0=BB=D0=B8=20=D0=BE=D0=BD=20=D0=BD=D0=B5?= =?UTF-8?q?=D0=B1=D1=8B=D0=BB=20=D0=BF=D1=80=D0=BE=D1=87=D1=82=D0=B5=D0=BD?= =?UTF-8?q?,=20=D0=B8=D0=BD=D0=B0=D1=87=D0=B5=20=D0=BC=D0=BE=D0=B6=D0=B5?= =?UTF-8?q?=D0=BC=20=D0=BF=D0=BE=D1=82=D0=B5=D1=80=D1=8F=D1=82=D1=8C=20?= =?UTF-8?q?=D0=B4=D0=B0=D0=BD=D0=BD=D1=8B=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Settings.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/Settings.php b/src/Settings.php index 69afd15..8345c1c 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -18,6 +18,7 @@ class Settings public $data = []; protected $file; protected $format = 'php'; + protected $is_read = false; public function __construct ($file = null, $format = false) { @@ -35,6 +36,7 @@ class Settings public function read() { if (!file_exists ($this->file)) { + $this->is_read = true; return false; } // Не include_once т.к читать настройки можно несколько раз @@ -49,6 +51,7 @@ class Settings throw new Exception('no data in ' . $this->file); } + $this->is_read = true; $this->data = $settings; return true; } @@ -165,6 +168,10 @@ class Settings */ public function write($file = null) { + if (!$this->is_read) { + throw new Exception('read settings before write'); + } + if ($this->format == 'json') { $result = json_encode($this->data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); } else { From 949510924a8340341cf4e76edaeee77f443fa4b9 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Mon, 27 Feb 2023 16:47:34 +0300 Subject: [PATCH 043/138] =?UTF-8?q?fix=20=D0=9C=D0=B5=D0=BB=D0=BA=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 2 +- src/Form/Upload.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 02bdd9f..a7ce660 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -131,7 +131,7 @@ class Component $tpl->set('media', Path::join($this->config->get('system', 'templates.web'), $template)); if ($default) { - $tpl->set('site_template', $this->config->get('site', 'templates.web') . $default); + $tpl->set('site_template', Path::join($this->config->get('site', 'templates.web'), $default)); } $tpl->set('base', $this->config->get('site', 'web')); diff --git a/src/Form/Upload.php b/src/Form/Upload.php index 3da54f8..7cd38b8 100644 --- a/src/Form/Upload.php +++ b/src/Form/Upload.php @@ -3,5 +3,5 @@ namespace ctiso\Form; use ctiso\Form\Field; -class TUpload extends Field { +class Upload extends Field { } From 3ca57c4557ab701037cee031486a17e5f73a86d0 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 1 Mar 2023 11:44:57 +0300 Subject: [PATCH 044/138] =?UTF-8?q?new=20=D0=9D=D0=BE=D0=B2=D0=BE=D0=B5=20?= =?UTF-8?q?=D0=BF=D1=80=D0=B0=D0=B2=D0=B8=D0=BB=D0=BE=20=D0=B4=D0=BB=D1=8F?= =?UTF-8?q?=20phptal=20=D0=B4=D0=BB=D1=8F=20=D0=BF=D0=BE=D0=B4=D0=BA=D0=BB?= =?UTF-8?q?=D1=8E=D1=87=D0=B5=D0=BD=D0=B8=D1=8F=20=D1=81=D1=82=D0=B8=D0=BB?= =?UTF-8?q?=D0=B5=D0=B9=20=D0=B2=20=D0=BA=D0=BE=D0=BC=D0=BF=D0=BE=D0=BD?= =?UTF-8?q?=D0=B5=D0=BD=D1=82=D0=B0=D1=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/tales.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/tales.php b/src/tales.php index 1bde50b..bc3be4f 100644 --- a/src/tales.php +++ b/src/tales.php @@ -30,6 +30,21 @@ class Component_Tales implements PHPTAL_Tales } } +class Assets_Tales implements PHPTAL_Tales +{ + static public function assets($expression, $nothrow = false) + { + $s = PHPTAL_Php_TalesInternal::string($expression); + return "phptal_asset(" . $s . ")"; + } +} + +function phptal_asset($s) { + if (class_exists("Controller_Site")) { + Controller_Site::addStyleSheet($s); + } + return ""; +} function phptal_date ($e) { @@ -68,4 +83,5 @@ $tales = PHPTAL_TalesRegistry::getInstance(); $tales->registerPrefix('component', array('Component_Tales', 'component')); $tales->registerPrefix('date', array('DateTime_Tales', 'date')); $tales->registerPrefix('time', array('DateTime_Tales', 'time')); +$tales->registerPrefix('assets', array('Assets_Tales', 'assets')); From ca2bcc428f6b1d6486e1b2dec8ebe0222326d78c Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 1 Mar 2023 12:05:27 +0300 Subject: [PATCH 045/138] =?UTF-8?q?fix=20=D0=9E=D0=BF=D0=B5=D1=87=D0=B0?= =?UTF-8?q?=D1=82=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Tales.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Tales.php b/src/Tales.php index eb598c6..5937db2 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -52,7 +52,7 @@ class Tales { } static function phptal_asset($s) { - self::$sit->addStyleSheet($s); + self::$site->addStyleSheet($s); return ""; } From 7c0a5ab310cdb849d97a160f1f6849f5f90cb67a Mon Sep 17 00:00:00 2001 From: System Administrator Date: Thu, 16 Mar 2023 16:27:52 +0300 Subject: [PATCH 046/138] =?UTF-8?q?fix=20=D0=98=D1=81=D0=BF=D1=80=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D0=B5=D0=BD=D0=BE=20=D0=BF=D0=BE=D0=BB=D1=83=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=B7=D0=BD=D0=B0=D1=87=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=20=D0=B7=D0=B0=D0=BF=D1=80=D0=BE=D1=81=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ComponentRequest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/ComponentRequest.php b/src/ComponentRequest.php index 15db81b..6bc7dbc 100644 --- a/src/ComponentRequest.php +++ b/src/ComponentRequest.php @@ -19,7 +19,8 @@ class ComponentRequest { if ($key == 'active_page') { return $this->r->get($key); } - if ($arr = $this->r->get($key)) { + $arr = $this->r->get($key); + if (!is_null($arr)) { if (is_array($arr)) { return Arr::get($arr, $this->component_id, $default); } else { From 93c0a67241c0e4646e58c76fe7d6ad6e9664d2a8 Mon Sep 17 00:00:00 2001 From: anatoly Date: Fri, 31 Mar 2023 18:09:34 +0300 Subject: [PATCH 047/138] creating views --- src/Database/Manager.php | 409 ++++++++++++++++++++------------------- 1 file changed, 209 insertions(+), 200 deletions(-) diff --git a/src/Database/Manager.php b/src/Database/Manager.php index 354a722..c54bd73 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -1,227 +1,236 @@ -db = $db; - } + function __construct(Database $db) { + $this->db = $db; + } - public function ExecuteAction($action/*: array*/, $db_file = "") { - switch($action["type"]) { - case "dropTable": - $this->DropTableQuery($action["table_name"], true); - break; - case "createTable": - $constraints = isset($action["constraints"]) ? $action["constraints"] : NULL; - $this->CreateTableQuery($action["table_name"], $action["fields"], $constraints); - break; - case "addColumn": - $this->AddColumn($action["table_name"], $action["column_name"], $action["field"]); - break; - case "insert": - $this->db->insertQuery($action["table_name"], $action["values"]); - break; - case "alterReference": - $this->AlterReference($action["table"], $action["column"], $action["refTable"], $action["refColumn"]); - break; - case "renameColumn": - $this->RenameColumn($action["table"], $action["old_name"], $action["new_name"]); - break; - case "executeFile": - if ($this->db->isPostgres() && isset($action["pgsql"])) { - $file = $action["pgsql"]; - } else { - $file = $action["source"]; - } + public function ExecuteAction($action/*: array*/, $db_file = "") { + switch($action["type"]) { + case "dropTable": + $this->DropTableQuery($action["table_name"], true); + break; + case "createTable": + $constraints = isset($action["constraints"]) ? $action["constraints"] : NULL; + $this->CreateTableQuery($action["table_name"], $action["fields"], $constraints); + break; + case "addColumn": + $this->AddColumn($action["table_name"], $action["column_name"], $action["field"]); + break; + case "insert": + $this->db->insertQuery($action["table_name"], $action["values"]); + break; + case "alterReference": + $this->AlterReference($action["table"], $action["column"], $action["refTable"], $action["refColumn"]); + break; + case "renameColumn": + $this->RenameColumn($action["table"], $action["old_name"], $action["new_name"]); + break; + case "createView": + $this->recreateView($action["view"], $action["select"]); + break; + case "executeFile": + if ($this->db->isPostgres() && isset($action["pgsql"])) { + $file = $action["pgsql"]; + } else { + $file = $action["source"]; + } - $stmtList = SQLStatementExtractor::extractFile(Path::join(dirname($db_file), $file)); - foreach($stmtList as $stmt) { - $this->db->executeQuery($stmt); - } + $stmtList = SQLStatementExtractor::extractFile(Path::join(dirname($db_file), $file)); + foreach($stmtList as $stmt) { + $this->db->executeQuery($stmt); + } - break; - default: - throw new Exception("unknown action ". $action["type"] . PHP_EOL); - } - } + break; + default: + throw new Exception("unknown action ". $action["type"] . PHP_EOL); + } + } - public function DropTableQuery($table, $cascade=false) { - $statement = "DROP TABLE IF EXISTS ".$table; - if ($this->db->isPostgres()&&$cascade) { - $statement = $statement." CASCADE"; - } - $this->db->query($statement); - } + //Дропает и создаёт SQL VIEW + public function recreateView($viewName, $selectStatement) { + $this->db->query("DROP VIEW ".$viewName); + $this->db->query("CREATE VIEW ".$viewName." AS ".$selectStatement); + } - public function AlterReference($table,$column,$refTable,$refColumn) { - $this->db->query("ALTER TABLE ".$table." ADD CONSTRAINT ".$table."_".$column."fk"." FOREIGN KEY (".$column.") REFERENCES ".$refTable." (".$refColumn.")"); - } + public function DropTableQuery($table, $cascade=false) { + $statement = "DROP TABLE IF EXISTS ".$table; + if ($this->db->isPostgres()&&$cascade) { + $statement = $statement." CASCADE"; + } + $this->db->query($statement); + } - //Извлечение информации о полях таблицы - 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.");"); - if (empty($results)) { - return null; - } - $fields = []; - foreach ($results as $result) { - $fields[$result["name"]] = [ - "type"=> $result["type"], - "not_null"=> boolval($result["notnull"]), - "constraint"=> ((boolean) $result["pk"]) ? "PRIMARY KEY" : null - ]; - } - return $fields; - } - } + public function AlterReference($table,$column,$refTable,$refColumn) { + $this->db->query("ALTER TABLE ".$table." ADD CONSTRAINT ".$table."_".$column."fk"." FOREIGN KEY (".$column.") REFERENCES ".$refTable." (".$refColumn.")"); + } - public function RenameColumn($table, $old_name, $new_name) { - $pg = $this->db->isPostgres(); - if ($pg) { - $this->db->query("ALTER TABLE ".$table." RENAME COLUMN ".$old_name." TO ".$new_name); - } else { - $tmp_table = "tmp_" . $table; - $this->DropTableQuery($tmp_table); - $table_info = $this->TableInfo($table); + //Извлечение информации о полях таблицы + 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.");"); + if (empty($results)) { + return null; + } + $fields = []; + foreach ($results as $result) { + $fields[$result["name"]] = [ + "type"=> $result["type"], + "not_null"=> boolval($result["notnull"]), + "constraint"=> ((boolean) $result["pk"]) ? "PRIMARY KEY" : null + ]; + } + return $fields; + } + } - if (isset($table_info[$new_name])) { - return; - } + public function RenameColumn($table, $old_name, $new_name) { + $pg = $this->db->isPostgres(); + if ($pg) { + $this->db->query("ALTER TABLE ".$table." RENAME COLUMN ".$old_name." TO ".$new_name); + } else { + $tmp_table = "tmp_" . $table; + $this->DropTableQuery($tmp_table); + $table_info = $this->TableInfo($table); - $data/*: array*/ = $this->DumpTable($table); + if (isset($table_info[$new_name])) { + return; + } - $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); + $data/*: array*/ = $this->DumpTable($table); - foreach ($data as $row) { - $values = $row['values']; - $values[$new_name] = $values[$old_name]; - unset($values[$old_name]); - $this->db->insertQuery($table, $values); - } - $this->DropTableQuery($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); - //Обновление ключа serial после ручной вставки - public function UpdateSerial($table,$column) { - $this->db->query("SELECT setval(pg_get_serial_sequence('".$table."', '".$column."'), coalesce(max(".$column."),0) + 1, false) FROM ".$table); - } + foreach ($data as $row) { + $values = $row['values']; + $values[$new_name] = $values[$old_name]; + unset($values[$old_name]); + $this->db->insertQuery($table, $values); + } + $this->DropTableQuery($tmp_table); + } + } - public function Column_Definition($name,$data,$pg){ - $constraint = isset($data['constraint'])?" ".$data['constraint']:""; - $references = ""; - if (isset($data['references'])) { - $references = " REFERENCES ".$data['references']; - } - if (isset($data["not_null"]) && $data["not_null"]) - $constraint .=" NOT NULL"; - $type = $data['type']; - if (!$pg) { - if (strtolower($type)=="serial") - $type = "integer"; - //if (strtolower($type)=="boolean") - // $type = "integer"; - } - return $name." ".$type.$references.$constraint; - } + //Обновление ключа serial после ручной вставки + public function UpdateSerial($table,$column) { + $this->db->query("SELECT setval(pg_get_serial_sequence('".$table."', '".$column."'), coalesce(max(".$column."),0) + 1, false) FROM ".$table); + } - public function AddColumn($table_name,$column_name,$field){ - $pg = $this->db->isPostgres(); - $q = "ALTER TABLE ".$table_name." ADD COLUMN ". - $this->Column_Definition($column_name, $field, $pg); - $this->db->query($q); - } + public function Column_Definition($name,$data,$pg){ + $constraint = isset($data['constraint'])?" ".$data['constraint']:""; + $references = ""; + if (isset($data['references'])) { + $references = " REFERENCES ".$data['references']; + } + if (isset($data["not_null"]) && $data["not_null"]) + $constraint .=" NOT NULL"; + $type = $data['type']; + if (!$pg) { + if (strtolower($type)=="serial") + $type = "integer"; + //if (strtolower($type)=="boolean") + // $type = "integer"; + } + return $name." ".$type.$references.$constraint; + } - function getConstraintDef($c/*: array*/) { - if ($c['type'] == 'unique') { - return "UNIQUE(" . implode(", ", $c['fields']) . ")"; - } - return ""; + public function AddColumn($table_name,$column_name,$field){ + $pg = $this->db->isPostgres(); + $q = "ALTER TABLE ".$table_name." ADD COLUMN ". + $this->Column_Definition($column_name, $field, $pg); + $this->db->query($q); + } + + function getConstraintDef($c/*: array*/) { + if ($c['type'] == 'unique') { + return "UNIQUE(" . implode(", ", $c['fields']) . ")"; + } + return ""; + } + + //CreateTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']]) + public function CreateTableQuery($table, $fields, $constraints) { + $pg = $this->db->isPostgres(); + if ($constraints) { + if (is_array($constraints)) { + $constraints = $this->getConstraintDef($constraints); + } + $constraints = ", " . $constraints; } - //CreateTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']]) - public function CreateTableQuery($table, $fields, $constraints) { - $pg = $this->db->isPostgres(); - if ($constraints) { - if (is_array($constraints)) { - $constraints = $this->getConstraintDef($constraints); + $statement = "CREATE TABLE $table (" . implode(",", + array_map(function($name,$data) use ($pg) { + return $this->Column_Definition($name,$data,$pg); + }, array_keys($fields), array_values($fields)) + ) . " " . $constraints . ")"; + $this->db->query($statement); + } + + public function DumpTable($table_name) { + $pg = $this->db->isPostgres(); + + $result/*: array*/ = array(); + $data/*: array*/ = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); + + if (!$pg) { + $table_fields = $this->TableInfo($table_name); + foreach ($table_fields as $name => $value) { + $type = strtolower($value['type']); + if ($type == "boolean") { + foreach ($data as &$row) { + $row/*: array*/ = $row; + if (isset($row[$name])) { + $row[$name] = boolval($row[$name]); } - $constraints = ", " . $constraints; + } } + } + } + foreach ($data as $r) { + $result[] = array( + "type" => "insert", + "table_name" => $table_name, + "values" => $r + ); + } + return $result; + } - $statement = "CREATE TABLE $table (" . implode(",", - array_map(function($name,$data) use ($pg) { - return $this->Column_Definition($name,$data,$pg); - }, array_keys($fields), array_values($fields)) - ) . " " . $constraints . ")"; - $this->db->query($statement); - } + public function GetAllTableNames() { + $result = []; + if ($this->db->isPostgres()) { + $query = "SELECT table_name as name FROM information_schema.tables WHERE table_schema='public'"; + } else { + $query = "SELECT * FROM sqlite_master WHERE type='table'"; + } + $tables = $this->db->fetchAllArray($query); + foreach ($tables as $table) { + $result[] = $table['name']; + } + return $result; + } - public function DumpTable($table_name) { - $pg = $this->db->isPostgres(); - - $result/*: array*/ = array(); - $data/*: array*/ = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); - - if (!$pg) { - $table_fields = $this->TableInfo($table_name); - foreach ($table_fields as $name => $value) { - $type = strtolower($value['type']); - if ($type == "boolean") { - foreach ($data as &$row) { - $row/*: array*/ = $row; - if (isset($row[$name])) { - $row[$name] = boolval($row[$name]); - } - } - } - } - } - foreach ($data as $r) { - $result[] = array( - "type" => "insert", - "table_name" => $table_name, - "values" => $r - ); - } - return $result; - } - - public function GetAllTableNames() { - $result = []; - if ($this->db->isPostgres()) { - $query = "SELECT table_name as name FROM information_schema.tables WHERE table_schema='public'"; - } else { - $query = "SELECT * FROM sqlite_master WHERE type='table'"; - } - $tables = $this->db->fetchAllArray($query); - foreach ($tables as $table) { - $result[] = $table['name']; - } - return $result; - } - - public function DumpInserts() { - $table_names = $this->GetAllTableNames(); - $result = array(); - foreach ($table_names as $table_name) { - $result = array_merge($result, $this->DumpTable($table_name)); - } - return $result; - } -} \ No newline at end of file + public function DumpInserts() { + $table_names = $this->GetAllTableNames(); + $result = array(); + foreach ($table_names as $table_name) { + $result = array_merge($result, $this->DumpTable($table_name)); + } + return $result; + } +} From 29a18f5410e3fcb6a4495726a440c4699b1ea92e Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 13 Apr 2023 11:34:19 +0300 Subject: [PATCH 048/138] =?UTF-8?q?fix=20=D0=9F=D0=B0=D1=80=D0=B0=D0=BC?= =?UTF-8?q?=D0=B5=D1=82=D1=80=D1=8B=20=D0=B4=D0=BB=D1=8F=20=D0=BA=D0=BE?= =?UTF-8?q?=D0=BC=D0=BF=D0=BE=D0=BD=D0=B5=D0=BD=D1=82=D0=BE=D0=B2=20=D0=B8?= =?UTF-8?q?=D0=B7=20get?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 2 +- src/Form/Form.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index a7ce660..4e6f459 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -320,7 +320,7 @@ class Component } $params = new Collection(); - $params->import($arguments); + $params->import(array_merge($_GET, $arguments)); $component->parameter = $params; $component->template = $params->get('template', false); diff --git a/src/Form/Form.php b/src/Form/Form.php index 343f254..3bdd32e 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -96,7 +96,7 @@ class Form extends View { $el->hint = $init['hint']; } - $this->field [$init['name']] = $el; + $this->field[$init['name']] = $el; return $el; } From 2edd65d145d77846401ad05597a60c697d223d0c Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 13 Apr 2023 11:38:49 +0300 Subject: [PATCH 049/138] fix format --- src/Controller/Action.php | 44 +-- src/Database/JsonInstall.php | 240 +++++++-------- src/Database/Manager.php | 455 +++++++++++++++-------------- src/Database/PDOStatement.php | 32 +- src/Database/StatementIterator.php | 24 +- 5 files changed, 407 insertions(+), 388 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 2066995..b73b685 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -23,7 +23,7 @@ class Action const TEMPLATE_EXTENSION = ".html"; // Расширение для шаблонов const ACTION_PREFIX = "action"; // Префикс для функций действий - // Параметры устанавливаются при создании контроллера + // Параметры устанавливаются при создании контроллера public $name = ''; // Имя модуля public $front; @@ -37,12 +37,12 @@ class Action */ public $db; - // Фильтры + // Фильтры public $access = null; // Обьект хранит параметры доступа public $logger = null; // Обьект для ведения лога - private $factory = null; // Ссылка на обьект создания модели - private $helpers = array(); // Помошники для действий + private $factory = null; // Ссылка на обьект создания модели + private $helpers = array(); // Помошники для действий public $part = null; // Параметры для ссылки public $config/*: Registry*/; // Ссылка на настройки @@ -100,7 +100,7 @@ class Action /** * Создает представление - * @param string + * @param string * @param string $viewClass * @return Composite */ @@ -130,7 +130,7 @@ class Action $scriptPath = Path::join($webPath, 'assets'); $tpl->set('icons', $iconsPath); // Путь к файлам текущей темы - $tpl->set('assets', $stylePath); + $tpl->set('assets', $stylePath); $tpl->set('script', $scriptPath); // Путь к файлам скриптов $tpl->set('template', $path); // Путь к файлам текущего шаблона @@ -162,7 +162,7 @@ class Action * Т.к действия являются методами класса то * 1. Можно переопределить действия * 2. Использовать наследование чтобы добавить к старому обработчику новое поведение - * @param HttpRequest $request запроса + * @param HttpRequest $request запроса */ public function preProcess(HttpRequest $request) { @@ -172,12 +172,12 @@ class Action } $view = $this->forward($action, $request); if ($view instanceof View) { - $view->active_module = get_class($this); - $view->module_action = $action; - } - return $view; + $view->active_module = get_class($this); + $view->module_action = $action; + } + return $view; } - + public function execute(HttpRequest $request) { $result = $this->preProcess($request); @@ -298,14 +298,14 @@ class Action /** * Установка заголовка для отображения - */ + */ public function setTitle($title) { $this->view->setTitle($title); } /** - * Добавление widget к отображению + * Добавление widget к отображению */ public function addChild($section, $node) { @@ -318,9 +318,9 @@ class Action } /** - * Добавление дочернего отображения к текущему отображению + * Добавление дочернего отображения к текущему отображению */ - public function addView($section, $node) + public function addView($section, $node) { $this->childViews[$section] = $node; } @@ -329,11 +329,11 @@ class Action * Генерация содержания * Путаница c execute и render */ - public function render() + public function render() { $view = $this->view; - if ($view instanceof View) { - $this->view->assignValues($this->ctrlValues); + if ($view instanceof View) { + $this->view->assignValues($this->ctrlValues); $node/*: Composite*/ = null; foreach ($this->childNodes as $name => $node) { @@ -344,17 +344,17 @@ class Action foreach ($this->childViews as $name => $node) { $this->view->setView($name, $node); } - } + } return $this->view; } function getPageId(HttpRequest $request) { - $pageId = time(); + $pageId = time(); $request->session()->set('page', $pageId); return $pageId; } - function checkPageId(HttpRequest $request, $page) + function checkPageId(HttpRequest $request, $page) { if ($request->get('__forced__')) { return true; diff --git a/src/Database/JsonInstall.php b/src/Database/JsonInstall.php index 6acb9b7..9fc0c2f 100644 --- a/src/Database/JsonInstall.php +++ b/src/Database/JsonInstall.php @@ -8,139 +8,139 @@ class JsonInstall { public $db_manager; public $serialColumns; - public function __construct(Manager $db_manager) { - $this->db_manager = $db_manager; - } + public function __construct(Manager $db_manager) { + $this->db_manager = $db_manager; + } - function install($dbinit_path, $dbfill_path = null) { - $dbinit_file = file_get_contents($dbinit_path); - if (is_string($dbinit_file)) { - $initActions = json_decode($dbinit_file, true); - if (!$initActions) { - echo "Invalid ".$dbinit_path; - return 0; - } - } else { - echo "No ".$dbinit_path; - return 0; - } + function install($dbinit_path, $dbfill_path = null) { + $dbinit_file = file_get_contents($dbinit_path); + if (is_string($dbinit_file)) { + $initActions = json_decode($dbinit_file, true); + if (!$initActions) { + echo "Invalid ".$dbinit_path; + return 0; + } + } else { + echo "No ".$dbinit_path; + return 0; + } - $this->initDataBase($initActions, $dbinit_path); - if ($dbfill_path) { - $this->fillDataBase($dbfill_path); - } - $this->makeConstraints($initActions); - } + $this->initDataBase($initActions, $dbinit_path); + if ($dbfill_path) { + $this->fillDataBase($dbfill_path); + } + $this->makeConstraints($initActions); + } - function missingTables($tables) { - $actual_tables = $this->db_manager->GetAllTableNames(); - $missingTables = []; - foreach ($tables as $table) { - if (!in_array($table, $actual_tables)) - $missingTables[] = $table; - } - return $missingTables; - } + function missingTables($tables) { + $actual_tables = $this->db_manager->GetAllTableNames(); + $missingTables = []; + foreach ($tables as $table) { + if (!in_array($table, $actual_tables)) + $missingTables[] = $table; + } + return $missingTables; + } - //Создать таблицы - function initDataBase($initActions/*: array*/, $dbinit_path) { - $pg = $this->db_manager->db->isPostgres(); - if (!$pg) { - $refs = []; - //В sqlite нет alter reference. Референсы надо создавать при создании таблицы. - foreach ($initActions as $action) { - if ($action["type"] == "alterReference") { - if (!isset($refs[$action["table"]])) - $refs[$action["table"]] = []; - $refs[$action["table"]][]=$action;//добавить к списку референсов для таблицы - } - } - } + //Создать таблицы + function initDataBase($initActions/*: array*/, $dbinit_path) { + $pg = $this->db_manager->db->isPostgres(); + if (!$pg) { + $refs = []; + //В sqlite нет alter reference. Референсы надо создавать при создании таблицы. + foreach ($initActions as $action) { + if ($action["type"] == "alterReference") { + if (!isset($refs[$action["table"]])) + $refs[$action["table"]] = []; + $refs[$action["table"]][]=$action;//добавить к списку референсов для таблицы + } + } + } - foreach ($initActions as $action) { - if (!$pg) { - if ($action["type"] == "createTable") { - $table_name = $action["table_name"]; - if (isset($refs[$table_name])) { - foreach ($refs[$table_name] as $value) { - $action['fields'][$value['column']]['references'] = - $value['refTable']."(".$value['refColumn'].")"; - } - } + foreach ($initActions as $action) { + if (!$pg) { + if ($action["type"] == "createTable") { + $table_name = $action["table_name"]; + if (isset($refs[$table_name])) { + foreach ($refs[$table_name] as $value) { + $action['fields'][$value['column']]['references'] = + $value['refTable']."(".$value['refColumn'].")"; + } + } - } - } - if ($action["type"] != "alterReference") { - $this->db_manager->ExecuteAction($action, $dbinit_path); - } - } + } + } + if ($action["type"] != "alterReference") { + $this->db_manager->ExecuteAction($action, $dbinit_path); + } + } - //Запомнить все колонки serial - $this->serialColumns = []; - if ($pg) { - foreach ($initActions as $action) { - if ($action["type"] == "createTable") { - foreach ($action["fields"] as $name => $field) { - if ($field["type"]=="serial") { - $this->serialColumns[] = [ + //Запомнить все колонки serial + $this->serialColumns = []; + if ($pg) { + foreach ($initActions as $action) { + if ($action["type"] == "createTable") { + foreach ($action["fields"] as $name => $field) { + if ($field["type"]=="serial") { + $this->serialColumns[] = [ "table"=>$action["table_name"], - "column"=>$name + "column"=>$name ]; - } - } - } - } - } - } + } + } + } + } + } + } - //Заполнить данными - function fillDataBase($dbfill_file_path) { - $dbfill_file = file_get_contents($dbfill_file_path); - if (is_string($dbfill_file)) { - $actions = json_decode($dbfill_file,true); - if ($actions) { - - //Проверка что упоминаемые в списке действий таблицы уже есть в базе - $affected_tables = []; - foreach ($actions as $action) { - if ($action["table_name"]) { - $affected_tables[$action["table_name"]] = 1; + //Заполнить данными + function fillDataBase($dbfill_file_path) { + $dbfill_file = file_get_contents($dbfill_file_path); + if (is_string($dbfill_file)) { + $actions = json_decode($dbfill_file,true); + if ($actions) { + + //Проверка что упоминаемые в списке действий таблицы уже есть в базе + $affected_tables = []; + foreach ($actions as $action) { + if ($action["table_name"]) { + $affected_tables[$action["table_name"]] = 1; } } - $missing = $this->missingTables(array_keys($affected_tables)); - if (!empty($missing)) { - echo "dbfill error. Missing tables: ".implode(" ", $missing); - return; - } - - //Выполнение действий - foreach ($actions as $action) { - $this->db_manager->ExecuteAction($action, $dbfill_file_path); - } - } else { - echo "Invalid dbfill.json"; - } - } else { - echo "No dbfill.json"; - } - } - - //Обновить ключи serial и создать ограничения - function makeConstraints($initActions) { - $pg = $this->db_manager->db->isPostgres(); - if ($pg) { - foreach ($this->serialColumns as $serialColumn) { - $this->db_manager->UpdateSerial($serialColumn["table"], $serialColumn["column"]); - } - - - foreach ($initActions as $action) { - if ($action["type"] == "alterReference") { - $this->db_manager->ExecuteAction($action); + $missing = $this->missingTables(array_keys($affected_tables)); + if (!empty($missing)) { + echo "dbfill error. Missing tables: ".implode(" ", $missing); + return; } - } - } - } + + //Выполнение действий + foreach ($actions as $action) { + $this->db_manager->ExecuteAction($action, $dbfill_file_path); + } + } else { + echo "Invalid dbfill.json"; + } + } else { + echo "No dbfill.json"; + } + } + + //Обновить ключи serial и создать ограничения + function makeConstraints($initActions) { + $pg = $this->db_manager->db->isPostgres(); + if ($pg) { + foreach ($this->serialColumns as $serialColumn) { + $this->db_manager->UpdateSerial($serialColumn["table"], $serialColumn["column"]); + } + + + foreach ($initActions as $action) { + if ($action["type"] == "alterReference") { + $this->db_manager->ExecuteAction($action); + } + } + } + } } \ No newline at end of file diff --git a/src/Database/Manager.php b/src/Database/Manager.php index c54bd73..669b570 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -1,236 +1,255 @@ db = $db; - } - - public function ExecuteAction($action/*: array*/, $db_file = "") { - switch($action["type"]) { - case "dropTable": - $this->DropTableQuery($action["table_name"], true); - break; - case "createTable": - $constraints = isset($action["constraints"]) ? $action["constraints"] : NULL; - $this->CreateTableQuery($action["table_name"], $action["fields"], $constraints); - break; - case "addColumn": - $this->AddColumn($action["table_name"], $action["column_name"], $action["field"]); - break; - case "insert": - $this->db->insertQuery($action["table_name"], $action["values"]); - break; - case "alterReference": - $this->AlterReference($action["table"], $action["column"], $action["refTable"], $action["refColumn"]); - break; - case "renameColumn": - $this->RenameColumn($action["table"], $action["old_name"], $action["new_name"]); - break; - case "createView": - $this->recreateView($action["view"], $action["select"]); - break; - case "executeFile": - if ($this->db->isPostgres() && isset($action["pgsql"])) { - $file = $action["pgsql"]; - } else { - $file = $action["source"]; - } - - $stmtList = SQLStatementExtractor::extractFile(Path::join(dirname($db_file), $file)); - foreach($stmtList as $stmt) { - $this->db->executeQuery($stmt); - } - - break; - default: - throw new Exception("unknown action ". $action["type"] . PHP_EOL); - } - } - - //Дропает и создаёт SQL VIEW - public function recreateView($viewName, $selectStatement) { - $this->db->query("DROP VIEW ".$viewName); - $this->db->query("CREATE VIEW ".$viewName." AS ".$selectStatement); - } - - public function DropTableQuery($table, $cascade=false) { - $statement = "DROP TABLE IF EXISTS ".$table; - if ($this->db->isPostgres()&&$cascade) { - $statement = $statement." CASCADE"; - } - $this->db->query($statement); - } - - public function AlterReference($table,$column,$refTable,$refColumn) { - $this->db->query("ALTER TABLE ".$table." ADD CONSTRAINT ".$table."_".$column."fk"." FOREIGN KEY (".$column.") REFERENCES ".$refTable." (".$refColumn.")"); - } - - //Извлечение информации о полях таблицы - 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.");"); - if (empty($results)) { - return null; - } - $fields = []; - foreach ($results as $result) { - $fields[$result["name"]] = [ - "type"=> $result["type"], - "not_null"=> boolval($result["notnull"]), - "constraint"=> ((boolean) $result["pk"]) ? "PRIMARY KEY" : null - ]; - } - return $fields; - } - } - - public function RenameColumn($table, $old_name, $new_name) { - $pg = $this->db->isPostgres(); - if ($pg) { - $this->db->query("ALTER TABLE ".$table." RENAME COLUMN ".$old_name." TO ".$new_name); - } else { - $tmp_table = "tmp_" . $table; - $this->DropTableQuery($tmp_table); - $table_info = $this->TableInfo($table); - - if (isset($table_info[$new_name])) { - return; - } - - $data/*: array*/ = $this->DumpTable($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); - - foreach ($data as $row) { - $values = $row['values']; - $values[$new_name] = $values[$old_name]; - unset($values[$old_name]); - $this->db->insertQuery($table, $values); - } - $this->DropTableQuery($tmp_table); - } - } - - //Обновление ключа serial после ручной вставки - public function UpdateSerial($table,$column) { - $this->db->query("SELECT setval(pg_get_serial_sequence('".$table."', '".$column."'), coalesce(max(".$column."),0) + 1, false) FROM ".$table); - } - - public function Column_Definition($name,$data,$pg){ - $constraint = isset($data['constraint'])?" ".$data['constraint']:""; - $references = ""; - if (isset($data['references'])) { - $references = " REFERENCES ".$data['references']; - } - if (isset($data["not_null"]) && $data["not_null"]) - $constraint .=" NOT NULL"; - $type = $data['type']; - if (!$pg) { - if (strtolower($type)=="serial") - $type = "integer"; - //if (strtolower($type)=="boolean") - // $type = "integer"; - } - return $name." ".$type.$references.$constraint; - } - - public function AddColumn($table_name,$column_name,$field){ - $pg = $this->db->isPostgres(); - $q = "ALTER TABLE ".$table_name." ADD COLUMN ". - $this->Column_Definition($column_name, $field, $pg); - $this->db->query($q); - } - - function getConstraintDef($c/*: array*/) { - if ($c['type'] == 'unique') { - return "UNIQUE(" . implode(", ", $c['fields']) . ")"; - } - return ""; - } - - //CreateTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']]) - public function CreateTableQuery($table, $fields, $constraints) { - $pg = $this->db->isPostgres(); - if ($constraints) { - if (is_array($constraints)) { - $constraints = $this->getConstraintDef($constraints); - } - $constraints = ", " . $constraints; + public function __construct(Database $db) + { + $this->db = $db; } - $statement = "CREATE TABLE $table (" . implode(",", - array_map(function($name,$data) use ($pg) { - return $this->Column_Definition($name,$data,$pg); - }, array_keys($fields), array_values($fields)) - ) . " " . $constraints . ")"; - $this->db->query($statement); - } + public function ExecuteAction($action/*: array*/, $db_file = "") + { + switch($action["type"]) { + case "dropTable": + $this->DropTableQuery($action["table_name"], true); + break; + case "createTable": + $constraints = isset($action["constraints"]) ? $action["constraints"] : null; + $this->CreateTableQuery($action["table_name"], $action["fields"], $constraints); + break; + case "addColumn": + $this->AddColumn($action["table_name"], $action["column_name"], $action["field"]); + break; + case "insert": + $this->db->insertQuery($action["table_name"], $action["values"]); + break; + case "alterReference": + $this->AlterReference($action["table"], $action["column"], $action["refTable"], $action["refColumn"]); + break; + case "renameColumn": + $this->RenameColumn($action["table"], $action["old_name"], $action["new_name"]); + break; + case "createView": + $this->recreateView($action["view"], $action["select"]); + break; + case "executeFile": + if ($this->db->isPostgres() && isset($action["pgsql"])) { + $file = $action["pgsql"]; + } else { + $file = $action["source"]; + } - public function DumpTable($table_name) { - $pg = $this->db->isPostgres(); + $stmtList = SQLStatementExtractor::extractFile(Path::join(dirname($db_file), $file)); + foreach ($stmtList as $stmt) { + $this->db->executeQuery($stmt); + } - $result/*: array*/ = array(); - $data/*: array*/ = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); - - if (!$pg) { - $table_fields = $this->TableInfo($table_name); - foreach ($table_fields as $name => $value) { - $type = strtolower($value['type']); - if ($type == "boolean") { - foreach ($data as &$row) { - $row/*: array*/ = $row; - if (isset($row[$name])) { - $row[$name] = boolval($row[$name]); - } - } + break; + default: + throw new Exception("unknown action ". $action["type"] . PHP_EOL); } - } } - foreach ($data as $r) { - $result[] = array( - "type" => "insert", - "table_name" => $table_name, - "values" => $r - ); - } - return $result; - } - public function GetAllTableNames() { - $result = []; - if ($this->db->isPostgres()) { - $query = "SELECT table_name as name FROM information_schema.tables WHERE table_schema='public'"; - } else { - $query = "SELECT * FROM sqlite_master WHERE type='table'"; + //Дропает и создаёт SQL VIEW + public function recreateView($viewName, $selectStatement) + { + $this->db->query("DROP VIEW ".$viewName); + $this->db->query("CREATE VIEW ".$viewName." AS ".$selectStatement); } - $tables = $this->db->fetchAllArray($query); - foreach ($tables as $table) { - $result[] = $table['name']; - } - return $result; - } - public function DumpInserts() { - $table_names = $this->GetAllTableNames(); - $result = array(); - foreach ($table_names as $table_name) { - $result = array_merge($result, $this->DumpTable($table_name)); + public function DropTableQuery($table, $cascade=false) + { + $statement = "DROP TABLE IF EXISTS ".$table; + if ($this->db->isPostgres()&&$cascade) { + $statement = $statement." CASCADE"; + } + $this->db->query($statement); + } + + public function AlterReference($table, $column, $refTable, $refColumn) + { + $this->db->query("ALTER TABLE ".$table." ADD CONSTRAINT ".$table."_".$column."fk"." FOREIGN KEY (".$column.") REFERENCES ".$refTable." (".$refColumn.")"); + } + + //Извлечение информации о полях таблицы + 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.");"); + 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 + ]; + } + return $fields; + } + } + + public function RenameColumn($table, $old_name, $new_name) + { + $pg = $this->db->isPostgres(); + if ($pg) { + $this->db->query("ALTER TABLE ".$table." RENAME COLUMN ".$old_name." TO ".$new_name); + } else { + $tmp_table = "tmp_" . $table; + $this->DropTableQuery($tmp_table); + $table_info = $this->TableInfo($table); + + if (isset($table_info[$new_name])) { + return; + } + + $data/*: array*/ = $this->DumpTable($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); + + foreach ($data as $row) { + $values = $row['values']; + $values[$new_name] = $values[$old_name]; + unset($values[$old_name]); + $this->db->insertQuery($table, $values); + } + $this->DropTableQuery($tmp_table); + } + } + + //Обновление ключа serial после ручной вставки + public function UpdateSerial($table, $column) + { + $this->db->query("SELECT setval(pg_get_serial_sequence('".$table."', '".$column."'), coalesce(max(".$column."),0) + 1, false) FROM ".$table); + } + + public function Column_Definition($name, $data, $pg) + { + $constraint = isset($data['constraint']) ? " ".$data['constraint'] : ""; + $references = ""; + if (isset($data['references'])) { + $references = " REFERENCES ".$data['references']; + } + if (isset($data["not_null"]) && $data["not_null"]) { + $constraint .=" NOT NULL"; + } + $type = $data['type']; + if (!$pg) { + if (strtolower($type)=="serial") { + $type = "integer"; + } + //if (strtolower($type)=="boolean") + // $type = "integer"; + } + return $name." ".$type.$references.$constraint; + } + + public function AddColumn($table_name, $column_name, $field) + { + $pg = $this->db->isPostgres(); + $q = "ALTER TABLE ".$table_name." ADD COLUMN ". + $this->Column_Definition($column_name, $field, $pg); + $this->db->query($q); + } + + public function getConstraintDef($c/*: array*/) + { + if ($c['type'] == 'unique') { + return "UNIQUE(" . implode(", ", $c['fields']) . ")"; + } + return ""; + } + + //CreateTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']]) + public function CreateTableQuery($table, $fields, $constraints) + { + $pg = $this->db->isPostgres(); + if ($constraints) { + if (is_array($constraints)) { + $constraints = $this->getConstraintDef($constraints); + } + $constraints = ", " . $constraints; + } + + $statement = "CREATE TABLE $table (" . implode( + ",", + array_map(function ($name, $data) use ($pg) { + return $this->Column_Definition($name, $data, $pg); + }, array_keys($fields), array_values($fields)) + ) . " " . $constraints . ")"; + $this->db->query($statement); + } + + public function DumpTable($table_name) + { + $pg = $this->db->isPostgres(); + + $result/*: array*/ = array(); + $data/*: array*/ = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); + + if (!$pg) { + $table_fields = $this->TableInfo($table_name); + foreach ($table_fields as $name => $value) { + $type = strtolower($value['type']); + if ($type == "boolean") { + foreach ($data as &$row) { + $row/*: array*/ = $row; + if (isset($row[$name])) { + $row[$name] = boolval($row[$name]); + } + } + } + } + } + foreach ($data as $r) { + $result[] = array( + "type" => "insert", + "table_name" => $table_name, + "values" => $r + ); + } + return $result; + } + + public function GetAllTableNames() + { + $result = []; + if ($this->db->isPostgres()) { + $query = "SELECT table_name as name FROM information_schema.tables WHERE table_schema='public'"; + } else { + $query = "SELECT * FROM sqlite_master WHERE type='table'"; + } + $tables = $this->db->fetchAllArray($query); + foreach ($tables as $table) { + $result[] = $table['name']; + } + return $result; + } + + public function DumpInserts() + { + $table_names = $this->GetAllTableNames(); + $result = array(); + foreach ($table_names as $table_name) { + $result = array_merge($result, $this->DumpTable($table_name)); + } + return $result; } - return $result; - } } diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index af8c19f..1ae56df 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -10,33 +10,33 @@ use TheSeer\Tokenizer\Exception; class PDOStatement extends \PDOStatement implements \IteratorAggregate { protected $cursorPos = 0; - public $cache = array(); + public $cache = array(); public $fields; function getIterator(): \Iterator { return new StatementIterator($this); } - protected function __construct() { + protected function __construct() { } - function rewind() { + function rewind() { $this->cursorPos = 0; } - public function seek($rownum) { - if ($rownum < 0) { - return false; - } - - // PostgreSQL rows start w/ 0, but this works, because we are - // looking to move the position _before_ the next desired position - $this->cursorPos = $rownum; - return true; - } + public function seek($rownum) { + if ($rownum < 0) { + return false; + } + + // PostgreSQL rows start w/ 0, but this works, because we are + // looking to move the position _before_ the next desired position + $this->cursorPos = $rownum; + return true; + } function valid() { - return true; + return true; } @@ -49,7 +49,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate if ($this->getRecordCount() > $this->cursorPos) { if (!isset($this->cache[$this->cursorPos])) { $this->cache[$this->cursorPos] = $this->fetch(PDO::FETCH_ASSOC); - } + } $this->fields = $this->cache[$this->cursorPos]; $this->cursorPos++; @@ -102,7 +102,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate function getRecordCount() { return count($this->cache); } - + function execute($args = null) { $result = parent::execute($args); return $result; diff --git a/src/Database/StatementIterator.php b/src/Database/StatementIterator.php index aad0c90..eebd752 100644 --- a/src/Database/StatementIterator.php +++ b/src/Database/StatementIterator.php @@ -10,40 +10,40 @@ class StatementIterator implements \Iterator private $pos = 0; private $fetchmode; private $row_count; - + public function __construct($rs/*: PDOStatement*/) { $this->result = $rs; - $this->row_count = $rs->getRecordCount(); + $this->row_count = $rs->getRecordCount(); } - - function rewind() { + + function rewind() { $this->pos = 0; } - + function valid() { - return ($this->pos < $this->row_count); + return ($this->pos < $this->row_count); } - + function key() { return $this->pos; } - + function current() { if (!isset($this->result->cache[$this->pos])) { $this->result->cache[$this->pos] = $this->result->fetch(PDO::FETCH_ASSOC); - } + } return $this->result->cache[$this->pos]; } - + function next() { $this->pos++; } function seek($index) { - $this->pos = $index; + $this->pos = $index; } function count() { - return $this->row_count; + return $this->row_count; } } From 5748ea9148f9f5e0738931a4efb5c55643a70a22 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 19 Apr 2023 11:25:28 +0300 Subject: [PATCH 050/138] =?UTF-8?q?new=20=D0=A1=D0=BE=D0=B2=D0=BC=D0=B5?= =?UTF-8?q?=D1=81=D1=82=D0=B8=D0=BC=D0=BE=D1=81=D1=82=D1=8C=20=D1=81=20php?= =?UTF-8?q?8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Collection.php | 8 ++++---- src/Controller/Action.php | 2 +- src/Database.php | 4 ++-- src/Database/PDOStatement.php | 2 +- src/Database/StatementIterator.php | 10 +++++----- src/HttpRequest.php | 15 +-------------- src/Path.php | 6 +++--- 7 files changed, 17 insertions(+), 30 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index 4eea3d1..7e3b808 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -79,22 +79,22 @@ class Collection implements \ArrayAccess $this->data = array(); } - public function offsetSet($key, $value) + public function offsetSet($key, $value): void { $this->data[$key] = $value; } - public function offsetExists($key) + public function offsetExists($key): bool { return isset($this->data[$key]); } - public function offsetUnset($key) + public function offsetUnset($key): void { unset($this->data[$key]); } - public function offsetGet($key) + public function offsetGet($key): mixed { return isset($this->data[$key]) ? $this->data[$key] : null; } diff --git a/src/Controller/Action.php b/src/Controller/Action.php index b73b685..f3496e5 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -30,7 +30,7 @@ class Action public $modulePath = null; // Путь к модулю public $moduleTitle = ''; - public $viewPathPrefix = null; // Путь к шаблонам контроллера + public $viewPathPrefix = ''; // Путь к шаблонам контроллера /** * Соединение с базой данных diff --git a/src/Database.php b/src/Database.php index ad989d7..dc572d1 100644 --- a/src/Database.php +++ b/src/Database.php @@ -30,8 +30,8 @@ class Database/**/ extends PDO $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('ctiso\\Database\\PDOStatement', array())); } - function prepare($sql, $args = []) { - $result/*: PDOStatement*/ = parent::prepare($sql, $args); + function prepare(string $sql, array $options = []): PDOStatement|false { + $result/*: PDOStatement*/ = parent::prepare($sql, $options); return $result; } diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index 1ae56df..b4c351b 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -103,7 +103,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate return count($this->cache); } - function execute($args = null) { + function execute($args = null): bool { $result = parent::execute($args); return $result; } diff --git a/src/Database/StatementIterator.php b/src/Database/StatementIterator.php index eebd752..41314a4 100644 --- a/src/Database/StatementIterator.php +++ b/src/Database/StatementIterator.php @@ -16,26 +16,26 @@ class StatementIterator implements \Iterator $this->row_count = $rs->getRecordCount(); } - function rewind() { + function rewind(): void{ $this->pos = 0; } - function valid() { + function valid(): bool { return ($this->pos < $this->row_count); } - function key() { + function key(): mixed { return $this->pos; } - function current() { + function current(): mixed{ if (!isset($this->result->cache[$this->pos])) { $this->result->cache[$this->pos] = $this->result->fetch(PDO::FETCH_ASSOC); } return $this->result->cache[$this->pos]; } - function next() { + function next(): void{ $this->pos++; } diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 0a65a4c..048c33b 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -10,7 +10,7 @@ use Exception, ctiso\Session; // HTTPRequest = ArrayAccess -class HttpRequest extends Collection implements ArrayAccess +class HttpRequest extends Collection { public $_session; @@ -117,19 +117,6 @@ class HttpRequest extends Collection implements ArrayAccess exit(); } - - public function offsetSet($key, $value) { - } - - public function offsetExists($key) { - } - - public function offsetUnset($key) { - } - - public function offsetGet($key) { - } - static function getProtocol() { return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; } diff --git a/src/Path.php b/src/Path.php index bafed76..f2ca20a 100644 --- a/src/Path.php +++ b/src/Path.php @@ -16,10 +16,9 @@ class Path protected $url = array(); protected $absolute = false; - public function __construct($path) + public function __construct($path = '') { -// assert(is_string($path)); - + //assert(is_string($path)); $this->url = parse_url($path); if (isset($this->url['path'])) { @@ -289,6 +288,7 @@ class Path */ static function fromJoin($_rest) { $args = func_get_args(); + $result = array(); $parts0 = new Path(array_shift($args)); $result [] = $parts0->getParts(); From 9d730c2961eb71621c740de1954b2c3408488421 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 16 Jun 2023 11:34:51 +0300 Subject: [PATCH 051/138] =?UTF-8?q?fix:=20=D0=A1=D0=BB=D0=B5=D1=88=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Filter/Login.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Filter/Login.php b/src/Filter/Login.php index e17205b..a6591bd 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -202,7 +202,7 @@ class Login extends Filter $module = $request->get('module'); $action = $request->get('action'); - $moduleDir = explode('_',$module)[0]; + $moduleDir = explode('\\',$module)[0]; $file = Path::join($this->config->get('system', 'path'), 'modules', $moduleDir, 'filters', 'white.json'); if (file_exists($file)) { $whiteList = json_decode(file_get_contents($file), true); From 2b021ffb61fb15ba374714573abda7071fdf4ca2 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 16 Jun 2023 17:58:23 +0300 Subject: [PATCH 052/138] =?UTF-8?q?feat:=20=D0=92=D0=BE=D0=B7=D0=BC=D0=BE?= =?UTF-8?q?=D0=B6=D0=BD=D0=BE=D1=81=D1=82=D1=8C=20=D0=B4=D0=BE=D0=B1=D0=B0?= =?UTF-8?q?=D0=B2=D0=BB=D1=8F=D1=82=D1=8C=20=D0=BF=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=D0=B0=20=D0=B2=D0=B0=D0=BB=D0=B8=D0=B4=D0=B0=D1=86=D0=B8?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Validator/Validator.php | 49 ++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 23 deletions(-) diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 88fd870..c8303ad 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -3,7 +3,7 @@ /// /** - * Проверка коллекции + * Проверка коллекции */ namespace ctiso\Validator; use Exception, @@ -14,35 +14,38 @@ class Validator { protected $chain = array(); // Массив правил protected $errorMsg = array(); // Массив ошибок + protected $type = array( + 'date' => 'ctiso\\Validator\\Rule\\Date', + 'email' => 'ctiso\\Validator\\Rule\\Email', + 'emaillist'=> 'ctiso\\Validator\\Rule\\EmailList', + 'match' => 'ctiso\\Validator\\Rule\\MatchRule', + 'time' => 'ctiso\\Validator\\Rule\\Time', + 'alpha' => 'ctiso\\Validator\\Rule\\Alpha', + 'require' => 'ctiso\\Validator\\Rule\\Notnull', + 'numeric' => 'ctiso\\Validator\\Rule\\Numeric', + 'unique' => 'ctiso\\Validator\\Rule\\Unique', + 'filename' => 'ctiso\\Validator\\Rule\\FileName', + 'count' => 'ctiso\\Validator\\Rule\\Count', + 'isfile' => 'ctiso\\Validator\\Rule\\IsFile', + 'code' => 'ctiso\\Validator\\Rule\\Code' + ); function __construct($rules = array()) { $this->addRuleList($rules); } + function addRuleType($name, $className) { + $this->type[$name] = $className; + } + /** * Добавление списка правил в специальном формате * array(array('name' => fieldname, 'validate' => ruletext), ...) - * fieldname - Имя переменой для проверки + * fieldname - Имя переменой для проверки * ruletext - Описание правила см. формат правила ниже */ public function addRuleList(array $input) { - $type = array( - 'date' => 'ctiso\\Validator\\Rule\\Date', - 'email' => 'ctiso\\Validator\\Rule\\Email', - 'emaillist'=> 'ctiso\\Validator\\Rule\\EmailList', - 'match' => 'ctiso\\Validator\\Rule\\MatchRule', - 'time' => 'ctiso\\Validator\\Rule\\Time', - 'alpha' => 'ctiso\\Validator\\Rule\\Alpha', - 'require' => 'ctiso\\Validator\\Rule\\Notnull', - 'numeric' => 'ctiso\\Validator\\Rule\\Numeric', - 'unique' => 'ctiso\\Validator\\Rule\\Unique', - 'filename' => 'ctiso\\Validator\\Rule\\FileName', - 'count' => 'ctiso\\Validator\\Rule\\Count', - 'isfile' => 'ctiso\\Validator\\Rule\\IsFile', - 'code' => 'ctiso\\Validator\\Rule\\Code' - ); - // Разбор правила проверки // Формат правила 'rule1|rule2,param1=value1|rule3,param1=value1,param2=value2' foreach ($input as $value) { @@ -55,8 +58,8 @@ class Validator $rule_param = explode(",", $rule); $name = array_shift($rule_param); - if (isset($type[$name])) { - $constructor = $type[$name]; + if (isset($this->type[$name])) { + $constructor = $this->type[$name]; $ruleObj = new $constructor($value['name'], false); // Нужны шаблонные сообщения для правил if (isset($value['context'])) { $ruleObj->setContext($value['context']); @@ -81,7 +84,7 @@ class Validator $this->chain[] = $rule; } } - + public function skip($rule/*: AbstractRule*/, $container/*: Collection*/) // -> Rule_Abstract { if ($rule->skipEmpty()) { @@ -90,10 +93,10 @@ class Validator $value = trim($data); return $value == ''; } - } + } return false; } - + public function validate(Collection $container, $rule = null, $status = null) { $fields = array(); From bfaaf77b3e55257f27e7837b47a052db8fb119cf Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Mon, 3 Jul 2023 16:11:57 +0300 Subject: [PATCH 053/138] =?UTF-8?q?fix:=20=D0=9F=D1=83=D1=82=D1=8C=20?= =?UTF-8?q?=D0=BA=20action=20=D1=84=D0=B8=D0=BB=D1=8C=D1=82=D1=80=D0=B0?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Front.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Controller/Front.php b/src/Controller/Front.php index d5e6d12..ed9148a 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -78,10 +78,11 @@ class Front extends Action $module->front = $this; // Ведение лога $logger = new ActionLogger($module, $logPath, $this->user); - $logger->before = $this->loadSettings(Path::join($modPath, 'filter', 'logger.php')); + $filename = Path::join($modPath, 'filters', 'logger.json'); + $logger->before = $this->loadSettings($filename); // Управление доступом $module->access = new ActionAccess($logger, $this->user); - $module->access->access = $this->loadSettings(Path::join($modPath, 'filter', 'access.php')); + $module->access->access = $this->loadSettings(Path::join($modPath, 'filters', 'access.json')); $module->setUp(); From e9231ead67109701250615a07481883f11c2bbde Mon Sep 17 00:00:00 2001 From: anatoly Date: Thu, 6 Jul 2023 16:51:38 +0300 Subject: [PATCH 054/138] new validator --- src/Validator/Rule/PregMatch.php | 21 +++++++++++++++++++++ src/Validator/Validator.php | 7 ++++--- 2 files changed, 25 insertions(+), 3 deletions(-) create mode 100644 src/Validator/Rule/PregMatch.php diff --git a/src/Validator/Rule/PregMatch.php b/src/Validator/Rule/PregMatch.php new file mode 100644 index 0000000..3d400bb --- /dev/null +++ b/src/Validator/Rule/PregMatch.php @@ -0,0 +1,21 @@ +pattern,$container->get($this->field)); + } +} diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index c8303ad..1d625e0 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -27,7 +27,8 @@ class Validator 'filename' => 'ctiso\\Validator\\Rule\\FileName', 'count' => 'ctiso\\Validator\\Rule\\Count', 'isfile' => 'ctiso\\Validator\\Rule\\IsFile', - 'code' => 'ctiso\\Validator\\Rule\\Code' + 'code' => 'ctiso\\Validator\\Rule\\Code', + 'reg' => 'ctiso\\Validator\\Rule\\PregMatch', ); function __construct($rules = array()) { @@ -77,7 +78,7 @@ class Validator } } - public function addRule($rule/*: any*/) { + public function addRule($rule/*:z any*/) { if (is_array($rule)) { $this->chain = array_merge($this->chain, $rule); } else { @@ -85,7 +86,7 @@ class Validator } } - public function skip($rule/*: AbstractRule*/, $container/*: Collection*/) // -> Rule_Abstract + public function skip($rule/*z: AbstractRule*/, $container/*: Collection*/) // -> Rule_Abstract { if ($rule->skipEmpty()) { $data = $container->get($rule->field); From 2ac4b250766c7fcdea444ab8e596e33197ca9807 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 6 Oct 2023 19:23:14 +0300 Subject: [PATCH 055/138] =?UTF-8?q?fix:=20=D0=9F=D1=80=D0=B8=20=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BD=D0=BE=D0=B2=D0=BA=D0=B5=20=D0=BC=D0=BE?= =?UTF-8?q?=D0=B4=D1=83=D0=BB=D1=8F=20=D0=B7=D0=B0=D0=BF=D0=B8=D1=81=D1=8B?= =?UTF-8?q?=D0=B2=D0=B0=D0=B5=D1=82=D1=81=D1=8F=20=D1=82=D0=BE=D0=BB=D1=8C?= =?UTF-8?q?=D0=BA=D0=BE=20=D0=B2=D0=B5=D1=80=D1=81=D0=B8=D1=8F=20=D0=B8=20?= =?UTF-8?q?=D0=B2=D1=80=D0=B5=D0=BC=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Installer.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Controller/Installer.php b/src/Controller/Installer.php index 2adff19..5ac3ebc 100644 --- a/src/Controller/Installer.php +++ b/src/Controller/Installer.php @@ -28,14 +28,14 @@ class Installer return $setup; } - function getUninstallFile($name){ + function getUninstallFile($name) { return Path::join(call_user_func($this->installPath, $name), "sql", "uninstall.json"); } // Проверка версии обновления function isChanged($name) // Информация о модулях { - $item = $this->_registry->get('system', $name); + $item = $this->_registry->get($name); if ($item) { $setup = $this->getSetupFile($name); if (file_exists($setup) && (filemtime($setup) > $item['time'])) { @@ -78,10 +78,11 @@ class Installer if (file_exists($setup) && ($this->isChanged($name) || $force)) { $registry = $this->_registry; + $settings = new Settings($setup); $settings->read(); - $item = $registry->get('system', $name); + $item = $registry->get($name); $version_new = $settings->get('version'); if ($item) { @@ -106,7 +107,7 @@ class Installer 'version' => $version_new, 'time' => filemtime($setup) ]); - $registry->writeKey([$name], $settings->get('settings')); + // $registry->writeKey([$name], $settings->export()); $registry->write(); } From ad6efaf36d0db634af6d2555e0f0f5b339e25f2e Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 16 Nov 2023 12:58:28 +0300 Subject: [PATCH 056/138] =?UTF-8?q?fix:=20=D0=A3=D1=81=D1=82=D0=B0=D0=BD?= =?UTF-8?q?=D0=BE=D0=B2=D0=BA=D0=B0=20=D1=82=D0=B0=D0=B1=D0=BB=D0=B8=D1=86?= =?UTF-8?q?=20=D0=B8=D0=B7=20json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Installer.php | 2 +- src/Database/JsonInstall.php | 6 ++++-- src/Database/Manager.php | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/Controller/Installer.php b/src/Controller/Installer.php index 5ac3ebc..72be02b 100644 --- a/src/Controller/Installer.php +++ b/src/Controller/Installer.php @@ -78,7 +78,7 @@ class Installer if (file_exists($setup) && ($this->isChanged($name) || $force)) { $registry = $this->_registry; - + $settings = new Settings($setup); $settings->read(); diff --git a/src/Database/JsonInstall.php b/src/Database/JsonInstall.php index 9fc0c2f..eef8f8b 100644 --- a/src/Database/JsonInstall.php +++ b/src/Database/JsonInstall.php @@ -63,8 +63,10 @@ class JsonInstall { $table_name = $action["table_name"]; if (isset($refs[$table_name])) { foreach ($refs[$table_name] as $value) { - $action['fields'][$value['column']]['references'] = - $value['refTable']."(".$value['refColumn'].")"; + $action['fields'][$value['column']]['references'] = [ + "refTable" => $value['refTable'], + 'refColumn' => $value['refColumn'] + ]; } } diff --git a/src/Database/Manager.php b/src/Database/Manager.php index 669b570..9e8c044 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -145,7 +145,7 @@ class Manager $constraint = isset($data['constraint']) ? " ".$data['constraint'] : ""; $references = ""; if (isset($data['references'])) { - $references = " REFERENCES ".$data['references']; + $references = " REFERENCES " . $data['references']['refTable'] . '(' .$data['references']['refColumn'] . ')'; } if (isset($data["not_null"]) && $data["not_null"]) { $constraint .=" NOT NULL"; From cab1a44698e6e04df7cfeb383ec48a30984448eb Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 28 Nov 2023 17:35:48 +0300 Subject: [PATCH 057/138] =?UTF-8?q?feat:=20=D0=9F=D1=80=D0=B5=D1=84=D0=B8?= =?UTF-8?q?=D0=BA=D1=81=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D1=8F=D0=B5?= =?UTF-8?q?=D1=82=D1=81=D1=8F=20=D0=B0=D0=B2=D1=82=D0=BE=D0=BC=D0=B0=D1=82?= =?UTF-8?q?=D0=B8=D1=87=D0=B5=D1=81=D0=BA=D0=B8=20=D0=BA=20=D1=81=D0=BA?= =?UTF-8?q?=D1=80=D0=B8=D0=BF=D1=82=D0=B0=D0=BC=20=D0=B8=20=D1=81=D1=82?= =?UTF-8?q?=D0=B8=D0=BB=D1=8F=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Tales.php | 4 ++-- src/View/View.php | 15 ++++++++++----- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/Tales.php b/src/Tales.php index 5937db2..7cbd91c 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -51,7 +51,7 @@ class Tales { return date("H:i", $e); } - static function phptal_asset($s) { + static function phptal_asset($s) { self::$site->addStyleSheet($s); return ""; } @@ -59,7 +59,7 @@ class Tales { /** * Функция подключения компонента */ - static function phptal_component ($expression) { + static function phptal_component($expression) { $begin = floatval(microtime(true)); $component/*: Component*/ = null; diff --git a/src/View/View.php b/src/View/View.php index 088cd43..a30e9fa 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -15,8 +15,9 @@ class View protected $_title = null; // Заголовок текущего шаблона - public $active_module; - public $module_action; + public $active_module; + public $module_action; + public $prefix; public $suggestions; //подсказки @@ -59,7 +60,7 @@ class View */ public function addScript($name) { - $output = $this->resolveName($this->alias, $name); + $output = $this->resolveName($this->alias, $name . '?' . http_build_query($this->prefix)); $this->_script [] = $output; } @@ -77,6 +78,10 @@ class View } } + public function setPrefix($name, $val) { + $this->prefix[$name] = $val; + } + /** * Добавляет стили к текущему шаблону * @@ -84,8 +89,8 @@ class View */ public function addStyleSheet($name) { - $output = $this->resolveName($this->alias, $name); - $this->_stylesheet [] = $output; + $output = $this->resolveName($this->alias, $name . '?' . http_build_query($this->prefix)); + $this->_stylesheet [] = $output; } /** From 0d6da39e9002e67d260f61e422a0d84a7fc03ccb Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 16 Jan 2024 18:24:03 +0300 Subject: [PATCH 058/138] =?UTF-8?q?fix:=20=D1=81=D0=BE=D0=B2=D0=BC=D0=B5?= =?UTF-8?q?=D1=81=D1=82=D0=B8=D0=BC=D0=BE=D1=81=D1=82=D1=8C=20=D1=81=20php?= =?UTF-8?q?8.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Filter/Login.php | 2 +- src/Model/Factory.php | 1 + src/Path.php | 8 ++++---- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/Filter/Login.php b/src/Filter/Login.php index a6591bd..61d20ec 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -185,7 +185,7 @@ class Login extends Filter } } else if (isset($_SERVER['HTTP_REFERER'])) { $arr = array(); - parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $arr); + parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY) ?? '', $arr); if (isset($arr['back_page']) && $request->get('mode') != 'ajax') { $request->redirect($arr['back_page']); } diff --git a/src/Model/Factory.php b/src/Model/Factory.php index dd99fd7..cf7f46e 100644 --- a/src/Model/Factory.php +++ b/src/Model/Factory.php @@ -9,6 +9,7 @@ class Factory { public $db; public $config; + public $user; public function __construct (Database $db, Registry $config = null, User $user = null) { diff --git a/src/Path.php b/src/Path.php index f2ca20a..d7d0d04 100644 --- a/src/Path.php +++ b/src/Path.php @@ -19,12 +19,12 @@ class Path public function __construct($path = '') { //assert(is_string($path)); - $this->url = parse_url($path); + $this->url = parse_url($path ?? ''); if (isset($this->url['path'])) { $path = $this->url['path']; // $path = preg_replace('/\/{2,}/', '/', $path); - $list = self::listFromString($path); + $list = $this->listFromString($path); if (isset($this->url['scheme']) && !isset($this->url['host'])) { $this->absolute = false; @@ -32,7 +32,7 @@ class Path $this->absolute = true; } - $this->path = self::optimize($list); + $this->path = $this->optimize($list); } } @@ -311,7 +311,7 @@ class Path static function join($_rest) { $args = func_get_args(); - $path = call_user_func_array("self::fromJoin", $args); + $path = call_user_func_array([self::class, "fromJoin"], $args); return self::makeUrl($path->url); } From d6864daae402ce7659bcc4ee007c35444cef6f1f Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 17 Jan 2024 15:43:49 +0300 Subject: [PATCH 059/138] =?UTF-8?q?fix:=20=D1=81=D0=BE=D0=B2=D0=BC=D0=B5?= =?UTF-8?q?=D1=81=D1=82=D0=B8=D0=BC=D0=BE=D1=81=D1=82=D1=8C=20=D1=81=20php?= =?UTF-8?q?8.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/View/View.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/View/View.php b/src/View/View.php index a30e9fa..e03ffef 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -9,7 +9,7 @@ class View // Блоки protected $_stylesheet = array(); // Массив стилей текущего шаблона protected $_script = array(); // Массив скриптов текущего шаблона - protected $_scriptstring = array(); + public $_scriptstring = array(); protected $_startup = array(); protected $_values = array(); From bbc9d0e7fe1f593515b0caa02febeddd0a7cf76f Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 18 Jan 2024 17:42:44 +0300 Subject: [PATCH 060/138] fix: php8 --- src/Primitive.php | 2 +- src/Tools/StringUtil.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Primitive.php b/src/Primitive.php index be695a9..2cba7c8 100644 --- a/src/Primitive.php +++ b/src/Primitive.php @@ -46,7 +46,7 @@ class Primitive { public static function to_date($value) { $result = 0; - $tmp = explode("/", $value, 3); + $tmp = explode("/", $value ?? '', 3); if (!empty($tmp)) { if (count($tmp) != 3) return $result; diff --git a/src/Tools/StringUtil.php b/src/Tools/StringUtil.php index 70c92e6..8fb208f 100644 --- a/src/Tools/StringUtil.php +++ b/src/Tools/StringUtil.php @@ -73,7 +73,7 @@ class StringUtil { } static function mb_str_split($str) { - return preg_split('~~u', $str, null, PREG_SPLIT_NO_EMPTY); + return preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY); } static function mb_strtr($str, $from, $to) { From f59461165675c7be75b3cac110956add3e71aa46 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Mon, 22 Jan 2024 14:00:52 +0300 Subject: [PATCH 061/138] fix: phpstan level=3 --- src/Controller/Action.php | 2 +- src/Model/BaseMapper.php | 3 ++- src/Role/User.php | 4 ++-- src/Validator/Validator.php | 2 +- src/View/Composite.php | 1 + src/View/View.php | 2 +- 6 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index f3496e5..7e7eafa 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -104,7 +104,7 @@ class Action * @param string $viewClass * @return Composite */ - public function getView($name, $viewClass = 'ctiso\\View\\Composite') + public function getView($name, $viewClass = Composite::class) { $file = $name . self::TEMPLATE_EXTENSION; diff --git a/src/Model/BaseMapper.php b/src/Model/BaseMapper.php index 50cad30..88a3572 100644 --- a/src/Model/BaseMapper.php +++ b/src/Model/BaseMapper.php @@ -2,5 +2,6 @@ namespace ctiso\Model; -class BaseMapper { +abstract class BaseMapper { + abstract function getAllAsOptions(): array; } \ No newline at end of file diff --git a/src/Role/User.php b/src/Role/User.php index a22cb13..818c318 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -31,7 +31,7 @@ class User implements UserInterface } function isLogged() { - return \ctiso\Filter\Authorization::isLogged(); + return \ctiso\Filter\Authorization::isLogged(); } @@ -41,7 +41,7 @@ class User implements UserInterface if ($result->next()) { $this->access = $this->groups[$result->getString('access')]; $this->name = $result->getString('login'); - $this->id = $result->getInt('id_user'); + $this->id = $result->getInt('id_user'); $this->password = $result->getString('password'); $this->fullname = implode(' ', array( $result->getString('surname'), diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 1d625e0..2e003d7 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -91,7 +91,7 @@ class Validator if ($rule->skipEmpty()) { $data = $container->get($rule->field); if (!is_array($data)) { - $value = trim($data); + $value = trim($data ?: ''); return $value == ''; } } diff --git a/src/View/Composite.php b/src/View/Composite.php index ff659ef..aa2890a 100644 --- a/src/View/Composite.php +++ b/src/View/Composite.php @@ -8,6 +8,7 @@ namespace ctiso\View; use ctiso\View\View, PHPTAL; + class Composite extends View { private $tal; diff --git a/src/View/View.php b/src/View/View.php index e03ffef..7acbebb 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -3,7 +3,7 @@ namespace ctiso\View; use Exception; -class View +class View extends \stdClass { protected $_section = array(); // Вложенные шаблоны // Блоки From 277a297b8ae35b72962920e7df80e154be550fcb Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Mon, 22 Jan 2024 14:07:45 +0300 Subject: [PATCH 062/138] fix: BaseMapper --- src/Model/BaseMapper.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Model/BaseMapper.php b/src/Model/BaseMapper.php index 88a3572..7e55e72 100644 --- a/src/Model/BaseMapper.php +++ b/src/Model/BaseMapper.php @@ -3,5 +3,7 @@ namespace ctiso\Model; abstract class BaseMapper { - abstract function getAllAsOptions(): array; + function getAllAsOptions(): array { + return []; + } } \ No newline at end of file From 4fc2e2ac7dbbebbf07bce362f09c423b2e55fa3e Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Mon, 22 Jan 2024 19:56:45 +0300 Subject: [PATCH 063/138] fix: phpstan level=3 --- config.php | 4 ++++ phpstan.neon | 10 ++++++++++ src/Controller/Action.php | 2 +- src/Controller/Component.php | 12 +++++++----- src/Controller/Front.php | 4 ++-- src/Database.php | 6 +----- src/Functions.php | 18 +++++++++--------- src/HttpRequest.php | 2 +- src/Path.php | 10 +++++----- src/Process.php | 1 + src/Settings.php | 7 +++---- src/Setup.php | 20 ++++++++++++-------- src/Tools/SQLStatementExtractor.php | 6 +++--- src/Tools/TemplateImage.php | 3 --- src/View/Pages.php | 2 +- src/View/View.php | 16 +++++++++------- 16 files changed, 69 insertions(+), 54 deletions(-) create mode 100644 config.php create mode 100644 phpstan.neon diff --git a/config.php b/config.php new file mode 100644 index 0000000..502a2b4 --- /dev/null +++ b/config.php @@ -0,0 +1,4 @@ +template) ? $this->template : $this->getTemplateName($config); $selected = null; + $tpl = null; foreach ($this->viewPath as $index => $viewPath) { // Загружать шаблон по умолчанию если не найден текущий $dir = Path::join($this->viewPath[$index], 'templates', $template); @@ -147,7 +148,7 @@ class Component } public function getTemplatePath($name) { - $registry/*: \ctiso\Settings*/ = $this->config; + $registry = $this->config; // Брать настройки из куков если есть $template = ($this->template) ? $this->template : $this->getTemplateName($registry); foreach ($this->viewPath as $index => $viewPath) { @@ -167,7 +168,7 @@ class Component /** * Создает модель * @param string $name - * @return model + * @return mixed */ public function getModel($name) { @@ -302,6 +303,7 @@ class Component $component->component_id = $cid->getInt('id_component'); } else { $last = $db->getIdGenerator(); + $result = null; if ($last->isBeforeInsert()) { $result = $last->getId('component_id_component_seq'); diff --git a/src/Controller/Front.php b/src/Controller/Front.php index ed9148a..ac9bfdc 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -24,7 +24,7 @@ class Front extends Action protected $modules = array(); /** - * @param Settings $settings + * @param Settings $config */ public function __construct($db, $config, $user, $default) { parent::__construct(); @@ -41,7 +41,7 @@ class Front extends Action /** * Создает экземпляр модуля и выполняет действия для него * @param string $name Имя модуля - * @param Request $request Имя модуля + * @param Collection $request Имя модуля * @return string */ public function loadModule($name, Collection $request) diff --git a/src/Database.php b/src/Database.php index dc572d1..3c06748 100644 --- a/src/Database.php +++ b/src/Database.php @@ -48,6 +48,7 @@ class Database/**/ extends PDO static function getConnection(array $dsn) { + $connection = null; if ($dsn['phptype'] == 'pgsql' || $dsn['phptype'] == 'mysql') { $port = (isset($dsn['port'])) ? "port={$dsn['port']};" : ""; $connection/*: Database*/ = new static("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']); @@ -107,11 +108,6 @@ class Database/**/ extends PDO return $sth->fetch(PDO::FETCH_ASSOC); } - private static function assignQuote($x, $y) - { - return $x . "=" . $this->quote($y); - } - private function prepareValues($values) { if (!$values) { diff --git a/src/Functions.php b/src/Functions.php index 1c64ed1..bab33e8 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -98,9 +98,7 @@ class Functions { /** * Композиция функций - * @param mixed $a - * @param mixed $b - * + * @param array $_rest * @return mixed */ static function compose($_rest) { @@ -330,19 +328,21 @@ class Functions { /** * Поиск элемента в массиве * @param mixed $cb сравнение с элементом массива - * @param Array $hs массив в котором ищется значение + * @param array $hs массив в котором ищется значение * - * @return int|string ключ найденого элемента в массиве + * @return int|string|null ключ найденого элемента в массиве */ static function array_usearch($cb, array $hs, $strict = false) { - foreach($hs as $key => $value) if (call_user_func_array($cb, array($value, $key, $strict))) return $key; + foreach($hs as $key => $value) { + if (call_user_func_array($cb, array($value, $key, $strict))) return $key; + } return null; } /** * Выбирает все сроки из таблицы с уникальными значениями ключа * @param string $name Имя ключа - * @param Array $table Двухмерный массив + * @param array $table Двухмерный массив * @example * key_unique_values ('name', array (array ('name' => 1), array ('name' => 2), array ('name' => 1))) => array (1, 2) @@ -360,9 +360,9 @@ class Functions { /** * Сортировка двумерного массива по заданному ключу - * @param Array $array Массив + * @param array $array Массив * @param string $key Имя ключа по значению которого будет идти сравнение - * @return Array Отсортированный массив + * @return array Отсортированный массив */ static function sortOn($array, $key, $fn = '\\ctiso\\Functions::__cmp') { usort ($array, Functions::rcurry($fn, $key)); diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 048c33b..186ae12 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -59,7 +59,7 @@ class HttpRequest extends Collection function set($key, $value/*: any*/) { - return parent::get('data')->set($key, $value); + parent::get('data')->set($key, $value); } function export($key = 'data') diff --git a/src/Path.php b/src/Path.php index d7d0d04..f285116 100644 --- a/src/Path.php +++ b/src/Path.php @@ -471,12 +471,12 @@ class Path /** * Обновить относительную ссылку в файле при переносе папки * - * @param String $relativePath - относительная ссылка до переноса - * @param String $fileDir - абсолютный путь к директории файла содержащего ссылку до переноса - * @param String $srcDir - абсолютный путь к переносимой директории до переноса - * @param String $dstDir - абсолютный путь к переносимой директории после переноса + * @param string $relativePath относительная ссылка до переноса + * @param string $fileDir абсолютный путь к директории файла содержащего ссылку до переноса + * @param string $srcDir абсолютный путь к переносимой директории до переноса + * @param string $dstDir абсолютный путь к переносимой директории после переноса * - * @return + * @return string */ static function updateRelativePathOnDirectoryMove($relativePath, $fileDir, $srcDir, $dstDir) { $relativePath = self::normalize($relativePath); diff --git a/src/Process.php b/src/Process.php index 18f813d..a1728f5 100644 --- a/src/Process.php +++ b/src/Process.php @@ -6,6 +6,7 @@ if (!function_exists('str_getcsv')) { function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") { $fiveMBs = 1024; $fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+'); + $data = ''; if (is_resource($fp)) { fputs($fp, $input); rewind($fp); diff --git a/src/Settings.php b/src/Settings.php index 8345c1c..6033c71 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -98,7 +98,7 @@ class Settings /** * Чтение ключа из реестра - * @param mixed $args Путь к значению ключа + * @param array $key Путь к значению ключа */ public function readKey(array $key) { @@ -130,9 +130,8 @@ class Settings * Чтение ключа из реестра (Собирает все ключи с определенным значением во всех модулях) * @param mixed $key Путь к значению ключа внутри модуля */ - public function readKeyList($_rest) - { - $key = func_get_args(); + public function readKeyList(...$key) + { $result = array(); foreach ($this->data as $name => $value) { $output = $this->readKeyData($key, $value); diff --git a/src/Setup.php b/src/Setup.php index cfad705..52958f8 100644 --- a/src/Setup.php +++ b/src/Setup.php @@ -114,7 +114,7 @@ class Setup /** * Выполняет список действий если для действия не указан аттрибут when то оно выполняется всегда * - * @param $action специальное действие + * @param string $action специальное действие */ function executeActions($action = "install") { @@ -136,10 +136,12 @@ class Setup /** * Копирования файла - * @param preserve Не переписывать файл если он существует - * @param template Файл является шаблоном подставить параметры до копирования - * @param src Исходный файл - * @param dst Новый файл + * preserver - Не переписывать файл если он существует + * template Файл является шаблоном подставить параметры до копирования + * src Исходный файл + * dst Новый файл + * + * @param array{preserve: string, template: string, src: string, dst: string} $attributes */ public function copyFile(array $attributes) { @@ -152,7 +154,7 @@ class Setup /** * Создает символическую ссылку на папку/файл - * @param dst Имя папки + * @param array{target: string, link: string} $attributes */ public function makeLink(array $attributes) { @@ -163,7 +165,7 @@ class Setup /** * Подключение файла установки - * @param file Имя подключаемого файла + * @param array{file: string} $attributes Имя подключаемого файла */ public function includeFile(array $attributes) { @@ -180,7 +182,9 @@ class Setup /** * Создает новую папку - * @param dst Имя папки + * dst Имя папки + * + * @param array{dst:string} $attributes */ public function makeDirectory(array $attributes) { diff --git a/src/Tools/SQLStatementExtractor.php b/src/Tools/SQLStatementExtractor.php index a084113..746423b 100644 --- a/src/Tools/SQLStatementExtractor.php +++ b/src/Tools/SQLStatementExtractor.php @@ -50,7 +50,7 @@ class SQLStatementExtractor { /** * Extract statements from string. * - * @param string $txt + * @param string $buffer * @return array */ public static function extract($buffer) { @@ -61,7 +61,7 @@ class SQLStatementExtractor { * Extract SQL statements from array of lines. * * @param array $lines Lines of the read-in file. - * @return string + * @return array */ protected static function extractStatements($lines) { @@ -156,7 +156,7 @@ class SQLStatementExtractor { /** * Convert string buffer into array of lines. * - * @param string $filename + * @param string $buffer * @return array string[] lines of file. */ protected static function getLines($buffer) { diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index 478b3df..ad9d8f0 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -38,9 +38,6 @@ class TemplateImage protected $image; protected $_prepare = true; public $debug = false; - public $filename; - public $resource; - public $resource; public $filename; diff --git a/src/View/Pages.php b/src/View/Pages.php index 1bba197..f621cef 100644 --- a/src/View/Pages.php +++ b/src/View/Pages.php @@ -7,7 +7,7 @@ namespace ctiso\View; class Pages { - static $range = 5; + static int $range = 5; static function getPages($page, $onpage, $count, $prefix = '?') { $n = ceil($count / $onpage); diff --git a/src/View/View.php b/src/View/View.php index 7acbebb..0151523 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -120,8 +120,6 @@ class View extends \stdClass /** * Обработка всех вложенных шаблонов - * - * @return string */ public function execute() { @@ -166,16 +164,20 @@ class View extends \stdClass throw new Exception("file not found: $file"); } + // FIXME: Префикс, конфликтует с протоколом function resolveName($alias, $file) { list($type, $filename) = explode(":", $file, 2); // Сделать поиск а не просто замену папки при совпадении имени - if (is_array($alias[$type])) { - $output = $this->find_file($alias[$type], $filename); - } else { - $output = $alias[$type] . '/' . $filename; + if (isset($alias[$type])) { + if (is_array($alias[$type])) { + $output = $this->find_file($alias[$type], $filename); + } else { + $output = $alias[$type] . '/' . $filename; + } + return $output; } - return $output; + return $file; } function loadImports($importFile) From dcf36cda7e5bb76a4abb856b098bce2ee0370870 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 23 Jan 2024 11:40:24 +0300 Subject: [PATCH 064/138] =?UTF-8?q?fix:=20=D0=9B=D0=BE=D0=BA=D0=B0=D0=BB?= =?UTF-8?q?=D1=8C=D0=BD=D1=8B=D0=B5=20=D0=B7=D0=B0=D0=B2=D0=B8=D1=81=D0=B8?= =?UTF-8?q?=D0=BC=D0=BE=D1=81=D1=82=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- composer.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/composer.json b/composer.json index 4c325c2..25add6b 100644 --- a/composer.json +++ b/composer.json @@ -11,5 +11,8 @@ "psr-4": { "ctiso\\": "src/" } + }, + "require": { + "phpmailer/phpmailer": "^6.8.0" } } From c514d747b8fa50ffb4e43b0758f241da322651bb Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 23 Jan 2024 11:44:42 +0300 Subject: [PATCH 065/138] fix: PHPMailer --- src/MailAlt.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/MailAlt.php b/src/MailAlt.php index 753dedf..7a42a7a 100644 --- a/src/MailAlt.php +++ b/src/MailAlt.php @@ -1,7 +1,7 @@ Date: Tue, 23 Jan 2024 18:12:29 +0300 Subject: [PATCH 066/138] =?UTF-8?q?fix:=20=D0=9D=D0=B5=D0=B8=D1=81=D0=BF?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D0=B7=D1=83=D0=B5=D0=BC=D1=8B=D0=B9=20=D0=BA?= =?UTF-8?q?=D0=BE=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 2 +- src/Form/Select.php | 2 +- src/View/Plain.php | 2 +- src/View/Top.php | 30 ++---------------------------- 4 files changed, 5 insertions(+), 31 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 92aea5b..39308a8 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -219,7 +219,7 @@ class Component /** * Генерация интерфейса для выбора галлереи фотографии */ - public function setParameters($view/*: Composite*/, $options = null) + public function setParameters(Composite $view, $options = null) { $form = new Form(); diff --git a/src/Form/Select.php b/src/Form/Select.php index 3a4ec2c..44d26f4 100644 --- a/src/Form/Select.php +++ b/src/Form/Select.php @@ -8,7 +8,7 @@ class Select extends Field public $options = array(); public function __construct ($input, $factory) { - parent::__construct($input, $factory); + parent::__construct($input); if ($factory != null) { $factory->create($this, $input); diff --git a/src/View/Plain.php b/src/View/Plain.php index fae072c..5ffb102 100644 --- a/src/View/Plain.php +++ b/src/View/Plain.php @@ -8,7 +8,7 @@ */ namespace ctiso\View; -class Plain +class Plain extends \stdClass { protected $document; protected $values = array(); diff --git a/src/View/Top.php b/src/View/Top.php index f27e44e..4779624 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -28,32 +28,6 @@ class Top extends Composite return false; } - private function groupFiles(array $list, $debugMode = true) - { - $debug = ($debugMode) ? 'debug=1' : ''; - $path = parse_url($this->config->get('system', 'web'), PHP_URL_PATH); - - $groups = array(); - $use = array(); - - $result = array(); - foreach ($list as $file) { - $name = $this->findGroup($groups, $file); - if ($name) { - $use[$name] = 1; - } else { - $result[] = $file; - } - } - $list = array(); - foreach ($use as $name => $value) { - $list[] = $groups[$name]; - } - - return array_merge($list, $result); - } - - function getId($pref) { $this->mid++; @@ -72,8 +46,8 @@ class Top extends Composite // Скрипты и стили $this->set('scriptstring', $this->getScriptRaw()); - $this->set('scripts', array_unique($this->groupFiles($this->getScripts(), false))); - $this->set('stylesheet', array_unique($this->groupFiles($this->getStyleSheet(), false))); + $this->set('scripts', array_unique($this->getScripts())); + $this->set('stylesheet', array_unique($this->getStyleSheet())); $this->require = array('admin' => 'ma'); $this->deps = array(); From 1638d558c58339d9a9a46bf0d44410f245cafa87 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 24 Jan 2024 12:49:11 +0300 Subject: [PATCH 067/138] =?UTF-8?q?fix:=20phpstan.=20=D0=A3=D0=B4=D0=B0?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D0=B5=20State?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 6 +--- src/Controller/Service.php | 5 +-- src/Controller/State.php | 74 -------------------------------------- src/Database.php | 4 +-- src/Form/Field.php | 6 ++-- src/Primitive.php | 24 +++++++------ 6 files changed, 22 insertions(+), 97 deletions(-) delete mode 100644 src/Controller/State.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index b4d1db0..49f345e 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -6,14 +6,10 @@ use Exception, ctiso\Url, ctiso\Model\Factory, ctiso\HttpRequest, - ctiso\Functions, ctiso\Settings, - ctiso\Registry, - ctiso\Role\User, ctiso\View\Composite, - ctiso\Filter\ActionAccess, ctiso\View\View, - ctiso\Controller\State; + App\Controller\State; /** * Контроллер страниц */ diff --git a/src/Controller/Service.php b/src/Controller/Service.php index cccecdf..0d527ef 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -5,6 +5,7 @@ */ namespace ctiso\Controller; use ctiso\Path, + ctiso\Model\BaseMapper, ctiso\File, ctiso\Registry, ctiso\Database\PDOStatement; @@ -40,8 +41,8 @@ class Service /** * Создает модель - * @param string $name - * @return Model + * @param string $name + * @return BaseMapper */ public function getModel($name) { diff --git a/src/Controller/State.php b/src/Controller/State.php deleted file mode 100644 index 225de1a..0000000 --- a/src/Controller/State.php +++ /dev/null @@ -1,74 +0,0 @@ -action = $action; - } - - static function make($action) - { - return new State($action); - } - - public function addTitle($name, $url = array()) - { - $this->titles [] = array($name, $url); - return $this; - } - - public function addState(State $state) - { - $this->states [$state->getAction()] = $state; - return $this; - } - - public function getAction() - { - return $this->action; - } - - function checkAction($action, &$list) - { - if ($this->action == $action) { - array_push($list, $this); - return true; - } else { - foreach ($this->states as $state) { - if ($state->checkAction($action, $list)) { - array_push($list, $this); - return true; - } - } - } - return false; - } - - function makeTitle(Action $module) - { - foreach ($this->titles as $item) { - $module->path->addMenuItem($module->nUrl($this->action, $item[1]), $item[0]); - } - } - - function getPath($module, $action) - { - $list = array(); - if ($this->checkAction($action, $list)) { - foreach (array_reverse($list) as $item) { - $item->makeTitle($module); - } - } else { - $this->makeTitle($module); - } - } -} diff --git a/src/Database.php b/src/Database.php index 3c06748..2e86124 100644 --- a/src/Database.php +++ b/src/Database.php @@ -51,7 +51,7 @@ class Database/**/ extends PDO $connection = null; if ($dsn['phptype'] == 'pgsql' || $dsn['phptype'] == 'mysql') { $port = (isset($dsn['port'])) ? "port={$dsn['port']};" : ""; - $connection/*: Database*/ = new static("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']); + $connection/*: Database*/ = new self("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']); if ($dsn['phptype'] == 'pgsql') { $connection->query('SET client_encoding="UTF-8"'); } @@ -61,7 +61,7 @@ class Database/**/ extends PDO } } if ($dsn['phptype'] == 'sqlite') { - $connection/*: Database*/ = new static("{$dsn['phptype']}:{$dsn['database']}"); + $connection/*: Database*/ = new self("{$dsn['phptype']}:{$dsn['database']}"); $connection->setAttribute(PDO::ATTR_TIMEOUT, 5); $mode = defined('SQLITE_JOURNAL_MODE') ? SQLITE_JOURNAL_MODE : 'WAL'; $connection->query("PRAGMA journal_mode=$mode"); diff --git a/src/Form/Field.php b/src/Form/Field.php index 83a23ea..1b2c0d2 100644 --- a/src/Form/Field.php +++ b/src/Form/Field.php @@ -21,10 +21,10 @@ class Field public $_title = array(); public $description = ""; public $alias = array(); - + + /** @phpstan-ignore-next-line */ public function __construct ($input = array(), $factory = null) - { - + { $this->default = null; if (isset($input['validate'])) { $this->require = strpos($input['validate'], 'require') !== false; diff --git a/src/Primitive.php b/src/Primitive.php index 2cba7c8..13a5bb5 100644 --- a/src/Primitive.php +++ b/src/Primitive.php @@ -47,21 +47,23 @@ class Primitive { { $result = 0; $tmp = explode("/", $value ?? '', 3); - if (!empty($tmp)) { - if (count($tmp) != 3) return $result; + + if (count($tmp) != 3) { + return $result; + } - $year = (int)$tmp[2]; - $month = (int)$tmp[1]; - $day = (int)$tmp[0]; + $year = (int)$tmp[2]; + $month = (int)$tmp[1]; + $day = (int)$tmp[0]; - if ($month != 0 && $day != 0 && $year != 0) { - if (checkdate($month, $day, $year)) { - return mktime(0, 0, 0, $month, $day, $year); - } else { - return 0; - } + if ($month != 0 && $day != 0 && $year != 0) { + if (checkdate($month, $day, $year)) { + return mktime(0, 0, 0, $month, $day, $year); + } else { + return 0; } } + return $result; } From 2947e4aac39c201f5ddcba4b8f1e5f611ea531ff Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 24 Jan 2024 17:13:38 +0300 Subject: [PATCH 068/138] fix: phpstan level=5 --- src/Controller/Front.php | 12 +++++------- src/Database/StatementIterator.php | 1 - src/Excel/Table.php | 8 ++++---- src/Filter/Authorization.php | 3 +-- src/Path.php | 3 --- src/Primitive.php | 4 ++-- src/Validator/Rule/Date.php | 4 +--- src/View/Top.php | 10 ---------- 8 files changed, 13 insertions(+), 32 deletions(-) diff --git a/src/Controller/Front.php b/src/Controller/Front.php index ac9bfdc..396d659 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -6,14 +6,15 @@ */ namespace ctiso\Controller; use ctiso\Controller\Action, - ctiso\Settings, - ctiso\Database, + ctiso\Registry, + ctiso\Database, ctiso\Collection, ctiso\Filter\ActionAccess, ctiso\Filter\ActionLogger, ctiso\Path, ctiso\UserMessageException, - ctiso\HttpRequest; + ctiso\HttpRequest, + ctiso\Role\User; class Front extends Action { @@ -23,10 +24,7 @@ class Front extends Action protected $modules = array(); - /** - * @param Settings $config - */ - public function __construct($db, $config, $user, $default) { + public function __construct(Database $db, Registry $config, User $user, $default) { parent::__construct(); $this->config = $config; $this->db = $db; diff --git a/src/Database/StatementIterator.php b/src/Database/StatementIterator.php index 41314a4..f767408 100644 --- a/src/Database/StatementIterator.php +++ b/src/Database/StatementIterator.php @@ -8,7 +8,6 @@ class StatementIterator implements \Iterator private $result; private $pos = 0; - private $fetchmode; private $row_count; public function __construct($rs/*: PDOStatement*/) { diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 7754aa1..96eaedf 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -252,8 +252,8 @@ class Table $rows = $this->getRows(); $doc->startElement('Table'); - $doc->writeAttribute('ss:ExpandedColumnCount', $columns); - $doc->writeAttribute('ss:ExpandedRowCount', $rows); + $doc->writeAttribute('ss:ExpandedColumnCount', (string)$columns); + $doc->writeAttribute('ss:ExpandedRowCount', (string)$rows); // Переписать цыкл !!!!!!! for ($i = 1; $i <= $rows; $i++) { @@ -306,9 +306,9 @@ class Table $doc->writeElement('TopRowBottomPane', $this->_splitHorizontal); } if ($this->_splitHorizontal && $this->_splitVertical) { - $doc->writeElement('ActivePane', 0); + $doc->writeElement('ActivePane', (string)0); } else if($this->_splitHorizontal) { - $doc->writeElement('ActivePane', 2); + $doc->writeElement('ActivePane', (string)2); } $doc->endElement(); } diff --git a/src/Filter/Authorization.php b/src/Filter/Authorization.php index 0df3e6f..ffe3282 100644 --- a/src/Filter/Authorization.php +++ b/src/Filter/Authorization.php @@ -42,8 +42,7 @@ class Authorization { static function getBrowserSign() { $rawSign = self::SESSION_BROWSER_SIGN_SECRET; -// $signParts = array('HTTP_USER_AGENT', 'HTTP_ACCEPT_ENCODING'); - $signParts = array(); + $signParts = ['HTTP_USER_AGENT']; foreach ($signParts as $signPart) { $rawSign .= '::' . (isset($_SERVER[$signPart]) ? $_SERVER[$signPart] : 'none'); diff --git a/src/Path.php b/src/Path.php index f285116..3b0bcdc 100644 --- a/src/Path.php +++ b/src/Path.php @@ -66,13 +66,10 @@ class Path * Возвращает расширение файла * * @param string $fileName Полное имя файла - * * @return string */ static function getExtension($fileName) { - assert(is_string($fileName) || is_null($fileName)); - return pathinfo($fileName, PATHINFO_EXTENSION); } diff --git a/src/Primitive.php b/src/Primitive.php index 13a5bb5..db3228e 100644 --- a/src/Primitive.php +++ b/src/Primitive.php @@ -73,8 +73,8 @@ class Primitive { $tmp = array(); if (preg_match('/(\d+)-(\d+)-(\d+)T(\d+):(\d+)Z/', $value, $tmp)) { - if (checkdate($tmp[2], $tmp[3], $tmp[1])) { - $result = mktime($tmp[4], $tmp[5], 0, $tmp[2], $tmp[3], $tmp[1]); + if (checkdate((int)$tmp[2], (int)$tmp[3], (int)$tmp[1])) { + $result = mktime((int)$tmp[4], (int)$tmp[5], 0, (int)$tmp[2], (int)$tmp[3], (int)$tmp[1]); } } return $result; diff --git a/src/Validator/Rule/Date.php b/src/Validator/Rule/Date.php index 1b416b0..fdfff71 100644 --- a/src/Validator/Rule/Date.php +++ b/src/Validator/Rule/Date.php @@ -9,8 +9,6 @@ use ctiso\Validator\Rule\AbstractRule, class Date extends AbstractRule { - private $split = "\\/"; - public function getErrorMsg() { return "Неверный формат даты"; @@ -21,7 +19,7 @@ class Date extends AbstractRule $pattern = "/^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/"; $matches = []; return (preg_match($pattern, $container->get($this->field), $matches) - && checkdate($matches[2], $matches[1], $matches[3])); + && checkdate((int)$matches[2], (int)$matches[1], (int)$matches[3])); } } diff --git a/src/View/Top.php b/src/View/Top.php index 4779624..804ac0f 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -18,16 +18,6 @@ class Top extends Composite return implode(" - ", array_filter($this->doTree('_title', false), array($this, 'isNotNull'))); } - private function findGroup($groups, $file) - { - foreach ($groups as $key => $group) { - if (in_array($file, $group)) { - return $key; - } - } - return false; - } - function getId($pref) { $this->mid++; From 5cfd2ee773e14d90e663bfba4d73901d15da4e6d Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 25 Jan 2024 20:22:52 +0300 Subject: [PATCH 069/138] fix: deprecated --- src/View/Top.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/View/Top.php b/src/View/Top.php index 804ac0f..6cf27d7 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -32,7 +32,7 @@ class Top extends Composite public function render() { - $alias = $this->doTree('alias'); + $this->doTree('alias'); // Скрипты и стили $this->set('scriptstring', $this->getScriptRaw()); @@ -47,7 +47,7 @@ class Top extends Composite if (is_string($s)) { continue; } - $moduleName = explode('_', $s->active_module, 2); + $moduleName = explode('_', $s->active_module ?: '', 2); if (count($moduleName) < 2) { continue; } From 548d5daaa9cce7293e9556c3283a66bac373c879 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 26 Jan 2024 16:56:51 +0300 Subject: [PATCH 070/138] =?UTF-8?q?fix:=20=D0=A3=D1=82=D0=BE=D1=87=D0=BD?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Database.php | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/Database.php b/src/Database.php index 2e86124..b641ebf 100644 --- a/src/Database.php +++ b/src/Database.php @@ -1,6 +1,4 @@ - namespace { if(!function_exists('sqliteLower')){ function sqliteLower($str) { @@ -18,7 +16,7 @@ use PDO, /** * Класс оболочка для PDO для замены Creole */ -class Database/**/ extends PDO +class Database extends PDO { public $dsn; @@ -27,7 +25,7 @@ class Database/**/ extends PDO parent::__construct($dsn, $username, $password); $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); - $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('ctiso\\Database\\PDOStatement', array())); + $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array(PDOStatement::class, array())); } function prepare(string $sql, array $options = []): PDOStatement|false { @@ -71,9 +69,9 @@ class Database/**/ extends PDO return $connection; } - public function executeQuery($query, $values=null) + public function executeQuery($query, $values=null): PDOStatement|bool { - $stmt/*: PDOStatement*/ = $this->prepare($query); + $stmt = $this->prepare($query); $stmt->execute($values); $stmt->cache = $stmt->fetchAll(PDO::FETCH_ASSOC); @@ -91,7 +89,7 @@ class Database/**/ extends PDO */ public function fetchAllArray($query, $values = null) { - $sth/*: PDOStatement*/ = $this->prepare($query); + $sth = $this->prepare($query); $prep = $this->prepareValues($values); $sth->execute($prep); return $sth->fetchAll(PDO::FETCH_ASSOC); @@ -102,7 +100,7 @@ class Database/**/ extends PDO */ public function fetchOneArray($query, $values = null) { - $sth/*: PDOStatement*/ = $this->prepare($query); + $sth = $this->prepare($query); $prep = $this->prepareValues($values); $sth->execute($prep); return $sth->fetch(PDO::FETCH_ASSOC); From 6ae14fd5f021b8f6194a12e037010c1f35864828 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 13 Feb 2024 15:33:25 +0300 Subject: [PATCH 071/138] =?UTF-8?q?fix:=20=D0=A0=D0=B0=D1=81=D1=87=D0=B5?= =?UTF-8?q?=D1=82=20=D1=85=D0=B5=D1=88=D0=B0=20=D0=B4=D0=BB=D1=8F=20=D0=B1?= =?UTF-8?q?=D1=80=D0=B0=D1=83=D0=B7=D0=B5=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Filter/Authorization.php | 12 ++++++++++-- src/Filter/Login.php | 15 ++------------- 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/src/Filter/Authorization.php b/src/Filter/Authorization.php index ffe3282..814418f 100644 --- a/src/Filter/Authorization.php +++ b/src/Filter/Authorization.php @@ -36,10 +36,11 @@ class Authorization { $_SESSION [$group] = $id; $_SESSION [self::SESSION_BROWSER_SIGN_KEYNAME] = self::getBrowserSign(); + $_SESSION ["sign"] = self::getRawSign(); $_SESSION ["time"] = time(); } - static function getBrowserSign() + static function getRawSign() { $rawSign = self::SESSION_BROWSER_SIGN_SECRET; $signParts = ['HTTP_USER_AGENT']; @@ -47,7 +48,14 @@ class Authorization { foreach ($signParts as $signPart) { $rawSign .= '::' . (isset($_SERVER[$signPart]) ? $_SERVER[$signPart] : 'none'); } - return md5($rawSign); + + return $rawSign; + } + + static function getBrowserSign() + { + + return md5(self::getRawSign()); } function logout() { diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 61d20ec..a891d32 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -108,7 +108,7 @@ class Login extends Filter break; */ default: - $hash = $this->getBrowserSign(); + $hash = Authorization::getBrowserSign(); // Если $hash не совпадает $_SESSION['hash'] то удаляем сессию if (isset($_SESSION ['access']) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { if ($hash == $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME]) { @@ -125,17 +125,6 @@ class Login extends Filter return false; } - private function getBrowserSign() { - $rawSign = self::SESSION_BROWSER_SIGN_SECRET; - //$signParts = array('HTTP_USER_AGENT', 'HTTP_ACCEPT_ENCODING'); - $signParts = array(); - - foreach ($signParts as $signPart) { - $rawSign .= '::' . (isset($_SERVER[$signPart]) ? $_SERVER[$signPart] : 'none'); - } - return md5($rawSign); - } - private function enter($result) { $this->user = $result; @@ -145,7 +134,7 @@ class Login extends Filter $_SESSION["group"] = $result->getInt('access'); $_SESSION["access"] = $result->getInt('id_user'); // id_user $_SESSION["random"] = $random; // id_user - $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME] = $this->getBrowserSign(); + $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME] = Authorization::getBrowserSign(); $_SESSION["time"] = time(); } From 671163039855a89c283c605467c720bfca63aee6 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 28 Feb 2024 11:04:21 +0300 Subject: [PATCH 072/138] =?UTF-8?q?fix:=20=D0=9E=D0=B1=D1=8C=D1=8F=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D1=82=D0=B8=D0=BF=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Path.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Path.php b/src/Path.php index 3b0bcdc..4e35405 100644 --- a/src/Path.php +++ b/src/Path.php @@ -454,11 +454,11 @@ class Path /** * Обновить относительную ссылку при переносе файла * - * @param String $relativePath - относительная ссылка до переноса - * @param String $srcFile - абсолютный путь к папке содержащей файл со ссылкой до переноса - * @param String $dstFile - абсолютный путь к папке содержащей файл со ссылкой после переноса + * @param string $relativePath - относительная ссылка до переноса + * @param string $srcFile - абсолютный путь к папке содержащей файл со ссылкой до переноса + * @param string $dstFile - абсолютный путь к папке содержащей файл со ссылкой после переноса * - * @return String + * @return string */ static function updateRelativePathOnFileMove($relativePath, $srcFile, $dstFile) { $srcToDst = self::relative($srcFile, $dstFile); From 56e1f5b02fa94d6eb02f089f3d98702684ce84d6 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 12 Mar 2024 12:43:14 +0300 Subject: [PATCH 073/138] =?UTF-8?q?fix:=20=D0=A2=D0=B8=D0=BF=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 2 +- src/Path.php | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 39308a8..a86bd14 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -286,7 +286,7 @@ class Component ); $component->COMPONENTS_WEB = $config->get('system', 'components.web'); } else { - $component->webPath = array('', $config->get('site', 'components.web') . '/' . $name, ''); + $component->webPath = array('', $config->get('site', 'components.web') . '/' . $name, '', ''); } } diff --git a/src/Path.php b/src/Path.php index 3b0bcdc..4e35405 100644 --- a/src/Path.php +++ b/src/Path.php @@ -454,11 +454,11 @@ class Path /** * Обновить относительную ссылку при переносе файла * - * @param String $relativePath - относительная ссылка до переноса - * @param String $srcFile - абсолютный путь к папке содержащей файл со ссылкой до переноса - * @param String $dstFile - абсолютный путь к папке содержащей файл со ссылкой после переноса + * @param string $relativePath - относительная ссылка до переноса + * @param string $srcFile - абсолютный путь к папке содержащей файл со ссылкой до переноса + * @param string $dstFile - абсолютный путь к папке содержащей файл со ссылкой после переноса * - * @return String + * @return string */ static function updateRelativePathOnFileMove($relativePath, $srcFile, $dstFile) { $srcToDst = self::relative($srcFile, $dstFile); From 85b957c8af244a9e7a5495ab46b162b98ad966f6 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 17 Apr 2024 20:37:27 +0300 Subject: [PATCH 074/138] =?UTF-8?q?=D0=A3=D1=81=D1=82=D0=B0=D0=BD=D0=BE?= =?UTF-8?q?=D0=B2=D0=BA=D0=B0=20=D0=B8=D0=B7=20=D0=BF=D0=B0=D0=BF=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B2=D0=BC=D0=B5=D1=81=D1=82=D0=BE=20=D0=B0=D1=80?= =?UTF-8?q?=D1=85=D0=B8=D0=B2=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Setup.php | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/Setup.php b/src/Setup.php index 52958f8..a001080 100644 --- a/src/Setup.php +++ b/src/Setup.php @@ -8,8 +8,19 @@ * */ namespace ctiso; -use ZipArchive, - ctiso\Tools\SQLStatementExtractor; +use ctiso\Tools\SQLStatementExtractor; +use ctiso\Path; + +class FakeZipArchive { + public $base; + function open($path) { + $this->base = $path; + } + + function getFromName($file) { + return file_get_contents(Path::join($this->base, $file)); + } +} class Setup { @@ -32,8 +43,8 @@ class Setup $this->target = ''; $this->source = ''; - $this->zip = new ZipArchive(); - $this->zip->open(strtr($file, array('.xml' => '.zip'))); + $this->zip = new FakeZipArchive(); + $this->zip->open(strtr($file, array('.xml' => ''))); array_push($this->stack, $this->node); From 5aff28d2b856945e0179ce4c5995f98417002298 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 17 May 2024 16:36:22 +0300 Subject: [PATCH 075/138] =?UTF-8?q?=D0=92=20=D1=84=D0=B0=D0=B9=D0=BB=D0=B5?= =?UTF-8?q?=20=D1=83=D1=81=D1=82=D0=B0=D0=BD=D0=BE=D0=B2=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=20=D0=BF=D0=B0?= =?UTF-8?q?=D1=80=D0=B0=D0=BC=D0=B5=D1=82=D1=80=20=D1=83=D0=BA=D0=B0=D0=B7?= =?UTF-8?q?=D1=8B=D0=B2=D0=B0=D1=8E=D1=89=D0=B8=D0=B9=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=BF=D0=B0=D0=BF=D0=BA=D1=83=20=D1=81=20=D1=84=D0=B0=D0=B9?= =?UTF-8?q?=D0=BB=D0=B0=D0=BC=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Setup.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Setup.php b/src/Setup.php index a001080..34da2ed 100644 --- a/src/Setup.php +++ b/src/Setup.php @@ -44,8 +44,7 @@ class Setup $this->target = ''; $this->source = ''; $this->zip = new FakeZipArchive(); - $this->zip->open(strtr($file, array('.xml' => ''))); - + $this->zip->open(dirname($this->file) . '/' . $this->node->attributes()['dir']); array_push($this->stack, $this->node); From 117640a75566547b70820384d6f5d9f1c8929e47 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 14 Jun 2024 14:12:02 +0300 Subject: [PATCH 076/138] fix: noverify --fix --- src/Arr.php | 2 +- src/Collection.php | 4 ++-- src/Connection/HttpResponse.php | 2 +- src/Controller/Action.php | 22 +++++++++---------- src/Controller/Component.php | 32 +++++++++++++-------------- src/Controller/Installer.php | 4 ++-- src/Controller/Request.php | 2 +- src/Controller/Service.php | 10 ++++----- src/Database.php | 6 ++--- src/Database/Manager.php | 12 +++++----- src/Database/PDOStatement.php | 2 +- src/Database/Statement.php | 6 ++--- src/Excel/Document.php | 4 ++-- src/Excel/Table.php | 4 ++-- src/Filter/Authorization.php | 2 +- src/Filter/Login.php | 12 +++++----- src/Form/Field.php | 4 ++-- src/Form/Form.php | 6 ++--- src/Form/Select.php | 4 ++-- src/Form/SelectMany.php | 2 +- src/Functions.php | 34 ++++++++++++++--------------- src/Layout/Manager.php | 6 ++--- src/Mail.php | 18 +++++++-------- src/Numbers.php | 2 +- src/Path.php | 18 +++++++-------- src/Primitive.php | 4 ++-- src/Role/User.php | 4 ++-- src/Settings.php | 10 ++++----- src/Setup.php | 18 +++++++-------- src/SortRecord.php | 12 +++++----- src/TableTree.php | 2 +- src/Tales.php | 8 +++---- src/Tools/Drawing.php | 6 ++--- src/Tools/SQLStatementExtractor.php | 2 +- src/Tools/StringUtil.php | 10 ++++----- src/UTF8.php | 2 +- src/Validator/Rule/Code.php | 8 +++---- src/Validator/Rule/Count.php | 2 +- src/Validator/Validator.php | 6 ++--- src/View/ListView.php | 2 +- src/View/Pages.php | 12 +++++----- src/View/Top.php | 10 ++++----- src/View/View.php | 8 +++---- src/ZipFile.php | 2 +- 44 files changed, 174 insertions(+), 174 deletions(-) diff --git a/src/Arr.php b/src/Arr.php index 5a421b3..38cbb35 100644 --- a/src/Arr.php +++ b/src/Arr.php @@ -5,6 +5,6 @@ namespace ctiso; class Arr { static function get($data, $key, $default = null) { - return isset($data[$key]) ? $data[$key] : $default; + return $data[$key] ?? $default; } } diff --git a/src/Collection.php b/src/Collection.php index 7e3b808..2f7cea3 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -76,7 +76,7 @@ class Collection implements \ArrayAccess public function clear() { - $this->data = array(); + $this->data = []; } public function offsetSet($key, $value): void @@ -96,6 +96,6 @@ class Collection implements \ArrayAccess public function offsetGet($key): mixed { - return isset($this->data[$key]) ? $this->data[$key] : null; + return $this->data[$key] ?? null; } } diff --git a/src/Connection/HttpResponse.php b/src/Connection/HttpResponse.php index 9d6f2b8..1da2036 100644 --- a/src/Connection/HttpResponse.php +++ b/src/Connection/HttpResponse.php @@ -39,7 +39,7 @@ class HttpResponse if (isset($this->param['Transfer-Encoding']) && $this->param['Transfer-Encoding'] == 'chunked') { //$this->data = substr($this->response, $this->offset); $index = hexdec($this->getLine()); - $chunk = array(); + $chunk = []; while ($index > 0) { $chunk [] = substr($this->response, $this->offset, $index); $this->offset += $index; diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 49f345e..c9b29eb 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -82,7 +82,7 @@ class Action } public function addSuggest(View $view, $name) { - $suggest = array(); + $suggest = []; $file = Path::join($this->modulePath, 'help', $name . '.suggest'); if (file_exists($file)) { $view->suggestions = include($file); @@ -107,10 +107,10 @@ class Action $basePath = $this->config->get('system', 'path'); $webPath = $this->config->get('system', 'web'); - $list = array( + $list = [ Path::join($this->modulePath, 'templates', $this->viewPathPrefix) => Path::join($webPath, "modules", $this->name, 'templates', $this->viewPathPrefix), Path::join($basePath, "templates") => Path::join($webPath, "templates") - ); + ]; // Поиск файла для шаблона foreach($list as $ospath => $path) { @@ -130,14 +130,14 @@ class Action $tpl->set('script', $scriptPath); // Путь к файлам скриптов $tpl->set('template', $path); // Путь к файлам текущего шаблона - $tpl->setAlias(array( + $tpl->setAlias([ 'assets' => $stylePath, 'icons' => $iconsPath, 'script' => $scriptPath, // Для media и template поиск происходит как для файлов шаблонов 'media' => $list, 'template' => $list - )); + ]); $tpl->loadImports(Path::skipExtension($template) . ".import"); @@ -185,7 +185,7 @@ class Action } public function forward($action, HttpRequest $args) { - $value = call_user_func(array($this, $action), $args); + $value = call_user_func([$this, $action], $args); return $value; } @@ -207,7 +207,7 @@ class Action * 'mode' означает что элемент до отправки обрабатывается javascript * @return Url|null */ - public function nUrl($name, array $param = array()) + public function nUrl($name, array $param = []) { $access/*: ActionAccess*/ = $this->access; $url = new Url(); @@ -220,7 +220,7 @@ class Action array_shift($moduleName); } } - $param = array_merge(array('module' => implode("\\", $moduleName), "action" => $name), $param); + $param = array_merge(['module' => implode("\\", $moduleName), "action" => $name], $param); $url->setParent($this->part); $url->setQuery($param); @@ -239,9 +239,9 @@ class Action * @example ?action=$name&mode=ajax * {$param[i].key = $param[i].value} */ - public function aUrl($name, array $param = array()) + public function aUrl($name, array $param = []) { - return $this->nUrl($name, array_merge(array('mode' => 'ajax'), $param)); + return $this->nUrl($name, array_merge(['mode' => 'ajax'], $param)); } /** @@ -260,7 +260,7 @@ class Action $action = self::ACTION_PREFIX . $request->getAction(); foreach ($this->helpers as $helper) { if (method_exists($helper, $action)) { - return call_user_func(array($helper, $action), $request, $this); + return call_user_func([$helper, $action], $request, $this); } else { return $helper->actionIndex($request, $this); // Вместо return response ??? } diff --git a/src/Controller/Component.php b/src/Controller/Component.php index a86bd14..4d168c7 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -82,7 +82,7 @@ class Component $this->before(); if (method_exists($this, $action)) { - return call_user_func(array($this, $action), $crequest); + return call_user_func([$this, $action], $crequest); } else { return $this->actionIndex($crequest); } @@ -180,17 +180,17 @@ class Component } public function options($key, $val, $res/*: PDOStatement*/) { - $result = array(); + $result = []; while($res->next()) { - $result[] = array('value' => $res->getString($key), 'name' => $res->getString($val)); + $result[] = ['value' => $res->getString($key), 'name' => $res->getString($val)]; } return $result; } public function optionsPair($list, $selected = false) { - $result = array(); + $result = []; foreach ($list as $key => $value) { - $result [] = array('value' => $key, 'name' => $value, 'selected' => $key == $selected); + $result [] = ['value' => $key, 'name' => $value, 'selected' => $key == $selected]; } return $result; } @@ -213,7 +213,7 @@ class Component return $settings; } } - return array('parameter' => []); + return ['parameter' => []]; } /** @@ -238,7 +238,7 @@ class Component $offset = strpos($expression, '?'); $url = parse_url($expression); - $arguments = array(); + $arguments = []; if ($offset === false) { $path = $expression; } else if (is_int($offset)) { @@ -259,34 +259,34 @@ class Component // require_once ($path); $component = new $className(); - $component->viewPath = array($config->get('site', 'components') . '/' . $name . '/'); - $component->webPath = array($config->get('site', 'components.web') . '/' . $name); + $component->viewPath = [$config->get('site', 'components') . '/' . $name . '/']; + $component->webPath = [$config->get('site', 'components.web') . '/' . $name]; $component->COMPONENTS_WEB = $config->get('site', 'web') . '/components/'; } else { $component = new $className(); $template = $component->getTemplateName($site->config); - $component->viewPath = array( + $component->viewPath = [ // Сначало ищем локально $config->get('site', 'templates') . '/'. $template . '/_components/' . $name . '/', $config->get('site', 'components') . '/' . $name . '/', // Потом в общем хранилище $config->get('system', 'templates'). '/' . $template . '/_components/' . $name . '/', $config->get('system', 'components') . '/' . $name . '/', - ); + ]; if (defined('COMPONENTS_WEB')) { - $component->webPath = array( + $component->webPath = [ // Сначало локально $config->get('site', 'templates.web') . '/' . $template . '/_components/' . $name, $config->get('site', 'components.web') . '/' . $name, // Потом в общем хранилище $config->get('system', 'templates.web') . '/' . $template . '/_components/' . $name, $config->get('system', 'components.web') . '/' . $name, - ); + ]; $component->COMPONENTS_WEB = $config->get('system', 'components.web'); } else { - $component->webPath = array('', $config->get('site', 'components.web') . '/' . $name, '', ''); + $component->webPath = ['', $config->get('site', 'components.web') . '/' . $name, '', '']; } } @@ -343,13 +343,13 @@ class Component { $arr = $request->r->export('get'); - $param = array(); + $param = []; $parameter/*: Collection*/ = $this->parameter; foreach($parameter->export() as $key => $value) { $param[$key] = $value; } - $data = array(); + $data = []; foreach($arr as $key => $value) { if (is_array($value)) { $data[$key] = Arr::get($value, $this->component_id); diff --git a/src/Controller/Installer.php b/src/Controller/Installer.php index 72be02b..e00b705 100644 --- a/src/Controller/Installer.php +++ b/src/Controller/Installer.php @@ -73,7 +73,7 @@ class Installer // Устанавливает обновления если есть function doUpdates($name, $force = false) // Установка модуля { - $result = array(); + $result = []; $setup = $this->getSetupFile($name); if (file_exists($setup) && ($this->isChanged($name) || $force)) { @@ -89,7 +89,7 @@ class Installer $version_old = $item['version']; } else { $version_old = "0.0"; - $registry->writeKey(array($name), array()); + $registry->writeKey([$name], []); } if (version_compare($version_old, $settings->get('version'), "!=")) { $sql = $settings->get('sql'); diff --git a/src/Controller/Request.php b/src/Controller/Request.php index 81fbc46..fb2d950 100644 --- a/src/Controller/Request.php +++ b/src/Controller/Request.php @@ -16,7 +16,7 @@ class Request { $v = $this->r->get($name); $id = $this->id; if ($id && is_array($v)) { - return isset($v[$id]) ? $v[$id] : $def; + return $v[$id] ?? $def; } return $v; } diff --git a/src/Controller/Service.php b/src/Controller/Service.php index 0d527ef..331475d 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -54,17 +54,17 @@ class Service } public function options($key, $val, $res/*: PDOStatement*/) { - $result = array(); + $result = []; while($res->next()) { - $result[] = array('value' => $res->getInt($key), 'name' => $res->getString($val)); + $result[] = ['value' => $res->getInt($key), 'name' => $res->getString($val)]; } return $result; } public function optionsPair($list, $selected = false) { - $result = array(); + $result = []; foreach ($list as $key => $value) { - $result [] = array('value' => $key, 'name' => $value, 'selected' => $key == $selected); + $result [] = ['value' => $key, 'name' => $value, 'selected' => $key == $selected]; } return $result; } @@ -75,7 +75,7 @@ class Service $settings = json_decode(File::getContents($filename), true); return $settings; } - return array(); + return []; } } diff --git a/src/Database.php b/src/Database.php index b641ebf..1f39d3d 100644 --- a/src/Database.php +++ b/src/Database.php @@ -25,7 +25,7 @@ class Database extends PDO parent::__construct($dsn, $username, $password); $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); - $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array(PDOStatement::class, array())); + $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, [PDOStatement::class, array()]); } function prepare(string $sql, array $options = []): PDOStatement|false { @@ -112,7 +112,7 @@ class Database extends PDO return null; } $pg = $this->isPostgres(); - $prep = array(); + $prep = []; foreach ($values as $key => $value) { $result = null; if(is_bool($value)) { @@ -139,7 +139,7 @@ class Database extends PDO . ") VALUES (" . implode(",", array_keys($prep)). ")"; if ($return_id) { if ($this->isPostgres()){ - $sql = $sql." RETURNING $index"; + $sql .= " RETURNING $index"; } } $stmt = $this->prepare($sql); diff --git a/src/Database/Manager.php b/src/Database/Manager.php index 9e8c044..1fbc101 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -23,7 +23,7 @@ class Manager $this->DropTableQuery($action["table_name"], true); break; case "createTable": - $constraints = isset($action["constraints"]) ? $action["constraints"] : null; + $constraints = $action["constraints"] ?? null; $this->CreateTableQuery($action["table_name"], $action["fields"], $constraints); break; case "addColumn": @@ -70,7 +70,7 @@ class Manager { $statement = "DROP TABLE IF EXISTS ".$table; if ($this->db->isPostgres()&&$cascade) { - $statement = $statement." CASCADE"; + $statement .= " CASCADE"; } $this->db->query($statement); } @@ -201,7 +201,7 @@ class Manager { $pg = $this->db->isPostgres(); - $result/*: array*/ = array(); + $result/*: array*/ = []; $data/*: array*/ = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); if (!$pg) { @@ -219,11 +219,11 @@ class Manager } } foreach ($data as $r) { - $result[] = array( + $result[] = [ "type" => "insert", "table_name" => $table_name, "values" => $r - ); + ]; } return $result; } @@ -246,7 +246,7 @@ class Manager public function DumpInserts() { $table_names = $this->GetAllTableNames(); - $result = array(); + $result = []; foreach ($table_names as $table_name) { $result = array_merge($result, $this->DumpTable($table_name)); } diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index b4c351b..2a6a834 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -84,7 +84,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate } function getString($name) { - return isset($this->fields[$name]) ? $this->fields[$name]: null; + return $this->fields[$name] ?? null; } function getBoolean($name) { diff --git a/src/Database/Statement.php b/src/Database/Statement.php index 38652e5..e4d5ff1 100644 --- a/src/Database/Statement.php +++ b/src/Database/Statement.php @@ -22,15 +22,15 @@ class Statement } function setInt($n, $value) { - $this->binds [] = array($n, $value, PDO::PARAM_INT); + $this->binds [] = [$n, $value, PDO::PARAM_INT]; } function setString($n, $value) { - $this->binds [] = array($n, $value, PDO::PARAM_STR); + $this->binds [] = [$n, $value, PDO::PARAM_STR]; } function setBlob($n, $value) { - $this->binds [] = array($n, $value, PDO::PARAM_LOB); + $this->binds [] = [$n, $value, PDO::PARAM_LOB]; } function setLimit($limit) { diff --git a/src/Excel/Document.php b/src/Excel/Document.php index dff1c3b..e149da2 100644 --- a/src/Excel/Document.php +++ b/src/Excel/Document.php @@ -25,7 +25,7 @@ class Document { function setStyle ($name, array $values, $type = 'Interior') { if(!isset($this->styles[$name])) { - $this->styles[$name] = array(); + $this->styles[$name] = []; } $this->styles[$name][$type] = $values; } @@ -70,7 +70,7 @@ class Document { function clean ($s) { assert(is_string($s)); - return strtr($s, array ("\n" => " ")); + return strtr($s, ["\n" => " "]); } /** diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 96eaedf..d5a539c 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -142,7 +142,7 @@ class Table /** * Добавляет строку к таблице */ - function addRow($index = 1, array $data = array("")) + function addRow($index = 1, array $data = [""]) { assert(is_numeric($index) && $index > 0); $offset = $this->getRows() + 1; @@ -196,7 +196,7 @@ class Table * @return int */ function getColumns() { - return max(array_map(array($this, 'getRowCells'), $this->rows)); + return max(array_map([$this, 'getRowCells'], $this->rows)); } function encode($s) diff --git a/src/Filter/Authorization.php b/src/Filter/Authorization.php index 814418f..8510433 100644 --- a/src/Filter/Authorization.php +++ b/src/Filter/Authorization.php @@ -46,7 +46,7 @@ class Authorization { $signParts = ['HTTP_USER_AGENT']; foreach ($signParts as $signPart) { - $rawSign .= '::' . (isset($_SERVER[$signPart]) ? $_SERVER[$signPart] : 'none'); + $rawSign .= '::' . ($_SERVER[$signPart] ?? 'none'); } return $rawSign; diff --git a/src/Filter/Login.php b/src/Filter/Login.php index a891d32..b190270 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -56,7 +56,7 @@ class Login extends Filter if ($this->role->access == 'site_root' && defined('PARENT_PATH')) { $s = new Settings(PARENT_PATH . '/settings.json'); $s->read(); - $dsn = $s->readKey(array('system', 'dsn')); + $dsn = $s->readKey(['system', 'dsn']); $db = Database::getConnection($dsn); $user = $db->fetchOneArray("SELECT * FROM users WHERE login = :login", ['login' => $login]); @@ -143,7 +143,7 @@ class Login extends Filter $logged = $this->isLoggin($request); if ($request->get('action') == 'user_access') { if ($logged) { - $result = array(); + $result = []; $result['fullname'] = $this->user->getString('patronymic') . " " . $this->user->getString('firstname'); $result['email'] = $this->user->getString('email'); $result['hash'] = sha1(self::SESSION_BROWSER_SIGN_SECRET . $this->user->getString('email')); @@ -155,9 +155,9 @@ class Login extends Filter if ($request->get('action') == 'relogin') { if ($logged) { - return json_encode(array('result' => 'ok', 'message' => "Авторизация успешна")); + return json_encode(['result' => 'ok', 'message' => "Авторизация успешна"]); } else { - return json_encode(array('result' => 'fail', 'message' => "Неправильное имя пользователя или пароль")); + return json_encode(['result' => 'fail', 'message' => "Неправильное имя пользователя или пароль"]); } } @@ -166,14 +166,14 @@ class Login extends Filter // Действия по умолчанию !! Возможно переход на форму регистрации if ($request->get('mode') == 'ajax') { if (!$this->requestIsWhite($request)) { - return json_encode(array('result' => 'fail', 'message' =>"NOT_AUTHORIZED")); + return json_encode(['result' => 'fail', 'message' =>"NOT_AUTHORIZED"]); } } else { $request->set('module', 'login'); $request->set('mode', $this->mode); } } else if (isset($_SERVER['HTTP_REFERER'])) { - $arr = array(); + $arr = []; parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY) ?? '', $arr); if (isset($arr['back_page']) && $request->get('mode') != 'ajax') { $request->redirect($arr['back_page']); diff --git a/src/Form/Field.php b/src/Form/Field.php index 1b2c0d2..d4e8a34 100644 --- a/src/Form/Field.php +++ b/src/Form/Field.php @@ -23,7 +23,7 @@ class Field public $alias = array(); /** @phpstan-ignore-next-line */ - public function __construct ($input = array(), $factory = null) + public function __construct ($input = [], $factory = null) { $this->default = null; if (isset($input['validate'])) { @@ -33,7 +33,7 @@ class Field $this->fieldset = $input['fieldset']; } // Инициализация свойст обьетка - foreach (array('label', 'name', 'type', 'description') as $name) { + foreach (['label', 'name', 'type', 'description'] as $name) { if (isset($input[$name])) { $this->$name = $input[$name]; } diff --git a/src/Form/Form.php b/src/Form/Form.php index 3bdd32e..5f8da65 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -35,7 +35,7 @@ class Form extends View { */ public function __construct() { - $this->constructor = array( + $this->constructor = [ 'input' => 'ctiso\\Form\\Input', // input с проверкой на заполненность 'inputreq' => 'ctiso\\Form\\Input', @@ -64,7 +64,7 @@ class Form extends View { 'chooser' => 'ctiso\\Form\\Input', 'select_chooser' => 'ctiso\\Form\\SelectOne', 'html_text' => 'ctiso\\Form\\HtmlText' - ); + ]; } @@ -168,7 +168,7 @@ class Form extends View { { foreach ($schema as $key => $conv) { list($value, $type) = $conv; - $this->field [$key]->setValue(call_user_func(array('ctiso\\Primitive', 'from_' . $type), $data->$value)); + $this->field [$key]->setValue(call_user_func(['ctiso\\Primitive', 'from_' . $type], $data->$value)); } } diff --git a/src/Form/Select.php b/src/Form/Select.php index 44d26f4..4b00b0a 100644 --- a/src/Form/Select.php +++ b/src/Form/Select.php @@ -25,9 +25,9 @@ class Select extends Field } public function optionsPair($list, $selected = false) { - $result = array(); + $result = []; foreach ($list as $key => $value) { - $result [] = array('value' => $key, 'name' => $value, 'selected' => $key == $selected); + $result [] = ['value' => $key, 'name' => $value, 'selected' => $key == $selected]; } return $result; } diff --git a/src/Form/SelectMany.php b/src/Form/SelectMany.php index e0edcb9..86f4295 100644 --- a/src/Form/SelectMany.php +++ b/src/Form/SelectMany.php @@ -8,7 +8,7 @@ class SelectMany extends Select function setValue($value) { // Установить selected у options - if (!is_array($value)) { $value = array($value); } + if (!is_array($value)) { $value = [$value]; } $this->value = $value; foreach ($this->options as &$option) { $option['selected'] = (in_array($option['value'], $value)); diff --git a/src/Functions.php b/src/Functions.php index bab33e8..b547974 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -54,7 +54,7 @@ class partial { function apply() { $params = func_get_args(); - $result = array(); + $result = []; $count = count($this->params); for($i = 0, $j = 0; $i < $count; $i++) { if ($this->params[$i] == __) { @@ -92,7 +92,7 @@ class Functions { static function partial($_rest) { $closure = new partial(func_get_args()); - return array($closure, 'apply'); + return [$closure, 'apply']; } @@ -103,7 +103,7 @@ class Functions { */ static function compose($_rest) { $closure = new compose(func_get_args()); - return array($closure, 'apply'); + return [$closure, 'apply']; } /** @@ -113,7 +113,7 @@ class Functions { */ static function rcurry($_rest) { $closure = new right(func_get_args ()); - return array($closure, 'apply'); + return [$closure, 'apply']; } /** @@ -123,7 +123,7 @@ class Functions { */ static function lcurry($_rest) { $closure = new left(func_get_args ()); - return array($closure, 'apply'); + return [$closure, 'apply']; } /** @@ -134,8 +134,8 @@ class Functions { * @return mixed */ static function partition($pred, $lst) { - $left = array (); - $right = array (); + $left = []; + $right = []; foreach ($lst as $n) { if (call_user_func($pred, $n) !== false) { $left [] = $n; @@ -143,7 +143,7 @@ class Functions { $right [] = $n; } } - return array ($left, $right); + return [$left, $right]; } /** @@ -191,7 +191,7 @@ class Functions { } static function __self($name, $o) { - return call_user_func(array($o, $name)); + return call_user_func([$o, $name]); } static function concat(/* $args ...*/) { @@ -225,7 +225,7 @@ class Functions { * @return mixed */ static function key_values($key, $array/*: array|ArrayIterator*/) { - $result = array(); + $result = []; foreach($array as $item) { $result[] = $item[$key]; @@ -234,7 +234,7 @@ class Functions { } static function key_values_object($key, $array/*: array|ArrayIterator*/) { - $result = array(); + $result = []; foreach($array as $item) { $result[] = $item->{$key}; @@ -243,7 +243,7 @@ class Functions { } static function assoc_key_values($key, $value, $array) { - $result = array(); + $result = []; foreach ($array as $item) { $result[$item[$key]] = $item[$value]; } @@ -251,7 +251,7 @@ class Functions { } static function assoc_key($key, $array) { - $result = array(); + $result = []; foreach ($array as $item) { $result[$item[$key]] = $item; } @@ -307,7 +307,7 @@ class Functions { static function span($length, array $array) { assert(is_int($length)); - $result = array(); + $result = []; $count = count($array); for($i = 0; $i < $count; $i += $length) { $result [] = array_slice($array, $i, $length); @@ -334,7 +334,7 @@ class Functions { */ static function array_usearch($cb, array $hs, $strict = false) { foreach($hs as $key => $value) { - if (call_user_func_array($cb, array($value, $key, $strict))) return $key; + if (call_user_func_array($cb, [$value, $key, $strict])) return $key; } return null; } @@ -350,7 +350,7 @@ class Functions { */ static function key_unique_values ($name, $table) { // Ищем уникальные значения для заданного ключа - $keys = array (); + $keys = []; foreach ($table as $row) { if (!in_array ($row[$name], $keys)) $keys[] = $row[$name]; @@ -375,7 +375,7 @@ class Functions { * @return mixed */ static function hash_key ($key_name,$array/*: array */) { - $result = array(); + $result = []; foreach($array as $value) { $result[$value[$key_name]] = $value; diff --git a/src/Layout/Manager.php b/src/Layout/Manager.php index d687113..78a4686 100644 --- a/src/Layout/Manager.php +++ b/src/Layout/Manager.php @@ -24,7 +24,7 @@ class Manager extends Filter */ public function addConditionGet($get, Filter $layout) { - $this->addCondition(Functions::rcurry(array($this, 'checkGet'), $get), $layout); + $this->addCondition(Functions::rcurry([$this, 'checkGet'], $get), $layout); } /** @@ -32,7 +32,7 @@ class Manager extends Filter */ public function addConditionXHR($get, Filter $layout) { - $this->addCondition(Functions::rcurry(array($this, 'checkXHR'), $get), $layout); + $this->addCondition(Functions::rcurry([$this, 'checkXHR'], $get), $layout); } public function checkGet($request/*: HttpRequest*/, $get) @@ -59,7 +59,7 @@ class Manager extends Filter */ public function addCondition($get, Filter $layout) { - $this->condition [] = array($get, $layout); + $this->condition [] = [$get, $layout]; } /** diff --git a/src/Mail.php b/src/Mail.php index 20cdb7c..9daae2c 100644 --- a/src/Mail.php +++ b/src/Mail.php @@ -96,7 +96,7 @@ class Mail $file = fopen($filename, "rb"); if (is_resource($file)) { $data = fread($file, filesize($filename)); - $this->attachment [] = ($name) ? array($data, $name) : array($data, basename($filename)); + $this->attachment [] = ($name) ? [$data, $name] : [$data, basename($filename)]; } } } @@ -113,7 +113,7 @@ class Mail { assert(is_string($name)); - $this->attachment [] = array($data, $name); + $this->attachment [] = [$data, $name]; } function quote($var, $val) @@ -125,12 +125,12 @@ class Mail * Общий формат тегов MIME * @see http://tools.ietf.org/html/rfc2045 */ - function mimeTag($name, $value, array $args = array()) + function mimeTag($name, $value, array $args = []) { assert (is_string($name)); assert (is_string($value)); - return $name . ": " . $value . implode("", array_map(array($this, 'quote'), array_keys($args), array_values($args))) . PHP_EOL; + return $name . ": " . $value . implode("", array_map([$this, 'quote'], array_keys($args), array_values($args))) . PHP_EOL; } /** @@ -148,7 +148,7 @@ class Mail function getMessage() { $message = "--".$this->uniqid . PHP_EOL; - $message .= $this->mimeTag("Content-Type", $this->type, array ('charset' => $this->encoding)); + $message .= $this->mimeTag("Content-Type", $this->type, ['charset' => $this->encoding]); $message .= $this->mimeTag("Content-Transfer-Encoding", "8bit"); $message .= PHP_EOL . $this->content . PHP_EOL . PHP_EOL; @@ -159,9 +159,9 @@ class Mail foreach ($this->attachment as $value) { list($data, $name) = $value; $message .= "--" . $this->uniqid . PHP_EOL; - $message .= $this->mimeTag("Content-Type", "application/octet-stream", array ('name' => basename($name))); + $message .= $this->mimeTag("Content-Type", "application/octet-stream", ['name' => basename($name)]); $message .= $this->mimeTag("Content-Transfer-Encoding", "base64"); - $message .= $this->mimeTag("Content-Disposition", "attachment", array ('filename' => basename($name))); + $message .= $this->mimeTag("Content-Disposition", "attachment", ['filename' => basename($name)]); $message .= PHP_EOL . chunk_split(base64_encode($data)) . PHP_EOL; } @@ -180,7 +180,7 @@ class Mail if (is_string($this->_notify)) { $head .= $this->mimeTag("Disposition-Notification-To", "\"" . $this->_notify . "\" <" . $this->_from . ">"); } - $head .= $this->mimeTag("Content-Type", "multipart/mixed", array ("boundary" => $this->uniqid)); + $head .= $this->mimeTag("Content-Type", "multipart/mixed", ["boundary" => $this->uniqid]); if ($this->copy) { $head .= $this->mimeTag("BCC", $this->copy); } @@ -218,6 +218,6 @@ class Mail foreach ($this->attachment as $key => &$value) { unset($this->attachment[$key]); } - $this->attachment = array(); + $this->attachment = []; } } diff --git a/src/Numbers.php b/src/Numbers.php index 5fc73e4..2494706 100644 --- a/src/Numbers.php +++ b/src/Numbers.php @@ -16,7 +16,7 @@ class Numbers static function prefix($prefix, array $array, $key = false) { - $result = array(); + $result = []; $count = count($array); for ($i = 0; $i < $count; $i++) { $result [] = call_user_func($prefix, $i + 1) . '. ' . $array[$i]; diff --git a/src/Path.php b/src/Path.php index 4e35405..09d7e29 100644 --- a/src/Path.php +++ b/src/Path.php @@ -138,7 +138,7 @@ class Path */ public static function optimize($path) // { - $result = array(); + $result = []; foreach ($path as $n) { switch ($n) { // Может быть относительным или абсолютным путем @@ -254,7 +254,7 @@ class Path $self_path = $self->getParts(); $list_path = $list->getParts(); - $result = array(); + $result = []; $count = count($list_path); for ($i = 0; $i < $count; $i++) { if (($i >= count($self_path)) || $list_path[$i] != $self_path[$i]) { @@ -286,7 +286,7 @@ class Path static function fromJoin($_rest) { $args = func_get_args(); - $result = array(); + $result = []; $parts0 = new Path(array_shift($args)); $result [] = $parts0->getParts(); foreach ($args as $file) { @@ -371,9 +371,9 @@ class Path * * @returnarray */ - public function getContent($allow = null, $ignore = array()) + public function getContent($allow = null, $ignore = []) { - $ignore = array_merge(array(".", ".."), $ignore); + $ignore = array_merge([".", ".."], $ignore); return self::fileList($this->__toString(), $allow, $ignore); } @@ -385,10 +385,10 @@ class Path * * @return array */ - function getContentRec($allow = null, $ignore = array()) + function getContentRec($allow = null, $ignore = []) { - $result = array (); - $ignore = array_merge(array (".", ".."), $ignore); + $result = []; + $ignore = array_merge([".", ".."], $ignore); self::fileListAll($result, $this->__toString(), $allow, $ignore); return $result; } @@ -397,7 +397,7 @@ class Path protected static function fileList($base, &$allow, &$ignore) { if ($base == '') $base = '.'; - $result = array (); + $result = []; $handle = opendir($base); if (is_resource($handle)) { while (true) { diff --git a/src/Primitive.php b/src/Primitive.php index db3228e..283d7e1 100644 --- a/src/Primitive.php +++ b/src/Primitive.php @@ -71,7 +71,7 @@ class Primitive { { $result = 0; - $tmp = array(); + $tmp = []; if (preg_match('/(\d+)-(\d+)-(\d+)T(\d+):(\d+)Z/', $value, $tmp)) { if (checkdate((int)$tmp[2], (int)$tmp[3], (int)$tmp[1])) { $result = mktime((int)$tmp[4], (int)$tmp[5], 0, (int)$tmp[2], (int)$tmp[3], (int)$tmp[1]); @@ -112,7 +112,7 @@ class Primitive { // array public static function to_array($value) { - return (is_array($value)) ? $value : array(); + return (is_array($value)) ? $value : []; } public static function from_array($value) diff --git a/src/Role/User.php b/src/Role/User.php index 818c318..291048c 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -43,10 +43,10 @@ class User implements UserInterface $this->name = $result->getString('login'); $this->id = $result->getInt('id_user'); $this->password = $result->getString('password'); - $this->fullname = implode(' ', array( + $this->fullname = implode(' ', [ $result->getString('surname'), $result->getString('firstname'), - $result->getString('patronymic'))); + $result->getString('patronymic')]); return $result; } return null; diff --git a/src/Settings.php b/src/Settings.php index 6033c71..1f38299 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -25,7 +25,7 @@ class Settings $fileFormat = ['theme' => 'json']; $extname = pathinfo($file, PATHINFO_EXTENSION); - $this->format = $format ? $format : Arr::get($fileFormat, $extname, $extname); + $this->format = $format ?: Arr::get($fileFormat, $extname, $extname); $this->file = $file; } @@ -40,7 +40,7 @@ class Settings return false; } // Не include_once т.к читать настройки можно несколько раз - $settings = array(); + $settings = []; if ($this->format == 'json') { $settings = json_decode(File::getContents($this->file), true); } else { @@ -73,7 +73,7 @@ class Settings $name = array_shift($key); if (is_array($value)) { if (!isset($data[$name])) { - $data[$name] = array(); + $data[$name] = []; } $this->merge($data[$name], $value); } else { @@ -88,7 +88,7 @@ class Settings { foreach ($value as $key => $subvalue) { if (is_array($subvalue)) { - if (! isset($data[$key])) $data[$key] = array(); + if (! isset($data[$key])) $data[$key] = []; $this->merge($data[$key], $subvalue); } else { $data[$key] = $subvalue; @@ -132,7 +132,7 @@ class Settings */ public function readKeyList(...$key) { - $result = array(); + $result = []; foreach ($this->data as $name => $value) { $output = $this->readKeyData($key, $value); if ($output) { diff --git a/src/Setup.php b/src/Setup.php index 34da2ed..8574adc 100644 --- a/src/Setup.php +++ b/src/Setup.php @@ -48,11 +48,11 @@ class Setup array_push($this->stack, $this->node); - $this->registerAction('copy', array($this, 'copyFile')); - $this->registerAction('make-directory', array($this, 'makeDirectory')); - $this->registerAction('make-link', array($this, 'makeLink')); - $this->registerAction('include', array($this, 'includeFile')); - $this->registerAction('when', array($this, 'testWhen')); + $this->registerAction('copy', [$this, 'copyFile']); + $this->registerAction('make-directory', [$this, 'makeDirectory']); + $this->registerAction('make-link', [$this, 'makeLink']); + $this->registerAction('include', [$this, 'includeFile']); + $this->registerAction('when', [$this, 'testWhen']); } /** @@ -87,7 +87,7 @@ class Setup public function fileContent($file, array $tpl) { $result = $this->zip->getFromName($file); - $result = preg_replace_callback('/\{\{\s*(\*?)(\w+)\s*\}\}/', array($this, 'replaceFn'), $result); + $result = preg_replace_callback('/\{\{\s*(\*?)(\w+)\s*\}\}/', [$this, 'replaceFn'], $result); return $result; } @@ -114,9 +114,9 @@ class Setup */ function resolve($attributes) { - $result = array(); + $result = []; foreach ($attributes as $key => $value) { - $result [$key] = preg_replace_callback("/\\\${(\w+)}/", array($this, 'replaceVariable'), $value); + $result [$key] = preg_replace_callback("/\\\${(\w+)}/", [$this, 'replaceVariable'], $value); } return $result; } @@ -139,7 +139,7 @@ class Setup { $attributes = $node->attributes(); array_push($this->stack, $node); - $this->callAction($node->getName(), array($this->resolve($attributes))); + $this->callAction($node->getName(), [$this->resolve($attributes)]); array_pop($this->stack); } } diff --git a/src/SortRecord.php b/src/SortRecord.php index 030bb52..3c4fe48 100644 --- a/src/SortRecord.php +++ b/src/SortRecord.php @@ -33,21 +33,21 @@ class SortRecord function sort(&$list) { - return usort($list, array($this, 'compare')); + return usort($list, [$this, 'compare']); } function sortKeys(&$list) { - return usort($list, array($this, 'compareKeys')); + return usort($list, [$this, 'compareKeys']); } function group(&$list, $key, $types) { - $groups = array(); + $groups = []; foreach ($types as $name) { - $groups[$name] = array(); + $groups[$name] = []; } - $groups['_any_'] = array(); + $groups['_any_'] = []; foreach ($list as $item) { if (isset($groups[$item[$key]])) { $groups[$item[$key]][] = $item; @@ -55,7 +55,7 @@ class SortRecord $groups['_any_'][] = $item; } } - $result = array(); + $result = []; foreach ($groups as $value) { $result = array_merge($result, $value); } diff --git a/src/TableTree.php b/src/TableTree.php index 70b3cb6..ba0ec60 100644 --- a/src/TableTree.php +++ b/src/TableTree.php @@ -25,7 +25,7 @@ class TableTree { $name = array_shift ($level); $keys = Functions::key_unique_values($name, $table); - $data = array (); + $data = []; foreach ($keys as $index) { list($rows, $table) = Functions::partition (Functions::lcurry(['\ctiso\Functions', '__index'], $index, $name), $table); // $rows = array_filter ($table, lcurry('__index', intval($index), $name)); diff --git a/src/Tales.php b/src/Tales.php index 7cbd91c..6538d86 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -77,9 +77,9 @@ class Tales { /* Регистрация нового префикса для подключения компонента */ $tales = PHPTAL_TalesRegistry::getInstance(); - $tales->registerPrefix('component', array('ctiso\\Tales_Component', 'component')); - $tales->registerPrefix('date', array('ctiso\\Tales_DateTime', 'date')); - $tales->registerPrefix('time', array('ctiso\\Tales_DateTime', 'time')); - $tales->registerPrefix('assets', array('ctiso\\Tales_Assets', 'assets')); + $tales->registerPrefix('component', ['ctiso\\Tales_Component', 'component']); + $tales->registerPrefix('date', ['ctiso\\Tales_DateTime', 'date']); + $tales->registerPrefix('time', ['ctiso\\Tales_DateTime', 'time']); + $tales->registerPrefix('assets', ['ctiso\\Tales_Assets', 'assets']); } } diff --git a/src/Tools/Drawing.php b/src/Tools/Drawing.php index ab4d43d..829e3c3 100644 --- a/src/Tools/Drawing.php +++ b/src/Tools/Drawing.php @@ -32,8 +32,8 @@ class Drawing // self::drawrectnagle($image, $left, $top, $max_width, $max_height, array(0xFF,0,0)); $text_lines = explode("\n", $text); // Supports manual line breaks! - $lines = array(); - $line_widths = array(); + $lines = []; + $line_widths = []; $largest_line_height = 0; foreach ($text_lines as $block) { @@ -54,7 +54,7 @@ class Drawing if ($line_width > $max_width && !$first_word) { $lines[] = $current_line; - $line_widths[] = $last_width ? $last_width : $line_width; + $line_widths[] = $last_width ?: $line_width; $current_line = $item; } else { $current_line .= ($first_word ? '' : ' ') . $item; diff --git a/src/Tools/SQLStatementExtractor.php b/src/Tools/SQLStatementExtractor.php index 746423b..771b52b 100644 --- a/src/Tools/SQLStatementExtractor.php +++ b/src/Tools/SQLStatementExtractor.php @@ -65,7 +65,7 @@ class SQLStatementExtractor { */ protected static function extractStatements($lines) { - $statements = array(); + $statements = []; $sql = ""; foreach($lines as $line) { diff --git a/src/Tools/StringUtil.php b/src/Tools/StringUtil.php index 8fb208f..35baa93 100644 --- a/src/Tools/StringUtil.php +++ b/src/Tools/StringUtil.php @@ -7,9 +7,9 @@ class StringUtil { // from creole static function strToArray($str) { $str = substr($str, 1, -1); // remove { } - $res = array(); + $res = []; - $subarr = array(); + $subarr = []; $in_subarr = 0; $toks = explode(',', $str); @@ -24,7 +24,7 @@ class StringUtil { if ('}' !== substr($tok, -1, 1)) { $in_subarr++; // if sub-array has more than one element - $subarr[$in_subarr] = array(); + $subarr[$in_subarr] = []; $subarr[$in_subarr][] = $tok; } else { $res[] = static::strToArray($tok); @@ -83,7 +83,7 @@ class StringUtil { static function encodestring($st) { $st = self::mb_strtr($st,"абвгдеёзийклмнопрстуфхъыэ !+()", "abvgdeeziyklmnoprstufh_ie_____"); $st = self::mb_strtr($st,"АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ", "ABVGDEEZIYKLMNOPRSTUFH_IE"); - $st = strtr($st, array( + $st = strtr($st, [ " " => '_', "." => '_', "," => '_', @@ -101,7 +101,7 @@ class StringUtil { "Щ"=>"SHCH","Ь"=>"", "Ю"=>"YU", "Я"=>"YA", "Й"=>"i", "й"=>"ie", "ё"=>"Ye", "№"=>"N" - )); + ]); return strtolower($st); } diff --git a/src/UTF8.php b/src/UTF8.php index fe97742..5eb93a0 100644 --- a/src/UTF8.php +++ b/src/UTF8.php @@ -6,7 +6,7 @@ class UTF8 { static function str_split($str, $split_length = 1) { $split_length = (int) $split_length; - $matches = array(); + $matches = []; preg_match_all('/.{'.$split_length.'}|[^\x00]{1,'.$split_length.'}$/us', $str, $matches); return $matches[0]; diff --git a/src/Validator/Rule/Code.php b/src/Validator/Rule/Code.php index 8e6e122..4ae1b48 100644 --- a/src/Validator/Rule/Code.php +++ b/src/Validator/Rule/Code.php @@ -31,7 +31,7 @@ class Code extends AbstractRule if (is_array($_POST[$name . '_code_genre'])) { $count = count($_POST[$name . '_code_genre']); for($n = 0; $n < $count; $n++) { - $code = array( + $code = [ $_POST[$name . '_code_genre'][$n], $_POST[$name . '_code_f'][$n], $_POST[$name . '_code_i'][$n], @@ -39,14 +39,14 @@ class Code extends AbstractRule $_POST[$name . '_code_year'][$n], $_POST[$name . '_code_month'][$n], $_POST[$name . '_code_day'][$n] - ); + ]; if (!$this->checkCode($code)) { return false; } } return true; } else { - $code = array( + $code = [ $_POST[$name . '_code_genre'], $_POST[$name . '_code_f'], $_POST[$name . '_code_i'], @@ -54,7 +54,7 @@ class Code extends AbstractRule $_POST[$name . '_code_year'], $_POST[$name . '_code_month'], $_POST[$name . '_code_day'] - ); + ]; return $this->checkCode($code); } diff --git a/src/Validator/Rule/Count.php b/src/Validator/Rule/Count.php index ff030a4..c346892 100644 --- a/src/Validator/Rule/Count.php +++ b/src/Validator/Rule/Count.php @@ -28,7 +28,7 @@ class Count extends AbstractRule $this->max = $this->size; } $count = count(array_filter(array_map('trim', - explode(";", $container->get($this->field))), array($this, 'not_empty'))); + explode(";", $container->get($this->field))), [$this, 'not_empty'])); return $count >= $this->size && $count <= ((int)$this->max); } diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 2e003d7..465c679 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -31,7 +31,7 @@ class Validator 'reg' => 'ctiso\\Validator\\Rule\\PregMatch', ); - function __construct($rules = array()) { + function __construct($rules = []) { $this->addRuleList($rules); } @@ -100,11 +100,11 @@ class Validator public function validate(Collection $container, $rule = null, $status = null) { - $fields = array(); + $fields = []; if ($rule) { $this->chain = $rule; } - $this->errorMsg = array(); + $this->errorMsg = []; foreach ($this->chain as $rule) { //echo $key; if (!in_array($rule->field, $fields) && !$this->skip($rule, $container) && !$rule->isValid($container, $status)) { diff --git a/src/View/ListView.php b/src/View/ListView.php index 16945ff..3acd298 100644 --- a/src/View/ListView.php +++ b/src/View/ListView.php @@ -7,7 +7,7 @@ class ListView extends View { function execute() { - $result = array(); + $result = []; foreach ($this->_section as $key => $value) { $result [] = $value->execute(); } diff --git a/src/View/Pages.php b/src/View/Pages.php index f621cef..e5e93c7 100644 --- a/src/View/Pages.php +++ b/src/View/Pages.php @@ -14,17 +14,17 @@ class Pages if ($page > $n) $page = $n; if ($page < 1) $page = 1; $url = 'page='; - $result = array(); + $result = []; for ($i = max($page - self::$range, 1); $i <= min($n, $page + self::$range); $i++) { - $result [] = array('page' => $i, 'href' => ($i != $page) ? self::href($prefix, $url . $i) : false); + $result [] = ['page' => $i, 'href' => ($i != $page) ? self::href($prefix, $url . $i) : false]; } - return array( + return [ 'all' => ($n > 1), 'list' => $result, 'first' => self::href($prefix, $url . 1), 'last' => self::href($prefix, $url . $n), 'next' => ($page == $n)? false : self::href($prefix, $url . ($page + 1)) , - 'prev' => ($page == 1)? false : self::href($prefix, $url . ($page - 1))); + 'prev' => ($page == 1)? false : self::href($prefix, $url . ($page - 1))]; } /** @@ -45,10 +45,10 @@ class Pages */ static function _getLimit($page, $onpage) { if ($page <= 0) { $page = 1; } - return array( + return [ 'count' => $onpage, 'start' => ($page - 1) * $onpage, - ); + ]; } static function href($prefix, $x) { diff --git a/src/View/Top.php b/src/View/Top.php index 6cf27d7..37b3339 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -15,7 +15,7 @@ class Top extends Composite public function getTitle() { - return implode(" - ", array_filter($this->doTree('_title', false), array($this, 'isNotNull'))); + return implode(" - ", array_filter($this->doTree('_title', false), [$this, 'isNotNull'])); } function getId($pref) @@ -39,10 +39,10 @@ class Top extends Composite $this->set('scripts', array_unique($this->getScripts())); $this->set('stylesheet', array_unique($this->getStyleSheet())); - $this->require = array('admin' => 'ma'); - $this->deps = array(); + $this->require = ['admin' => 'ma']; + $this->deps = []; - $startup = array(); + $startup = []; foreach ($this->_section as $s) { if (is_string($s)) { continue; @@ -67,7 +67,7 @@ class Top extends Composite $script .= $value . "." . $key . " = " . json_encode($v /*, JSON_PRETTY_PRINT*/) . ";\n"; } - $init = array(); + $init = []; foreach ($s->_section as $key => $item) { $ss /*: View*/= $item; if ($ss->codeGenerator !== null) { diff --git a/src/View/View.php b/src/View/View.php index 0151523..c8abbf2 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -101,7 +101,7 @@ class View extends \stdClass */ protected function doTree($list, $flatten = true) { - $result = ($flatten == true) ? $this->$list : array($this->$list); + $result = ($flatten == true) ? $this->$list : [$this->$list]; foreach ($this->_section as $value) { if (is_object($value)) { if ($list == '_script' || $list == '_stylesheet') { @@ -182,10 +182,10 @@ class View extends \stdClass function loadImports($importFile) { - $types = array( + $types = [ 'js' => array($this, 'addScript'), 'css' => array($this, 'addStyleSheet') - ); + ]; // Подключение стилей и скриптов if (file_exists($importFile)) { $files = file($importFile); @@ -201,7 +201,7 @@ class View extends \stdClass } public function resolveAllNames($alias, $list) { - $result = array(); + $result = []; foreach($list as $item) { $result [] = $this->resolveName($alias, $item); } diff --git a/src/ZipFile.php b/src/ZipFile.php index c788806..e858432 100644 --- a/src/ZipFile.php +++ b/src/ZipFile.php @@ -30,7 +30,7 @@ class ZipFile extends ZipArchive if (in_array($file, $this->ignore)) continue; // Rekursiv, If dir: FlxZipArchive::addDir(), else ::File(); $call = (is_dir($location . $file)) ? 'addDir' : 'addFile'; - call_user_func(array($this, $call), $location . $file, $name . $file); + call_user_func([$this, $call], $location . $file, $name . $file); } } From 8941f5f102301191954933a46e65eb67f2effd89 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 14 Jun 2024 14:15:01 +0300 Subject: [PATCH 077/138] fix: noverify --fix (repeat) --- src/Database.php | 2 +- src/View/View.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Database.php b/src/Database.php index 1f39d3d..3f61550 100644 --- a/src/Database.php +++ b/src/Database.php @@ -25,7 +25,7 @@ class Database extends PDO parent::__construct($dsn, $username, $password); $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); - $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, [PDOStatement::class, array()]); + $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, [PDOStatement::class, []]); } function prepare(string $sql, array $options = []): PDOStatement|false { diff --git a/src/View/View.php b/src/View/View.php index c8abbf2..141e541 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -183,8 +183,8 @@ class View extends \stdClass function loadImports($importFile) { $types = [ - 'js' => array($this, 'addScript'), - 'css' => array($this, 'addStyleSheet') + 'js' => [$this, 'addScript'], + 'css' => [$this, 'addStyleSheet'] ]; // Подключение стилей и скриптов if (file_exists($importFile)) { From d692538163f063c2d5ae48652c9d776aa9e40c67 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 29 Aug 2024 11:11:20 +0300 Subject: [PATCH 078/138] =?UTF-8?q?style:=20=D0=A4=D0=BE=D1=80=D0=BC=D0=B0?= =?UTF-8?q?=D1=82=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 3 +- src/Controller/Component.php | 53 +++++++++++++++-------------- src/Controller/Front.php | 64 +++++++++++++++++------------------- src/Form/Form.php | 2 +- src/Mail.php | 2 +- src/Role/User.php | 2 +- src/Setup.php | 4 +-- src/Tools/Drawing.php | 53 ++++++++++++++--------------- src/Validator/Rule/Time.php | 1 + 9 files changed, 92 insertions(+), 92 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index c9b29eb..b1f7db2 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -7,6 +7,7 @@ use Exception, ctiso\Model\Factory, ctiso\HttpRequest, ctiso\Settings, + ctiso\Database, ctiso\View\Composite, ctiso\View\View, App\Controller\State; @@ -31,7 +32,7 @@ class Action /** * Соединение с базой данных */ - public $db; + public Database $db; // Фильтры public $access = null; // Обьект хранит параметры доступа diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 4d168c7..386d6ac 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -19,14 +19,14 @@ use ctiso\HttpRequest, class FakeTemplate { public $_data = []; public $_name = ''; - + function __construct($name) { $this->_name = $name; } function __set($key, $value) { $this->_data[$key] = $value; - } + } function execute() { return json_encode($this->_data); @@ -49,7 +49,7 @@ class Component public $COMPONENTS_WEB; - public Registry $config; + public Registry $config; public Database $db; public Collection $parameter; @@ -79,7 +79,7 @@ class Component } else { $action = 'action' . ucfirst($_action); } - + $this->before(); if (method_exists($this, $action)) { return call_user_func([$this, $action], $crequest); @@ -89,16 +89,16 @@ class Component } public function getTemplateName($_registry/*: \ctiso\Settings*/) { - return (isset($_COOKIE['with_template']) && preg_match('/^[\w\d-]{3,20}$/', $_COOKIE['with_template'])) + return (isset($_COOKIE['with_template']) && preg_match('/^[\w\d-]{3,20}$/', $_COOKIE['with_template'])) ? $_COOKIE['with_template'] : ($_registry ? $_registry->get('site', 'template') : 'modern'); - } + } public function getView($name) { if ($this->output == 'json') { return new FakeTemplate($name); } - + $config/*: Registry*/ = $this->config; $default = $config->get('site', 'template'); $template = ($this->template) ? $this->template : $this->getTemplateName($config); @@ -113,12 +113,12 @@ class Component $tpl->setPhpCodeDestination(PHPTAL_PHP_CODE_DESTINATION); $selected = $index; break; - } + } } if ($selected === null) { // Последний вариант viewPath, путь к папке компонента - $selected = count($this->viewPath) - 1; + $selected = count($this->viewPath) - 1; $tpl = new PHPTAL(Path::join($this->viewPath[$selected], 'templates', 'modern', $name)); $tpl->setPhpCodeDestination(PHPTAL_PHP_CODE_DESTINATION); $template = 'modern'; @@ -156,7 +156,7 @@ class Component return Path::join($this->viewPath[$index], 'templates', $template, $name); } } - + return Path::join($this->viewPath[count($this->viewPath) - 1], 'templates', 'modern', $name); } @@ -167,7 +167,7 @@ class Component /** * Создает модель - * @param string $name + * @param string $name * @return mixed */ public function getModel($name) @@ -198,7 +198,7 @@ class Component function findFile($pathList, $name) { foreach($pathList as $item) { $filename = Path::join($item, $name); - if (file_exists($filename)) { + if (file_exists($filename)) { return $filename; } } @@ -233,15 +233,14 @@ class Component static function loadComponent($expression, $site/*: SiteInterface*/) { - + $expression = htmlspecialchars_decode($expression); $offset = strpos($expression, '?'); $url = parse_url($expression); - + $arguments = []; - if ($offset === false) { - $path = $expression; - } else if (is_int($offset)) { + $path = $expression; + if (is_int($offset)) { $path = substr($expression, 0, $offset); $query = substr($expression, $offset + 1); parse_str($query, $arguments); @@ -254,10 +253,10 @@ class Component $className = implode("\\", ['Components', ucfirst($name), $filename]); $component/*: Component*/ = null; - + if (file_exists($path)) { // require_once ($path); - $component = new $className(); + $component = new $className(); $component->viewPath = [$config->get('site', 'components') . '/' . $name . '/']; $component->webPath = [$config->get('site', 'components.web') . '/' . $name]; @@ -272,30 +271,30 @@ class Component $config->get('site', 'templates') . '/'. $template . '/_components/' . $name . '/', $config->get('site', 'components') . '/' . $name . '/', // Потом в общем хранилище - $config->get('system', 'templates'). '/' . $template . '/_components/' . $name . '/', - $config->get('system', 'components') . '/' . $name . '/', + $config->get('system', 'templates'). '/' . $template . '/_components/' . $name . '/', + $config->get('system', 'components') . '/' . $name . '/', ]; if (defined('COMPONENTS_WEB')) { $component->webPath = [ // Сначало локально $config->get('site', 'templates.web') . '/' . $template . '/_components/' . $name, $config->get('site', 'components.web') . '/' . $name, - // Потом в общем хранилище + // Потом в общем хранилище $config->get('system', 'templates.web') . '/' . $template . '/_components/' . $name, - $config->get('system', 'components.web') . '/' . $name, + $config->get('system', 'components.web') . '/' . $name, ]; $component->COMPONENTS_WEB = $config->get('system', 'components.web'); } else { $component->webPath = ['', $config->get('site', 'components.web') . '/' . $name, '', '']; } - } + } $db = $site->getDatabase(); $component->db = $db; $component->config = $site->config; $component->site = $site; - + $stmt = $db->prepareStatement("SELECT * FROM component WHERE code = ?"); $stmt->setString(1, $expression); $cid = $stmt->executeQuery(); @@ -339,7 +338,7 @@ class Component return null; } - function raw_query($request/*: ComponentRequest*/) + function raw_query($request/*: ComponentRequest*/) { $arr = $request->r->export('get'); @@ -362,7 +361,7 @@ class Component } - function query($request/*: ComponentRequest*/, $list) + function query($request/*: ComponentRequest*/, $list) { $arr = $request->r->export('get'); diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 396d659..d1bc119 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -7,7 +7,7 @@ namespace ctiso\Controller; use ctiso\Controller\Action, ctiso\Registry, - ctiso\Database, + ctiso\Database, ctiso\Collection, ctiso\Filter\ActionAccess, ctiso\Filter\ActionLogger, @@ -38,11 +38,11 @@ class Front extends Action /** * Создает экземпляр модуля и выполняет действия для него - * @param string $name Имя модуля - * @param Collection $request Имя модуля - * @return string + * @param string $name Имя модуля + * @param HttpRequest $request + * @return string */ - public function loadModule($name, Collection $request) + public function loadModule($name, HttpRequest $request) { if ($this->isLoaded($name)) { $module = $this->modules[$name]; @@ -50,45 +50,43 @@ class Front extends Action } $parts = explode('\\', $name); - + $config = $this->config; - + $moulesPath = Path::join($config->get('system', 'path'), 'modules'); $logPath = Path::join($config->get('site', 'path'), $config->get('system', 'access.log')); $first = $parts[0]; $second = (count($parts) >= 2) ? $parts[1] : $parts[0]; - + $ucname = ucfirst($first); $ucpart = ucfirst($second); - + $moduleClass = "Modules\\$ucname\\$ucpart"; $module = new $moduleClass(); - if ($module) { - // Инициализация модуля - $modPath = Path::join($moulesPath, $first); - $module->modulePath = $modPath; - $module->name = $name; - // - $module->config = $this->config; - $module->db = $this->db; - $module->user = $this->user; - $module->front = $this; - // Ведение лога - $logger = new ActionLogger($module, $logPath, $this->user); - $filename = Path::join($modPath, 'filters', 'logger.json'); - $logger->before = $this->loadSettings($filename); - // Управление доступом - $module->access = new ActionAccess($logger, $this->user); - $module->access->access = $this->loadSettings(Path::join($modPath, 'filters', 'access.json')); - $module->setUp(); - - $this->modules[$name] = $module; - $result = $module->access->execute($request); - return $result; - } - return null; // throw new FileNotFoundException(); + // Инициализация модуля + $modPath = Path::join($moulesPath, $first); + $module->modulePath = $modPath; + $module->name = $name; + // + $module->config = $this->config; + $module->db = $this->db; + $module->user = $this->user; + $module->front = $this; + // Ведение лога + $logger = new ActionLogger($module, $logPath, $this->user); + $filename = Path::join($modPath, 'filters', 'logger.json'); + $logger->before = $this->loadSettings($filename); + // Управление доступом + $module->access = new ActionAccess($logger, $this->user); + $module->access->access = $this->loadSettings(Path::join($modPath, 'filters', 'access.json')); + + $module->setUp(); + + $this->modules[$name] = $module; + $result = $module->access->execute($request); + return $result; } diff --git a/src/Form/Form.php b/src/Form/Form.php index 5f8da65..7cc74f8 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -153,7 +153,7 @@ class Form extends View { * Устанавливает значения из масива */ function setValues(HttpRequest $request) { - foreach ($this->field as $key => $el) { + foreach ($this->field as $key => $_) { $value = $request->getRawData($this->method, $key); $this->field[$key]->setValue($value); } diff --git a/src/Mail.php b/src/Mail.php index 9daae2c..7f3930d 100644 --- a/src/Mail.php +++ b/src/Mail.php @@ -25,7 +25,7 @@ class Mail function __construct() { $this->setEncoding("UTF-8"); - $this->uniqid = strtoupper(uniqid(time())); // Идентефикатор разделителя + $this->uniqid = strtoupper(uniqid((string)time())); // Идентефикатор разделителя } /** diff --git a/src/Role/User.php b/src/Role/User.php index 291048c..3f5728e 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -13,7 +13,7 @@ class User implements UserInterface public $name; public $access; public $password; - public $id; + public $id; public $db; public $groups; diff --git a/src/Setup.php b/src/Setup.php index 8574adc..1aef431 100644 --- a/src/Setup.php +++ b/src/Setup.php @@ -146,12 +146,12 @@ class Setup /** * Копирования файла - * preserver - Не переписывать файл если он существует + * preserve - Не переписывать файл если он существует * template Файл является шаблоном подставить параметры до копирования * src Исходный файл * dst Новый файл * - * @param array{preserve: string, template: string, src: string, dst: string} $attributes + * @param array{preserve?: string, template: string, src: string, dst: string} $attributes */ public function copyFile(array $attributes) { diff --git a/src/Tools/Drawing.php b/src/Tools/Drawing.php index 829e3c3..306d914 100644 --- a/src/Tools/Drawing.php +++ b/src/Tools/Drawing.php @@ -9,8 +9,8 @@ class Drawing const ALIGN_BOTTOM = "bottom"; const ALIGN_CENTER = "center"; const ALIGN_RIGHT = "right"; - - static function drawrectnagle(&$image, $left, $top, $width, $height, $rgb) + + static function drawrectnagle(&$image, $left, $top, $width, $height, $rgb) { $color = imagecolorallocate($image, $rgb[0], $rgb[1], $rgb[2]); $right = $left + $width; @@ -22,68 +22,69 @@ class Drawing } /** - * http://ru2.php.net/imagettftext + * http://ru2.php.net/imagettftext */ - static function imagettftextbox(&$image, $size, $angle, $left, $top, $color, $font, $text, + static function imagettftextbox(&$image, $size, $angle, $left, $top, $color, $font, $text, $max_width, $max_height, $align, $valign) { // 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)); $text_lines = explode("\n", $text); // Supports manual line breaks! - + $lines = []; $line_widths = []; - - $largest_line_height = 0; + + $largest_line_height = 0; foreach ($text_lines as $block) { - $current_line = ''; // Reset current line - $words = explode(' ', $block); // Split the text into an array of single words + $current_line = ''; // Reset current line + $words = explode(' ', $block); // Split the text into an array of single words $first_word = true; - - $last_width = 0; + + $last_width = 0; $count = count($words); + $item = ''; for ($i = 0; $i < $count; $i++) { $item = $words[$i]; $dimensions = imagettfbbox($size, $angle, $font, $current_line . ($first_word ? '' : ' ') . $item); $line_width = $dimensions[2] - $dimensions[0]; $line_height = $dimensions[1] - $dimensions[7]; - + $largest_line_height = max($line_height, $largest_line_height); - + if ($line_width > $max_width && !$first_word) { $lines[] = $current_line; - + $line_widths[] = $last_width ?: $line_width; $current_line = $item; } else { $current_line .= ($first_word ? '' : ' ') . $item; } - + if ($i == count($words) - 1) { - $lines[] = $current_line; + $lines[] = $current_line; $line_widths[] = $line_width; } - - $last_width = $line_width; + + $last_width = $line_width; $first_word = false; } - + if ($current_line) { $current_line = $item; } } - + // vertical align $top_offset = 0; if ($valign == self::ALIGN_CENTER) { $top_offset = ($max_height - $largest_line_height * count($lines)) / 2; } elseif ($valign == self::ALIGN_BOTTOM) { $top_offset = $max_height - $largest_line_height * count($lines); - } - + } + $top += $largest_line_height + $top_offset; - + $i = 0; foreach ($lines as $line) { // horizontal align @@ -93,17 +94,17 @@ class Drawing } elseif ($align == self::ALIGN_RIGHT) { $left_offset = ($max_width - $line_widths[$i]); } - + imagettftext($image, $size, $angle, $left + $left_offset, $top + ($largest_line_height * $i), $color, $font, $line); $i++; } - + return $largest_line_height * count($lines); } function imagettftextSp($image, $size, $angle, $x, $y, $color, $font, $text, $spacing = 0) - { + { if ($spacing == 0) { imagettftext($image, $size, $angle, $x, $y, $color, $font, $text); diff --git a/src/Validator/Rule/Time.php b/src/Validator/Rule/Time.php index 44fd7e3..6a3b81e 100644 --- a/src/Validator/Rule/Time.php +++ b/src/Validator/Rule/Time.php @@ -25,6 +25,7 @@ class Time extends AbstractRule public function isValid(Collection $container, $status = null) { + /** @var array[string]|null */ $tmp = explode($this->split, $container->get($this->field), 2); if ($tmp) { if (self::checktime ((int)$tmp[0], (int)$tmp[1])) { From f599a6852906cddd1fd66702c9e58b75e89e10c6 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 14 Nov 2024 12:04:09 +0300 Subject: [PATCH 079/138] feat: sqlite in memory db --- src/Database.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Database.php b/src/Database.php index 3f61550..0308b89 100644 --- a/src/Database.php +++ b/src/Database.php @@ -57,8 +57,10 @@ class Database extends PDO if (isset($dsn['schema'])) { $connection->query('SET search_path TO ' . $dsn['schema']); } - } - if ($dsn['phptype'] == 'sqlite') { + } elseif ($dsn['phptype'] == 'sqlite::memory') { + $connection = new self("{$dsn['phptype']}:"); + $connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1); + } elseif ($dsn['phptype'] == 'sqlite') { $connection/*: Database*/ = new self("{$dsn['phptype']}:{$dsn['database']}"); $connection->setAttribute(PDO::ATTR_TIMEOUT, 5); $mode = defined('SQLITE_JOURNAL_MODE') ? SQLITE_JOURNAL_MODE : 'WAL'; From e5e0b6735fa667c0d4d9597acc2defb46c7af3a5 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 5 Dec 2024 12:48:08 +0300 Subject: [PATCH 080/138] =?UTF-8?q?feat:=20=D0=9D=D0=B5=D0=B1=D0=BE=D0=BB?= =?UTF-8?q?=D1=8C=D1=88=D0=BE=D0=B9=20=D1=80=D0=B5=D1=84=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=BD=D0=B3.=20=D0=9E=D0=B3=D1=80=D0=B0?= =?UTF-8?q?=D0=BD=D0=B8=D1=87=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B4=D0=BB=D0=B8?= =?UTF-8?q?=D0=BD=D0=BD=D1=8B=20=D0=B7=D0=BD=D0=B0=D1=87=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=20=D0=B2=20=D0=BF=D0=BE=D0=BB=D0=B5=20=D0=B2=D0=B2=D0=BE?= =?UTF-8?q?=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 9 +++-- src/Controller/Component.php | 4 ++ src/Form/CheckBox.php | 2 +- src/Form/Field.php | 3 +- src/Form/Form.php | 78 ++++++++++++++++++++---------------- 5 files changed, 56 insertions(+), 40 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index b1f7db2..d209a46 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -203,17 +203,18 @@ class Action /** * Генерация ссылки c учетом прав пользователя на ссылки - * @param string $name Действие + * @param string $actionName Действие * @param array $param Дополнительные параметры * 'mode' означает что элемент до отправки обрабатывается javascript * @return Url|null */ - public function nUrl($name, array $param = []) + public function nUrl($actionName, array $param = []) { $access/*: ActionAccess*/ = $this->access; $url = new Url(); - if ($access == null || $access->checkAction($name)) { + //print_r([$name, $param]); + if ($access == null || $access->checkAction($actionName)) { $moduleName = explode("\\", strtolower(get_class($this))); if (count($moduleName) > 2) { array_shift($moduleName); @@ -221,7 +222,7 @@ class Action array_shift($moduleName); } } - $param = array_merge(['module' => implode("\\", $moduleName), "action" => $name], $param); + $param = array_merge(['module' => implode("\\", $moduleName), "action" => $actionName], $param); $url->setParent($this->part); $url->setQuery($param); diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 386d6ac..2dc5ffc 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -231,6 +231,9 @@ class Component $view->component_title = $settings['title']; } + /** + * Обьеденить с ComponentFactory + */ static function loadComponent($expression, $site/*: SiteInterface*/) { @@ -289,6 +292,7 @@ class Component } } + // Вынести в отдельную функцию $db = $site->getDatabase(); $component->db = $db; diff --git a/src/Form/CheckBox.php b/src/Form/CheckBox.php index ea5f880..6eb1619 100644 --- a/src/Form/CheckBox.php +++ b/src/Form/CheckBox.php @@ -3,7 +3,7 @@ namespace ctiso\Form; use ctiso\Form\Field; -class Checkbox extends Field +class CheckBox extends Field { public $checked = false; function setValue($value) diff --git a/src/Form/Field.php b/src/Form/Field.php index d4e8a34..c3df594 100644 --- a/src/Form/Field.php +++ b/src/Form/Field.php @@ -16,6 +16,7 @@ class Field public $error = false; public $require = false; public $hint = null; + public $maxlength = null; public $fieldset = null; // Блоки (Убрать в отдельный класс!!!) public $_title = array(); @@ -33,7 +34,7 @@ class Field $this->fieldset = $input['fieldset']; } // Инициализация свойст обьетка - foreach (['label', 'name', 'type', 'description'] as $name) { + foreach (['label', 'name', 'type', 'description', 'maxlength'] as $name) { if (isset($input[$name])) { $this->$name = $input[$name]; } diff --git a/src/Form/Form.php b/src/Form/Form.php index 7cc74f8..6906ee5 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -29,41 +29,41 @@ class Form extends View { public $_title = array(); public $alias = array(); public $constructor = array(); - + /** * Строим форму по ее структуре. Каждому типу соответствует определенный класс. */ public function __construct() { $this->constructor = [ - 'input' => 'ctiso\\Form\\Input', + 'input' => Input::class, // input с проверкой на заполненность - 'inputreq' => 'ctiso\\Form\\Input', + 'inputreq' => Input::class, - 'date' => 'ctiso\\Form\\Date', - 'datereq' => 'ctiso\\Form\\Date', - 'datetime' => 'ctiso\\Form\\DateTime', + 'date' => Date::class, + 'datereq' => Date::class, + 'datetime' => DateTime::class, - 'color' => 'ctiso\\Form\\Color', - 'textarea' => 'ctiso\\Form\\TextArea', - 'text' => 'ctiso\\Form\\TextArea', - 'multiselect' => 'ctiso\\Form\\SelectMany', - 'select1' => 'ctiso\\Form\\SelectOne', - 'select' => 'ctiso\\Form\\SelectOne', - - 'questiontype'=> 'ctiso\\Form\\QuestionType', - 'secret' => 'ctiso\\Form\\Secret', - 'upload' => 'ctiso\\Form\\Upload', - 'image' => 'ctiso\\Form\\Upload', - 'checkbox' => 'ctiso\\Form\\CheckBox', - 'checkmany' => 'ctiso\\Form\\SelectMany', - 'hidden' => 'ctiso\\Form\\Hidden', - 'radio' => 'ctiso\\Form\\SelectOne', - 'filebrowser' => 'ctiso\\Form\\BrowserInput', - 'documents' => 'ctiso\\Form\\BrowserInput', - 'chooser' => 'ctiso\\Form\\Input', - 'select_chooser' => 'ctiso\\Form\\SelectOne', - 'html_text' => 'ctiso\\Form\\HtmlText' + 'color' => Color::class, + 'textarea' => TextArea::class, + 'text' => TextArea::class, + 'multiselect' => SelectMany::class, + 'select1' => SelectOne::class, + 'select' => SelectOne::class, + + 'questiontype'=> QuestionType::class, + 'secret' => Secret::class, + 'upload' => Upload::class, + 'image' => Upload::class, + 'checkbox' => CheckBox::class, + 'checkmany' => SelectMany::class, + 'hidden' => Hidden::class, + 'radio' => SelectOne::class, + 'filebrowser' => BrowserInput::class, + 'documents' => BrowserInput::class, + 'chooser' => Input::class, + 'select_chooser' => SelectOne::class, + 'html_text' => HtmlText::class ]; } @@ -77,7 +77,7 @@ class Form extends View { { $this->constructor [$name] = $class; } - + /** * Добавляет одно поле ввода на форму */ @@ -95,7 +95,7 @@ class Form extends View { if(isset($init['hint'])) { $el->hint = $init['hint']; } - + $this->field[$init['name']] = $el; return $el; } @@ -112,7 +112,7 @@ class Form extends View { /** * Добавление массива fieldset на форму */ - + public function addFieldSetList(array $list) { foreach ($list as $fieldset) { @@ -122,7 +122,7 @@ class Form extends View { /** * Добавляет список полей для формы - * @param array $list + * @param array $list */ public function addFieldList(array $list, $factory = null) { @@ -151,7 +151,7 @@ class Form extends View { /** * Устанавливает значения из масива - */ + */ function setValues(HttpRequest $request) { foreach ($this->field as $key => $_) { $value = $request->getRawData($this->method, $key); @@ -160,9 +160,9 @@ class Form extends View { } /** - * Заполняет форму данными из обьекта + * Заполняет форму данными из обьекта * @param object $data - * @param array $schema Связь между элементами формы и свойствами обьекта + * @param array $schema Связь между элементами формы и свойствами обьекта */ public function fill($data, array $schema) { @@ -177,7 +177,17 @@ class Form extends View { $this->field[$name]->setValue($value); } - function execute() + public function getSchema() { + return [ + 'field' => $this->field, + 'fieldset' => $this->fieldsets, + 'method' => $this->method, + 'action' => $this->action, + 'header' => $this->header + ]; + } + + function execute() { return $this; } From 1d22953f682c1569d3ad5f099f5b25a36de39937 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 12 Dec 2024 12:12:00 +0300 Subject: [PATCH 081/138] fix: type --- src/Validator/Rule/Time.php | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/Validator/Rule/Time.php b/src/Validator/Rule/Time.php index 6a3b81e..c4ecc58 100644 --- a/src/Validator/Rule/Time.php +++ b/src/Validator/Rule/Time.php @@ -12,10 +12,10 @@ class Time extends AbstractRule private $split = ":"; public function getErrorMsg() - { + { return "Неверный формат времени"; } - + static function checktime($hour, $minute) { if ($hour > -1 && $hour < 24 && $minute > -1 && $minute < 60) { @@ -25,13 +25,12 @@ class Time extends AbstractRule public function isValid(Collection $container, $status = null) { - /** @var array[string]|null */ + /** @var list */ $tmp = explode($this->split, $container->get($this->field), 2); - if ($tmp) { - if (self::checktime ((int)$tmp[0], (int)$tmp[1])) { - return true; - } + if (self::checktime ((int)$tmp[0], (int)$tmp[1])) { + return true; } + return false; } } From 82f6dd163089cdc87e511d7d14e7ce1214e3b9d3 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Mon, 16 Dec 2024 17:10:44 +0300 Subject: [PATCH 082/138] =?UTF-8?q?refactor:=20=D0=97=D0=B0=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D0=B0=20=D1=81=D1=82=D1=80=D0=BE=D0=BA=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=B8=D0=BC=D0=B5=D0=BD=D0=B0=20=D0=BA=D0=BB=D0=B0=D1=81=D1=81?= =?UTF-8?q?=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 7 ++++++- src/Controller/Component.php | 3 ++- src/HttpRequest.php | 26 ++++++++++++++++---------- src/Model/Factory.php | 12 ++++++------ 4 files changed, 30 insertions(+), 18 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index d209a46..d10d2eb 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -98,7 +98,7 @@ class Action /** * Создает представление * @param string $name - * @param string $viewClass + * @param class-string $viewClass * @return Composite */ public function getView($name, $viewClass = Composite::class) @@ -146,6 +146,11 @@ class Action return $tpl; } + /** + * @template T + * @param class-string $name + * @return T + */ public function getModel($name) { if (!$this->factory) { diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 2dc5ffc..761f8fb 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -99,7 +99,8 @@ class Component return new FakeTemplate($name); } - $config/*: Registry*/ = $this->config; + /* @var Registry $config */ + $config = $this->config; $default = $config->get('site', 'template'); $template = ($this->template) ? $this->template : $this->getTemplateName($config); diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 186ae12..c8c0f7c 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -1,16 +1,18 @@ $_REQUEST, - 'get' => $_GET, - 'post' => $_POST, + 'data' => $_REQUEST, + 'get' => $_GET, + 'post' => $_POST, 'cookie' => $_COOKIE ]; @@ -44,15 +46,19 @@ class HttpRequest extends Collection return parent::get($key); } + /** + * @param T $key + * @return mixed + */ function get($key, $default = null) { return parent::get('data')->get($key, $default); } - + function session(Session $value = null) { if ($value) { - $this->_session = $value; + $this->_session = $value; } return $this->_session; } @@ -97,7 +103,7 @@ class HttpRequest extends Collection } public function setAction($name) - { + { $this->setRawData('get', 'action', $name); } diff --git a/src/Model/Factory.php b/src/Model/Factory.php index cf7f46e..ab560e3 100644 --- a/src/Model/Factory.php +++ b/src/Model/Factory.php @@ -11,21 +11,21 @@ class Factory public $config; public $user; - public function __construct (Database $db, Registry $config = null, User $user = null) + public function __construct(Database $db, Registry $config = null, User $user = null) { $this->db = $db; $this->config = $config; $this->user = $user; } - + /** * Создает модель - * @param string $name - * @return BaseMapper + * @template T + * @param class-string $modelName + * @return T */ - public function getModel ($name) + public function getModel($modelName) { - $modelName = "App\\Mapper\\" . $name; $model = new $modelName(); $model->db = $this->db; $model->factory = $this; From 9680409ba9e3a8b68e23ebbca4e393469373ae3c Mon Sep 17 00:00:00 2001 From: Wizard Date: Mon, 16 Dec 2024 23:35:20 +0300 Subject: [PATCH 083/138] =?UTF-8?q?refactor:=20=D0=9D=D0=B0=D0=B7=D0=B2?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D0=B5=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Database/Manager.php | 61 ++++++++++++++++++++-------------------- src/Excel/Document.php | 2 +- 2 files changed, 31 insertions(+), 32 deletions(-) diff --git a/src/Database/Manager.php b/src/Database/Manager.php index 1fbc101..1629a92 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -16,27 +16,27 @@ class Manager $this->db = $db; } - public function ExecuteAction($action/*: array*/, $db_file = "") + public function executeAction($action/*: array*/, $db_file = "") { switch($action["type"]) { case "dropTable": - $this->DropTableQuery($action["table_name"], true); + $this->dropTableQuery($action["table_name"], true); break; case "createTable": $constraints = $action["constraints"] ?? null; - $this->CreateTableQuery($action["table_name"], $action["fields"], $constraints); + $this->createTableQuery($action["table_name"], $action["fields"], $constraints); break; case "addColumn": - $this->AddColumn($action["table_name"], $action["column_name"], $action["field"]); + $this->addColumn($action["table_name"], $action["column_name"], $action["field"]); break; case "insert": $this->db->insertQuery($action["table_name"], $action["values"]); break; case "alterReference": - $this->AlterReference($action["table"], $action["column"], $action["refTable"], $action["refColumn"]); + $this->alterReference($action["table"], $action["column"], $action["refTable"], $action["refColumn"]); break; case "renameColumn": - $this->RenameColumn($action["table"], $action["old_name"], $action["new_name"]); + $this->renameColumn($action["table"], $action["old_name"], $action["new_name"]); break; case "createView": $this->recreateView($action["view"], $action["select"]); @@ -66,7 +66,7 @@ class Manager $this->db->query("CREATE VIEW ".$viewName." AS ".$selectStatement); } - public function DropTableQuery($table, $cascade=false) + public function dropTableQuery($table, $cascade=false) { $statement = "DROP TABLE IF EXISTS ".$table; if ($this->db->isPostgres()&&$cascade) { @@ -75,13 +75,13 @@ class Manager $this->db->query($statement); } - public function AlterReference($table, $column, $refTable, $refColumn) + public function alterReference($table, $column, $refTable, $refColumn) { $this->db->query("ALTER TABLE ".$table." ADD CONSTRAINT ".$table."_".$column."fk"." FOREIGN KEY (".$column.") REFERENCES ".$refTable." (".$refColumn.")"); } //Извлечение информации о полях таблицы - public function TableInfo($table) + public function tableInfo($table) { $pg = $this->db->isPostgres(); if ($pg) { @@ -103,26 +103,26 @@ class Manager } } - public function RenameColumn($table, $old_name, $new_name) + public function renameColumn($table, $old_name, $new_name) { $pg = $this->db->isPostgres(); if ($pg) { $this->db->query("ALTER TABLE ".$table." RENAME COLUMN ".$old_name." TO ".$new_name); } else { $tmp_table = "tmp_" . $table; - $this->DropTableQuery($tmp_table); - $table_info = $this->TableInfo($table); + $this->dropTableQuery($tmp_table); + $table_info = $this->tableInfo($table); if (isset($table_info[$new_name])) { return; } - $data/*: array*/ = $this->DumpTable($table); + $data/*: array*/ = $this->dumpTable($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); + $this->createTableQuery($table, $table_info, null); foreach ($data as $row) { $values = $row['values']; @@ -130,17 +130,17 @@ class Manager unset($values[$old_name]); $this->db->insertQuery($table, $values); } - $this->DropTableQuery($tmp_table); + $this->dropTableQuery($tmp_table); } } //Обновление ключа serial после ручной вставки - public function UpdateSerial($table, $column) + public function updateSerial($table, $column) { $this->db->query("SELECT setval(pg_get_serial_sequence('".$table."', '".$column."'), coalesce(max(".$column."),0) + 1, false) FROM ".$table); } - public function Column_Definition($name, $data, $pg) + public function columnDefinition($name, $data, $pg) { $constraint = isset($data['constraint']) ? " ".$data['constraint'] : ""; $references = ""; @@ -161,11 +161,11 @@ class Manager return $name." ".$type.$references.$constraint; } - public function AddColumn($table_name, $column_name, $field) + public function addColumn($table_name, $column_name, $field) { $pg = $this->db->isPostgres(); $q = "ALTER TABLE ".$table_name." ADD COLUMN ". - $this->Column_Definition($column_name, $field, $pg); + $this->columnDefinition($column_name, $field, $pg); $this->db->query($q); } @@ -178,7 +178,7 @@ class Manager } //CreateTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']]) - public function CreateTableQuery($table, $fields, $constraints) + public function createTableQuery($table, $fields, $constraints) { $pg = $this->db->isPostgres(); if ($constraints) { @@ -191,26 +191,25 @@ class Manager $statement = "CREATE TABLE $table (" . implode( ",", array_map(function ($name, $data) use ($pg) { - return $this->Column_Definition($name, $data, $pg); + return $this->columnDefinition($name, $data, $pg); }, array_keys($fields), array_values($fields)) ) . " " . $constraints . ")"; $this->db->query($statement); } - public function DumpTable($table_name) + public function dumpTable($table_name) { $pg = $this->db->isPostgres(); - $result/*: array*/ = []; - $data/*: array*/ = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); + $result = []; + $data = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";"); if (!$pg) { - $table_fields = $this->TableInfo($table_name); + $table_fields = $this->tableInfo($table_name); foreach ($table_fields as $name => $value) { $type = strtolower($value['type']); if ($type == "boolean") { - foreach ($data as &$row) { - $row/*: array*/ = $row; + foreach ($data as &$row) { if (isset($row[$name])) { $row[$name] = boolval($row[$name]); } @@ -228,7 +227,7 @@ class Manager return $result; } - public function GetAllTableNames() + public function getAllTableNames() { $result = []; if ($this->db->isPostgres()) { @@ -243,12 +242,12 @@ class Manager return $result; } - public function DumpInserts() + public function dumpInserts() { - $table_names = $this->GetAllTableNames(); + $table_names = $this->getAllTableNames(); $result = []; foreach ($table_names as $table_name) { - $result = array_merge($result, $this->DumpTable($table_name)); + $result = array_merge($result, $this->dumpTable($table_name)); } return $result; } diff --git a/src/Excel/Document.php b/src/Excel/Document.php index e149da2..a8adddd 100644 --- a/src/Excel/Document.php +++ b/src/Excel/Document.php @@ -80,7 +80,7 @@ class Document { function save($filename) { $doc = new XMLWriter(); - if (!$doc->openURI($filename)) { + if (!$doc->openUri($filename)) { throw new Exception("unknown file " . $filename); } $doc->setIndent(false); From 90cbd3b2b644e14ed78897b0134def391f5422a5 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 21 Jan 2025 19:33:33 +0300 Subject: [PATCH 084/138] =?UTF-8?q?fix:=20noverify=20+=20=D1=82=D0=B8?= =?UTF-8?q?=D0=BF=D1=8B=20=D0=B4=D0=BB=D1=8F=20=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D0=BB=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 6 +- src/Database.php | 342 ++++++++++++++++++----------------- src/Database/JsonInstall.php | 8 +- src/Database/Statement.php | 10 +- src/Excel/Document.php | 21 +-- src/Excel/Table.php | 68 +++---- src/Form/Form.php | 7 + src/Path.php | 102 +++++------ src/Validator/Rule/Email.php | 8 +- src/Validator/Validator.php | 47 +++-- 10 files changed, 319 insertions(+), 300 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 761f8fb..e0dd498 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -95,7 +95,7 @@ class Component public function getView($name) { - if ($this->output == 'json') { + if ($this->output === 'json') { return new FakeTemplate($name); } @@ -126,7 +126,7 @@ class Component } $tpl->stripComments(true); - $tpl->addPreFilter(new PHPTAL_PreFilter_Normalize()); + $tpl->addPreFilter(new \PHPTAL_PreFilter_Normalize()); $tpl->set('common', Path::join($this->config->get('system', 'web'), '../', 'common')); $tpl->set('script', Path::join($this->config->get('system', 'web'), 'js')); @@ -152,7 +152,7 @@ class Component $registry = $this->config; // Брать настройки из куков если есть $template = ($this->template) ? $this->template : $this->getTemplateName($registry); - foreach ($this->viewPath as $index => $viewPath) { + foreach ($this->viewPath as $index => $_) { if(is_dir(Path::join($this->viewPath[$index], 'templates', $template))) { return Path::join($this->viewPath[$index], 'templates', $template, $name); } diff --git a/src/Database.php b/src/Database.php index 0308b89..c967d6d 100644 --- a/src/Database.php +++ b/src/Database.php @@ -1,192 +1,202 @@ setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - $this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); - $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, [PDOStatement::class, []]); - } - - function prepare(string $sql, array $options = []): PDOStatement|false { - $result/*: PDOStatement*/ = parent::prepare($sql, $options); - return $result; - } - - public function getDSN() - { - return $this->dsn; - } - public function isPostgres(){ - return ($this->dsn["phptype"] == "pgsql"); - } /** - * Создает соединение с базой данных + * Класс оболочка для PDO для замены Creole */ - static function getConnection(array $dsn) + class Database extends PDO { - $connection = null; - if ($dsn['phptype'] == 'pgsql' || $dsn['phptype'] == 'mysql') { - $port = (isset($dsn['port'])) ? "port={$dsn['port']};" : ""; - $connection/*: Database*/ = new self("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']); - if ($dsn['phptype'] == 'pgsql') { - $connection->query('SET client_encoding="UTF-8"'); - } - - if (isset($dsn['schema'])) { - $connection->query('SET search_path TO ' . $dsn['schema']); - } - } elseif ($dsn['phptype'] == 'sqlite::memory') { - $connection = new self("{$dsn['phptype']}:"); - $connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1); - } elseif ($dsn['phptype'] == 'sqlite') { - $connection/*: Database*/ = new self("{$dsn['phptype']}:{$dsn['database']}"); - $connection->setAttribute(PDO::ATTR_TIMEOUT, 5); - $mode = defined('SQLITE_JOURNAL_MODE') ? SQLITE_JOURNAL_MODE : 'WAL'; - $connection->query("PRAGMA journal_mode=$mode"); - $connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1); + public $dsn; + public function __construct($dsn, $username = null, $password = null) + { + parent::__construct($dsn, $username, $password); + $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + $this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); + $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, [PDOStatement::class, []]); } - $connection->dsn = $dsn; - return $connection; - } - public function executeQuery($query, $values=null): PDOStatement|bool - { - $stmt = $this->prepare($query); + function prepare(string $sql, array $options = []): PDOStatement|false + { + $result/*: PDOStatement*/ = parent::prepare($sql, $options); + return $result; + } - $stmt->execute($values); - $stmt->cache = $stmt->fetchAll(PDO::FETCH_ASSOC); - return $stmt; - } + public function getDSN() + { + return $this->dsn; + } + public function isPostgres() + { + return ($this->dsn["phptype"] == "pgsql"); + } + /** + * Создает соединение с базой данных + */ + static function getConnection(array $dsn) + { - public function prepareStatement($query) - { - return new Statement($query, $this); - } + $connection = null; + if ($dsn['phptype'] == 'pgsql' || $dsn['phptype'] == 'mysql') { + $port = (isset($dsn['port'])) ? "port={$dsn['port']};" : ""; + $connection/*: Database*/ = new self("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']); + if ($dsn['phptype'] == 'pgsql') { + $connection->query('SET client_encoding="UTF-8"'); + } - // Для совместимости со старым представлением баз данных CIS - /** - * Извлекает из базы все элементы по запросу - */ - public function fetchAllArray($query, $values = null) - { - $sth = $this->prepare($query); - $prep = $this->prepareValues($values); - $sth->execute($prep); - return $sth->fetchAll(PDO::FETCH_ASSOC); - } + if (isset($dsn['schema'])) { + $connection->query('SET search_path TO ' . $dsn['schema']); + } + } elseif ($dsn['phptype'] == 'sqlite::memory') { + $connection = new self("{$dsn['phptype']}:"); + $connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1); + } elseif ($dsn['phptype'] == 'sqlite') { + $connection/*: Database*/ = new self("{$dsn['phptype']}:{$dsn['database']}"); + $connection->setAttribute(PDO::ATTR_TIMEOUT, 5); + $mode = defined('SQLITE_JOURNAL_MODE') ? SQLITE_JOURNAL_MODE : 'WAL'; + $connection->query("PRAGMA journal_mode=$mode"); + $connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1); + } + $connection->dsn = $dsn; + return $connection; + } - /** - * Извлекает из базы первый элемент по запросу - */ - public function fetchOneArray($query, $values = null) - { - $sth = $this->prepare($query); - $prep = $this->prepareValues($values); - $sth->execute($prep); - return $sth->fetch(PDO::FETCH_ASSOC); - } + public function executeQuery($query, $values = null): PDOStatement|bool + { + $stmt = $this->prepare($query); - private function prepareValues($values) - { - if (!$values) { + $stmt->execute($values); + $stmt->cache = $stmt->fetchAll(PDO::FETCH_ASSOC); + return $stmt; + } + + public function prepareStatement($query) + { + return new Statement($query, $this); + } + + // Для совместимости со старым представлением баз данных CIS + /** + * Извлекает из базы все элементы по запросу + */ + public function fetchAllArray($query, $values = null) + { + $sth = $this->prepare($query); + $prep = $this->prepareValues($values); + $sth->execute($prep); + return $sth->fetchAll(PDO::FETCH_ASSOC); + } + + /** + * Извлекает из базы первый элемент по запросу + */ + public function fetchOneArray($query, $values = null) + { + $sth = $this->prepare($query); + $prep = $this->prepareValues($values); + $sth->execute($prep); + return $sth->fetch(PDO::FETCH_ASSOC); + } + + private function prepareValues($values) + { + if (!$values) { + return null; + } + $pg = $this->isPostgres(); + $prep = []; + foreach ($values as $key => $value) { + $result = null; + if (is_bool($value)) { + if ($pg) { + $result = $value ? 'true' : 'false'; + } else { + $result = $value ? 1 : 0; + } + } else { + $result = $value; + } + $prep[":" . $key] = $result; + } + return $prep; + } + /** + * Создает INSERT запрос + */ + function insertQuery($table, array $values, $return_id = false, $index = null) + { + $prep = $this->prepareValues($values); + + $sql = "INSERT INTO $table (" . implode(",", array_keys($values)) + . ") VALUES (" . implode(",", array_keys($prep)) . ")"; + if ($return_id) { + if ($this->isPostgres()) { + $sql .= " RETURNING $index"; + } + } + $stmt = $this->prepare($sql); + $stmt->setFetchMode(PDO::FETCH_ASSOC); + $stmt->execute($prep); + $result = $stmt->fetch(); + if ($return_id) { + if ($this->isPostgres()) { + return $result[$index]; + } else { + $result = $this->fetchOneArray("SELECT $index AS lastid FROM $table WHERE OID = last_insert_rowid()"); + return $result['lastid']; + } + } + } + + /** + * Создает UPDATE запрос + */ + function updateQuery($table, array $values, $cond) + { + $prep = $this->prepareValues($values); + $sql = "UPDATE $table SET " . implode( + ",", + array_map(function ($k, $v) { + return $k . "=" . $v; }, array_keys($values), array_keys($prep)) + ) . " WHERE $cond"; + + $stmt = $this->prepare($sql); + $stmt->setFetchMode(PDO::FETCH_ASSOC); + $stmt->execute($prep); + } + + function getIdGenerator() + { + return new IdGenerator($this); + } + + /** + * Замечание: Только для Postgres SQL + * @param string $seq Имя последовательности для ключа таблицы + * @return int Идентефикатор следующей записи + */ + function getNextId($seq) + { + $result = $this->fetchOneArray("SELECT nextval('$seq')"); + return $result['nextval']; + } + + function close() + { return null; } - $pg = $this->isPostgres(); - $prep = []; - foreach ($values as $key => $value) { - $result = null; - if(is_bool($value)) { - if ($pg) { - $result = $value ? 'true' : 'false'; - } else { - $result = $value ? 1 : 0; - } - } else { - $result = $value; - } - $prep[":" . $key] = $result; - } - return $prep; } - /** - * Создает INSERT запрос - */ - function insertQuery($table, array $values, $return_id = false, $index = null) - { - $prep = $this->prepareValues($values); - - $sql = "INSERT INTO $table (" . implode(",", array_keys($values)) - . ") VALUES (" . implode(",", array_keys($prep)). ")"; - if ($return_id) { - if ($this->isPostgres()){ - $sql .= " RETURNING $index"; - } - } - $stmt = $this->prepare($sql); - $stmt->setFetchMode(PDO::FETCH_ASSOC); - $stmt->execute($prep); - $result = $stmt->fetch(); - if ($return_id) { - if ($this->isPostgres()) { - return $result[$index]; - } else { - $result = $this->fetchOneArray("SELECT $index AS lastid FROM $table WHERE OID = last_insert_rowid()"); - return $result['lastid']; - } - } - } - - /** - * Создает UPDATE запрос - */ - function updateQuery($table, array $values, $cond) - { - $prep = $this->prepareValues($values); - $sql = "UPDATE $table SET " . implode(",", - array_map(function($k,$v){return $k."=".$v;}, array_keys($values), array_keys($prep))) . " WHERE $cond"; - - $stmt = $this->prepare($sql); - $stmt->setFetchMode(PDO::FETCH_ASSOC); - $stmt->execute($prep); - } - - function getIdGenerator() { - return new IdGenerator($this); - } - - /** - * Замечание: Только для Postgres SQL - * @param string $seq Имя последовательности для ключа таблицы - * @return int Идентефикатор следующей записи - */ - function getNextId($seq) { - $result = $this->fetchOneArray("SELECT nextval('$seq')"); - return $result['nextval']; - } - - function close() { - return null; - } -}} +} diff --git a/src/Database/JsonInstall.php b/src/Database/JsonInstall.php index eef8f8b..3e6eef1 100644 --- a/src/Database/JsonInstall.php +++ b/src/Database/JsonInstall.php @@ -33,7 +33,7 @@ class JsonInstall { } function missingTables($tables) { - $actual_tables = $this->db_manager->GetAllTableNames(); + $actual_tables = $this->db_manager->getAllTableNames(); $missingTables = []; foreach ($tables as $table) { if (!in_array($table, $actual_tables)) @@ -118,7 +118,7 @@ class JsonInstall { //Выполнение действий foreach ($actions as $action) { - $this->db_manager->ExecuteAction($action, $dbfill_file_path); + $this->db_manager->executeAction($action, $dbfill_file_path); } } else { echo "Invalid dbfill.json"; @@ -133,13 +133,13 @@ class JsonInstall { $pg = $this->db_manager->db->isPostgres(); if ($pg) { foreach ($this->serialColumns as $serialColumn) { - $this->db_manager->UpdateSerial($serialColumn["table"], $serialColumn["column"]); + $this->db_manager->updateSerial($serialColumn["table"], $serialColumn["column"]); } foreach ($initActions as $action) { if ($action["type"] == "alterReference") { - $this->db_manager->ExecuteAction($action); + $this->db_manager->executeAction($action); } } } diff --git a/src/Database/Statement.php b/src/Database/Statement.php index e4d5ff1..b0f6ebd 100644 --- a/src/Database/Statement.php +++ b/src/Database/Statement.php @@ -1,13 +1,13 @@ query = $query; $this->conn = $conn; } - - function setInt($n, $value) { + + function setInt($n, $value) { $this->binds [] = [$n, $value, PDO::PARAM_INT]; } diff --git a/src/Excel/Document.php b/src/Excel/Document.php index a8adddd..d4d033e 100644 --- a/src/Excel/Document.php +++ b/src/Excel/Document.php @@ -17,21 +17,21 @@ class Document { } /** - * Добавление стиля к документу - * @param $name string Имя стиля - * @param $values array Параметры стиля - * @param $type Тип стиля + * Добавление стиля к документу + * @param string $name string Имя стиля + * @param array $values array Параметры стиля + * @param string $type Тип стиля */ function setStyle ($name, array $values, $type = 'Interior') { if(!isset($this->styles[$name])) { - $this->styles[$name] = []; - } + $this->styles[$name] = []; + } $this->styles[$name][$type] = $values; } /** - * Генерация стилей + * Генерация стилей */ private function createStyles (XMLWriter $doc) { $doc->startElement('Styles'); @@ -43,7 +43,6 @@ class Document { if ($type == 'Borders') { $doc->startElement('Borders'); foreach ($s as $border) { - $border/*: array*/ = $border; $doc->startElement('Border'); foreach ($border as $key => $value) { $doc->writeAttribute('ss:' . $key, $value); @@ -72,8 +71,8 @@ class Document { return strtr($s, ["\n" => " "]); } - - /** + + /** * Сохраняет таблицу в формате Office 2003 XML * http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats */ @@ -90,7 +89,7 @@ class Document { $doc->writeAttribute('xmlns:ss', self::$ns); $this->createStyles($doc); - + foreach ($this->table as $table) { if ($table instanceof Table) { $table->createTable($doc); diff --git a/src/Excel/Table.php b/src/Excel/Table.php index d5a539c..ea28a2e 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -1,14 +1,14 @@ cells[$y] = new TableCell($value); } - - function setCellStyle($y, $name) + + function setCellStyle($y, $name) { $this->cells[$y]->style = $name; } } /** - * Таблица + * Таблица */ class Table { @@ -59,7 +59,7 @@ class Table } /** - * Записать значение в клетку с заданными координатами + * Записать значение в клетку с заданными координатами */ function setCell($x, $y, $value) { @@ -116,7 +116,7 @@ class Table * Обьединяет клетки в строке * @param $row Номер ряда * @param $cell Номер столбца - * @param $merge Количество клеток для обьединения + * @param $merge Количество клеток для обьединения */ function setCellMerge($x, $cell, $merge) { @@ -129,9 +129,9 @@ class Table /** * Устанавливает стиль для клеток ряда - * @param $row integer Номер ряда - * @param $y integer Номер столбца - * @parma $name string Имя стиля + * @param int $row Номер ряда + * @param int $y Номер столбца + * @param string $name Имя стиля */ function setCellStyle ($row, $y, $name) { @@ -141,41 +141,41 @@ class Table /** * Добавляет строку к таблице - */ + */ function addRow($index = 1, array $data = [""]) { assert(is_numeric($index) && $index > 0); $offset = $this->getRows() + 1; - + $this->setRow($offset, $index, $data); return $offset; - } + } /** * Количество строк в таблице * * @return int - */ + */ function getRows() { $keys/*: array*/ = array_keys($this->rows); return max($keys); } - + /** * Количество столбцов в строке - * - * @return int + * + * @return int */ function getRowCells(TableRow $row) { $keys/*: array*/ = array_keys($row->cells); return max($keys); - } + } /** * Разделяет таблицу на две части по вертикали - * @param $n integer Количество столбцов слева + * @param int $n Количество столбцов слева */ function splitVertical($n) { $this->_splitVertical = $n; @@ -183,7 +183,7 @@ class Table /** * Разделяет таблицу на две части по горизонтали - * @param $n integer Количество столбцов сверху + * @param int $n Количество столбцов сверху */ function splitHorizontal($n) { $this->_splitHorizontal = $n; @@ -192,9 +192,9 @@ class Table /** * Количество столбцов в таблице - * + * * @return int - */ + */ function getColumns() { return max(array_map([$this, 'getRowCells'], $this->rows)); } @@ -228,21 +228,21 @@ class Table $doc->text($value->getString()); } else if ($value instanceof Excel_Number) { $doc->writeAttribute('ss:Type', "Number"); - $doc->text($value->getString()); + $doc->text($value->getString()); } else { if (is_string($value)) { $doc->writeAttribute('ss:Type', "String"); } else { $doc->writeAttribute('ss:Type', "Number"); } - $doc->writeCdata($this->encode($value)); - } + $doc->writeCdata($this->encode($value)); + } + $doc->endElement(); $doc->endElement(); - $doc->endElement(); } - + /** - * Генерация таблицы + * Генерация таблицы */ public function createTable (XMLWriter $doc) { $doc->startElement('Worksheet'); @@ -271,19 +271,19 @@ class Table // Флаг индикатор подстановки номера столбца $setIndex = false; for ($j = 1; $j <= $columns; $j++) { - + $value = null; if (isset($nrow->cells[$j])) { $value = $nrow->cells[$j]->value; } - + if (!empty($value)) { $this->createCell($nrow->cells[$j], $doc, $j, $value, $setIndex); $setIndex = false; } else { $setIndex = true; } - } + } } $doc->endElement(); } @@ -293,7 +293,7 @@ class Table } protected function splitPane (XMLWriter $doc) { - $doc->startElement('WorksheetOptions'); + $doc->startElement('WorksheetOptions'); $doc->writeAttribute('xmlns', 'urn:schemas-microsoft-com:office:excel'); $doc->writeElement('FrozenNoSplit'); diff --git a/src/Form/Form.php b/src/Form/Form.php index 6906ee5..dd97618 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -73,6 +73,12 @@ class Form extends View { return '_form_edit'; } + /** + * Добавление конструкторя для поля формы + * @param string $name Краткое название поля + * @param class-string $class + * @return void + */ public function addFieldClass($name, $class) { $this->constructor [$name] = $class; @@ -80,6 +86,7 @@ class Form extends View { /** * Добавляет одно поле ввода на форму + * @return Field */ public function addField(array $init, $factory = null) { diff --git a/src/Path.php b/src/Path.php index 09d7e29..77bdccf 100644 --- a/src/Path.php +++ b/src/Path.php @@ -8,13 +8,13 @@ namespace ctiso; -class Path +class Path { const SEPARATOR = "/"; protected $path = array(); protected $url = array(); - protected $absolute = false; + protected $absolute = false; public function __construct($path = '') { @@ -24,7 +24,7 @@ class Path if (isset($this->url['path'])) { $path = $this->url['path']; // $path = preg_replace('/\/{2,}/', '/', $path); - $list = $this->listFromString($path); + $list = self::listFromString($path); if (isset($this->url['scheme']) && !isset($this->url['host'])) { $this->absolute = false; @@ -32,9 +32,9 @@ class Path $this->absolute = true; } - $this->path = $this->optimize($list); + $this->path = self::optimize($list); } - } + } static function factory($path) { return new Path($path); @@ -87,14 +87,14 @@ class Path * * @param string $fileName Имя файла * - * @return string + * @return string */ static function skipExtension($fileName) { assert(is_string($fileName)); $path = pathinfo($fileName); - if ($path['dirname'] == ".") { + if ($path['dirname'] === ".") { return $path['filename']; } else { return self::join($path['dirname'], $path['filename']); @@ -134,22 +134,22 @@ class Path } /** - * Преобразует относительный путь в абсолютный + * Преобразует относительный путь в абсолютный */ - public static function optimize($path) // + public static function optimize($path) // { $result = []; foreach ($path as $n) { switch ($n) { // Может быть относительным или абсолютным путем - case "": break; - case ".": break; + case "": case ".": break; case "..": - if (count($result) > 0 && $result[count($result) - 1] != '..') { - array_pop($result); break; + if (count($result) > 0 && $result[count($result) - 1] != '..') { + array_pop($result); break; } + break; default: - array_push($result, $n); + $result[] = $n; } } return $result; @@ -162,7 +162,7 @@ class Path if ($count == count($path->path)) { for ($i = 0; $i < $count; $i++) { if ($this->path[$i] != $path->path[$i]) { - return false; + return false; } } return true; @@ -170,16 +170,16 @@ class Path return false; } - public static function makeUrl($path) + public static function makeUrl($path) { $slash = (isset($path['host']) && (strlen($path['path']) > 0) && ($path['path'][0] != '/')) ? '/' : ''; - - return (isset($path['scheme']) ? $path['scheme'] . ':/' : '') - . (isset($path['host']) ? ('/' - . (isset($path['user']) ? $path['user'] . (isset($path['pass']) ? ':' . $path['pass'] : '') . '@' : '') - . $path['host'] + + return (isset($path['scheme']) ? $path['scheme'] . ':/' : '') + . (isset($path['host']) ? ('/' + . (isset($path['user']) ? $path['user'] . (isset($path['pass']) ? ':' . $path['pass'] : '') . '@' : '') + . $path['host'] . (isset($path['port']) ? ':' . $path['port'] : '')) : '') - . $slash + . $slash . $path['path'] . (isset($path['query']) ? '?' . $path['query'] : '') . (isset($path['fragment']) ? '#' . $path['fragment'] : ''); @@ -188,7 +188,7 @@ class Path /** * Преобразует путь в строку * - * @return string + * @return string */ public function __toString() { @@ -200,13 +200,13 @@ class Path /** * Проверяет является ли папка родительской для другой папки * - * @parma Path $path + * @parma Path $path * * @return boolean */ public function isParent($path/*: Path*/) { - if (isset($this->url['host']) && isset($path->url['host']) + if (isset($this->url['host']) && isset($path->url['host']) && ($this->url['host'] != $path->url['host'])) return false; $count = count($this->path); @@ -226,11 +226,11 @@ class Path $path = new Path($path1); return $path->isParent(new Path($path2)); } - + /** * Находит путь относительно текущего путя - * - * @param string $name Полный путь к файлу + * + * @param string $name Полный путь к файлу * * @return string Относительный путь к файлу */ @@ -257,10 +257,10 @@ class Path $result = []; $count = count($list_path); for ($i = 0; $i < $count; $i++) { - if (($i >= count($self_path)) || $list_path[$i] != $self_path[$i]) { - break; + if (($i >= count($self_path)) || $list_path[$i] != $self_path[$i]) { + break; } - } + } $list_count = count($list_path); for($j = $i; $j < $list_count; $j++) { array_push($result, '..'); @@ -281,7 +281,7 @@ class Path /** * Обьединяет строки в Path соединяя необходимым разделителем * fixme не обрабатывает параметры урла, решение Path::join(SITE_WWW_PATH) . '?param=pampam' - * @return string + * @return string */ static function fromJoin($_rest) { $args = func_get_args(); @@ -295,7 +295,7 @@ class Path } // При обьединении ссылок можно обьеденить path, query, fragment - $path = implode(self::SEPARATOR, self::optimize(call_user_func_array('array_merge', $result))); + $path = implode(self::SEPARATOR, self::optimize(call_user_func_array('array_merge', $result))); $parts0->url['path'] = ($parts0->isAbsolute()) ? '/' . $path : $path; return $parts0; } @@ -303,7 +303,7 @@ class Path /** * Обьединяет строки в строку пути соединяя необходимым разделителем * fixme не обрабатывает параметры урла, решение Path::join(SITE_WWW_PATH) . '?param=pampam' - * @return string + * @return string */ static function join($_rest) { @@ -324,11 +324,11 @@ class Path return ((($ch >= ord('a')) && ($ch <= ord('z'))) || (strpos('-._', $char) !== false) || (($ch >= ord('0')) && ($ch <= ord('9')))); } - // Проверка имени файла + // Проверка имени файла static function isName($name) { if (strlen(trim($name)) == 0) { return false; - } + } for ($i = 0; $i < strlen($name); $i++) { if (!self::isCharName($name[$i])) { return false; @@ -363,13 +363,13 @@ class Path } - /** - * Список файлов в директории + /** + * Список файлов в директории * - * @param array $allow массив расширений для файлов - * @param array $ignore массив имен пааок которые не нужно обрабатывать + * @param array $allow массив расширений для файлов + * @param array $ignore массив имен пааок которые не нужно обрабатывать * - * @returnarray + * @returnarray */ public function getContent($allow = null, $ignore = []) { @@ -379,12 +379,12 @@ class Path /** * Обьединяет строки в путь соединяя необходимым разделителем - * - * @param array $allow массив расширений разрешеных для файлов - * @param array $ignore массив имен пааок которые не нужно обрабатывать + * + * @param array $allow массив расширений разрешеных для файлов + * @param array $ignore массив имен пааок которые не нужно обрабатывать * * @return array - */ + */ function getContentRec($allow = null, $ignore = []) { $result = []; @@ -406,7 +406,7 @@ class Path if (! in_array($file, $ignore)) { $isDir = is_dir(Path::join($base, $file)); if ($isDir || ($allow == null) || in_array(self::getExtension($file), $allow)) { - $result[] = $file; + $result[] = $file; } } continue; @@ -418,7 +418,7 @@ class Path // При обьединении ссылок можно обьеденить path, query, fragment return $result; } - + protected static function fileListAll(&$result, $base, &$allow, &$ignore) { $files = self::fileList($base, $allow, $ignore); @@ -453,11 +453,11 @@ class Path /** * Обновить относительную ссылку при переносе файла - * + * * @param string $relativePath - относительная ссылка до переноса * @param string $srcFile - абсолютный путь к папке содержащей файл со ссылкой до переноса * @param string $dstFile - абсолютный путь к папке содержащей файл со ссылкой после переноса - * + * * @return string */ static function updateRelativePathOnFileMove($relativePath, $srcFile, $dstFile) { @@ -467,12 +467,12 @@ class Path /** * Обновить относительную ссылку в файле при переносе папки - * + * * @param string $relativePath относительная ссылка до переноса * @param string $fileDir абсолютный путь к директории файла содержащего ссылку до переноса * @param string $srcDir абсолютный путь к переносимой директории до переноса * @param string $dstDir абсолютный путь к переносимой директории после переноса - * + * * @return string */ static function updateRelativePathOnDirectoryMove($relativePath, $fileDir, $srcDir, $dstDir) { diff --git a/src/Validator/Rule/Email.php b/src/Validator/Rule/Email.php index 49ad808..22c1287 100644 --- a/src/Validator/Rule/Email.php +++ b/src/Validator/Rule/Email.php @@ -10,20 +10,14 @@ use ctiso\Validator\Rule\AbstractRule, class Email extends AbstractRule { public function getErrorMsg() - { + { return "Неверный формат электронной почты"; } public function isValid(Collection $container, $status = null) { - $user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\|\{\}~\']+'; - $doIsValid = '(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]\.?)+'; - $ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}'; - $ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}'; - $emails = explode(",", $container->get($this->field)); foreach ($emails as $email) { -// if (! preg_match("/^$user@($doIsValid|(\[($ipv4|$ipv6)\]))$/", $email)) return false; if (! filter_var($email, FILTER_VALIDATE_EMAIL)) return false; } diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 465c679..8c08cbe 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -12,24 +12,29 @@ use Exception, class Validator { - protected $chain = array(); // Массив правил - protected $errorMsg = array(); // Массив ошибок - protected $type = array( - 'date' => 'ctiso\\Validator\\Rule\\Date', - 'email' => 'ctiso\\Validator\\Rule\\Email', - 'emaillist'=> 'ctiso\\Validator\\Rule\\EmailList', - 'match' => 'ctiso\\Validator\\Rule\\MatchRule', - 'time' => 'ctiso\\Validator\\Rule\\Time', - 'alpha' => 'ctiso\\Validator\\Rule\\Alpha', - 'require' => 'ctiso\\Validator\\Rule\\Notnull', - 'numeric' => 'ctiso\\Validator\\Rule\\Numeric', - 'unique' => 'ctiso\\Validator\\Rule\\Unique', - 'filename' => 'ctiso\\Validator\\Rule\\FileName', - 'count' => 'ctiso\\Validator\\Rule\\Count', - 'isfile' => 'ctiso\\Validator\\Rule\\IsFile', - 'code' => 'ctiso\\Validator\\Rule\\Code', - 'reg' => 'ctiso\\Validator\\Rule\\PregMatch', - ); + protected $chain = []; // Массив правил + protected $errorMsg = []; // Массив ошибок + + /** + * Поля по умолчанию + * @var array> + */ + protected $type = [ + 'date' => Rule\Date::class, + 'email' => Rule\Email::class, + 'emaillist'=> Rule\EmailList::class, + 'match' => Rule\MatchRule::class, + 'time' => Rule\Time::class, + 'alpha' => Rule\Alpha::class, + 'require' => Rule\Notnull::class, + 'numeric' => Rule\Numeric::class, + 'unique' => Rule\Unique::class, + 'filename' => Rule\FileName::class, + 'count' => Rule\Count::class, + 'isfile' => Rule\IsFile::class, + 'code' => Rule\Code::class, + 'reg' => Rule\PregMatch::class, + ]; function __construct($rules = []) { $this->addRuleList($rules); @@ -98,13 +103,17 @@ class Validator return false; } + function reset() { + $this->errorMsg = []; + } + public function validate(Collection $container, $rule = null, $status = null) { $fields = []; if ($rule) { $this->chain = $rule; } - $this->errorMsg = []; + // $this->errorMsg = []; foreach ($this->chain as $rule) { //echo $key; if (!in_array($rule->field, $fields) && !$this->skip($rule, $container) && !$rule->isValid($container, $status)) { From 2aa77efd941421a4c06e5da33dc24ee3e3ebffc9 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 22 Jan 2025 11:06:30 +0300 Subject: [PATCH 085/138] =?UTF-8?q?fix:=20=D0=9E=D1=88=D0=B8=D0=B1=D0=BA?= =?UTF-8?q?=D0=B0=20=D0=BF=D1=80=D0=B8=20=D0=BE=D0=BF=D1=82=D0=B8=D0=BC?= =?UTF-8?q?=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BF=D1=83=D1=82=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Path.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Path.php b/src/Path.php index 77bdccf..e9d3c6b 100644 --- a/src/Path.php +++ b/src/Path.php @@ -147,7 +147,6 @@ class Path if (count($result) > 0 && $result[count($result) - 1] != '..') { array_pop($result); break; } - break; default: $result[] = $n; } From 2f8c788664e83deb04715c8bfc0344b1f59c720a Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 27 Mar 2025 15:37:31 +0300 Subject: [PATCH 086/138] =?UTF-8?q?feat:=20=D0=9F=D0=BE=D0=BB=D1=83=D1=87?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D1=81=D0=BF=D0=B8=D1=81=D0=BA=D0=B0?= =?UTF-8?q?=20=D1=81=D0=B2=D0=BE=D0=B9=D1=81=D1=82=20=D0=BA=D0=BE=D0=BC?= =?UTF-8?q?=D0=BF=D0=BE=D0=BD=D0=B5=D0=BD=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index e0dd498..c0edb7c 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -232,6 +232,13 @@ class Component $view->component_title = $settings['title']; } + public function getFields($options = null) { + $form = new Form(); + $form->addFieldList($this->getInfo()['parameter'], $options); + + return $form->field; + } + /** * Обьеденить с ComponentFactory */ From 6ef65fc8261d37b8b53f7c4c3268b9031252290b Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 3 Apr 2025 19:59:56 +0300 Subject: [PATCH 087/138] =?UTF-8?q?refactor:=20Form=20=D0=B1=D0=BE=D0=BB?= =?UTF-8?q?=D1=8C=D1=88=D0=B5=20=D0=BD=D0=B5=20=D0=BD=D0=B0=D1=81=D0=BB?= =?UTF-8?q?=D0=B5=D0=B4=D1=83=D0=B5=D1=82=20View?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Form/Form.php | 18 ++++-------------- src/View/Composite.php | 5 ----- src/View/Pages.php | 7 +++---- src/View/Plain.php | 9 +++------ 4 files changed, 10 insertions(+), 29 deletions(-) diff --git a/src/Form/Form.php b/src/Form/Form.php index dd97618..b634115 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -15,7 +15,7 @@ use ctiso\Form\Field, /** * Форма для ввода */ -class Form extends View { +class Form { public $field = array(); //Поля формы public $fieldsets = array(); //Группы полей (fieldset). Некоторые поля могут не принадлежать никаким группам @@ -28,7 +28,7 @@ class Form extends View { public $_title = array(); public $alias = array(); - public $constructor = array(); + private $constructor = array(); /** * Строим форму по ее структуре. Каждому типу соответствует определенный класс. @@ -175,7 +175,7 @@ class Form extends View { { foreach ($schema as $key => $conv) { list($value, $type) = $conv; - $this->field [$key]->setValue(call_user_func(['ctiso\\Primitive', 'from_' . $type], $data->$value)); + $this->field [$key]->setValue(call_user_func([\ctiso\Primitive::class, 'from_' . $type], $data->$value)); } } @@ -183,17 +183,7 @@ class Form extends View { { $this->field[$name]->setValue($value); } - - public function getSchema() { - return [ - 'field' => $this->field, - 'fieldset' => $this->fieldsets, - 'method' => $this->method, - 'action' => $this->action, - 'header' => $this->header - ]; - } - + function execute() { return $this; diff --git a/src/View/Composite.php b/src/View/Composite.php index aa2890a..6edba92 100644 --- a/src/View/Composite.php +++ b/src/View/Composite.php @@ -1,13 +1,8 @@ Date: Tue, 13 May 2025 17:26:49 +0300 Subject: [PATCH 088/138] =?UTF-8?q?chore:=20=D0=A2=D0=B8=D0=BF=D1=8B=20?= =?UTF-8?q?=D0=B4=D0=BB=D1=8F=20=D0=BF=D0=B0=D1=80=D0=B0=D0=BC=D0=B5=D1=82?= =?UTF-8?q?=D1=80=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 5 +-- src/Controller/Component.php | 4 ++ src/Validator/Rule/Code.php | 35 +++++++++-------- src/View/Composite.php | 2 +- src/View/ListView.php | 16 -------- src/View/View.php | 73 ++++++++++++------------------------ src/ZipFile.php | 15 ++++---- 7 files changed, 55 insertions(+), 95 deletions(-) delete mode 100644 src/View/ListView.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index d10d2eb..4393ab7 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -119,7 +119,8 @@ class Action if(file_exists($template)) { break; } } - $tpl/*: Composite*/ = new $viewClass($template); + /** @var \ctiso\View\Composite */ + $tpl = new $viewClass($template); $tpl->config = $this->config; $stylePath = Path::join($webPath, "assets", "css"); @@ -140,8 +141,6 @@ class Action 'template' => $list ]); - $tpl->loadImports(Path::skipExtension($template) . ".import"); - $this->addSuggest($tpl, $name); return $tpl; } diff --git a/src/Controller/Component.php b/src/Controller/Component.php index c0edb7c..6beb987 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -57,6 +57,10 @@ class Component public $module; public $item_module; + + /** + * @var \App\Controller\Site + */ public $site; function before() { diff --git a/src/Validator/Rule/Code.php b/src/Validator/Rule/Code.php index 4ae1b48..1102766 100644 --- a/src/Validator/Rule/Code.php +++ b/src/Validator/Rule/Code.php @@ -9,12 +9,11 @@ use ctiso\Validator\Rule\AbstractRule, class Code extends AbstractRule { - public function getErrorMsg() - { + public function getErrorMsg(): string { return "Неправильно указан персональный код"; } - function checkCode($code) { + function checkCode($code): bool { foreach($code as $c) { if (empty($c)) { return false; @@ -23,7 +22,7 @@ class Code extends AbstractRule return true; } - public function isValid(Collection $container, $status = null) + public function isValid(Collection $container, $status = null): bool { if ($status == 'update') return true; $name = $this->field; @@ -32,27 +31,27 @@ class Code extends AbstractRule $count = count($_POST[$name . '_code_genre']); for($n = 0; $n < $count; $n++) { $code = [ - $_POST[$name . '_code_genre'][$n], - $_POST[$name . '_code_f'][$n], - $_POST[$name . '_code_i'][$n], - $_POST[$name . '_code_o'][$n], - $_POST[$name . '_code_year'][$n], - $_POST[$name . '_code_month'][$n], - $_POST[$name . '_code_day'][$n] + $_POST[$name . '_code_genre'][$n], + $_POST[$name . '_code_f'][$n], + $_POST[$name . '_code_i'][$n], + $_POST[$name . '_code_o'][$n], + $_POST[$name . '_code_year'][$n], + $_POST[$name . '_code_month'][$n], + $_POST[$name . '_code_day'][$n] ]; if (!$this->checkCode($code)) { return false; } } return true; - } else { + } else { $code = [ - $_POST[$name . '_code_genre'], - $_POST[$name . '_code_f'], - $_POST[$name . '_code_i'], - $_POST[$name . '_code_o'], - $_POST[$name . '_code_year'], - $_POST[$name . '_code_month'], + $_POST[$name . '_code_genre'], + $_POST[$name . '_code_f'], + $_POST[$name . '_code_i'], + $_POST[$name . '_code_o'], + $_POST[$name . '_code_year'], + $_POST[$name . '_code_month'], $_POST[$name . '_code_day'] ]; diff --git a/src/View/Composite.php b/src/View/Composite.php index 6edba92..046e18e 100644 --- a/src/View/Composite.php +++ b/src/View/Composite.php @@ -35,7 +35,7 @@ class Composite extends View function execute() { - parent::execute(); + $this->processChild(); return $this->tal->execute(); } diff --git a/src/View/ListView.php b/src/View/ListView.php deleted file mode 100644 index 3acd298..0000000 --- a/src/View/ListView.php +++ /dev/null @@ -1,16 +0,0 @@ -_section as $key => $value) { - $result [] = $value->execute(); - } - return $result; - } -} diff --git a/src/View/View.php b/src/View/View.php index 141e541..036cc72 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -21,7 +21,7 @@ class View extends \stdClass public $suggestions; //подсказки - public $alias = array(); + public $alias = []; public $codeGenerator = null; public $parent_view = null; @@ -34,7 +34,7 @@ class View extends \stdClass * @param string $section переменная шаблона * @param View|string $view вложенный шаблон */ - public function setView($section, $view/*: View|string*/) + public function setView($section, $view) { $this->_section [$section] = $view; if (is_object($view)) { @@ -42,23 +42,18 @@ class View extends \stdClass } } - public function assignValues($values) + public function assignValues($values): void { $this->_values = $values; $this->_values["suggestions"] = $this->suggestions; } - public function setGlobal($name, $args) - { - $this->addScriptRaw("var " . $name . " = " . json_encode($args) . ";\n", false); - } - /** * Добавляет скипт к текущему шаблону - * - * @param string $name путь к скрипту + * + * @param string $name путь к скрипту */ - public function addScript($name) + public function addScript($name): void { $output = $this->resolveName($this->alias, $name . '?' . http_build_query($this->prefix)); $this->_script [] = $output; @@ -69,7 +64,7 @@ class View extends \stdClass * * @param string $name строка javascript кода */ - public function addScriptRaw($name, $startup = false) + public function addScriptRaw($name, $startup = false): void { if ($startup) { $this->_startup [] = $name; @@ -84,16 +79,16 @@ class View extends \stdClass /** * Добавляет стили к текущему шаблону - * + * * @param string $name путь к стилю */ public function addStyleSheet($name) { - $output = $this->resolveName($this->alias, $name . '?' . http_build_query($this->prefix)); - $this->_stylesheet [] = $output; + $output = $this->resolveName($this->alias, $name . '?' . http_build_query($this->prefix)); + $this->_stylesheet [] = $output; } - /** + /** * Рекурсивно извлекает из значение свойства обьекта * * @param string $list Имя свойства @@ -117,11 +112,11 @@ class View extends \stdClass /*abstract*/ public function set($key, $value) { } - + /** * Обработка всех вложенных шаблонов */ - public function execute() + public function processChild(): void { foreach ($this->_section as $key => $value) { $this->set($key, (is_object($value)) ? $value->execute() : $value); // ? @@ -133,28 +128,28 @@ class View extends \stdClass * * @param string $title */ - public function setTitle($title) + public function setTitle($title): void { - $this->_title = $title; + $this->_title = $title; } - protected function isNotNull($title) + protected function isNotNull($title): bool { - return $title !== null; + return $title !== null; } - function setAlias($alias) + function setAlias($alias): void { $this->alias = $alias; } - function addAlias($name, $path) + function addAlias($name, $path): void { $this->alias[$name] = $path; $this->set($name, $path); } - function find_file($pathlist, $file) { + function findFile($pathlist, string $file): string { foreach($pathlist as $key => $www) { if (file_exists($key . '/' . $file)) { @@ -162,16 +157,16 @@ class View extends \stdClass } } throw new Exception("file not found: $file"); - } + } // FIXME: Префикс, конфликтует с протоколом function resolveName($alias, $file) { list($type, $filename) = explode(":", $file, 2); - - // Сделать поиск а не просто замену папки при совпадении имени + + // Сделать поиск а не просто замену папки при совпадении имени if (isset($alias[$type])) { if (is_array($alias[$type])) { - $output = $this->find_file($alias[$type], $filename); + $output = $this->findFile($alias[$type], $filename); } else { $output = $alias[$type] . '/' . $filename; } @@ -180,26 +175,6 @@ class View extends \stdClass return $file; } - function loadImports($importFile) - { - $types = [ - 'js' => [$this, 'addScript'], - 'css' => [$this, 'addStyleSheet'] - ]; - // Подключение стилей и скриптов - if (file_exists($importFile)) { - $files = file($importFile); - foreach ($files as $file) { - // Получить расширение вместо strpos - $file = trim($file); - if (!empty($file)) { - $ext = pathinfo($file, PATHINFO_EXTENSION); - call_user_func($types[$ext], $file); - } - } - } - } - public function resolveAllNames($alias, $list) { $result = []; foreach($list as $item) { diff --git a/src/ZipFile.php b/src/ZipFile.php index e858432..99ae70b 100644 --- a/src/ZipFile.php +++ b/src/ZipFile.php @@ -8,17 +8,18 @@ use ZipArchive; class ZipFile extends ZipArchive { - private $ignore = array('.', '..'); + /** + * @var list + */ + private $ignore = ['.', '..']; - public function addIgnore($name) + public function addIgnore(string $name): void { $this->ignore [] = $name; } - private function addDirDo($location, $name) + private function addDirDo(string $location, string $name): void { - assert(is_string($location) && is_string($name)); - $name .= '/'; $location .= '/'; $file = null; @@ -34,10 +35,8 @@ class ZipFile extends ZipArchive } } - public function addDir($location, $name) + public function addDir(string $location, string $name): void { - assert(is_string($location) && is_string($name)); - $this->addEmptyDir($name); $this->addDirDo($location, $name); } From 5474090f852f484b5ab8d15da950055a1ac5def5 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 23 May 2025 13:35:46 +0300 Subject: [PATCH 089/138] =?UTF-8?q?fix:=20=D0=98=D0=BD=D1=82=D0=B5=D1=80?= =?UTF-8?q?=D1=84=D0=B5=D0=B9=D1=81=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 98 +++++++++++++++++++++----------- src/Controller/SiteInterface.php | 11 +++- src/Form/Form.php | 12 ++-- src/Form/OptionsFactory.php | 7 +++ src/Form/Select.php | 6 +- 5 files changed, 90 insertions(+), 44 deletions(-) create mode 100644 src/Form/OptionsFactory.php diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 6beb987..993521b 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -1,20 +1,20 @@ get('site', 'template') : 'modern'); } @@ -184,7 +188,12 @@ class Component return $model; } - public function options($key, $val, $res/*: PDOStatement*/) { + /** + * @param string $key + * @param string $val + * @param $res + */ + public function options(string $key, string $val, $res) { $result = []; while($res->next()) { $result[] = ['value' => $res->getString($key), 'name' => $res->getString($val)]; @@ -192,7 +201,7 @@ class Component return $result; } - public function optionsPair($list, $selected = false) { + public function optionsPair(array $list, $selected = false) { $result = []; foreach ($list as $key => $value) { $result [] = ['value' => $key, 'name' => $value, 'selected' => $key == $selected]; @@ -200,7 +209,13 @@ class Component return $result; } - function findFile($pathList, $name) { + /** + * Найти файл по пути + * @param string[] $pathList + * @param string $name + * @return string|null + */ + function findFile(array $pathList, string $name) { foreach($pathList as $item) { $filename = Path::join($item, $name); if (file_exists($filename)) { @@ -223,6 +238,8 @@ class Component /** * Генерация интерфейса для выбора галлереи фотографии + * @param Composite $view + * @param \ctiso\Form\OptionsFactory $options */ public function setParameters(Composite $view, $options = null) { @@ -245,10 +262,12 @@ class Component /** * Обьеденить с ComponentFactory + * @param string $expression + * @param SiteInterface $site + * @return Component */ - static function loadComponent($expression, $site/*: SiteInterface*/) + static function loadComponent(string $expression, $site) { - $expression = htmlspecialchars_decode($expression); $offset = strpos($expression, '?'); $url = parse_url($expression); @@ -261,16 +280,18 @@ class Component parse_str($query, $arguments); } $name = $path; - $config = $site->config; + $config = $site->getConfig(); $filename = ucfirst($name); $path = Path::join ($config->get('site', 'components'), $name, $filename . '.php'); $className = implode("\\", ['Components', ucfirst($name), $filename]); - $component/*: Component*/ = null; + /** + * @var ?Component $component + */ + $component = null; if (file_exists($path)) { - // require_once ($path); $component = new $className(); $component->viewPath = [$config->get('site', 'components') . '/' . $name . '/']; @@ -279,7 +300,7 @@ class Component } else { $component = new $className(); - $template = $component->getTemplateName($site->config); + $template = $component->getTemplateName($site->getConfig()); $component->viewPath = [ // Сначало ищем локально @@ -308,7 +329,7 @@ class Component $db = $site->getDatabase(); $component->db = $db; - $component->config = $site->config; + $component->config = $site->getConfig(); $component->site = $site; $stmt = $db->prepareStatement("SELECT * FROM component WHERE code = ?"); @@ -344,7 +365,7 @@ class Component $editor = $component->getEditUrl(); if ($editor) { - $site->componentsConfig[] = $editor; + $site->addComponentConfig($editor); } return $component; @@ -354,12 +375,15 @@ class Component return null; } - function raw_query($request/*: ComponentRequest*/) + /** + * @param ComponentRequest $request + */ + function raw_query($request) { $arr = $request->r->export('get'); $param = []; - $parameter/*: Collection*/ = $this->parameter; + $parameter = $this->parameter; foreach($parameter->export() as $key => $value) { $param[$key] = $value; } @@ -377,7 +401,10 @@ class Component } - function query($request/*: ComponentRequest*/, $list) + /** + * @param ComponentRequest $request + */ + function query($request, $list) { $arr = $request->r->export('get'); @@ -393,6 +420,9 @@ class Component $this->site->addRequireJsPath($name, $path, $shim); } - function actionIndex($request/*: ComponentRequest*/) { + /** + * @param ComponentRequest $request + */ + function actionIndex($request) { } } diff --git a/src/Controller/SiteInterface.php b/src/Controller/SiteInterface.php index 1125601..e5abe67 100644 --- a/src/Controller/SiteInterface.php +++ b/src/Controller/SiteInterface.php @@ -4,9 +4,14 @@ namespace ctiso\Controller; interface SiteInterface { function getResource(); - function loadComponent($expression); function getDatabase(); function getConfig(); - function setComponentConfig($config); - function addRequireJsPath($name, $path, $schim = null); + function getTheme(); + function addComponentConfig($config); + function addRequireJsPath(string $name, string $path, ?array $shim = null); + function addStyleSheet(string $url); + + function loadComponent(string $expression); + function findTemplate(string $name); + function replaceImg(string $src, int $width, int $height); } diff --git a/src/Form/Form.php b/src/Form/Form.php index b634115..30450d8 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -16,8 +16,8 @@ use ctiso\Form\Field, * Форма для ввода */ class Form { - public $field = array(); //Поля формы - public $fieldsets = array(); //Группы полей (fieldset). Некоторые поля могут не принадлежать никаким группам + public $field = []; //Поля формы + public $fieldsets = []; //Группы полей (fieldset). Некоторые поля могут не принадлежать никаким группам public $action = ""; public $method = 'post'; @@ -26,9 +26,9 @@ class Form { protected $replace; protected $before; - public $_title = array(); - public $alias = array(); - private $constructor = array(); + public $_title = []; + public $alias = []; + private $constructor = []; /** * Строим форму по ее структуре. Каждому типу соответствует определенный класс. @@ -183,7 +183,7 @@ class Form { { $this->field[$name]->setValue($value); } - + function execute() { return $this; diff --git a/src/Form/OptionsFactory.php b/src/Form/OptionsFactory.php new file mode 100644 index 0000000..8921b56 --- /dev/null +++ b/src/Form/OptionsFactory.php @@ -0,0 +1,7 @@ + Date: Fri, 1 Aug 2025 12:41:09 +0300 Subject: [PATCH 090/138] =?UTF-8?q?fix:=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4=20=D0=BA=20?= =?UTF-8?q?=D0=B8=D0=BD=D1=82=D0=B5=D1=80=D1=84=D0=B5=D0=B9=D1=81=D1=83=20?= =?UTF-8?q?=D1=81=D0=B0=D0=B9=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/SiteInterface.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Controller/SiteInterface.php b/src/Controller/SiteInterface.php index e5abe67..d176e34 100644 --- a/src/Controller/SiteInterface.php +++ b/src/Controller/SiteInterface.php @@ -14,4 +14,5 @@ interface SiteInterface { function loadComponent(string $expression); function findTemplate(string $name); function replaceImg(string $src, int $width, int $height); + function updatePageTime(int $time); } From 170c30f82141d604a0f3e5aa284348ae016fc97d Mon Sep 17 00:00:00 2001 From: Wizard Date: Wed, 24 Sep 2025 13:04:25 +0300 Subject: [PATCH 091/138] fix: type decl --- src/HttpRequest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/HttpRequest.php b/src/HttpRequest.php index c8c0f7c..bc34252 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -55,7 +55,7 @@ class HttpRequest extends Collection return parent::get('data')->get($key, $default); } - function session(Session $value = null) + function session(?Session $value = null) { if ($value) { $this->_session = $value; From df5fd1ca6a108e3c8e0b52f24e4ca4424ed27c59 Mon Sep 17 00:00:00 2001 From: Wizard Date: Wed, 24 Sep 2025 16:46:59 +0300 Subject: [PATCH 092/138] =?UTF-8?q?chore:=20=D0=9E=D1=88=D0=B8=D0=B1=D0=BA?= =?UTF-8?q?=D0=B0=20deprecated=20implicitly=20nullable=20=D0=B2=20phpstan?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Model/Factory.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Model/Factory.php b/src/Model/Factory.php index ab560e3..34f589b 100644 --- a/src/Model/Factory.php +++ b/src/Model/Factory.php @@ -11,7 +11,7 @@ class Factory public $config; public $user; - public function __construct(Database $db, Registry $config = null, User $user = null) + public function __construct(Database $db, ?Registry $config = null, ?User $user = null) { $this->db = $db; $this->config = $config; From dd74a978949d2bacd9faed3366321ede20184ac5 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 1 Oct 2025 12:37:39 +0300 Subject: [PATCH 093/138] =?UTF-8?q?fix:=20=D0=9E=D0=BF=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=D0=B5=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D1=82=D0=B8=D0=BF=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Collection.php | 2 +- src/Controller/Action.php | 14 ++- src/Controller/Request.php | 5 +- src/Controller/Service.php | 14 ++- src/Database.php | 10 +- src/Database/JsonInstall.php | 4 +- src/Database/Manager.php | 11 ++- src/Database/Statement.php | 8 +- src/Database/StatementIterator.php | 5 +- src/Excel/Table.php | 51 ++++++----- src/Filter/ActionAccess.php | 10 +- src/Filter/ActionLogger.php | 9 +- src/Filter/Filter.php | 9 +- src/Form/Field.php | 15 +-- src/Functions.php | 136 +++++++++++++++------------- src/HttpRequest.php | 4 +- src/Layout/Manager.php | 22 +++-- src/MailAlt.php | 21 +++-- src/Path.php | 9 +- src/Setup.php | 64 +++++++------ src/Tales.php | 10 +- src/Tools/SQLStatementExtractor.php | 52 +++++------ src/Tools/TemplateImage.php | 46 +++++----- src/Url.php | 5 +- src/Validator/Validator.php | 8 +- src/View/Pages.php | 24 ++--- src/View/Top.php | 13 +-- src/View/View.php | 2 +- 28 files changed, 334 insertions(+), 249 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index 2f7cea3..04e02ee 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -41,7 +41,7 @@ class Collection implements \ArrayAccess * * @return void */ - public function set($key/*: string*/, $value/*: any*/) + public function set($key, $value) { $this->data[$key] = $value; } diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 4393ab7..73ef7aa 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -35,6 +35,7 @@ class Action public Database $db; // Фильтры + /** @var ?ActionAccess */ public $access = null; // Обьект хранит параметры доступа public $logger = null; // Обьект для ведения лога @@ -42,8 +43,10 @@ class Action private $helpers = array(); // Помошники для действий public $part = null; // Параметры для ссылки - public $config/*: Registry*/; // Ссылка на настройки - public $user/*: User*/; // Обьект пользователя + /** @var \ctiso\Registry */ + public $config; // Ссылка на настройки + /** @var \ctiso\Role\User */ + public $user; // Обьект пользователя // Для Widgets public $view = null; @@ -214,7 +217,7 @@ class Action */ public function nUrl($actionName, array $param = []) { - $access/*: ActionAccess*/ = $this->access; + $access = $this->access; $url = new Url(); //print_r([$name, $param]); @@ -337,7 +340,8 @@ class Action if ($view instanceof View) { $this->view->assignValues($this->ctrlValues); - $node/*: Composite*/ = null; + /** @var ?Composite $node */ + $node = null; foreach ($this->childNodes as $name => $node) { $node->make($this); $this->view->setView($name, $node->view); @@ -376,7 +380,7 @@ class Action $this->_getActionPath()->getPath($this, ($action) ? $action : $request->getAction()); } - function redirect($action/*: string*/) { + function redirect(string $action) { header('location: ' . $action); exit(); } diff --git a/src/Controller/Request.php b/src/Controller/Request.php index fb2d950..6bfd653 100644 --- a/src/Controller/Request.php +++ b/src/Controller/Request.php @@ -7,7 +7,10 @@ class Request { public $r; public $id; - function __construct($request/*: HttpRequest*/, $id) { + /** + * @param HttpRequest $request + */ + function __construct($request, $id) { $this->r = $request; $this->id = $id; } diff --git a/src/Controller/Service.php b/src/Controller/Service.php index 331475d..b12c807 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -14,11 +14,12 @@ class Service { public $viewPath = []; public $webPath = []; - public $config/*: Registry*/; + /** @var Registry */ + public $config; public $template; public $templatePath; public $COMPONENTS_WEB; - + public $db; public function getTemplatePath($name) @@ -53,7 +54,12 @@ class Service return $model; } - public function options($key, $val, $res/*: PDOStatement*/) { + /** + * @param string $key + * @param string $val + * @param PDOStatement $res + */ + public function options($key, $val, $res) { $result = []; while($res->next()) { $result[] = ['value' => $res->getInt($key), 'name' => $res->getString($val)]; @@ -68,7 +74,7 @@ class Service } return $result; } - + function getInfo() { $filename = Path::join($this->viewPath[0], 'install.json'); if (file_exists($filename)) { diff --git a/src/Database.php b/src/Database.php index c967d6d..5206c08 100644 --- a/src/Database.php +++ b/src/Database.php @@ -31,7 +31,8 @@ namespace ctiso { function prepare(string $sql, array $options = []): PDOStatement|false { - $result/*: PDOStatement*/ = parent::prepare($sql, $options); + /** @var PDOStatement $result */ + $result = parent::prepare($sql, $options); return $result; } @@ -49,10 +50,11 @@ namespace ctiso { static function getConnection(array $dsn) { + /** @var ?Database */ $connection = null; if ($dsn['phptype'] == 'pgsql' || $dsn['phptype'] == 'mysql') { $port = (isset($dsn['port'])) ? "port={$dsn['port']};" : ""; - $connection/*: Database*/ = new self("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']); + $connection = new self("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']); if ($dsn['phptype'] == 'pgsql') { $connection->query('SET client_encoding="UTF-8"'); } @@ -64,9 +66,9 @@ namespace ctiso { $connection = new self("{$dsn['phptype']}:"); $connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1); } elseif ($dsn['phptype'] == 'sqlite') { - $connection/*: Database*/ = new self("{$dsn['phptype']}:{$dsn['database']}"); + $connection = new self("{$dsn['phptype']}:{$dsn['database']}"); $connection->setAttribute(PDO::ATTR_TIMEOUT, 5); - $mode = defined('SQLITE_JOURNAL_MODE') ? SQLITE_JOURNAL_MODE : 'WAL'; + $mode = defined('SQLITE_JOURNAL_MODE') ? \SQLITE_JOURNAL_MODE : 'WAL'; $connection->query("PRAGMA journal_mode=$mode"); $connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1); } diff --git a/src/Database/JsonInstall.php b/src/Database/JsonInstall.php index 3e6eef1..e6f384f 100644 --- a/src/Database/JsonInstall.php +++ b/src/Database/JsonInstall.php @@ -42,8 +42,8 @@ class JsonInstall { return $missingTables; } - //Создать таблицы - function initDataBase($initActions/*: array*/, $dbinit_path) { + // Создать таблицы + function initDataBase(array $initActions, $dbinit_path) { $pg = $this->db_manager->db->isPostgres(); if (!$pg) { $refs = []; diff --git a/src/Database/Manager.php b/src/Database/Manager.php index 1629a92..ee58fbf 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -9,14 +9,15 @@ use Exception; class Manager { - public $db/*: Database*/; + /** @var Database */ + public $db; public function __construct(Database $db) { $this->db = $db; } - public function executeAction($action/*: array*/, $db_file = "") + public function executeAction(array $action, $db_file = "") { switch($action["type"]) { case "dropTable": @@ -117,7 +118,7 @@ class Manager return; } - $data/*: array*/ = $this->dumpTable($table); + $data = $this->dumpTable($table); $this->db->query("ALTER TABLE ".$table." RENAME TO ".$tmp_table.";"); $table_info[$new_name] = $table_info[$old_name]; @@ -169,7 +170,7 @@ class Manager $this->db->query($q); } - public function getConstraintDef($c/*: array*/) + public function getConstraintDef(array $c) { if ($c['type'] == 'unique') { return "UNIQUE(" . implode(", ", $c['fields']) . ")"; @@ -209,7 +210,7 @@ class Manager foreach ($table_fields as $name => $value) { $type = strtolower($value['type']); if ($type == "boolean") { - foreach ($data as &$row) { + foreach ($data as &$row) { if (isset($row[$name])) { $row[$name] = boolval($row[$name]); } diff --git a/src/Database/Statement.php b/src/Database/Statement.php index b0f6ebd..387221f 100644 --- a/src/Database/Statement.php +++ b/src/Database/Statement.php @@ -16,7 +16,11 @@ class Statement protected $conn; protected $query; - function __construct($query, $conn/*: Database*/) { + /** + * @param string $query + * @param Database $conn + */ + function __construct($query, $conn) { $this->query = $query; $this->conn = $conn; } @@ -45,7 +49,7 @@ class Statement if ($this->limit) { $this->query .= " LIMIT {$this->limit} OFFSET {$this->offset}"; } - $stmt/*: PDOStatement*/ = $this->conn->prepare($this->query); + $stmt = $this->conn->prepare($this->query); foreach ($this->binds as $bind) { list($n, $value, $type) = $bind; $stmt->bindValue($n, $value, (int) $type); diff --git a/src/Database/StatementIterator.php b/src/Database/StatementIterator.php index f767408..70413fe 100644 --- a/src/Database/StatementIterator.php +++ b/src/Database/StatementIterator.php @@ -10,7 +10,10 @@ class StatementIterator implements \Iterator private $pos = 0; private $row_count; - public function __construct($rs/*: PDOStatement*/) { + /** + * @param PDOStatement $rs + */ + public function __construct($rs) { $this->result = $rs; $this->row_count = $rs->getRecordCount(); } diff --git a/src/Excel/Table.php b/src/Excel/Table.php index ea28a2e..ac8eba2 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -61,25 +61,26 @@ class Table /** * Записать значение в клетку с заданными координатами */ - function setCell($x, $y, $value) + function setCell(int $x, int $y, $value) { - assert(is_numeric($x) && $x > 0); - assert(is_numeric($y) && $y > 0); + assert($x > 0); + assert($y > 0); if(! isset($this->rows[$x])) { $this->rows[$x] = new TableRow(); } - $row/*: TableRow*/ = $this->rows[$x]; + /** @var TableRow $row */ + $row = $this->rows[$x]; $row->setCell($y, $value); } /** * Заполняет ряд начиная с указанного столбца значениями из массива */ - function setRow($row, $index, array $data) + function setRow(int $row, int $index, array $data) { - assert(is_numeric($index) && $index > 0); - assert(is_numeric($row) && $row > 0); + assert($index > 0); + assert($row > 0); reset($data); for ($i = $index; $i < $index + count($data); $i++) { @@ -90,20 +91,20 @@ class Table /** * Устанавливает высоту ряда - * @param $row integer Номер ряда - * @parma $value real Высота ряда + * @param int $row Номер ряда + * @param number $value Высота ряда */ - function setRowHeight ($row, $value) + function setRowHeight (int $row, $value) { - assert(is_numeric($row) && $row > 0); + assert($row > 0); $this->rows[$row]->height = $value; } /** * Устанавливает стиль ряда - * @param $row integer Номер ряда - * @parma $name string Имя стиля + * @param int $row Номер ряда + * @param string $name Имя стиля */ function setRowStyle ($row, $name) { @@ -118,12 +119,13 @@ class Table * @param $cell Номер столбца * @param $merge Количество клеток для обьединения */ - function setCellMerge($x, $cell, $merge) + function setCellMerge(int $x, int $cell, $merge) { - assert(is_numeric($x) && $x > 0); - assert(is_numeric($cell) && $cell > 0); + assert($x > 0); + assert($cell > 0); - $row/*: TableRow*/ = $this->rows[$x]; + /** @var TableRow $row */ + $row = $this->rows[$x]; $row->cells[$cell]->merge = $merge; } @@ -135,14 +137,15 @@ class Table */ function setCellStyle ($row, $y, $name) { - if (isset($this->rows[$row])) + if (isset($this->rows[$row])) { $this->rows[$row]->setCellStyle($y, $name); + } } /** * Добавляет строку к таблице */ - function addRow($index = 1, array $data = [""]) + function addRow(int $index = 1, array $data = [""]) { assert(is_numeric($index) && $index > 0); $offset = $this->getRows() + 1; @@ -158,7 +161,7 @@ class Table */ function getRows() { - $keys/*: array*/ = array_keys($this->rows); + $keys = array_keys($this->rows); return max($keys); } @@ -169,7 +172,7 @@ class Table */ function getRowCells(TableRow $row) { - $keys/*: array*/ = array_keys($row->cells); + $keys = array_keys($row->cells); return max($keys); } @@ -207,7 +210,7 @@ class Table /** * Генерация клетки таблицы (Переработать) */ - function createCell (TableCell $ncell, XMLWriter $doc, $j, $value/*: any*/, $setIndex) { + function createCell (TableCell $ncell, XMLWriter $doc, $j, mixed $value, $setIndex) { $doc->startElement("Cell"); if ($ncell->style) { @@ -266,8 +269,8 @@ class Table if ($this->rows[$i]->height) { $doc->writeAttribute('ss:Height', $this->rows[$i]->height); } - - $nrow/*: TableRow*/ = $this->rows[$i]; + /** @var TableRow $nrow */ + $nrow = $this->rows[$i]; // Флаг индикатор подстановки номера столбца $setIndex = false; for ($j = 1; $j <= $columns; $j++) { diff --git a/src/Filter/ActionAccess.php b/src/Filter/ActionAccess.php index 4fabc60..9e05a73 100644 --- a/src/Filter/ActionAccess.php +++ b/src/Filter/ActionAccess.php @@ -1,7 +1,7 @@ processor = $processor; $this->user = $user; } diff --git a/src/Filter/ActionLogger.php b/src/Filter/ActionLogger.php index b2b02ff..9b07344 100644 --- a/src/Filter/ActionLogger.php +++ b/src/Filter/ActionLogger.php @@ -6,14 +6,19 @@ use ctiso\Role\UserInterface, /* Переделать формат Логов на список json */ class ActionLogger -{ +{ public $before = array(); public $file; public $user; public $action; public $processor; - function __construct($processor/*: Filter*/, $logPath, $user/*: UserInterface*/) { + /** + * @param $processor Filter + * @param $logPath string + * @param $user UserInterface + */ + function __construct($processor, $logPath, $user) { $this->processor = $processor; $this->user = $user; diff --git a/src/Filter/Filter.php b/src/Filter/Filter.php index 156d4e0..afa35b5 100644 --- a/src/Filter/Filter.php +++ b/src/Filter/Filter.php @@ -10,12 +10,17 @@ use ctiso\Controller\Action, class Filter { + /** @var Action */ public $processor; - public function __construct($processor/*: Action*/) + + /** + * @param Action $processor + */ + public function __construct($processor) { $this->processor = $processor; } - + public function execute(HttpRequest $request) { return $this->processor->execute($request); diff --git a/src/Form/Field.php b/src/Form/Field.php index c3df594..a76fbe2 100644 --- a/src/Form/Field.php +++ b/src/Form/Field.php @@ -11,9 +11,9 @@ class Field public $label; // Метка поля public $value; // Значение поля public $type = ""; // Каждому типу элемента соответствует макрос TAL - public $error_msg = null; - public $default = null; - public $error = false; + public $error_msg = null; + public $default = null; + public $error = false; public $require = false; public $hint = null; public $maxlength = null; @@ -22,10 +22,10 @@ class Field public $_title = array(); public $description = ""; public $alias = array(); - + /** @phpstan-ignore-next-line */ public function __construct ($input = [], $factory = null) - { + { $this->default = null; if (isset($input['validate'])) { $this->require = strpos($input['validate'], 'require') !== false; @@ -41,7 +41,10 @@ class Field } } - function setValue($value/*: any*/) + /** + * @param mixed $value + */ + function setValue($value) { $this->value = $value; } diff --git a/src/Functions.php b/src/Functions.php index b547974..68d6a08 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -11,25 +11,25 @@ namespace ctiso; class right { - protected $params; + protected $params; protected $fn; - + public function __construct($params) { $this->fn = array_shift($params); $this->params = $params; } - + function apply() { $params = func_get_args(); array_splice($params, count($params), 0, $this->params); return call_user_func_array($this->fn, $params); - } + } } class left { - protected $params; + protected $params; protected $fn; - + public function __construct($params) { $this->fn = array_shift($params); $this->params = $params; @@ -44,9 +44,9 @@ class left { define('__', '_ARGUMENT_PLACE_'); class partial { - protected $params; + protected $params; protected $fn; - + public function __construct($params) { $this->fn = array_shift($params); $this->params = $params; @@ -66,7 +66,7 @@ class partial { } return call_user_func_array ($this->fn, $result); } -} +} /** * Композиция функций @@ -99,7 +99,7 @@ class Functions { /** * Композиция функций * @param array $_rest - * @return mixed + * @return mixed */ static function compose($_rest) { $closure = new compose(func_get_args()); @@ -109,7 +109,7 @@ class Functions { /** * Карирование справа * - * @return mixed + * @return mixed */ static function rcurry($_rest) { $closure = new right(func_get_args ()); @@ -119,7 +119,7 @@ class Functions { /** * Карирование слева * - * @return mixed + * @return mixed */ static function lcurry($_rest) { $closure = new left(func_get_args ()); @@ -129,9 +129,9 @@ class Functions { /** * Разделение массива на два по условию * @param mixed $pred Условие по которому разделяется массив - * @param array $lst + * @param array $lst * - * @return mixed + * @return mixed */ static function partition($pred, $lst) { $left = []; @@ -148,24 +148,24 @@ class Functions { /** * @param array $value - * @param string $name + * @param string $name * * @return mixed */ static function __key($value, $name) { return $value[$name]; } - + static function identity($value) { return $value; } - + /** * @param array $a * @param array $b * @param $key * - * @return int + * @return int */ static function __cmp($a, $b, $key) { if ($a[$key] == $b[$key]) { @@ -173,75 +173,81 @@ class Functions { } return ($a[$key] > $b[$key]) ? -1 : 1; } - + static function __cmp_less($a, $b, $key) { if ($a[$key] == $b[$key]) { return 0; } return ($a[$key] < $b[$key]) ? -1 : 1; } - + // Сравнение по ключу массиве static function __index($n, $key, $row) { return ($row[$key] == $n); } - + static function __div($x, $y) { return $x / $y; } - + static function __self($name, $o) { return call_user_func([$o, $name]); } - + static function concat(/* $args ...*/) { $args = func_get_args(); return implode("", $args); } - + static function __empty($x) { return empty($x); } - + // Отрицание static function __not($x) { return !$x; } - + // Не равно static function __neq($x, $y) { return $x != $y; } - + // Равно static function __eq($x, $y) { return $x == $y; } - + /** * Извлекает из многомерого массива значения с определенным ключом * @example key_values('a', array(1 => array('a' => 1, 'b' => 2))) => array(1) * + * @param string $key + * @param array|ArrayIterator $array * @return mixed */ - static function key_values($key, $array/*: array|ArrayIterator*/) { + static function key_values($key, $array) { $result = []; - + foreach($array as $item) { $result[] = $item[$key]; } return $result; } - - static function key_values_object($key, $array/*: array|ArrayIterator*/) { + + /** + * @param string $key + * @param array|ArrayIterator $array + */ + static function key_values_object($key, $array) { $result = []; - + foreach($array as $item) { $result[] = $item->{$key}; } return $result; } - + static function assoc_key_values($key, $value, $array) { $result = []; foreach ($array as $item) { @@ -249,7 +255,7 @@ class Functions { } return $result; } - + static function assoc_key($key, $array) { $result = []; foreach ($array as $item) { @@ -257,22 +263,28 @@ class Functions { } return $result; } - - static function _get($key, $value/*: any*/, $array/*: array*/) { + + /** + * @param string $key + * @param mixed $value + * @param array $array + * @return mixed + */ + static function _get($key, $value, $array) { foreach ($array as $item) { if ($item[$key] == $value) return $item; } - return null; + return null; } - + static function _get_key($key, $value, $array) { foreach ($array as $name => $item) { if ($item[$key] == $value) return $name; } - return null; + return null; } - - + + /** * Логическа операция && ко всем элементам массива * @return bool @@ -285,17 +297,17 @@ class Functions { } return true; } - + /** * Логическа операция || ко всем элементам массива - * @param array $array - * @param mixed $callback + * @param array $array + * @param mixed $callback * * @return mixed */ static function some(array $array, $callback) { assert(is_callable($callback)); - + foreach ($array as $key => $value) { if (call_user_func($callback, $value) === true) { return $key; @@ -303,10 +315,10 @@ class Functions { } return false; } - + static function span($length, array $array) { assert(is_int($length)); - + $result = []; $count = count($array); for($i = 0; $i < $count; $i += $length) { @@ -314,17 +326,17 @@ class Functions { } return $result; } - + static function array_ref($data, $n) { return $data[$n]; } - + static function call() { - $args = func_get_args(); + $args = func_get_args(); $name = array_shift($args); return call_user_func_array($name, $args); } - + /** * Поиск элемента в массиве * @param mixed $cb сравнение с элементом массива @@ -337,19 +349,19 @@ class Functions { 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) + * => array (1, 2) * @end example */ static function key_unique_values ($name, $table) { - // Ищем уникальные значения для заданного ключа + // Ищем уникальные значения для заданного ключа $keys = []; foreach ($table as $row) { if (!in_array ($row[$name], $keys)) @@ -357,7 +369,7 @@ class Functions { } return $keys; } - + /** * Сортировка двумерного массива по заданному ключу * @param array $array Массив @@ -371,16 +383,18 @@ class Functions { } /** - * Преобразует ключи элементов для многомерного массива + * Преобразует ключи элементов для многомерного массива + * @param string $key_name Имя ключа + * @param array $array Многомерный массив * @return mixed */ - static function hash_key ($key_name,$array/*: array */) { + static function hash_key ($key_name, $array) { $result = []; foreach($array as $value) { - $result[$value[$key_name]] = $value; + $result[$value[$key_name]] = $value; } - return $result; + return $result; } } diff --git a/src/HttpRequest.php b/src/HttpRequest.php index c8c0f7c..9a782b7 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -55,7 +55,7 @@ class HttpRequest extends Collection return parent::get('data')->get($key, $default); } - function session(Session $value = null) + function session(?Session $value = null) { if ($value) { $this->_session = $value; @@ -63,7 +63,7 @@ class HttpRequest extends Collection return $this->_session; } - function set($key, $value/*: any*/) + function set($key, mixed $value) { parent::get('data')->set($key, $value); } diff --git a/src/Layout/Manager.php b/src/Layout/Manager.php index 78a4686..9c0256c 100644 --- a/src/Layout/Manager.php +++ b/src/Layout/Manager.php @@ -18,7 +18,7 @@ class Manager extends Filter * Функция которая добавляет условие для проверки параметров $_GET * @param $get array() | true Ассоциативный массив ключей и значений для $_GET * - * @example + * @example * addConditionGet(array('module' => 'personal'), 'personal') * addConditionGet(array('module' => 'login'), 'login') */ @@ -28,14 +28,19 @@ class Manager extends Filter } /** - * Условие для аякс запросов. Тоже самое что и addConditionGet но еще проверяется является ли запрос ajax + * Условие для аякс запросов. Тоже самое что и addConditionGet но еще проверяется является ли запрос ajax */ public function addConditionXHR($get, Filter $layout) { $this->addCondition(Functions::rcurry([$this, 'checkXHR'], $get), $layout); } - public function checkGet($request/*: HttpRequest*/, $get) + /** + * @param HttpRequest $request + * @param array $get + * @return bool + */ + public function checkGet($request, $get) { if (is_array($get)) { foreach ($get as $key => $value) { @@ -47,18 +52,23 @@ class Manager extends Filter return true; } - public function checkXHR($request/*: HttpRequest*/, $get) + /** + * @param HttpRequest $request + * @param array $get + * @return bool + */ + public function checkXHR($request, $get) { return $request->isAjax() && $this->checkGet($request, $get); } /** * Добавляет условие в общем виде - * @parma $get function(HttpRequest) Функция + * @parma $get function(HttpRequest) Функция * @parma $layout Layout Макет */ public function addCondition($get, Filter $layout) - { + { $this->condition [] = [$get, $layout]; } diff --git a/src/MailAlt.php b/src/MailAlt.php index 7a42a7a..f5812f6 100644 --- a/src/MailAlt.php +++ b/src/MailAlt.php @@ -20,7 +20,7 @@ class MailAlt function from($name) { $this->mailer->setFrom($name); - } + } /** * Установка получателя @@ -37,12 +37,13 @@ class MailAlt /** * Установка получателей копии + * @param string $name */ function copy($name) // recipient cc { $this->mailer->addCC($name); } - + function notify($notify) { $this->_notify = $notify; @@ -50,29 +51,31 @@ class MailAlt /** * Тема письма + * @param string $subject */ - function subject($subject/*: string*/) + function subject($subject) { - $this->mailer->Subject = $subject; + $this->mailer->Subject = $subject; } /** * Текст письма + * @param string $text */ - function setContent($text) + function setContent($text) { $this->mailer->Body = $text; } - function setType($text) + function setType($text) { $this->mailer->isHTML($text == 'text/html'); } - + /** * Кодировка текста в письме */ - function setEncoding($encoding) + function setEncoding($encoding) { $this->encoding = $encoding; } @@ -86,7 +89,7 @@ class MailAlt } /** - * Отправка почты + * Отправка почты */ function send() { diff --git a/src/Path.php b/src/Path.php index e9d3c6b..109da4a 100644 --- a/src/Path.php +++ b/src/Path.php @@ -155,7 +155,10 @@ class Path } // Сравнение двух путей на равентство - public function equal($path/*: Path*/) + /** + * @param Path $path + */ + public function equal($path) { $count = count($this->path); if ($count == count($path->path)) { @@ -199,11 +202,11 @@ class Path /** * Проверяет является ли папка родительской для другой папки * - * @parma Path $path + * @param Path $path * * @return boolean */ - public function isParent($path/*: Path*/) + public function isParent($path) { if (isset($this->url['host']) && isset($path->url['host']) && ($this->url['host'] != $path->url['host'])) return false; diff --git a/src/Setup.php b/src/Setup.php index 1aef431..a491155 100644 --- a/src/Setup.php +++ b/src/Setup.php @@ -6,7 +6,7 @@ * $setup->set('target', 'dst'); * $setup->executeActions('install'); * - */ + */ namespace ctiso; use ctiso\Tools\SQLStatementExtractor; use ctiso\Path; @@ -22,7 +22,7 @@ class FakeZipArchive { } } -class Setup +class Setup { protected $actions = array(); public $context = array(); @@ -30,7 +30,7 @@ class Setup protected $action; protected $node; protected $stack = array(); - + public $zip; public $target; @@ -56,7 +56,7 @@ class Setup } /** - * Регистрация новых действия для установки + * Регистрация новых действия для установки */ public function registerAction($name, $action) { @@ -71,7 +71,7 @@ class Setup $this->context[$name] = $value; } - function replaceFn($matches) { + function replaceFn($matches) { if (isset($this->context[$matches[2]])) { $v = $this->context[$matches[2]]; } else { @@ -85,7 +85,7 @@ class Setup } public function fileContent($file, array $tpl) - { + { $result = $this->zip->getFromName($file); $result = preg_replace_callback('/\{\{\s*(\*?)(\w+)\s*\}\}/', [$this, 'replaceFn'], $result); return $result; @@ -113,48 +113,49 @@ class Setup * Для всех аттрибутов заменяет переменные на их значения */ function resolve($attributes) - { + { $result = []; foreach ($attributes as $key => $value) { $result [$key] = preg_replace_callback("/\\\${(\w+)}/", [$this, 'replaceVariable'], $value); } return $result; } - + /** * Выполняет список действий если для действия не указан аттрибут when то оно выполняется всегда - * + * * @param string $action специальное действие */ function executeActions($action = "install") { - $this->action = $action; + $this->action = $action; if ($this->stack[count($this->stack) - 1] === false) { return; } - $item/*: \SimpleXMLElement*/ = $this->stack[count($this->stack) - 1]; + /** @var \SimpleXMLElement */ + $item = $this->stack[count($this->stack) - 1]; $root = $item->children(); foreach ($root as $node) - { + { $attributes = $node->attributes(); array_push($this->stack, $node); $this->callAction($node->getName(), [$this->resolve($attributes)]); array_pop($this->stack); } - } - + } + /** - * Копирования файла + * Копирования файла * preserve - Не переписывать файл если он существует * template Файл является шаблоном подставить параметры до копирования * src Исходный файл * dst Новый файл - * + * * @param array{preserve?: string, template: string, src: string, dst: string} $attributes */ public function copyFile(array $attributes) - { + { $path = $this->targetPath($attributes['dst']); if (!(file_exists($path) && isset($attributes['preserve']))) { @@ -164,7 +165,7 @@ class Setup /** * Создает символическую ссылку на папку/файл - * @param array{target: string, link: string} $attributes + * @param array{target: string, link: string} $attributes */ public function makeLink(array $attributes) { @@ -174,7 +175,7 @@ class Setup } /** - * Подключение файла установки + * Подключение файла установки * @param array{file: string} $attributes Имя подключаемого файла */ public function includeFile(array $attributes) @@ -182,7 +183,7 @@ class Setup $file = basename($this->file) . "/" . $attributes['file']; $setup = new Setup($file); - $setup->context = $this->context; + $setup->context = $this->context; $setup->executeActions(); } @@ -192,9 +193,9 @@ class Setup /** * Создает новую папку - * dst Имя папки - * - * @param array{dst:string} $attributes + * dst Имя папки + * + * @param array{dst:string} $attributes */ public function makeDirectory(array $attributes) { @@ -202,7 +203,7 @@ class Setup if (!file_exists($path)) { mkdir($path); } - } + } function testWhen(array $attributes) { @@ -212,9 +213,11 @@ class Setup } /** - * Выполнение Списка SQL команд - */ - function batchSQLZip($conn/*: Database*/, $file) + * Выполнение Списка SQL команд из ZIP файла + * @param Database $conn + * @param string $file + */ + function batchSQLZip($conn, $file) { $stmtList = SQLStatementExtractor::extract($this->zip->getFromName($file)); foreach ($stmtList as $stmt) { @@ -222,7 +225,12 @@ class Setup } } - static function batchSQL($conn/*: Database*/, $file) + /** + * Выполнение Списка SQL команд + * @param Database $conn + * @param string $file + */ + static function batchSQL($conn, $file) { $stmtList = SQLStatementExtractor::extractFile($file); foreach ($stmtList as $stmt) { diff --git a/src/Tales.php b/src/Tales.php index 6538d86..e8090b4 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -41,7 +41,8 @@ class Tales_Assets implements PHPTAL_Tales } class Tales { - static $site/*: SiteInterface*/; + /** @var SiteInterface */ + static $site; static function phptal_date ($e) { return date("d.m.Y", $e); @@ -61,12 +62,11 @@ class Tales { */ static function phptal_component($expression) { $begin = floatval(microtime(true)); - $component/*: Component*/ = null; - + /** @var Component */ $component = self::$site->loadComponent($expression); - $req = new HttpRequest(); + $req = new HttpRequest(); $result = $component->execute($req); - + echo ""; return $result; } diff --git a/src/Tools/SQLStatementExtractor.php b/src/Tools/SQLStatementExtractor.php index 771b52b..5598335 100644 --- a/src/Tools/SQLStatementExtractor.php +++ b/src/Tools/SQLStatementExtractor.php @@ -18,7 +18,7 @@ * and is licensed under the LGPL. For more information please see * . */ - + /** * Static class for extracting SQL statements from a string or file. * @@ -30,12 +30,12 @@ namespace ctiso\Tools; use Exception; class SQLStatementExtractor { - + protected static $delimiter = ';'; - + /** * Get SQL statements from file. - * + * * @param string $filename Path to file to read. * @return array SQL statements */ @@ -46,17 +46,17 @@ class SQLStatementExtractor { } throw new Exception("Unable to read file: " . $filename); } - + /** * Extract statements from string. - * + * * @param string $buffer * @return array */ public static function extract($buffer) { return self::extractStatements(self::getLines($buffer)); } - + /** * Extract SQL statements from array of lines. * @@ -64,20 +64,20 @@ class SQLStatementExtractor { * @return array */ protected static function extractStatements($lines) { - + $statements = []; $sql = ""; - + foreach($lines as $line) { - + $line = trim($line); - - if (self::startsWith("//", $line) || + + if (self::startsWith("//", $line) || self::startsWith("--", $line) || self::startsWith("#", $line)) { continue; } - + if (strlen($line) > 4 && strtoupper(substr($line,0, 4)) == "REM ") { continue; } @@ -91,19 +91,19 @@ class SQLStatementExtractor { if (strpos($line, "--") !== false) { $sql .= "\n"; } - + if (self::endsWith(self::$delimiter, $sql)) { $statements[] = self::substring($sql, 0, strlen($sql)-1 - strlen(self::$delimiter)); $sql = ""; } } - return $statements; + return $statements; } - + // // Some string helper methods - // - + // + /** * Tests if a string starts with a given string. * @param string $check The substring to check. @@ -117,24 +117,24 @@ class SQLStatementExtractor { return (strpos($string, $check) === 0); } } - + /** * Tests if a string ends with a given string. * @param string $check The substring to check. * @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. */ - protected static function endsWith($check/*: string*/, $string) { + protected static function endsWith(string $check, $string) { if ($check === "" || $check === $string) { return true; } else { return (strpos(strrev($string), strrev($check)) === 0); } - } + } /** * 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, $startpos, $endpos = -1) { $len = strlen($string); @@ -152,16 +152,16 @@ class SQLStatementExtractor { } return substr($string, $startpos, $len+1); } - + /** * Convert string buffer into array of lines. - * + * * @param string $buffer * @return array string[] lines of file. */ - protected static function getLines($buffer) { + protected static function getLines($buffer) { $lines = preg_split("/\r?\n|\r/", $buffer); return $lines; } - + } \ No newline at end of file diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index ad9d8f0..12cd201 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -41,9 +41,8 @@ class TemplateImage public $resource; public $filename; - function __construct ($template = null) + function __construct (?string $template = null) { -// assert(is_string($src)); if ($template) { $this->data = $template; } @@ -52,27 +51,21 @@ class TemplateImage /** * Путь к изображению */ - function resourcePath($path) + function resourcePath(string $path) { - assert(is_string($path)); - $this->resource = $path; } /** * Путь у шрифтам */ - function fontPath($path) + function fontPath(string $path) { - assert(is_string($path)); - $this->base = $path; } - function set($name, $value) + function set(string $name, $value) { - assert(is_string($name)); - $this->context['['.$name.']'] = $this->encode($value); } @@ -90,10 +83,8 @@ class TemplateImage /** * Создает изображение из файла */ - function imagefromfile($file) + function imagefromfile(string $file) { - assert(is_string($file)); - $suffix = pathinfo($file, PATHINFO_EXTENSION); if (array_key_exists($suffix, self::$listfiles)) { return call_user_func('imagecreatefrom' . self::$listfiles[$suffix], $file); @@ -101,17 +92,15 @@ class TemplateImage return null; } - function getFontFile($name) + function getFontFile(string $name) { - assert(is_string($name)); - if(array_key_exists(strtolower($name), self::$listfonts)) { return $this->base . self::$listfonts[$name]; } return $this->base . 'arial.ttf'; } - function fontSuffix($style) + function fontSuffix(array $style) { if($style[0] && $style[1]) return "z"; @@ -121,7 +110,11 @@ class TemplateImage return ""; } - function imageText($text, $value/*: \stdClass*/) + /** + * @param string $text + * @param object $value + */ + function imageText($text, $value) { assert(is_string($text)); @@ -130,29 +123,30 @@ class TemplateImage $fontfile = $this->getFontFile($value->fontFamily . $this->fontSuffix($value->fontStyle)); $color = intval(substr($value->color, 1), 16); - if ($value->align[0]) { + if ($value->align[0]) { $align = Drawing::ALIGN_LEFT; - } elseif ($value->align[2]) { + } elseif ($value->align[2]) { $align = Drawing::ALIGN_RIGHT; } else { $align = Drawing::ALIGN_CENTER; } - if ($value->valign[0]) { + if ($value->valign[0]) { $valign = Drawing::ALIGN_TOP; - } elseif ($value->valign[1]) { + } elseif ($value->valign[1]) { $valign = Drawing::ALIGN_CENTER; } else { $valign = Drawing::ALIGN_BOTTOM; } - Drawing::imagettftextbox($this->image, $size, 0, $value->left, $value->top, $color, $fontfile, $text, + Drawing::imagettftextbox($this->image, $size, 0, $value->left, $value->top, $color, $fontfile, $text, $value->width, $value->height, $align, $valign); } /** * Перекодировка текста + * @deprecated */ function encode($text) { @@ -160,6 +154,10 @@ class TemplateImage return $text; //iconv("WINDOWS-1251", "UTF-8", $text); } + /** + * @param int $new_width + * @param int $new_height + */ function setSize($new_width, $new_height) { $width = imagesx($this->image); diff --git a/src/Url.php b/src/Url.php index f4393b0..ec93adb 100644 --- a/src/Url.php +++ b/src/Url.php @@ -4,7 +4,8 @@ namespace ctiso; class Url { public $parts = []; - public $parent/*: Url*/; + /** @var Url */ + public $parent; function __construct() { } @@ -23,5 +24,5 @@ class Url { function toString() { return '?' . http_build_query(array_merge($this->parts, $this->parent ? $this->parent->parts : [])); - } + } } \ No newline at end of file diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 8c08cbe..c284746 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -83,7 +83,7 @@ class Validator } } - public function addRule($rule/*:z any*/) { + public function addRule($rule) { if (is_array($rule)) { $this->chain = array_merge($this->chain, $rule); } else { @@ -91,7 +91,11 @@ class Validator } } - public function skip($rule/*z: AbstractRule*/, $container/*: Collection*/) // -> Rule_Abstract + /** + * @param AbstractRule $rule + * @param Collection $container + */ + public function skip($rule, $container) // -> Rule_Abstract { if ($rule->skipEmpty()) { $data = $container->get($rule->field); diff --git a/src/View/Pages.php b/src/View/Pages.php index 48b2750..a37633b 100644 --- a/src/View/Pages.php +++ b/src/View/Pages.php @@ -20,30 +20,30 @@ class Pages } return [ 'all' => ($n > 1), - 'list' => $result, - 'first' => self::href($prefix, $url . 1), - 'last' => self::href($prefix, $url . $n), - 'next' => ($page == $n)? false : self::href($prefix, $url . ($page + 1)) , + 'list' => $result, + 'first' => self::href($prefix, $url . 1), + 'last' => self::href($prefix, $url . $n), + 'next' => ($page == $n)? false : self::href($prefix, $url . ($page + 1)) , 'prev' => ($page == 1)? false : self::href($prefix, $url . ($page - 1))]; } /** * @deprecated - * @param $page int номер страницы - * @param $onpage int количество элем на странице + * @param int $page номер страницы + * @param int $onpage количество элем на странице * @return string */ - static function getLimit($page/*: number*/, $onpage/*: number*/) { + static function getLimit(int $page, int $onpage) { if ($page <= 0) { $page = 1; } return "LIMIT $onpage OFFSET " . ($page - 1) * $onpage; } /** - * @param $page int номер страницы - * @param $onpage int количество элем на странице + * @param int $page номер страницы + * @param int $onpage количество элем на странице * @return array */ - static function _getLimit($page, $onpage) { + static function _getLimit(int $page, int $onpage) { if ($page <= 0) { $page = 1; } return [ 'count' => $onpage, @@ -51,8 +51,8 @@ class Pages ]; } - static function href($prefix, $x) { - return $prefix . $x; + static function href($prefix, $x) { + return $prefix . $x; } } diff --git a/src/View/Top.php b/src/View/Top.php index 37b3339..ed707d2 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -68,11 +68,12 @@ class Top extends Composite } $init = []; + /** @var View $item */ + foreach ($s->_section as $key => $item) { - $ss /*: View*/= $item; - if ($ss->codeGenerator !== null) { + if ($item->codeGenerator !== null) { // функцию которая вычисляет а не результат - $part = call_user_func($ss->codeGenerator, $this, $key, $value); + $part = call_user_func($item->codeGenerator, $this, $key, $value); $init[] = $part; } } @@ -89,14 +90,14 @@ class Top extends Composite $this->set('title', $this->getTitle()); $this->set('jspath', $this->config->get('system', 'web')); - // + // return $this->execute(); // execute+phptal ?? } /** * Массив имен файлов скриптов * - * return array + * return array */ public function getScripts() { @@ -121,7 +122,7 @@ class Top extends Composite /** * Массив имен файлов стилей * - * return array + * return array */ public function getStyleSheet() { diff --git a/src/View/View.php b/src/View/View.php index 036cc72..377e3ed 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -160,7 +160,7 @@ class View extends \stdClass } // FIXME: Префикс, конфликтует с протоколом - function resolveName($alias, $file) { + function resolveName($alias, $file): string { list($type, $filename) = explode(":", $file, 2); // Сделать поиск а не просто замену папки при совпадении имени From acbf2c847d10a2f1ff7b0a5c5d820085c7dc6cc2 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 1 Oct 2025 13:11:06 +0300 Subject: [PATCH 094/138] =?UTF-8?q?fix:=20=D0=9E=D0=BF=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=D0=B5=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D1=82=D0=B8=D0=BF=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 5 ++--- src/Controller/ActionInterface.php | 11 +++++++++++ src/Controller/Front.php | 1 + src/Excel/Table.php | 4 ++-- src/Filter/ActionAccess.php | 2 +- src/Filter/ActionLogger.php | 8 ++++---- src/Filter/Filter.php | 12 ++++++++---- src/Filter/FilterInterface.php | 8 ++++++++ src/Filter/Login.php | 6 +++--- src/Functions.php | 4 ++-- 10 files changed, 42 insertions(+), 19 deletions(-) create mode 100644 src/Controller/ActionInterface.php create mode 100644 src/Filter/FilterInterface.php diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 73ef7aa..3ccfa11 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -14,7 +14,7 @@ use Exception, /** * Контроллер страниц */ -class Action +class Action implements ActionInterface { const TEMPLATE_EXTENSION = ".html"; // Расширение для шаблонов @@ -35,7 +35,7 @@ class Action public Database $db; // Фильтры - /** @var ?ActionAccess */ + /** @var ?\ctiso\Filter\ActionAccess */ public $access = null; // Обьект хранит параметры доступа public $logger = null; // Обьект для ведения лога @@ -220,7 +220,6 @@ class Action $access = $this->access; $url = new Url(); - //print_r([$name, $param]); if ($access == null || $access->checkAction($actionName)) { $moduleName = explode("\\", strtolower(get_class($this))); if (count($moduleName) > 2) { diff --git a/src/Controller/ActionInterface.php b/src/Controller/ActionInterface.php new file mode 100644 index 0000000..e932c97 --- /dev/null +++ b/src/Controller/ActionInterface.php @@ -0,0 +1,11 @@ + 0); + assert($index > 0); $offset = $this->getRows() + 1; $this->setRow($offset, $index, $data); diff --git a/src/Filter/ActionAccess.php b/src/Filter/ActionAccess.php index 9e05a73..706efc1 100644 --- a/src/Filter/ActionAccess.php +++ b/src/Filter/ActionAccess.php @@ -16,7 +16,7 @@ class ActionAccess public $user; /** - * @param Filter $processor + * @param FilterInterface $processor */ function __construct($processor, $user) { $this->processor = $processor; diff --git a/src/Filter/ActionLogger.php b/src/Filter/ActionLogger.php index 9b07344..73ea856 100644 --- a/src/Filter/ActionLogger.php +++ b/src/Filter/ActionLogger.php @@ -5,7 +5,7 @@ use ctiso\Role\UserInterface, ctiso\HttpRequest; /* Переделать формат Логов на список json */ -class ActionLogger +class ActionLogger implements FilterInterface { public $before = array(); public $file; @@ -14,9 +14,9 @@ class ActionLogger public $processor; /** - * @param $processor Filter - * @param $logPath string - * @param $user UserInterface + * @param \ctiso\Controller\ActionInterface $processor + * @param string $logPath + * @param UserInterface $user */ function __construct($processor, $logPath, $user) { $this->processor = $processor; diff --git a/src/Filter/Filter.php b/src/Filter/Filter.php index afa35b5..da34f8e 100644 --- a/src/Filter/Filter.php +++ b/src/Filter/Filter.php @@ -8,13 +8,13 @@ namespace ctiso\Filter; use ctiso\Controller\Action, ctiso\HttpRequest; -class Filter +class Filter implements \ctiso\Controller\ActionInterface { - /** @var Action */ + /** @var \ctiso\Controller\ActionInterface */ public $processor; /** - * @param Action $processor + * @param \ctiso\Controller\ActionInterface $processor */ public function __construct($processor) { @@ -26,7 +26,7 @@ class Filter return $this->processor->execute($request); } - public function getView($name, $class = 'ctiso\\View\\Top') + public function getView($name, $class = \ctiso\View\Top::class) { return $this->processor->getView($name, $class); } @@ -35,4 +35,8 @@ class Filter { return $this->processor->getConnection(); } + + public function addUrlPart($key, $value) { + $this->processor->addUrlPart($key, $value); + } } diff --git a/src/Filter/FilterInterface.php b/src/Filter/FilterInterface.php new file mode 100644 index 0000000..075b80f --- /dev/null +++ b/src/Filter/FilterInterface.php @@ -0,0 +1,8 @@ +set('lastupdate', true); return false; }*/ - // Проверка на количества попыток авторизации + // Проверка на количества попыток авторизации $lastAttempt = $result; if ($lastAttempt->get('trie_count') >= self::AUTH_MAX_ATTEMPT /*&& time() - $lastAttempt['trie_time'] < self::AUTH_LAST_ATTEMPT_TIMER*/) { @@ -100,7 +100,7 @@ class Login extends Filter $result = $this->role->getUserByLogin($login); // Поиск по логину if ($result) { $temp = md5($result->getString('password') . $result->getString('login') . $result->getString('sid')); - if ($password == $temp) { + if ($password == $temp) { $this->enter($result); return true; } @@ -125,7 +125,7 @@ class Login extends Filter return false; } - private function enter($result) + private function enter($result) { $this->user = $result; $random = rand(0, 1024 * 1024); diff --git a/src/Functions.php b/src/Functions.php index 68d6a08..3fed5a4 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -223,7 +223,7 @@ class Functions { * @example key_values('a', array(1 => array('a' => 1, 'b' => 2))) => array(1) * * @param string $key - * @param array|ArrayIterator $array + * @param array|\ArrayIterator $array * @return mixed */ static function key_values($key, $array) { @@ -237,7 +237,7 @@ class Functions { /** * @param string $key - * @param array|ArrayIterator $array + * @param array|\ArrayIterator $array */ static function key_values_object($key, $array) { $result = []; From 48269bd42412064daa96bff1b8a80764dec9eedf Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Mon, 6 Oct 2025 12:49:36 +0300 Subject: [PATCH 095/138] fix: phpstan level=6 --- src/Collection.php | 2 +- src/Functions.php | 35 ++--------------- src/HttpRequest.php | 6 +-- src/MailAlt.php | 18 ++++----- src/Numbers.php | 8 ++-- src/Path.php | 16 ++++---- src/Primitive.php | 16 ++++---- src/Registry.php | 20 +++++----- src/Role/User.php | 36 +++++++++--------- src/Role/UserInterface.php | 6 +-- src/Security.php | 4 +- src/Session.php | 12 +++--- src/Setup.php | 17 +++++---- src/SortRecord.php | 24 ++++++------ src/Tales.php | 16 ++++---- src/Tools/Drawing.php | 41 ++++++++++++-------- src/Tools/Image.php | 12 ++++-- src/Tools/SQLStatementExtractor.php | 8 ++-- src/Tools/StringUtil.php | 51 +++++++++++++------------ src/Tools/TemplateImage.php | 47 +++++++++-------------- src/UTF8.php | 23 +++++++---- src/Url.php | 17 ++++----- src/Validator/Rule/AbstractRule.php | 20 +++++----- src/Validator/Rule/Alpha.php | 6 +-- src/Validator/Rule/Code.php | 2 +- src/Validator/Rule/Count.php | 12 +++--- src/Validator/Rule/Date.php | 10 ++--- src/Validator/Rule/Email.php | 4 +- src/Validator/Rule/EmailList.php | 12 ++---- src/Validator/Rule/FileName.php | 4 +- src/Validator/Rule/IsFile.php | 20 +++++----- src/Validator/Rule/MatchRule.php | 7 ++-- src/Validator/Rule/Notnull.php | 8 ++-- src/Validator/Rule/Numeric.php | 6 +-- src/Validator/Rule/PregMatch.php | 21 +++++----- src/Validator/Rule/Time.php | 7 ++-- src/Validator/Rule/Unique.php | 4 +- src/Validator/Validator.php | 22 ++++++----- src/View/Composite.php | 6 +-- src/View/Plain.php | 6 +-- src/View/View.php | 59 +++++++++++++++-------------- 41 files changed, 324 insertions(+), 347 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index 04e02ee..027eb30 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -41,7 +41,7 @@ class Collection implements \ArrayAccess * * @return void */ - public function set($key, $value) + public function set(string $key, mixed $value) { $this->data[$key] = $value; } diff --git a/src/Functions.php b/src/Functions.php index 3fed5a4..887d741 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -181,15 +181,6 @@ class Functions { return ($a[$key] < $b[$key]) ? -1 : 1; } - // Сравнение по ключу массиве - static function __index($n, $key, $row) { - return ($row[$key] == $n); - } - - static function __div($x, $y) { - return $x / $y; - } - static function __self($name, $o) { return call_user_func([$o, $name]); } @@ -203,21 +194,6 @@ class Functions { return empty($x); } - // Отрицание - static function __not($x) { - return !$x; - } - - // Не равно - static function __neq($x, $y) { - return $x != $y; - } - - // Равно - static function __eq($x, $y) { - return $x == $y; - } - /** * Извлекает из многомерого массива значения с определенным ключом * @example key_values('a', array(1 => array('a' => 1, 'b' => 2))) => array(1) @@ -300,13 +276,9 @@ class Functions { /** * Логическа операция || ко всем элементам массива - * @param array $array - * @param mixed $callback - * * @return mixed */ - static function some(array $array, $callback) { - assert(is_callable($callback)); + static function some(array $array, callable $callback) { foreach ($array as $key => $value) { if (call_user_func($callback, $value) === true) { @@ -316,8 +288,7 @@ class Functions { return false; } - static function span($length, array $array) { - assert(is_int($length)); + static function span(int $length, array $array) { $result = []; $count = count($array); @@ -327,7 +298,7 @@ class Functions { return $result; } - static function array_ref($data, $n) { + static function array_ref(array $data, string|int $n) { return $data[$n]; } diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 9a782b7..459bb82 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -63,12 +63,12 @@ class HttpRequest extends Collection return $this->_session; } - function set($key, mixed $value) + function set(string $key, mixed $value) { parent::get('data')->set($key, $value); } - function export($key = 'data') + function export(string $key = 'data') { return parent::get($key)->export(); } @@ -85,7 +85,7 @@ class HttpRequest extends Collection * @param string $key * @return mixed */ - public function getRawData($var, $key) + public function getRawData(string $var, $key) { $data = parent::get(strtolower($var)); if ($data) { diff --git a/src/MailAlt.php b/src/MailAlt.php index f5812f6..2775553 100644 --- a/src/MailAlt.php +++ b/src/MailAlt.php @@ -17,7 +17,7 @@ class MailAlt /** * Установка отправителя */ - function from($name) + function from(string $name) { $this->mailer->setFrom($name); } @@ -25,12 +25,12 @@ class MailAlt /** * Установка получателя */ - function to($name) // recipient + function to(string $name) // recipient { $this->mailer->addAddress($name); } - function replyTo($name) // recipient + function replyTo(string $name) // recipient { $this->mailer->AddReplyTo($name); } @@ -39,12 +39,12 @@ class MailAlt * Установка получателей копии * @param string $name */ - function copy($name) // recipient cc + function copy(string $name) // recipient cc { $this->mailer->addCC($name); } - function notify($notify) + function notify(string $notify) { $this->_notify = $notify; } @@ -53,7 +53,7 @@ class MailAlt * Тема письма * @param string $subject */ - function subject($subject) + function subject(string $subject) { $this->mailer->Subject = $subject; } @@ -83,7 +83,7 @@ class MailAlt /** * Добавление вложения из файла */ - function addAttachment($filename, $name = null) + function addAttachment(string $filename, $name = null) { $this->mailer->addAttachment($filename, $name); } @@ -91,12 +91,12 @@ class MailAlt /** * Отправка почты */ - function send() + function send(): bool { return $this->mailer->send(); } - function eml() { + function eml(): string { return $this->mailer->getSentMIMEMessage(); } } diff --git a/src/Numbers.php b/src/Numbers.php index 2494706..ed98b61 100644 --- a/src/Numbers.php +++ b/src/Numbers.php @@ -4,22 +4,22 @@ namespace ctiso; class Numbers { - static function roman($i) + static function roman(float $i): float { return 0; } - static function decimal($i) + static function decimal(float $i): float { return $i; } - static function prefix($prefix, array $array, $key = false) + static function prefix(callable $prefix, array $array, $key = false) { $result = []; $count = count($array); for ($i = 0; $i < $count; $i++) { - $result [] = call_user_func($prefix, $i + 1) . '. ' . $array[$i]; + $result [] = call_user_func($prefix, $i + 1) . '. ' . $array[$i]; } return $result; } diff --git a/src/Path.php b/src/Path.php index 109da4a..aee6a87 100644 --- a/src/Path.php +++ b/src/Path.php @@ -368,12 +368,12 @@ class Path /** * Список файлов в директории * - * @param array $allow массив расширений для файлов + * @param ?array $allow массив расширений для файлов * @param array $ignore массив имен пааок которые не нужно обрабатывать * * @returnarray */ - public function getContent($allow = null, $ignore = []) + public function getContent(?array $allow = null, array $ignore = []) { $ignore = array_merge([".", ".."], $ignore); return self::fileList($this->__toString(), $allow, $ignore); @@ -382,12 +382,12 @@ class Path /** * Обьединяет строки в путь соединяя необходимым разделителем * - * @param array $allow массив расширений разрешеных для файлов + * @param ?array $allow массив расширений разрешеных для файлов * @param array $ignore массив имен пааок которые не нужно обрабатывать * * @return array */ - function getContentRec($allow = null, $ignore = []) + function getContentRec(?array $allow = null, array $ignore = []) { $result = []; $ignore = array_merge([".", ".."], $ignore); @@ -396,7 +396,7 @@ class Path } // Использовать SPL ??? - protected static function fileList($base, &$allow, &$ignore) + protected static function fileList(string $base, ?array &$allow, array &$ignore): array { if ($base == '') $base = '.'; $result = []; @@ -441,7 +441,7 @@ class Path * * @return void */ - static function prepare($dst, $filename = true) + static function prepare(string $dst, bool $filename = true) { if ($filename) { $path_dst = pathinfo($dst, PATHINFO_DIRNAME); @@ -462,7 +462,7 @@ class Path * * @return string */ - static function updateRelativePathOnFileMove($relativePath, $srcFile, $dstFile) { + static function updateRelativePathOnFileMove(string $relativePath, string $srcFile, string $dstFile) { $srcToDst = self::relative($srcFile, $dstFile); return self::normalize(self::join($srcToDst, $relativePath)); } @@ -477,7 +477,7 @@ class Path * * @return string */ - static function updateRelativePathOnDirectoryMove($relativePath, $fileDir, $srcDir, $dstDir) { + static function updateRelativePathOnDirectoryMove(string $relativePath, string $fileDir, string $srcDir, string $dstDir) { $relativePath = self::normalize($relativePath); $fileDir = self::normalize($fileDir); $srcDir = self::normalize($srcDir); diff --git a/src/Primitive.php b/src/Primitive.php index 283d7e1..4385c77 100644 --- a/src/Primitive.php +++ b/src/Primitive.php @@ -10,7 +10,7 @@ namespace ctiso; class Primitive { // varchar - public static function to_varchar($value) + public static function to_varchar($value): string { return ((string) $value); } @@ -26,28 +26,28 @@ class Primitive { return filter_var($value, FILTER_VALIDATE_BOOLEAN);//(int)((bool) $value); } - public static function from_bool($value) + public static function from_bool($value): bool { return ((bool) $value); } // int - public static function to_int($value) + public static function to_int($value): int { return ((int) $value); } - public static function from_int($value) + public static function from_int($value): string { return ((string) $value); } - + // date public static function to_date($value) { $result = 0; $tmp = explode("/", $value ?? '', 3); - + if (count($tmp) != 3) { return $result; } @@ -63,7 +63,7 @@ class Primitive { return 0; } } - + return $result; } @@ -110,7 +110,7 @@ class Primitive { } // array - public static function to_array($value) + public static function to_array($value) { return (is_array($value)) ? $value : []; } diff --git a/src/Registry.php b/src/Registry.php index 21e08eb..e2e1a5e 100644 --- a/src/Registry.php +++ b/src/Registry.php @@ -5,47 +5,47 @@ use ctiso\File, Exception; class Registry { - public $namespace = []; + public array $namespace = []; public $data; - function importFile($namespace, $filePath = null) { + function importFile(string $namespace, ?string $filePath = null) { $data = json_decode(File::getContents($filePath), true); $data['_file'] = $filePath; $this->namespace[$namespace] = [ 'path' => $filePath, 'data' => $data - ]; + ]; } - function importArray($namespace, $data = []) { + function importArray(string $namespace, array $data = []) { if (isset($this->namespace[$namespace])) { $data = array_merge($this->namespace[$namespace]['data'], $data); - } + } $this->namespace[$namespace] = [ 'path' => null, 'data' => $data - ]; + ]; } - public function get($ns, $key) { + public function get(string $ns, string $key) { if (isset($this->namespace[$ns]['data'][$key])) { return $this->namespace[$ns]['data'][$key]; } throw new Exception('Unknown key ' . $ns . '::' . $key); } - public function getOpt($ns, $key) { + public function getOpt(string $ns, string $key) { if (isset($this->namespace[$ns]['data'][$key])) { return $this->namespace[$ns]['data'][$key]; } return null; } - public function has($ns, $key) { + public function has(string $ns, string $key): bool { return isset($this->namespace[$ns]['data'][$key]); } - function set($ns, $key, $value) { + function set(string $ns, string $key, mixed $value): void { $this->namespace[$ns]['data'][$key] = $value; } } diff --git a/src/Role/User.php b/src/Role/User.php index 3f5728e..44c5683 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -4,20 +4,20 @@ namespace ctiso\Role; use ctiso\Database, ctiso\Database\Statement; -// Класс должен быть в библиотеке приложения +// Класс должен быть в библиотеке приложения class User implements UserInterface { const LIFE_TIME = 1800; // = 30min * 60sec; - public $fullname; - public $name; + public string $fullname; + public string $name; public $access; - public $password; + public string $password; public $id; - public $db; - public $groups; + public Database $db; + public array $groups; - function __construct($db, $groups) { + function __construct(Database $db, array $groups) { $this->db = $db; $this->groups = $groups; } @@ -26,7 +26,7 @@ class User implements UserInterface $this->db = $db; } - public function getName() { + public function getName(): string { return $this->name; } @@ -35,7 +35,7 @@ class User implements UserInterface } - public function getUserByQuery(Statement $stmt) + public function getUserByQuery(Statement $stmt) { $result = $stmt->executeQuery(); if ($result->next()) { @@ -44,8 +44,8 @@ class User implements UserInterface $this->id = $result->getInt('id_user'); $this->password = $result->getString('password'); $this->fullname = implode(' ', [ - $result->getString('surname'), - $result->getString('firstname'), + $result->getString('surname'), + $result->getString('firstname'), $result->getString('patronymic')]); return $result; } @@ -56,12 +56,12 @@ class User implements UserInterface return $result->get('password'); } - public function getUserByLogin($login) + public function getUserByLogin(string $login) { $stmt = $this->db->prepareStatement("SELECT * FROM users WHERE login = ?"); $stmt->setString(1, $login); $result = $this->getUserByQuery($stmt); - if ($result) { + if ($result) { $time = time(); $id = $this->id; $this->db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время входа @@ -69,7 +69,7 @@ class User implements UserInterface return $result; } - public function getUserById($id) + public function getUserById(int $id) { $stmt = $this->db->prepareStatement("SELECT * FROM users WHERE id_user = ?"); $stmt->setInt(1, $_SESSION ['access']); @@ -77,24 +77,24 @@ class User implements UserInterface if ($result) { $lasttime = $result->getInt('lasttime'); $time = time(); - if ($time - $lasttime > self::LIFE_TIME) return null; // Вышло время сессии + if ($time - $lasttime > self::LIFE_TIME) return null; // Вышло время сессии $id = $this->id; } return $result; } - function setSID($random, $result) { + function setSID(string $random, $result) { return $this->db->executeQuery("UPDATE users SET sid = '$random', trie_count = 0 WHERE id_user = " . $result->getInt('id_user')); } - function resetTries($login) { + function resetTries(string $login): void { $this->db->executeQuery( "UPDATE users SET trie_count = :count WHERE login = :login", ['count' => 0, 'login' => $login] ); } - function updateTries($login) { + function updateTries(string $login): void { $user = $this->db->fetchOneArray("SELECT id_user, trie_count FROM users WHERE login = :login", ['login' => $login]); $this->db->executeQuery( "UPDATE users SET trie_time = :cur_time, trie_count = :count WHERE id_user = :id_user", diff --git a/src/Role/UserInterface.php b/src/Role/UserInterface.php index 295e4ca..53e7150 100644 --- a/src/Role/UserInterface.php +++ b/src/Role/UserInterface.php @@ -5,8 +5,8 @@ use ctiso\Database\Statement; interface UserInterface { function getUserByQuery(Statement $stmt); - function getUserByLogin($login); - function getUserById($id); + function getUserByLogin(string $login); + function getUserById(int $id); function getName(); - function setSID($random, $result); + function setSID(string $random, $result); } \ No newline at end of file diff --git a/src/Security.php b/src/Security.php index ea25461..fa9bea0 100644 --- a/src/Security.php +++ b/src/Security.php @@ -3,7 +3,7 @@ namespace ctiso; class Security { - static function generatePassword($length = 9, $strength = 0) { + static function generatePassword(int $length = 9, int $strength = 0): string { $vowels = 'aeuy'; $consonants = 'bdghjmnpqrstvz'; if ($strength & 1) { @@ -18,7 +18,7 @@ class Security { if ($strength & 8) { $consonants .= '@#$%'; } - + $password = ''; $alt = time() % 2; for ($i = 0; $i < $length; $i++) { diff --git a/src/Session.php b/src/Session.php index 6eab118..028e190 100644 --- a/src/Session.php +++ b/src/Session.php @@ -2,9 +2,9 @@ namespace ctiso; -class Session +class Session { - function get($key) + function get(string $key): mixed { if (isset($_SESSION[$key])) { return $_SESSION[$key]; @@ -12,7 +12,7 @@ class Session return null; } - function set($key, $value) + function set(string|array $key, mixed $value): void { if (is_array($key)) { $_SESSION[strtolower(get_class($key[0]))][$key[1]] = $value; @@ -21,17 +21,17 @@ class Session } } - function clean($key) + function clean(string $key): void { unset($_SESSION[$key]); } - function start() + function start(): void { @session_start(); } - function stop() + function stop(): void { session_destroy(); } diff --git a/src/Setup.php b/src/Setup.php index a491155..836579c 100644 --- a/src/Setup.php +++ b/src/Setup.php @@ -10,6 +10,7 @@ namespace ctiso; use ctiso\Tools\SQLStatementExtractor; use ctiso\Path; +use SimpleXMLElement; class FakeZipArchive { public $base; @@ -58,7 +59,7 @@ class Setup /** * Регистрация новых действия для установки */ - public function registerAction($name, $action) + public function registerAction(string $name, $action) { $this->actions[$name] = $action; } @@ -66,12 +67,12 @@ class Setup /** * Установка переменных для шаблона */ - public function set($name, $value) + public function set(string $name, $value) { $this->context[$name] = $value; } - function replaceFn($matches) { + function replaceFn(array $matches) { if (isset($this->context[$matches[2]])) { $v = $this->context[$matches[2]]; } else { @@ -84,14 +85,14 @@ class Setup return $v; } - public function fileContent($file, array $tpl) + public function fileContent(string $file, array $tpl): string { $result = $this->zip->getFromName($file); $result = preg_replace_callback('/\{\{\s*(\*?)(\w+)\s*\}\}/', [$this, 'replaceFn'], $result); return $result; } - function callAction($name, array $attributes) + function callAction(string $name, array $attributes): void { if(isset($this->actions[$name])) { call_user_func_array($this->actions[$name], $attributes); @@ -112,7 +113,7 @@ class Setup /** * Для всех аттрибутов заменяет переменные на их значения */ - function resolve($attributes) + function resolve(SimpleXMLElement $attributes): array { $result = []; foreach ($attributes as $key => $value) { @@ -167,7 +168,7 @@ class Setup * Создает символическую ссылку на папку/файл * @param array{target: string, link: string} $attributes */ - public function makeLink(array $attributes) + public function makeLink(array $attributes): void { if (function_exists('symlink')) { symlink($attributes['target'], $attributes['link']); @@ -178,7 +179,7 @@ class Setup * Подключение файла установки * @param array{file: string} $attributes Имя подключаемого файла */ - public function includeFile(array $attributes) + public function includeFile(array $attributes): void { $file = basename($this->file) . "/" . $attributes['file']; diff --git a/src/SortRecord.php b/src/SortRecord.php index 3c4fe48..f1ed4e6 100644 --- a/src/SortRecord.php +++ b/src/SortRecord.php @@ -2,20 +2,18 @@ namespace ctiso; -class SortRecord +class SortRecord { - public $key; - public $mode; - public $order; + public string $key; + public int $order; - function __construct($key, $mode, $order) - { + function __construct(string $key, bool $order) + { $this->key = $key; $this->order = ((boolean)($order) === false) ? 1 : -1; - $this->mode = $mode; } - function compare($a, $b) + function compare(array $a, array $b): int { if($a[$this->key] == $b[$this->key]) { return 0; @@ -23,7 +21,7 @@ class SortRecord return ($a[$this->key] > $b[$this->key]) ? $this->order : -$this->order; } - function compareKeys($a, $b) + function compareKeys(object $a, object $b): int { if($a->{$this->key} == $b->{$this->key}) { return 0; @@ -31,17 +29,17 @@ class SortRecord return ($a->{$this->key} > $b->{$this->key}) ? $this->order : -$this->order; } - function sort(&$list) + function sort(array &$list) { return usort($list, [$this, 'compare']); } - function sortKeys(&$list) + function sortKeys(array &$list) { return usort($list, [$this, 'compareKeys']); } - function group(&$list, $key, $types) + function group(array &$list, string $key, array $types) { $groups = []; foreach ($types as $name) { @@ -59,6 +57,6 @@ class SortRecord foreach ($groups as $value) { $result = array_merge($result, $value); } - $list = $result; + $list = $result; } } diff --git a/src/Tales.php b/src/Tales.php index e8090b4..21b15cb 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -13,18 +13,20 @@ use PHPTAL_Php_TalesInternal, class Tales_DateTime implements PHPTAL_Tales { - static public function date($expression, $nothrow = false) { + static public function date($expression, $nothrow = false): string + { return "ctiso\\Tales::phptal_date(".PHPTAL_Php_TalesInternal::path($expression).")"; } - static public function time($expression, $nothrow = false) { + static public function time($expression, $nothrow = false): string + { return "ctiso\\Tales::phptal_time(".PHPTAL_Php_TalesInternal::path($expression).")"; } } class Tales_Component implements PHPTAL_Tales { - static public function component($expression, $nothrow = false) + static public function component($expression, $nothrow = false): string { $s = PHPTAL_Php_TalesInternal::string($expression); return "ctiso\\Tales::phptal_component(" . $s . ")"; @@ -33,7 +35,7 @@ class Tales_Component implements PHPTAL_Tales class Tales_Assets implements PHPTAL_Tales { - static public function assets($expression, $nothrow = false) + static public function assets($expression, $nothrow = false): string { $s = PHPTAL_Php_TalesInternal::string($expression); return "ctiso\\Tales::phptal_asset(" . $s . ")"; @@ -44,15 +46,15 @@ class Tales { /** @var SiteInterface */ static $site; - static function phptal_date ($e) { + static function phptal_date ($e): string { return date("d.m.Y", $e); } - static function phptal_time ($e) { + static function phptal_time ($e): string { return date("H:i", $e); } - static function phptal_asset($s) { + static function phptal_asset($s): string { self::$site->addStyleSheet($s); return ""; } diff --git a/src/Tools/Drawing.php b/src/Tools/Drawing.php index 306d914..56183b6 100644 --- a/src/Tools/Drawing.php +++ b/src/Tools/Drawing.php @@ -2,6 +2,8 @@ namespace ctiso\Tools; +use GdImage; + class Drawing { const ALIGN_LEFT = "left"; @@ -10,13 +12,13 @@ class Drawing const ALIGN_CENTER = "center"; const ALIGN_RIGHT = "right"; - static function drawrectnagle(&$image, $left, $top, $width, $height, $rgb) + static function drawrectnagle(GdImage &$image, int $left, int $top, int $width, int $height, array $rgb): void { $color = imagecolorallocate($image, $rgb[0], $rgb[1], $rgb[2]); $right = $left + $width; $bottom = $top + $height; imageline($image, $left, $top, $right, $top, $color); - imageline($image, $right,$top, $right, $bottom, $color); + imageline($image, $right, $top, $right, $bottom, $color); imageline($image, $left, $bottom, $right, $bottom, $color); imageline($image, $left, $top, $left, $bottom, $color); } @@ -24,12 +26,23 @@ class Drawing /** * http://ru2.php.net/imagettftext */ - static function imagettftextbox(&$image, $size, $angle, $left, $top, $color, $font, $text, - $max_width, $max_height, $align, $valign) - { -// 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)); + static function imagettftextbox( + GdImage &$image, + int $size, + float $angle, + $left, + $top, + $color, + $font, + $text, + $max_width, + $max_height, + $align, + $valign + ) { + // 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)); $text_lines = explode("\n", $text); // Supports manual line breaks! $lines = []; @@ -103,17 +116,13 @@ class Drawing } - function imagettftextSp($image, $size, $angle, $x, $y, $color, $font, $text, $spacing = 0) + function imagettftextSp(GdImage $image, float $size, float $angle, int $x, int $y, int $color, string $font, string $text, int $spacing = 0) { - if ($spacing == 0) - { + if ($spacing == 0) { imagettftext($image, $size, $angle, $x, $y, $color, $font, $text); - } - else - { + } else { $temp_x = $x; - for ($i = 0; $i < mb_strlen($text); $i++) - { + for ($i = 0; $i < mb_strlen($text); $i++) { $bbox = imagettftext($image, $size, $angle, $temp_x, $y, $color, $font, $text[$i]); $temp_x += $spacing + ($bbox[2] - $bbox[0]); } diff --git a/src/Tools/Image.php b/src/Tools/Image.php index a59642f..b1c2395 100644 --- a/src/Tools/Image.php +++ b/src/Tools/Image.php @@ -2,9 +2,11 @@ namespace ctiso\Tools; +use GdImage; + class Image -{ - static function load($uri) +{ + static function load($uri): GdImage|false { $e = strtolower(pathinfo($uri, PATHINFO_EXTENSION)); switch ($e) { @@ -12,9 +14,10 @@ class Image case 'jpeg': case 'jpg': return imagecreatefromjpeg($uri); case 'gif': return imagecreatefromgif($uri); } + return false; } - static function fit($image, $prewidth, $preheight, $force = true) + static function fit(GdImage $image, int $prewidth, int $preheight, bool $force = true): GdImage|false { $width = imagesx($image); $height = imagesy($image); @@ -29,7 +32,7 @@ class Image return $image_p; } - static function save($image, $uri) + static function save($image, $uri): bool { $e = strtolower(pathinfo($uri, PATHINFO_EXTENSION)); switch ($e) { @@ -37,5 +40,6 @@ class Image case 'png': imagepng($image, $uri); break; case 'gif': imagegif($image, $uri); break; } + return false; } } \ No newline at end of file diff --git a/src/Tools/SQLStatementExtractor.php b/src/Tools/SQLStatementExtractor.php index 5598335..3759953 100644 --- a/src/Tools/SQLStatementExtractor.php +++ b/src/Tools/SQLStatementExtractor.php @@ -124,7 +124,7 @@ class SQLStatementExtractor { * @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. */ - protected static function endsWith(string $check, $string) { + protected static function endsWith(string $check, string $string) { if ($check === "" || $check === $string) { return true; } else { @@ -136,7 +136,7 @@ class SQLStatementExtractor { * 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 */ - protected static function substring($string, $startpos, $endpos = -1) { + protected static function substring(string $string, int $startpos, int $endpos = -1) { $len = strlen($string); $endpos = (int) (($endpos === -1) ? $len-1 : $endpos); if ($startpos > $len-1 || $startpos < 0) { @@ -157,9 +157,9 @@ class SQLStatementExtractor { * Convert string buffer into array of lines. * * @param string $buffer - * @return array string[] lines of file. + * @return string[] lines of file. */ - protected static function getLines($buffer) { + protected static function getLines(string $buffer): array { $lines = preg_split("/\r?\n|\r/", $buffer); return $lines; } diff --git a/src/Tools/StringUtil.php b/src/Tools/StringUtil.php index 35baa93..87e5db7 100644 --- a/src/Tools/StringUtil.php +++ b/src/Tools/StringUtil.php @@ -5,7 +5,7 @@ namespace ctiso\Tools; class StringUtil { // from creole - static function strToArray($str) { + static function strToArray(string $str): array { $str = substr($str, 1, -1); // remove { } $res = []; @@ -40,7 +40,7 @@ class StringUtil { } //Нормализация строк на русском - static function normalizeRussian($str) { + static function normalizeRussian(string $str): string { $result = preg_replace('/\s+/',' ', $str); if (is_string($result)) { $result = trim($result); //Замена длинных пробелов на одинарные, пробелы по краям @@ -62,8 +62,8 @@ class StringUtil { * output: true * input: $str="foo" $variants="foo1|foo2|foo3" * output: false -*/ - static function compare_string_to_variants($str, $variants){ + */ + static function compare_string_to_variants($str, string $variants){ $variants_array = explode('|', $variants); $founded = false; foreach ($variants_array as $variant) { @@ -72,7 +72,7 @@ class StringUtil { return $founded; } - static function mb_str_split($str) { + static function mb_str_split(string $str): array|false { return preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY); } @@ -80,32 +80,33 @@ class StringUtil { return str_replace(self::mb_str_split($from), self::mb_str_split($to), $str); } - static function encodestring($st) { + static function encodestring(string $st): string + { $st = self::mb_strtr($st,"абвгдеёзийклмнопрстуфхъыэ !+()", "abvgdeeziyklmnoprstufh_ie_____"); $st = self::mb_strtr($st,"АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ", "ABVGDEEZIYKLMNOPRSTUFH_IE"); $st = strtr($st, [ - " " => '_', - "." => '_', - "," => '_', - "?" => '_', - "\"" => '_', - "'" => '_', - "/" => '_', - "\\" => '_', - "%" => '_', - "#" => '_', - "*" => '_', - "ж"=>"zh", "ц"=>"ts", "ч"=>"ch", "ш"=>"sh", - "щ"=>"shch","ь"=>"", "ю"=>"yu", "я"=>"ya", - "Ж"=>"ZH", "Ц"=>"TS", "Ч"=>"CH", "Ш"=>"SH", - "Щ"=>"SHCH","Ь"=>"", "Ю"=>"YU", "Я"=>"YA", - "Й"=>"i", "й"=>"ie", "ё"=>"Ye", - "№"=>"N" - ]); + " " => '_', + "." => '_', + "," => '_', + "?" => '_', + "\"" => '_', + "'" => '_', + "/" => '_', + "\\" => '_', + "%" => '_', + "#" => '_', + "*" => '_', + "ж"=>"zh", "ц"=>"ts", "ч"=>"ch", "ш"=>"sh", + "щ"=>"shch","ь"=>"", "ю"=>"yu", "я"=>"ya", + "Ж"=>"ZH", "Ц"=>"TS", "Ч"=>"CH", "Ш"=>"SH", + "Щ"=>"SHCH","Ь"=>"", "Ю"=>"YU", "Я"=>"YA", + "Й"=>"i", "й"=>"ie", "ё"=>"Ye", + "№"=>"N" + ]); return strtolower($st); } - static function validate_encoded_string($st) { + static function validate_encoded_string(string $st): int|false { $enc_st = self::encodestring($st); return preg_match('/^[\w_-]+(\.[\w_-]+)?$/', $enc_st); } diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index 12cd201..6854bb6 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -8,8 +8,8 @@ use ctiso\Tools\Drawing; class TemplateImage { - static $listfiles = array('jpg' => 'jpeg', 'gif' => 'gif', 'png' => 'png', 'bmp' => 'wbmp'); - static $listfonts = array( + static array $listfiles = array('jpg' => 'jpeg', 'gif' => 'gif', 'png' => 'png', 'bmp' => 'wbmp'); + static array $listfonts = array( 'georgia' => 'georgia.ttf', 'georgiabd' => 'georgiab.ttf', 'georgiaz' => 'georgiaz.ttf', @@ -32,16 +32,16 @@ class TemplateImage ); protected $src; - protected $context = array(); - protected $data = array(); - protected $base = "c:\\windows\\fonts\\"; + protected array $context = []; + protected array $data = []; + protected string $base = "c:\\windows\\fonts\\"; protected $image; protected $_prepare = true; public $debug = false; public $resource; public $filename; - function __construct (?string $template = null) + function __construct (?array $template = null) { if ($template) { $this->data = $template; @@ -51,7 +51,7 @@ class TemplateImage /** * Путь к изображению */ - function resourcePath(string $path) + function resourcePath(string $path): void { $this->resource = $path; } @@ -59,7 +59,7 @@ class TemplateImage /** * Путь у шрифтам */ - function fontPath(string $path) + function fontPath(string $path): void { $this->base = $path; } @@ -69,13 +69,13 @@ class TemplateImage $this->context['['.$name.']'] = $this->encode($value); } - function setImage($name) + function setImage($name): void { $this->filename = $name; $this->image = $this->imagefromfile($name); } - function setEmptyImage($width, $height) + function setEmptyImage($width, $height): void { $this->image = imagecreatetruecolor($width, $height); } @@ -92,7 +92,7 @@ class TemplateImage return null; } - function getFontFile(string $name) + function getFontFile(string $name): string { if(array_key_exists(strtolower($name), self::$listfonts)) { return $this->base . self::$listfonts[$name]; @@ -100,7 +100,7 @@ class TemplateImage return $this->base . 'arial.ttf'; } - function fontSuffix(array $style) + function fontSuffix(array $style): string { if($style[0] && $style[1]) return "z"; @@ -110,14 +110,8 @@ class TemplateImage return ""; } - /** - * @param string $text - * @param object $value - */ - function imageText($text, $value) + function imageText(string $text, object $value) { - assert(is_string($text)); - $text = strtr($text, $this->context); $size = $value->fontSize; $fontfile = $this->getFontFile($value->fontFamily . $this->fontSuffix($value->fontStyle)); @@ -148,17 +142,12 @@ class TemplateImage * Перекодировка текста * @deprecated */ - function encode($text) + function encode(string $text): string { - assert(is_string($text)); return $text; //iconv("WINDOWS-1251", "UTF-8", $text); } - /** - * @param int $new_width - * @param int $new_height - */ - function setSize($new_width, $new_height) + function setSize(int $new_width, int $new_height): void { $width = imagesx($this->image); $height = imagesy($this->image); @@ -173,7 +162,7 @@ class TemplateImage $this->image = $image_p; } - function prepare() { + function prepare(): void { if($this->_prepare) { $this->_prepare = false; foreach ($this->data as $value) { @@ -185,10 +174,8 @@ class TemplateImage /** * Генерирует изображение из шаблона */ - function render($file = null) + function render(?string $file = null): string|bool { - assert(is_string($file) || is_null($file)); - $this->prepare(); if ($file == null) { diff --git a/src/UTF8.php b/src/UTF8.php index 5eb93a0..4eab203 100644 --- a/src/UTF8.php +++ b/src/UTF8.php @@ -2,13 +2,20 @@ namespace ctiso; -class UTF8 { - static function str_split($str, $split_length = 1) { - $split_length = (int) $split_length; - +class UTF8 +{ + /** + * @param string $str + * @param int $split_length + * @return list + */ + static function str_split(string $str, int $split_length = 1): array + { + $split_length = (int) $split_length; + $matches = []; - preg_match_all('/.{'.$split_length.'}|[^\x00]{1,'.$split_length.'}$/us', $str, $matches); - - return $matches[0]; + preg_match_all('/.{' . $split_length . '}|[^\x00]{1,' . $split_length . '}$/us', $str, $matches); + + return $matches[0]; } -} \ No newline at end of file +} diff --git a/src/Url.php b/src/Url.php index ec93adb..67e145a 100644 --- a/src/Url.php +++ b/src/Url.php @@ -3,26 +3,23 @@ namespace ctiso; class Url { - public $parts = []; - /** @var Url */ - public $parent; + /** @var array */ + public array $parts = []; + public ?Url $parent; - function __construct() { - } - - function setParent($parent) { + function setParent($parent): void { $this->parent = $parent; } - function setQuery($parts) { + function setQuery($parts): void { $this->parts = $parts; } - function addQueryParam($key, $value) { + function addQueryParam(string $key, string $value): void { $this->parts[$key] = $value; } - function toString() { + function toString(): string { return '?' . http_build_query(array_merge($this->parts, $this->parent ? $this->parent->parts : [])); } } \ No newline at end of file diff --git a/src/Validator/Rule/AbstractRule.php b/src/Validator/Rule/AbstractRule.php index 4ab8307..6a7ebef 100644 --- a/src/Validator/Rule/AbstractRule.php +++ b/src/Validator/Rule/AbstractRule.php @@ -5,43 +5,43 @@ use ctiso\Collection; abstract class AbstractRule { - public $field; + public string $field; protected $errorMsg; protected $ctx; - public function __construct($field, $errorMsg = null) + public function __construct(string $field, $errorMsg = null) { $this->field = $field; $this->errorMsg = $errorMsg; } - - public function setName($field) + + public function setName(string $field): self { $this->field = $field; return $this; } - public function setErrorMsg($errorMsg) + public function setErrorMsg($errorMsg): self { $this->errorMsg = $errorMsg; return $this; } - public function getErrorMsg() - { + public function getErrorMsg(): string + { return $this->errorMsg; } - public function isValid(Collection $container, $status = null) + public function isValid(Collection $container, $status = null): bool { return true; } - function skipEmpty() { + function skipEmpty(): bool { return true; } - public function setContext($ctx) + public function setContext($ctx): void { $this->ctx = $ctx; } diff --git a/src/Validator/Rule/Alpha.php b/src/Validator/Rule/Alpha.php index 06793fd..a353707 100644 --- a/src/Validator/Rule/Alpha.php +++ b/src/Validator/Rule/Alpha.php @@ -9,12 +9,12 @@ use ctiso\Validator\Rule\AbstractRule, class Alpha extends AbstractRule { - public function getErrorMsg() - { + public function getErrorMsg(): string + { return "Поле должно содержать только буквы"; } - public function isValid(Collection $container, $status = null) + public function isValid(Collection $container, $status = null): bool { return ctype_alpha($container->get($this->field)); } diff --git a/src/Validator/Rule/Code.php b/src/Validator/Rule/Code.php index 1102766..30f6e5e 100644 --- a/src/Validator/Rule/Code.php +++ b/src/Validator/Rule/Code.php @@ -13,7 +13,7 @@ class Code extends AbstractRule return "Неправильно указан персональный код"; } - function checkCode($code): bool { + function checkCode(array $code): bool { foreach($code as $c) { if (empty($c)) { return false; diff --git a/src/Validator/Rule/Count.php b/src/Validator/Rule/Count.php index c346892..008e24b 100644 --- a/src/Validator/Rule/Count.php +++ b/src/Validator/Rule/Count.php @@ -12,22 +12,22 @@ class Count extends AbstractRule public $size = 1; public $max = null; - public function getErrorMsg() - { + public function getErrorMsg(): string + { return "Количество записей должно быть не менне {$this->size} и не более {$this->max}"; } function not_empty($s) { return $s != ""; } - - public function isValid(Collection $container, $status = null) + + public function isValid(Collection $container, $status = null): bool { if (!$this->max) { $this->max = $this->size; - } - $count = count(array_filter(array_map('trim', + } + $count = count(array_filter(array_map('trim', explode(";", $container->get($this->field))), [$this, 'not_empty'])); return $count >= $this->size && $count <= ((int)$this->max); diff --git a/src/Validator/Rule/Date.php b/src/Validator/Rule/Date.php index fdfff71..a53975d 100644 --- a/src/Validator/Rule/Date.php +++ b/src/Validator/Rule/Date.php @@ -9,16 +9,16 @@ use ctiso\Validator\Rule\AbstractRule, class Date extends AbstractRule { - public function getErrorMsg() - { + public function getErrorMsg(): string + { return "Неверный формат даты"; } - - public function isValid(Collection $container, $status = null) + + public function isValid(Collection $container, $status = null): bool { $pattern = "/^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/"; $matches = []; - return (preg_match($pattern, $container->get($this->field), $matches) + return (preg_match($pattern, $container->get($this->field), $matches) && checkdate((int)$matches[2], (int)$matches[1], (int)$matches[3])); } } diff --git a/src/Validator/Rule/Email.php b/src/Validator/Rule/Email.php index 22c1287..ebbdc17 100644 --- a/src/Validator/Rule/Email.php +++ b/src/Validator/Rule/Email.php @@ -9,12 +9,12 @@ use ctiso\Validator\Rule\AbstractRule, class Email extends AbstractRule { - public function getErrorMsg() + public function getErrorMsg(): string { return "Неверный формат электронной почты"; } - public function isValid(Collection $container, $status = null) + public function isValid(Collection $container, $status = null): bool { $emails = explode(",", $container->get($this->field)); foreach ($emails as $email) { diff --git a/src/Validator/Rule/EmailList.php b/src/Validator/Rule/EmailList.php index 2132d0b..068becf 100644 --- a/src/Validator/Rule/EmailList.php +++ b/src/Validator/Rule/EmailList.php @@ -9,20 +9,14 @@ use ctiso\Validator\Rule\AbstractRule, class EmailList extends AbstractRule { - public function getErrorMsg() - { + public function getErrorMsg(): string + { return "Неверный формат электронной почты"; } - public function isValid(Collection $container, $status = null) { - $user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\|\{\}~\']+'; - $doIsValid = '(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]\.?)+'; - $ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}'; - $ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}'; - + public function isValid(Collection $container, $status = null): bool { $emails = $container->get($this->field); foreach ($emails as $email) { -// if (! preg_match("/^$user@($doIsValid|(\[($ipv4|$ipv6)\]))$/", $email)) return false; if (! filter_var($email, FILTER_VALIDATE_EMAIL)) return false; } return true; diff --git a/src/Validator/Rule/FileName.php b/src/Validator/Rule/FileName.php index d45d1f8..5f4410f 100644 --- a/src/Validator/Rule/FileName.php +++ b/src/Validator/Rule/FileName.php @@ -7,12 +7,12 @@ use ctiso\Validator\Rule\AbstractRule, class FileName extends AbstractRule { - public function getErrorMsg() + public function getErrorMsg(): string { return 'Название файла может содержать только символы латиницы в нижнем регистре и цифры'; } - public function isValid(Collection $container, $status = null) + public function isValid(Collection $container, $status = null): bool { return Path::isName($container->get($this->field)); } diff --git a/src/Validator/Rule/IsFile.php b/src/Validator/Rule/IsFile.php index 5304718..37115f8 100644 --- a/src/Validator/Rule/IsFile.php +++ b/src/Validator/Rule/IsFile.php @@ -9,42 +9,42 @@ use ctiso\Validator\Rule\AbstractRule, class IsFile extends AbstractRule { - private $type = array(); - private $maxsize = 1024; + private array $type = []; + private int $maxsize = 1024; - function skipEmpty() { + function skipEmpty(): bool { return false; } - function setSize($size) { + function setSize(int $size): void { $this->maxsize = $size; } - function setType(array $type) { + function setType(array $type): void { $this->type = $type; } - public function isValid(Collection $container, $status = null) + public function isValid(Collection $container, $status = null): bool { if (!isset($_FILES[$this->field]) || $_FILES[$this->field]['error'] == UPLOAD_ERR_NO_FILE) { $this->setErrorMsg('Файл не загружен'); - return false; + return false; } if ($_FILES[$this->field]['error'] == UPLOAD_ERR_INI_SIZE) { $this->setErrorMsg('Превышен размер файла'); - return false; + return false; } $tmp = $_FILES[$this->field]; if (!in_array($tmp['type'], $this->type)) { $this->setErrorMsg('Неверный формат файла'); - return false; + return false; } if (((int)$tmp['size']) > $this->maxsize*1024) { $this->setErrorMsg('Неверный размер файла'); - return false; + return false; } return true; diff --git a/src/Validator/Rule/MatchRule.php b/src/Validator/Rule/MatchRule.php index d54f448..ab167d3 100644 --- a/src/Validator/Rule/MatchRule.php +++ b/src/Validator/Rule/MatchRule.php @@ -11,12 +11,13 @@ class MatchRule extends AbstractRule { public $same; - public function getErrorMsg() - { + public function getErrorMsg(): string + { return "Поля не совпадают"; } - public function isValid(Collection $container, $status = null) { + public function isValid(Collection $container, $status = null): bool + { return (strcmp($container->get($this->field), $container->get($this->same)) == 0); } } diff --git a/src/Validator/Rule/Notnull.php b/src/Validator/Rule/Notnull.php index d9130da..2a146e2 100644 --- a/src/Validator/Rule/Notnull.php +++ b/src/Validator/Rule/Notnull.php @@ -6,16 +6,16 @@ use ctiso\Validator\Rule\AbstractRule, class Notnull extends AbstractRule { - function skipEmpty() { + function skipEmpty(): bool { return false; } - public function getErrorMsg() - { + public function getErrorMsg(): string + { return "Поле не должно быть пустым"; } - public function isValid(Collection $container, $status = null) + public function isValid(Collection $container, $status = null): bool { $data = $container->get($this->field); if (is_array($data)) { diff --git a/src/Validator/Rule/Numeric.php b/src/Validator/Rule/Numeric.php index a3c6a5a..1fe5b0d 100644 --- a/src/Validator/Rule/Numeric.php +++ b/src/Validator/Rule/Numeric.php @@ -9,12 +9,12 @@ use ctiso\Validator\Rule\AbstractRule, class Numeric extends AbstractRule { - public function getErrorMsg() - { + public function getErrorMsg(): string + { return "Значение поля должно быть числом"; } - public function isValid(Collection $container, $status = null) + public function isValid(Collection $container, $status = null): bool { return (is_numeric($container->get($this->field))); } diff --git a/src/Validator/Rule/PregMatch.php b/src/Validator/Rule/PregMatch.php index 3d400bb..6b7f75c 100644 --- a/src/Validator/Rule/PregMatch.php +++ b/src/Validator/Rule/PregMatch.php @@ -1,21 +1,20 @@ pattern,$container->get($this->field)); - } + public function isValid(Collection $container, $status = null): bool + { + return preg_match($this->pattern, $container->get($this->field)); + } } diff --git a/src/Validator/Rule/Time.php b/src/Validator/Rule/Time.php index c4ecc58..658e3e8 100644 --- a/src/Validator/Rule/Time.php +++ b/src/Validator/Rule/Time.php @@ -11,19 +11,20 @@ class Time extends AbstractRule { private $split = ":"; - public function getErrorMsg() + public function getErrorMsg(): string { return "Неверный формат времени"; } - static function checktime($hour, $minute) + static function checktime(int $hour, int $minute): bool { if ($hour > -1 && $hour < 24 && $minute > -1 && $minute < 60) { return true; } + return false; } - public function isValid(Collection $container, $status = null) + public function isValid(Collection $container, $status = null): bool { /** @var list */ $tmp = explode($this->split, $container->get($this->field), 2); diff --git a/src/Validator/Rule/Unique.php b/src/Validator/Rule/Unique.php index 81489c3..b3d49fa 100644 --- a/src/Validator/Rule/Unique.php +++ b/src/Validator/Rule/Unique.php @@ -8,12 +8,12 @@ use ctiso\Validator\Rule\AbstractRule, class Unique extends AbstractRule { - public function getErrorMsg() + public function getErrorMsg(): string { return $this->ctx->getMessage(); } - public function isValid(Collection $container, $status = null) + public function isValid(Collection $container, $status = null): bool { return $this->ctx->isUnique($container->get($this->field), $status, $container); } diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index c284746..8abd7dd 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -1,7 +1,5 @@ - /** * Проверка коллекции */ @@ -12,8 +10,10 @@ use Exception, class Validator { - protected $chain = []; // Массив правил - protected $errorMsg = []; // Массив ошибок + /** @var AbstractRule[] */ + protected array $chain = []; // Массив правил + /** @var array */ + protected array $errorMsg = []; // Массив ошибок /** * Поля по умолчанию @@ -40,7 +40,12 @@ class Validator $this->addRuleList($rules); } - function addRuleType($name, $className) { + /** + * Добавление правила в список + * @param string $name + * @param class-string $className + */ + function addRuleType(string $name, string $className) { $this->type[$name] = $className; } @@ -83,7 +88,7 @@ class Validator } } - public function addRule($rule) { + public function addRule(array|AbstractRule $rule): void { if (is_array($rule)) { $this->chain = array_merge($this->chain, $rule); } else { @@ -93,9 +98,8 @@ class Validator /** * @param AbstractRule $rule - * @param Collection $container */ - public function skip($rule, $container) // -> Rule_Abstract + public function skip($rule, Collection $container) // -> Rule_Abstract { if ($rule->skipEmpty()) { $data = $container->get($rule->field); @@ -111,7 +115,7 @@ class Validator $this->errorMsg = []; } - public function validate(Collection $container, $rule = null, $status = null) + public function validate(Collection $container, $rule = null, $status = null): bool { $fields = []; if ($rule) { diff --git a/src/View/Composite.php b/src/View/Composite.php index 046e18e..bc2101b 100644 --- a/src/View/Composite.php +++ b/src/View/Composite.php @@ -3,7 +3,7 @@ namespace ctiso\View; use ctiso\View\View, PHPTAL; - + class Composite extends View { private $tal; @@ -15,14 +15,14 @@ class Composite extends View $this->tal = new PHPTAL($file); $this->tal->setPhpCodeDestination(PHPTAL_PHP_CODE_DESTINATION); - $this->tal->setEncoding(PHPTAL_DEFAULT_ENCODING); + $this->tal->setEncoding(PHPTAL_DEFAULT_ENCODING); $this->tal->setTemplateRepository(PHPTAL_TEMPLATE_REPOSITORY); $this->tal->setOutputMode(PHPTAL::HTML5); $this->tal->stripComments(true); // $this->tal->addPreFilter(new PHPTAL_PreFilter_Normalize()); } - function set($key, $val) { + function set(string $key, mixed $val) { if ($key == 'title') { $this->setTitle($val); } diff --git a/src/View/Plain.php b/src/View/Plain.php index 8ffc877..032c259 100644 --- a/src/View/Plain.php +++ b/src/View/Plain.php @@ -8,7 +8,7 @@ namespace ctiso\View; class Plain extends \stdClass { protected $document; - protected $values = array(); + protected $values = []; public function __construct ($document) { @@ -36,10 +36,10 @@ class Plain extends \stdClass return self::getTemplateContent ($this->document, $result); } - static function getTemplateContent($document, $result) + static function getTemplateContent(string $document, $result): string { ob_start (); - include ($document); + include ($document); $content = ob_get_contents (); ob_clean (); return $content; diff --git a/src/View/View.php b/src/View/View.php index 377e3ed..70a565e 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -5,23 +5,23 @@ use Exception; class View extends \stdClass { - protected $_section = array(); // Вложенные шаблоны + protected array $_section = []; // Вложенные шаблоны // Блоки - protected $_stylesheet = array(); // Массив стилей текущего шаблона - protected $_script = array(); // Массив скриптов текущего шаблона - public $_scriptstring = array(); - protected $_startup = array(); - protected $_values = array(); + protected array $_stylesheet = []; // Массив стилей текущего шаблона + protected array $_script = []; // Массив скриптов текущего шаблона + public array $_scriptstring = []; + protected array $_startup = []; + protected array $_values = []; - protected $_title = null; // Заголовок текущего шаблона + protected ?string $_title = null; // Заголовок текущего шаблона - public $active_module; - public $module_action; - public $prefix; + public string $active_module; + public string $module_action; + public array $prefix; - public $suggestions; //подсказки + public array $suggestions; //подсказки - public $alias = []; + public array $alias = []; public $codeGenerator = null; public $parent_view = null; @@ -53,7 +53,7 @@ class View extends \stdClass * * @param string $name путь к скрипту */ - public function addScript($name): void + public function addScript(string $name): void { $output = $this->resolveName($this->alias, $name . '?' . http_build_query($this->prefix)); $this->_script [] = $output; @@ -62,18 +62,18 @@ class View extends \stdClass /** * Добавляет код скипта к текущему шаблону * - * @param string $name строка javascript кода + * @param string $code строка javascript кода */ - public function addScriptRaw($name, $startup = false): void + public function addScriptRaw(string $code, bool $startup = false): void { if ($startup) { - $this->_startup [] = $name; + $this->_startup [] = $code; } else { - $this->_scriptstring [] = $name; + $this->_scriptstring [] = $code; } } - public function setPrefix($name, $val) { + public function setPrefix(string $name, string $val): void { $this->prefix[$name] = $val; } @@ -82,7 +82,7 @@ class View extends \stdClass * * @param string $name путь к стилю */ - public function addStyleSheet($name) + public function addStyleSheet(string $name): void { $output = $this->resolveName($this->alias, $name . '?' . http_build_query($this->prefix)); $this->_stylesheet [] = $output; @@ -92,9 +92,9 @@ class View extends \stdClass * Рекурсивно извлекает из значение свойства обьекта * * @param string $list Имя свойства - * @param boolean $flatten + * @param bool $flatten */ - protected function doTree($list, $flatten = true) + protected function doTree($list, bool $flatten = true) { $result = ($flatten == true) ? $this->$list : [$this->$list]; foreach ($this->_section as $value) { @@ -109,7 +109,7 @@ class View extends \stdClass return $result; } - /*abstract*/ public function set($key, $value) + /*abstract*/ public function set(string $key, mixed $value) { } @@ -125,10 +125,8 @@ class View extends \stdClass /** * Установка заголовка шаблона - * - * @param string $title */ - public function setTitle($title): void + public function setTitle(string $title): void { $this->_title = $title; } @@ -143,13 +141,16 @@ class View extends \stdClass $this->alias = $alias; } - function addAlias($name, $path): void + function addAlias(string $name, string $path): void { $this->alias[$name] = $path; $this->set($name, $path); } - function findFile($pathlist, string $file): string { + /** + * @param string[] $pathlist + */ + function findFile(array $pathlist, string $file): string { foreach($pathlist as $key => $www) { if (file_exists($key . '/' . $file)) { @@ -160,7 +161,7 @@ class View extends \stdClass } // FIXME: Префикс, конфликтует с протоколом - function resolveName($alias, $file): string { + function resolveName($alias, string $file): string { list($type, $filename) = explode(":", $file, 2); // Сделать поиск а не просто замену папки при совпадении имени @@ -175,7 +176,7 @@ class View extends \stdClass return $file; } - public function resolveAllNames($alias, $list) { + public function resolveAllNames($alias, array $list): array { $result = []; foreach($list as $item) { $result [] = $this->resolveName($alias, $item); From a58f18c836281a70835e87ada6bf171361bf19c8 Mon Sep 17 00:00:00 2001 From: System Administrator Date: Tue, 7 Oct 2025 12:07:59 +0300 Subject: [PATCH 096/138] =?UTF-8?q?fix:=20=D0=98=D0=BD=D0=B8=D1=86=D0=B8?= =?UTF-8?q?=D0=B0=D0=BB=D0=B8=D0=B7=D0=B0=D1=86=D0=B8=D1=8F=20=D0=BF=D0=B0?= =?UTF-8?q?=D1=80=D0=B0=D0=BC=D0=B5=D1=82=D1=80=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Url.php | 2 +- src/View/View.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Url.php b/src/Url.php index 67e145a..4700e5f 100644 --- a/src/Url.php +++ b/src/Url.php @@ -15,7 +15,7 @@ class Url { $this->parts = $parts; } - function addQueryParam(string $key, string $value): void { + function addQueryParam(string $key, ?string $value): void { $this->parts[$key] = $value; } diff --git a/src/View/View.php b/src/View/View.php index 70a565e..ba3a474 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -15,11 +15,11 @@ class View extends \stdClass protected ?string $_title = null; // Заголовок текущего шаблона - public string $active_module; + public ?string $active_module = null; public string $module_action; public array $prefix; - public array $suggestions; //подсказки + public array $suggestions = []; //подсказки public array $alias = []; public $codeGenerator = null; From ad920f656cc09843119312c8a24688acf666038b Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 7 Oct 2025 13:23:09 +0300 Subject: [PATCH 097/138] =?UTF-8?q?chore:=20=D0=94=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D1=8B=20=D0=B0=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/Functions.php | 5 ++ src/Mail.php | 88 ++++++++++++++--------------- src/MailAlt.php | 8 +-- src/Path.php | 55 ++++++------------ src/SortRecord.php | 9 ++- src/Tales.php | 18 +++--- src/Tools/TemplateImage.php | 15 ++--- src/Url.php | 5 +- src/Validator/Rule/AbstractRule.php | 4 +- src/Validator/Rule/Count.php | 8 +-- src/Validator/Rule/Time.php | 2 +- src/Validator/Validator.php | 18 +++--- src/View/Composite.php | 10 ++-- src/View/View.php | 9 ++- 14 files changed, 127 insertions(+), 127 deletions(-) diff --git a/src/Functions.php b/src/Functions.php index 887d741..66e91f1 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -147,6 +147,7 @@ class Functions { } /** + * @deprecated * @param array $value * @param string $name * @@ -156,11 +157,15 @@ class Functions { return $value[$name]; } + /** + * @deprecated + */ static function identity($value) { return $value; } /** + * @deprecated * @param array $a * @param array $b * @param $key diff --git a/src/Mail.php b/src/Mail.php index 7f3930d..a92e0a4 100644 --- a/src/Mail.php +++ b/src/Mail.php @@ -4,7 +4,9 @@ * Класс для работы с почтой * http://en.wikipedia.org/wiki/MIME */ + namespace ctiso; + use ctiso\Path, Exception; @@ -16,14 +18,15 @@ class Mail public $content; public $copy; - private $encoding; + private $encoding; private $_notify = null; - protected $attachment = array (); + protected $attachment = array(); protected $uniqid; protected $type = "text/plain"; - function __construct() { + function __construct() + { $this->setEncoding("UTF-8"); $this->uniqid = strtoupper(uniqid((string)time())); // Идентефикатор разделителя } @@ -31,32 +34,32 @@ class Mail /** * Установка отправителя */ - function from($name) + function from(string $name) { + // filter_var($name, FILTER_VALIDATE_EMAIL); $this->_from = $name; - } + } /** * Установка получателя */ - function to($name) // recipient + function to(string $name) // recipient { $this->_to = $name; } function replyTo($name) // recipient - { - } + {} /** * Установка получателей копии */ - function copy($name) // recipient cc + function copy(string $name) // recipient cc { $this->copy = $name; } - - function notify($notify) + + function notify(string $notify) { $this->_notify = $notify; } @@ -64,23 +67,23 @@ class Mail /** * Тема письма */ - function subject($subject) + function subject(string $subject) { - $this->_subject = $subject; + $this->_subject = $subject; } /** * Текст письма */ - function setContent($text) + function setContent(string $text) { $this->content = $text; } - + /** * Кодировка текста в письме */ - function setEncoding($encoding) + function setEncoding(string $encoding) { $this->encoding = $encoding; } @@ -88,15 +91,13 @@ class Mail /** * Добавление вложения из файла */ - function addAttachment($filename, $name = false) + function addAttachment(string $filename, $name = false) { - assert(is_string($filename)); - - if(file_exists($filename)) { // assert ?? + if (file_exists($filename)) { // assert ?? $file = fopen($filename, "rb"); if (is_resource($file)) { $data = fread($file, filesize($filename)); - $this->attachment [] = ($name) ? [$data, $name] : [$data, basename($filename)]; + $this->attachment[] = ($name) ? [$data, $name] : [$data, basename($filename)]; } } } @@ -109,11 +110,9 @@ class Mail /** * Добавление вложения из строки с указанием имени файла */ - function addAttachmentRaw($data, $name) + function addAttachmentRaw($data, string $name) { - assert(is_string($name)); - - $this->attachment [] = [$data, $name]; + $this->attachment[] = [$data, $name]; } function quote($var, $val) @@ -127,33 +126,33 @@ class Mail */ function mimeTag($name, $value, array $args = []) { - assert (is_string($name)); - assert (is_string($value)); + assert(is_string($name)); + assert(is_string($value)); - return $name . ": " . $value . implode("", array_map([$this, 'quote'], array_keys($args), array_values($args))) . PHP_EOL; + return $name . ": " . $value . implode("", array_map([$this, 'quote'], array_keys($args), array_values($args))) . PHP_EOL; } /** - * - * @see http://tools.ietf.org/html/rfc2047 + * + * @see http://tools.ietf.org/html/rfc2047 */ - function encodedWord($text, $encoding = 'B') + function encodedWord(string $text, string $encoding = 'B') { - return "=?{$this->encoding}?$encoding?".base64_encode($text)."?="; + return "=?{$this->encoding}?$encoding?" . base64_encode($text) . "?="; } /** * Тело сообщения */ - function getMessage() + function getMessage(): string { - $message = "--".$this->uniqid . PHP_EOL; + $message = "--" . $this->uniqid . PHP_EOL; $message .= $this->mimeTag("Content-Type", $this->type, ['charset' => $this->encoding]); $message .= $this->mimeTag("Content-Transfer-Encoding", "8bit"); $message .= PHP_EOL . $this->content . PHP_EOL . PHP_EOL; /* - * Вложения + * Вложения * http://tools.ietf.org/html/rfc2046#section-5.1.3 */ foreach ($this->attachment as $value) { @@ -171,7 +170,7 @@ class Mail /** * Заголовок сообщения */ - function getHeader() + function getHeader(): string { $head = $this->mimeTag("MIME-Version", "1.0"); $head .= $this->mimeTag("From", $this->_from); @@ -188,7 +187,7 @@ class Mail return $head; } - function getSubject() + function getSubject(): string { return $this->encodedWord($this->_subject); } @@ -196,27 +195,28 @@ class Mail /** * Вывод строки для сохранения в формате .eml */ - function eml() + function eml(): string { return "To: " . $this->_to . PHP_EOL . "Subject: {$this->getSubject()}" . PHP_EOL . $this->getHeader() . $this->getMessage(); } /** - * Отправка почты + * Отправка почты */ - function send() + function send(): bool { $result = mail($this->_to, $this->getSubject(), $this->getMessage(), $this->getHeader()); - if(! $result) { + if (! $result) { file_put_contents(Path::resolveFile("send.eml"), $this->eml()); - throw new Exception('Невозможно отправить почту'); + throw new Exception('Невозможно отправить почту'); } return $result; } - function clear() { + function clear(): void + { foreach ($this->attachment as $key => &$value) { - unset($this->attachment[$key]); + unset($this->attachment[$key]); } $this->attachment = []; } diff --git a/src/MailAlt.php b/src/MailAlt.php index 2775553..1a08d50 100644 --- a/src/MailAlt.php +++ b/src/MailAlt.php @@ -62,12 +62,12 @@ class MailAlt * Текст письма * @param string $text */ - function setContent($text) + function setContent(string $text) { $this->mailer->Body = $text; } - function setType($text) + function setType(string $text) { $this->mailer->isHTML($text == 'text/html'); } @@ -75,7 +75,7 @@ class MailAlt /** * Кодировка текста в письме */ - function setEncoding($encoding) + function setEncoding(string $encoding) { $this->encoding = $encoding; } @@ -83,7 +83,7 @@ class MailAlt /** * Добавление вложения из файла */ - function addAttachment(string $filename, $name = null) + function addAttachment(string $filename, ?string $name = null) { $this->mailer->addAttachment($filename, $name); } diff --git a/src/Path.php b/src/Path.php index aee6a87..2cdbee5 100644 --- a/src/Path.php +++ b/src/Path.php @@ -12,14 +12,13 @@ class Path { const SEPARATOR = "/"; - protected $path = array(); - protected $url = array(); - protected $absolute = false; + protected array $path = []; + protected array $url = []; + protected bool $absolute = false; - public function __construct($path = '') + public function __construct(string $path = '') { - //assert(is_string($path)); - $this->url = parse_url($path ?? ''); + $this->url = parse_url($path); if (isset($this->url['path'])) { $path = $this->url['path']; @@ -36,16 +35,16 @@ class Path } } - static function factory($path) { + static function factory(string $path): Path { return new Path($path); } - public function getParts() + public function getParts(): array { return $this->path; } - public static function normalize($pathName) + public static function normalize(string $pathName): string { $path = new Path($pathName); return $path->__toString(); @@ -84,15 +83,9 @@ class Path /** * Полное имя файла без расширения - * - * @param string $fileName Имя файла - * - * @return string */ - static function skipExtension($fileName) + static function skipExtension(string $fileName): string { - assert(is_string($fileName)); - $path = pathinfo($fileName); if ($path['dirname'] === ".") { return $path['filename']; @@ -108,10 +101,8 @@ class Path * * @return string */ - static function getFileName($fileName) + static function getFileName(string $fileName) { - assert(is_string($fileName)); - return pathinfo($fileName, PATHINFO_FILENAME); } @@ -121,15 +112,10 @@ class Path * Преобразует строку пути в массив * * @param string $path Путь - * - * @return array */ - public static function listFromString($path) + public static function listFromString(string $path): array { - assert(is_string($path)); - $list = preg_split('#\\\\|/#s', $path); - return $list; } @@ -154,11 +140,10 @@ class Path return $result; } - // Сравнение двух путей на равентство /** - * @param Path $path + * Сравнение двух путей на равентство */ - public function equal($path) + public function equal(Path $path): bool { $count = count($this->path); if ($count == count($path->path)) { @@ -172,7 +157,7 @@ class Path return false; } - public static function makeUrl($path) + public static function makeUrl($path): string { $slash = (isset($path['host']) && (strlen($path['path']) > 0) && ($path['path'][0] != '/')) ? '/' : ''; @@ -189,10 +174,8 @@ class Path /** * Преобразует путь в строку - * - * @return string */ - public function __toString() + public function __toString(): string { $result = (($this->absolute) ? '/' : '') . implode(self::SEPARATOR, $this->path); $this->url['path'] = $result; @@ -203,10 +186,8 @@ class Path * Проверяет является ли папка родительской для другой папки * * @param Path $path - * - * @return boolean */ - public function isParent($path) + public function isParent($path): bool { if (isset($this->url['host']) && isset($path->url['host']) && ($this->url['host'] != $path->url['host'])) return false; @@ -223,7 +204,7 @@ class Path return false; } - public static function _isParent($path1, $path2) + public static function _isParent(string $path1, string $path2): bool { $path = new Path($path1); return $path->isParent(new Path($path2)); @@ -421,7 +402,7 @@ class Path return $result; } - protected static function fileListAll(&$result, $base, &$allow, &$ignore) + protected static function fileListAll(array &$result, string $base, ?array &$allow, array &$ignore) { $files = self::fileList($base, $allow, $ignore); foreach ($files as $name) { diff --git a/src/SortRecord.php b/src/SortRecord.php index f1ed4e6..855c85b 100644 --- a/src/SortRecord.php +++ b/src/SortRecord.php @@ -13,6 +13,11 @@ class SortRecord $this->order = ((boolean)($order) === false) ? 1 : -1; } + /** + * @template T + * @param array $a + * @param array $b + */ function compare(array $a, array $b): int { if($a[$this->key] == $b[$this->key]) { @@ -29,12 +34,12 @@ class SortRecord return ($a->{$this->key} > $b->{$this->key}) ? $this->order : -$this->order; } - function sort(array &$list) + function sort(array &$list): bool { return usort($list, [$this, 'compare']); } - function sortKeys(array &$list) + function sortKeys(array &$list): bool { return usort($list, [$this, 'compareKeys']); } diff --git a/src/Tales.php b/src/Tales.php index 21b15cb..400bf24 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -13,12 +13,12 @@ use PHPTAL_Php_TalesInternal, class Tales_DateTime implements PHPTAL_Tales { - static public function date($expression, $nothrow = false): string + static public function date(string $expression, $nothrow = false): string { return "ctiso\\Tales::phptal_date(".PHPTAL_Php_TalesInternal::path($expression).")"; } - static public function time($expression, $nothrow = false): string + static public function time(string $expression, $nothrow = false): string { return "ctiso\\Tales::phptal_time(".PHPTAL_Php_TalesInternal::path($expression).")"; } @@ -26,7 +26,7 @@ class Tales_DateTime implements PHPTAL_Tales class Tales_Component implements PHPTAL_Tales { - static public function component($expression, $nothrow = false): string + static public function component(string $expression, $nothrow = false): string { $s = PHPTAL_Php_TalesInternal::string($expression); return "ctiso\\Tales::phptal_component(" . $s . ")"; @@ -35,7 +35,7 @@ class Tales_Component implements PHPTAL_Tales class Tales_Assets implements PHPTAL_Tales { - static public function assets($expression, $nothrow = false): string + static public function assets(string $expression, $nothrow = false): string { $s = PHPTAL_Php_TalesInternal::string($expression); return "ctiso\\Tales::phptal_asset(" . $s . ")"; @@ -43,18 +43,18 @@ class Tales_Assets implements PHPTAL_Tales } class Tales { - /** @var SiteInterface */ + /** @var ?SiteInterface */ static $site; - static function phptal_date ($e): string { + static function phptal_date (int $e): string { return date("d.m.Y", $e); } - static function phptal_time ($e): string { + static function phptal_time (int $e): string { return date("H:i", $e); } - static function phptal_asset($s): string { + static function phptal_asset(string $s): string { self::$site->addStyleSheet($s); return ""; } @@ -74,7 +74,7 @@ class Tales { } - static function register($site) { + static function register(?SiteInterface $site) { self::$site = $site; /* Регистрация нового префикса для подключения компонента */ diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index 6854bb6..161c68a 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -5,6 +5,7 @@ */ namespace ctiso\Tools; use ctiso\Tools\Drawing; +use GdImage; class TemplateImage { @@ -35,11 +36,11 @@ class TemplateImage protected array $context = []; protected array $data = []; protected string $base = "c:\\windows\\fonts\\"; - protected $image; + protected GdImage $image; protected $_prepare = true; public $debug = false; - public $resource; - public $filename; + public string $resource; + public string $filename; function __construct (?array $template = null) { @@ -66,10 +67,10 @@ class TemplateImage function set(string $name, $value) { - $this->context['['.$name.']'] = $this->encode($value); + $this->context['['.$name.']'] = $value; } - function setImage($name): void + function setImage(string $name): void { $this->filename = $name; $this->image = $this->imagefromfile($name); @@ -140,11 +141,11 @@ class TemplateImage /** * Перекодировка текста - * @deprecated + * @deprecated Можно заменить encode($x) -> $x */ function encode(string $text): string { - return $text; //iconv("WINDOWS-1251", "UTF-8", $text); + return $text; } function setSize(int $new_width, int $new_height): void diff --git a/src/Url.php b/src/Url.php index 67e145a..56b8ddb 100644 --- a/src/Url.php +++ b/src/Url.php @@ -11,7 +11,10 @@ class Url { $this->parent = $parent; } - function setQuery($parts): void { + /** + * @param string[] $parts + */ + function setQuery(array $parts): void { $this->parts = $parts; } diff --git a/src/Validator/Rule/AbstractRule.php b/src/Validator/Rule/AbstractRule.php index 6a7ebef..52619ea 100644 --- a/src/Validator/Rule/AbstractRule.php +++ b/src/Validator/Rule/AbstractRule.php @@ -6,10 +6,10 @@ use ctiso\Collection; abstract class AbstractRule { public string $field; - protected $errorMsg; + protected ?string $errorMsg; protected $ctx; - public function __construct(string $field, $errorMsg = null) + public function __construct(string $field, ?string $errorMsg = null) { $this->field = $field; $this->errorMsg = $errorMsg; diff --git a/src/Validator/Rule/Count.php b/src/Validator/Rule/Count.php index 008e24b..7115587 100644 --- a/src/Validator/Rule/Count.php +++ b/src/Validator/Rule/Count.php @@ -9,15 +9,15 @@ use ctiso\Validator\Rule\AbstractRule, class Count extends AbstractRule { - public $size = 1; - public $max = null; + public int $size = 1; + public ?int $max = null; public function getErrorMsg(): string { return "Количество записей должно быть не менне {$this->size} и не более {$this->max}"; } - function not_empty($s) { + function notEmpty($s): bool { return $s != ""; } @@ -28,7 +28,7 @@ class Count extends AbstractRule $this->max = $this->size; } $count = count(array_filter(array_map('trim', - explode(";", $container->get($this->field))), [$this, 'not_empty'])); + explode(";", $container->get($this->field))), [$this, 'notEmpty'])); return $count >= $this->size && $count <= ((int)$this->max); } diff --git a/src/Validator/Rule/Time.php b/src/Validator/Rule/Time.php index 658e3e8..34534b9 100644 --- a/src/Validator/Rule/Time.php +++ b/src/Validator/Rule/Time.php @@ -9,7 +9,7 @@ use ctiso\Validator\Rule\AbstractRule, class Time extends AbstractRule { - private $split = ":"; + private string $split = ":"; public function getErrorMsg(): string { diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 8abd7dd..2b8bd32 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -17,7 +17,7 @@ class Validator /** * Поля по умолчанию - * @var array> + * @var array> */ protected $type = [ 'date' => Rule\Date::class, @@ -43,9 +43,9 @@ class Validator /** * Добавление правила в список * @param string $name - * @param class-string $className + * @param class-string $className */ - function addRuleType(string $name, string $className) { + function addRuleType(string $name, string $className): void { $this->type[$name] = $className; } @@ -99,7 +99,7 @@ class Validator /** * @param AbstractRule $rule */ - public function skip($rule, Collection $container) // -> Rule_Abstract + public function skip($rule, Collection $container): bool { if ($rule->skipEmpty()) { $data = $container->get($rule->field); @@ -111,7 +111,7 @@ class Validator return false; } - function reset() { + function reset(): void { $this->errorMsg = []; } @@ -121,7 +121,7 @@ class Validator if ($rule) { $this->chain = $rule; } - // $this->errorMsg = []; + foreach ($this->chain as $rule) { //echo $key; if (!in_array($rule->field, $fields) && !$this->skip($rule, $container) && !$rule->isValid($container, $status)) { @@ -133,17 +133,17 @@ class Validator return $this->isValid(); } - public function addError($name, $message) + public function addError(string $name, string $message) { $this->errorMsg[$name] = $message; } - public function isError() + public function isError(): bool { return !empty($this->errorMsg); } - public function isValid() + public function isValid(): bool { return empty($this->errorMsg); } diff --git a/src/View/Composite.php b/src/View/Composite.php index bc2101b..5261ba4 100644 --- a/src/View/Composite.php +++ b/src/View/Composite.php @@ -6,10 +6,10 @@ use ctiso\View\View, class Composite extends View { - private $tal; + private PHPTAL $tal; public $config; - function __construct($file) + function __construct(string $file) { parent::__construct(); @@ -29,17 +29,17 @@ class Composite extends View $this->tal->set($key, $val); } - function __set($key, $val) { + function __set(string $key, mixed $val) { $this->tal->set($key, $val); } - function execute() + function execute(): string { $this->processChild(); return $this->tal->execute(); } - function setTranslator($t) { + function setTranslator($t): void { $this->tal->setTranslator($t); } } diff --git a/src/View/View.php b/src/View/View.php index 70a565e..627d983 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -7,10 +7,15 @@ class View extends \stdClass { protected array $_section = []; // Вложенные шаблоны // Блоки + /** @var string[] $_stylesheet */ protected array $_stylesheet = []; // Массив стилей текущего шаблона + /** @var string[] $_script */ protected array $_script = []; // Массив скриптов текущего шаблона + /** @var string[] $_scriptstring */ public array $_scriptstring = []; + /** @var string[] $_startup */ protected array $_startup = []; + protected array $_values = []; protected ?string $_title = null; // Заголовок текущего шаблона @@ -94,7 +99,7 @@ class View extends \stdClass * @param string $list Имя свойства * @param bool $flatten */ - protected function doTree($list, bool $flatten = true) + protected function doTree($list, bool $flatten = true): array { $result = ($flatten == true) ? $this->$list : [$this->$list]; foreach ($this->_section as $value) { @@ -131,7 +136,7 @@ class View extends \stdClass $this->_title = $title; } - protected function isNotNull($title): bool + protected function isNotNull(?string $title): bool { return $title !== null; } From 09a61244ca1397d3b4159d1bdb0c60fd1e642723 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 16 Oct 2025 11:43:27 +0300 Subject: [PATCH 098/138] =?UTF-8?q?fix:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D1=82=D0=B8=D0=BF=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 16 ++++++++-------- src/Filter/Login.php | 2 +- src/Path.php | 23 +++++++++++++---------- 3 files changed, 22 insertions(+), 19 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 3ccfa11..b4b7957 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -21,13 +21,13 @@ class Action implements ActionInterface const ACTION_PREFIX = "action"; // Префикс для функций действий // Параметры устанавливаются при создании контроллера - public $name = ''; // Имя модуля + public string $name = ''; // Имя модуля public $front; - public $modulePath = null; // Путь к модулю - public $moduleTitle = ''; + public string $modulePath = ''; // Путь к модулю + public string $moduleTitle = ''; - public $viewPathPrefix = ''; // Путь к шаблонам контроллера + public string $viewPathPrefix = ''; // Путь к шаблонам контроллера /** * Соединение с базой данных @@ -40,7 +40,7 @@ class Action implements ActionInterface public $logger = null; // Обьект для ведения лога private $factory = null; // Ссылка на обьект создания модели - private $helpers = array(); // Помошники для действий + private array $helpers = []; // Помошники для действий public $part = null; // Параметры для ссылки /** @var \ctiso\Registry */ @@ -50,9 +50,9 @@ class Action implements ActionInterface // Для Widgets public $view = null; - public $childNodes = array(); - public $ctrlValues = array(); - public $childViews = array(); + public array $childNodes = []; + public array $ctrlValues = []; + public array $childViews = []; function __construct() { $this->part = new Url(); diff --git a/src/Filter/Login.php b/src/Filter/Login.php index ba5a00e..548c033 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -47,7 +47,7 @@ class Login extends Filter switch ($request->getAction()) { // Авторизация по постоянному паролю case 'login': - $login = $request->get('login'); + $login = $request->get('login', '') ; $password = $request->get('password'); $result = $this->role->getUserByLogin($login); // Поиск по логину diff --git a/src/Path.php b/src/Path.php index 2cdbee5..dcb6a2f 100644 --- a/src/Path.php +++ b/src/Path.php @@ -16,7 +16,10 @@ class Path protected array $url = []; protected bool $absolute = false; - public function __construct(string $path = '') + /** + * @param string $path Путь (Тип указан в doccomments т.к откудато приходит null) + */ + public function __construct($path = '') { $this->url = parse_url($path); @@ -264,11 +267,10 @@ class Path /** * Обьединяет строки в Path соединяя необходимым разделителем * fixme не обрабатывает параметры урла, решение Path::join(SITE_WWW_PATH) . '?param=pampam' + * @param string ...$args * @return string */ - static function fromJoin($_rest) { - $args = func_get_args(); - + static function fromJoin(string ...$args) { $result = []; $parts0 = new Path(array_shift($args)); $result [] = $parts0->getParts(); @@ -286,29 +288,30 @@ class Path /** * Обьединяет строки в строку пути соединяя необходимым разделителем * fixme не обрабатывает параметры урла, решение Path::join(SITE_WWW_PATH) . '?param=pampam' + * @param string ...$args * @return string */ - static function join($_rest) + static function join(string ...$args) { - $args = func_get_args(); $path = call_user_func_array([self::class, "fromJoin"], $args); return self::makeUrl($path->url); } // Проверка структуры имени файла - static function checkName($name, $extension) + static function checkName(string $name, string $extension) { return (strlen(pathinfo($name, PATHINFO_FILENAME)) > 0) && (pathinfo($name, PATHINFO_EXTENSION) == $extension); } - static function isCharName($char) + static function isCharName(string $char) { $ch = ord($char); return ((($ch >= ord('a')) && ($ch <= ord('z'))) || (strpos('-._', $char) !== false) || (($ch >= ord('0')) && ($ch <= ord('9')))); } // Проверка имени файла - static function isName($name) { + static function isName(string $name): bool + { if (strlen(trim($name)) == 0) { return false; } @@ -320,7 +323,7 @@ class Path return true; } - public function isAbsolute() + public function isAbsolute(): bool { return $this->absolute; } From 1e27648a121e62be5d6da92708b7b729d7d048d7 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 21 Oct 2025 12:00:06 +0300 Subject: [PATCH 099/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Filter/Login.php | 4 +- src/HttpRequest.php | 22 ++++++++--- src/Mail.php | 46 +++++++++++++++------- src/MailAlt.php | 25 ++++++------ src/Numbers.php | 1 - src/Path.php | 8 ++-- src/Process.php | 60 +++++++++++++++++++---------- src/Settings.php | 49 +++++++++++++++-------- src/Tools/Image.php | 9 +++++ src/Tools/StringUtil.php | 3 +- src/Tools/TemplateImage.php | 3 ++ src/Validator/Rule/AbstractRule.php | 2 +- src/Validator/Validator.php | 2 +- src/View/Pages.php | 13 +++++++ src/View/Plain.php | 29 +++++++++++++- src/View/Top.php | 20 +++++++++- src/View/View.php | 2 +- 17 files changed, 217 insertions(+), 81 deletions(-) diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 548c033..c3c7b32 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -184,9 +184,9 @@ class Login extends Filter return $text; } - /* --------------------- + /** * Проверка на попадание реквеста в белый список - */ + */ public function requestIsWhite(Collection $request) { $module = $request->get('module'); $action = $request->get('action'); diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 459bb82..35b6529 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -14,8 +14,9 @@ use Exception, */ class HttpRequest extends Collection { - + /** @var Session */ public $_session; + /** * Constructor * Stores "request data" in GPC order. @@ -94,6 +95,12 @@ class HttpRequest extends Collection return null; } + /** + * @param string $var + * @param string $key + * @param mixed $val + * @return mixed + */ public function setRawData($var, $key, $val) { $data = parent::get(strtolower($var)); @@ -102,28 +109,31 @@ class HttpRequest extends Collection } } - public function setAction($name) + /** + * @param string $name + */ + public function setAction($name): void { $this->setRawData('get', 'action', $name); } - public function getAction() + public function getAction(): string { $result = $this->getRawData('get', 'action'); return ($result) ? $result : 'index'; } - public function isAjax() + public function isAjax(): bool { return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'); } - public function redirect($url) { + public function redirect($url): void { header('location: ' . $url); exit(); } - static function getProtocol() { + static function getProtocol(): string { return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; } } diff --git a/src/Mail.php b/src/Mail.php index a92e0a4..ca785a0 100644 --- a/src/Mail.php +++ b/src/Mail.php @@ -12,17 +12,27 @@ use ctiso\Path, class Mail { + /** @var string */ public $_from; + /** @var string */ public $_to; + /** @var string */ public $_subject; + /** @var string */ public $content; + /** @var string */ public $copy; + /** @var string */ private $encoding; + /** @var string */ private $_notify = null; + /** @var array */ protected $attachment = array(); + /** @var string */ protected $uniqid; + /** @var string */ protected $type = "text/plain"; function __construct() @@ -34,7 +44,7 @@ class Mail /** * Установка отправителя */ - function from(string $name) + function from(string $name): void { // filter_var($name, FILTER_VALIDATE_EMAIL); $this->_from = $name; @@ -43,23 +53,23 @@ class Mail /** * Установка получателя */ - function to(string $name) // recipient + function to(string $name): void // recipient { $this->_to = $name; } - function replyTo($name) // recipient + function replyTo($name): void // recipient {} /** * Установка получателей копии */ - function copy(string $name) // recipient cc + function copy(string $name): void // recipient cc { $this->copy = $name; } - function notify(string $notify) + function notify(string $notify): void { $this->_notify = $notify; } @@ -67,7 +77,7 @@ class Mail /** * Тема письма */ - function subject(string $subject) + function subject(string $subject): void { $this->_subject = $subject; } @@ -75,7 +85,7 @@ class Mail /** * Текст письма */ - function setContent(string $text) + function setContent(string $text): void { $this->content = $text; } @@ -83,7 +93,7 @@ class Mail /** * Кодировка текста в письме */ - function setEncoding(string $encoding) + function setEncoding(string $encoding): void { $this->encoding = $encoding; } @@ -91,7 +101,7 @@ class Mail /** * Добавление вложения из файла */ - function addAttachment(string $filename, $name = false) + function addAttachment(string $filename, $name = false): void { if (file_exists($filename)) { // assert ?? $file = fopen($filename, "rb"); @@ -102,7 +112,7 @@ class Mail } } - function setType($type) + function setType($type): void { $this->type = $type; } @@ -110,12 +120,16 @@ class Mail /** * Добавление вложения из строки с указанием имени файла */ - function addAttachmentRaw($data, string $name) + function addAttachmentRaw($data, string $name): void { $this->attachment[] = [$data, $name]; } - function quote($var, $val) + /** + * @param string $var + * @param string $val + */ + function quote($var, $val): string { return ";" . PHP_EOL . "\t" . $var . "=\"" . $val . "\""; } @@ -123,8 +137,12 @@ class Mail /** * Общий формат тегов MIME * @see http://tools.ietf.org/html/rfc2045 + * + * @param string $name + * @param string $value + * @param array $args */ - function mimeTag($name, $value, array $args = []) + function mimeTag($name, $value, array $args = []): string { assert(is_string($name)); assert(is_string($value)); @@ -136,7 +154,7 @@ class Mail * * @see http://tools.ietf.org/html/rfc2047 */ - function encodedWord(string $text, string $encoding = 'B') + function encodedWord(string $text, string $encoding = 'B'): string { return "=?{$this->encoding}?$encoding?" . base64_encode($text) . "?="; } diff --git a/src/MailAlt.php b/src/MailAlt.php index 1a08d50..c9cae8a 100644 --- a/src/MailAlt.php +++ b/src/MailAlt.php @@ -5,8 +5,11 @@ use PHPMailer\PHPMailer\PHPMailer; class MailAlt { + /** @var PHPMailer */ public $mailer; + /** @var string */ public $_notify; + /** @var string */ public $encoding; function __construct() { @@ -17,7 +20,7 @@ class MailAlt /** * Установка отправителя */ - function from(string $name) + function from(string $name): void { $this->mailer->setFrom($name); } @@ -25,26 +28,26 @@ class MailAlt /** * Установка получателя */ - function to(string $name) // recipient + function to(string $name): void // recipient { $this->mailer->addAddress($name); } - function replyTo(string $name) // recipient + function replyTo(string $name): void // recipient { - $this->mailer->AddReplyTo($name); + $this->mailer->addReplyTo($name); } /** * Установка получателей копии * @param string $name */ - function copy(string $name) // recipient cc + function copy(string $name): void // recipient cc { $this->mailer->addCC($name); } - function notify(string $notify) + function notify(string $notify): void { $this->_notify = $notify; } @@ -53,7 +56,7 @@ class MailAlt * Тема письма * @param string $subject */ - function subject(string $subject) + function subject(string $subject): void { $this->mailer->Subject = $subject; } @@ -62,12 +65,12 @@ class MailAlt * Текст письма * @param string $text */ - function setContent(string $text) + function setContent(string $text): void { $this->mailer->Body = $text; } - function setType(string $text) + function setType(string $text): void { $this->mailer->isHTML($text == 'text/html'); } @@ -75,7 +78,7 @@ class MailAlt /** * Кодировка текста в письме */ - function setEncoding(string $encoding) + function setEncoding(string $encoding): void { $this->encoding = $encoding; } @@ -83,7 +86,7 @@ class MailAlt /** * Добавление вложения из файла */ - function addAttachment(string $filename, ?string $name = null) + function addAttachment(string $filename, ?string $name = null): void { $this->mailer->addAttachment($filename, $name); } diff --git a/src/Numbers.php b/src/Numbers.php index ed98b61..368db12 100644 --- a/src/Numbers.php +++ b/src/Numbers.php @@ -24,4 +24,3 @@ class Numbers return $result; } } - diff --git a/src/Path.php b/src/Path.php index dcb6a2f..1e435c4 100644 --- a/src/Path.php +++ b/src/Path.php @@ -217,7 +217,6 @@ class Path * Находит путь относительно текущего путя * * @param string $name Полный путь к файлу - * * @return string Относительный путь к файлу */ public function relPath($name) @@ -258,6 +257,9 @@ class Path return implode("/", $result); } + /** + * @param string $path + */ public function append($path) { $base = $this->__toString(); @@ -270,7 +272,7 @@ class Path * @param string ...$args * @return string */ - static function fromJoin(string ...$args) { + static function fromJoin(...$args) { $result = []; $parts0 = new Path(array_shift($args)); $result [] = $parts0->getParts(); @@ -291,7 +293,7 @@ class Path * @param string ...$args * @return string */ - static function join(string ...$args) + static function join(...$args) { $path = call_user_func_array([self::class, "fromJoin"], $args); return self::makeUrl($path->url); diff --git a/src/Process.php b/src/Process.php index a1728f5..fd319f9 100644 --- a/src/Process.php +++ b/src/Process.php @@ -2,25 +2,39 @@ namespace ctiso; -if (!function_exists('str_getcsv')) { - function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") { - $fiveMBs = 1024; - $fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+'); - $data = ''; - if (is_resource($fp)) { - fputs($fp, $input); - rewind($fp); - $data = fgetcsv($fp, 1000, $delimiter, $enclosure); - fclose($fp); - } - return $data; - } +/** + * str_getcsv + * @param string $input + * @param string $delimiter + * @param string $enclosure + * @param string $escape + * @return array + */ +function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") +{ + $fiveMBs = 1024; + $fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+'); + $data = ''; + if (is_resource($fp)) { + fputs($fp, $input); + rewind($fp); + $data = fgetcsv($fp, 1000, $delimiter, $enclosure); + fclose($fp); + } + return $data; } -function process_exists($pid) { + +/** + * process_exists + * @param int $pid + * @return bool + */ +function process_exists($pid) +{ if (PHP_OS == 'WINNT') { $processes = explode("\n", shell_exec("tasklist.exe /NH /FO CSV")); - foreach($processes as $process) { + foreach ($processes as $process) { if ($process != "") { $csv = str_getcsv($process); if ($pid == $csv[1]) return true; @@ -32,13 +46,19 @@ function process_exists($pid) { } } -function create_single_proces($fpid, $fn) { +/** + * create_single_proces + * @param string $fpid + * @param callable $fn + * @return int + */ +function create_single_process($fpid, $fn) +{ if (file_exists($fpid)) { - print_r(realpath($fpid)); - if (process_exists(file_get_contents($fpid))) { - return 1; + if (process_exists((int)file_get_contents($fpid))) { + return 1; } - } + } call_user_func($fn); return 0; } diff --git a/src/Settings.php b/src/Settings.php index 1f38299..d87e266 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -5,21 +5,30 @@ use ctiso\File, Exception; /** - * Класс реестра + * Класс реестра * Реестр организован как ассоциативный многомерный массив * array( 'name1' => parameters1, 'name2' => parameters1, ... ) * - * name1, name2 ... - Имена модулей + * name1, name2 ... - Имена модулей * parameters1, parameters1 - Массивы с параметрами модуля * Имя необходимо чтобы потом легко было удалить ненужные ветки дерева */ class Settings { + /** @var array */ public $data = []; + /** @var string */ protected $file; + /** @var string */ protected $format = 'php'; + /** @var bool */ protected $is_read = false; + /** + * Конструктор + * @param string $file Путь к файлу + * @param 'php'|'json'|false $format Формат файла + */ public function __construct ($file = null, $format = false) { $fileFormat = ['theme' => 'json']; @@ -33,7 +42,7 @@ class Settings * Чтение настроек из файла * @return Boolean */ - public function read() + public function read(): bool { if (!file_exists ($this->file)) { $this->is_read = true; @@ -59,7 +68,7 @@ class Settings /** * Запись ключа в реестр (Реестр это многомерный массив) */ - public function writeKey(array $key, $value) + public function writeKey(array $key, $value) { // assert(count($key) >= 1); $data = &$this->data; @@ -67,8 +76,8 @@ class Settings while (count($key) > 1) { $name = array_shift($key); $data = &$data[$name]; - } - + } + // assert(count($key) == 1); $name = array_shift($key); if (is_array($value)) { @@ -97,14 +106,20 @@ class Settings } /** - * Чтение ключа из реестра + * Чтение ключа из реестра * @param array $key Путь к значению ключа + * @return mixed */ public function readKey(array $key) { return $this->readKeyData($key, $this->data); } + /** + * Чтение ключа из реестра + * @param array $key Путь к значению ключа + * @return mixed + */ protected function readKeyData(array $key, $data) { // assert(count($key) >= 1); @@ -115,8 +130,8 @@ class Settings } else { return null; } - } - + } + // assert(count($key) == 1); $name = array_shift($key); if (isset($data[$name])) { @@ -131,7 +146,7 @@ class Settings * @param mixed $key Путь к значению ключа внутри модуля */ public function readKeyList(...$key) - { + { $result = []; foreach ($this->data as $name => $value) { $output = $this->readKeyData($key, $value); @@ -142,13 +157,17 @@ class Settings return $result; } - public function removeKey($name) + /** + * Удаление ключа из реестра + * @param string $name Имя ключа + */ + public function removeKey($name): void { unset($this->data[$name]); } - public function removeNode(array $key) + public function removeNode(array $key): void { $data = &$this->data; while (count($key) > 1) { @@ -158,11 +177,11 @@ class Settings $name = array_shift($key); unset($data[$name]); } - + /** * Запись настроек в файл (Может переименовать в store) * - * @param File $file + * @param File $file * @return void */ public function write($file = null) @@ -198,7 +217,7 @@ class Settings } /** - * Список модулей/ключей + * Список модулей/ключей */ public function getKeys() { diff --git a/src/Tools/Image.php b/src/Tools/Image.php index b1c2395..31e1c7c 100644 --- a/src/Tools/Image.php +++ b/src/Tools/Image.php @@ -6,6 +6,10 @@ use GdImage; class Image { + /** + * @param $uri + * @return GdImage|false + */ static function load($uri): GdImage|false { $e = strtolower(pathinfo($uri, PATHINFO_EXTENSION)); @@ -32,6 +36,11 @@ class Image return $image_p; } + /** + * @param GdImage $image + * @param string $uri + * @return bool + */ static function save($image, $uri): bool { $e = strtolower(pathinfo($uri, PATHINFO_EXTENSION)); diff --git a/src/Tools/StringUtil.php b/src/Tools/StringUtil.php index 87e5db7..661c14b 100644 --- a/src/Tools/StringUtil.php +++ b/src/Tools/StringUtil.php @@ -51,11 +51,10 @@ class StringUtil { } //Проверка равенства двух строк на русском языке. - static function equalRussianCheck($str1,$str2) { + static function equalRussianCheck($str1,$str2): bool { return self::normalizeRussian($str1) == self::normalizeRussian($str2); } - /** * Попадает ли строка в список вариантов * input: $str="foo1" $variants="foo1|foo2|foo3" diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index 161c68a..62c8e9c 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -32,12 +32,15 @@ class TemplateImage ); + /** @var string */ protected $src; protected array $context = []; protected array $data = []; protected string $base = "c:\\windows\\fonts\\"; protected GdImage $image; + /** @var bool */ protected $_prepare = true; + /** @var bool */ public $debug = false; public string $resource; public string $filename; diff --git a/src/Validator/Rule/AbstractRule.php b/src/Validator/Rule/AbstractRule.php index 52619ea..052d4a7 100644 --- a/src/Validator/Rule/AbstractRule.php +++ b/src/Validator/Rule/AbstractRule.php @@ -21,7 +21,7 @@ abstract class AbstractRule return $this; } - public function setErrorMsg($errorMsg): self + public function setErrorMsg(?string $errorMsg): self { $this->errorMsg = $errorMsg; return $this; diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 2b8bd32..f6acfee 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -55,7 +55,7 @@ class Validator * fieldname - Имя переменой для проверки * ruletext - Описание правила см. формат правила ниже */ - public function addRuleList(array $input) + public function addRuleList(array $input): void { // Разбор правила проверки // Формат правила 'rule1|rule2,param1=value1|rule3,param1=value1,param2=value2' diff --git a/src/View/Pages.php b/src/View/Pages.php index a37633b..a5f2170 100644 --- a/src/View/Pages.php +++ b/src/View/Pages.php @@ -8,6 +8,14 @@ namespace ctiso\View; class Pages { static int $range = 5; + + /** + * @param int $page номер страницы + * @param int $onpage количество страниц на странице + * @param int $count количество всех страниц + * @param string $prefix префикс + * @return array{'all': bool, 'list': array, 'first': string, 'last': string, 'next': string, 'prev': string} + */ static function getPages($page, $onpage, $count, $prefix = '?') { $n = ceil($count / $onpage); @@ -51,6 +59,11 @@ class Pages ]; } + /** + * @param string $prefix префикс + * @param string $x строка + * @return string + */ static function href($prefix, $x) { return $prefix . $x; } diff --git a/src/View/Plain.php b/src/View/Plain.php index 032c259..feb617c 100644 --- a/src/View/Plain.php +++ b/src/View/Plain.php @@ -7,35 +7,60 @@ namespace ctiso\View; */ class Plain extends \stdClass { + /** @var string */ protected $document; + /** @var array */ protected $values = []; + /** + * Конструктор + * @param string $document шаблон + */ public function __construct ($document) { $this->document = $document; } + /** + * Установка значения + * @param string $key ключ + * @param mixed $value значение + */ public function set($key, $value) { $this->values[$key] = $value; } - public function import($list) + /** + * Импорт значений + * @param array $list список значений + */ + public function import($list): void { $this->values = array_merge($this->values, $list); } - public function __set($key, $value) + public function __set($key, $value): void { $this->set($key, $value); } + /** + * Выполнение шаблона + * @return string + */ public function execute() { $result = $this->values; return self::getTemplateContent ($this->document, $result); } + /** + * Получение содержимого шаблона + * @param string $document шаблон + * @param array $result результат + * @return string содержимое шаблона + */ static function getTemplateContent(string $document, $result): string { ob_start (); diff --git a/src/View/Top.php b/src/View/Top.php index ed707d2..17f81f0 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -13,11 +13,22 @@ class Top extends Composite public $require = array(); public $deps = array(); + /** + * Заголовок страницы + * + * @return string + */ public function getTitle() { return implode(" - ", array_filter($this->doTree('_title', false), [$this, 'isNotNull'])); } + /** + * Идентификатор + * + * @param string $pref + * @return string + */ function getId($pref) { $this->mid++; @@ -97,7 +108,7 @@ class Top extends Composite /** * Массив имен файлов скриптов * - * return array + * @return array */ public function getScripts() { @@ -114,6 +125,11 @@ class Top extends Composite return implode("\n", $this->doTree('_scriptstring')); } + /** + * Строка со скриптом + * + * @return string + */ public function getScriptStartup() { return implode("\n", $this->doTree('_startup')); @@ -122,7 +138,7 @@ class Top extends Composite /** * Массив имен файлов стилей * - * return array + * @return array */ public function getStyleSheet() { diff --git a/src/View/View.php b/src/View/View.php index 807892e..e35f147 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -39,7 +39,7 @@ class View extends \stdClass * @param string $section переменная шаблона * @param View|string $view вложенный шаблон */ - public function setView($section, $view) + public function setView($section, $view): void { $this->_section [$section] = $view; if (is_object($view)) { From e2ba6bd46ec5e3136f46bb4726718af2cec33249 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 21 Oct 2025 15:55:49 +0300 Subject: [PATCH 100/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Collection.php | 24 ++++++++++++++---------- src/HttpRequest.php | 7 ++++++- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index 027eb30..b15f3c0 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -7,12 +7,8 @@ namespace ctiso; */ class Collection implements \ArrayAccess { - /** - * Holds collective request data - * - * @var array - */ - protected $data = array(); + /** @var array */ + protected $data = []; /** * Преобразование массива в коллекцию @@ -34,8 +30,7 @@ class Collection implements \ArrayAccess } /** - * Store "request data" in GPC order. - * + * @param string $key * @param mixed $value * @@ -50,7 +45,6 @@ class Collection implements \ArrayAccess * Read stored "request data" by referencing a key. * * @param string $key - * * @return mixed */ public function get($key, $default = null) @@ -58,12 +52,22 @@ class Collection implements \ArrayAccess return isset($this->data[$key]) && $this->data[$key] != '' ? $this->data[$key] : $default; } + /** + * @param string $key + * @param int $default + * @return int + */ public function getInt($key, $default = 0) { return (int)$this->get($key, $default); } - public function getString($key, $default = '') + /** + * @param string $key + * @param string $default + * @return string + */ + public function getString(string $key, string $default = ''): string { return (string)$this->get($key, $default); } diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 35b6529..b3fb8a3 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -48,7 +48,7 @@ class HttpRequest extends Collection } /** - * @param T $key + * @param string $key * @return mixed */ function get($key, $default = null) @@ -56,6 +56,11 @@ class HttpRequest extends Collection return parent::get('data')->get($key, $default); } + function getString(string $key, string $default = ''): string + { + return parent::get('data')->getString($key, $default); + } + function session(?Session $value = null) { if ($value) { From e5713e90156c36e80b04ca8b4c7ef7a729eecdc0 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 22 Oct 2025 17:48:37 +0300 Subject: [PATCH 101/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Database/Statement.php | 22 ++++++- src/Excel/Table.php | 8 +-- src/Filter/Authorization.php | 20 +++++-- src/Form/CheckBox.php | 3 +- src/Form/Field.php | 17 ++++-- src/Form/Form.php | 14 ++++- src/Form/Hidden.php | 1 + src/Form/QuestionType.php | 2 +- src/Form/SelectMany.php | 2 +- src/Form/SelectOne.php | 2 +- src/Form/TextArea.php | 4 +- src/Form/ViewState.php | 16 +++-- src/Functions.php | 7 +-- src/Model/Factory.php | 7 ++- src/Path.php | 40 +++++++++---- src/Primitive.php | 1 - src/Registry.php | 3 +- src/Role/User.php | 15 +++-- src/Settings.php | 15 ++++- src/Setup.php | 42 +++++++++---- src/Tales.php | 8 +-- src/Tools/Drawing.php | 24 +++++++- src/Tools/Image.php | 2 +- src/Tools/StringUtil.php | 112 ++++++++++++++++++++++++++--------- src/Validator/Validator.php | 14 ++++- src/View/Composite.php | 3 +- src/View/Top.php | 7 ++- src/View/View.php | 4 ++ 28 files changed, 305 insertions(+), 110 deletions(-) diff --git a/src/Database/Statement.php b/src/Database/Statement.php index 387221f..132b305 100644 --- a/src/Database/Statement.php +++ b/src/Database/Statement.php @@ -4,16 +4,23 @@ * Класс оболочка для PDOStatement для замены Creole */ namespace ctiso\Database; -use PDO, - ctiso\Database; + +use PDO; +use ctiso\Database; class Statement { + /** @var ?int */ protected $limit = null; + /** @var ?int */ protected $offset = null; + /** @var never */ protected $statement = null; - protected $binds = array(); + /** @var array{int|string, mixed, int}[] */ + protected $binds = []; + /** @var Database */ protected $conn; + /** @var string */ protected $query; /** @@ -37,14 +44,23 @@ class Statement $this->binds [] = [$n, $value, PDO::PARAM_LOB]; } + /** + * @param int $limit + */ function setLimit($limit) { $this->limit = $limit; } + /** + * @param int $offset + */ function setOffset($offset) { $this->offset = $offset; } + /** + * @return ?PDOStatement + */ function executeQuery() { if ($this->limit) { $this->query .= " LIMIT {$this->limit} OFFSET {$this->offset}"; diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 4ce28a3..26d9354 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -26,7 +26,7 @@ class TableCell class TableRow { public $style = false; - public $cells = array(); + public $cells = []; public $height = false; function setCell($y, $value) @@ -48,7 +48,7 @@ class Table static $index; private $name; private $style; - protected $rows = array(); + protected $rows = []; protected $_splitVertical = false; protected $_splitHorizontal = false; @@ -106,9 +106,9 @@ class Table * @param int $row Номер ряда * @param string $name Имя стиля */ - function setRowStyle ($row, $name) + function setRowStyle(int $row, $name) { - assert(is_numeric($row) && $row > 0); + assert($row > 0); $this->rows[$row]->style = $name; } diff --git a/src/Filter/Authorization.php b/src/Filter/Authorization.php index 8510433..5521f72 100644 --- a/src/Filter/Authorization.php +++ b/src/Filter/Authorization.php @@ -5,12 +5,19 @@ namespace ctiso\Filter; class Authorization { const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#'; const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; + /** @var string */ public $group; + /** + * @param string $group + */ function __construct($group) { $this->group = $group; } + /** + * @param string $group + */ static function isLogged($group = 'access') { // echo session_status(); if (session_status() == PHP_SESSION_NONE) { @@ -29,6 +36,10 @@ class Authorization { return false; } + /** + * @param int $id + * @param string $group + */ static function enter($id, $group = 'access') { // $db->executeQuery("UPDATE visitor SET sid = '' WHERE id_visitor = " . $result->getInt('id_user')); // session_register("access"); @@ -40,7 +51,7 @@ class Authorization { $_SESSION ["time"] = time(); } - static function getRawSign() + static function getRawSign(): string { $rawSign = self::SESSION_BROWSER_SIGN_SECRET; $signParts = ['HTTP_USER_AGENT']; @@ -48,17 +59,16 @@ class Authorization { foreach ($signParts as $signPart) { $rawSign .= '::' . ($_SERVER[$signPart] ?? 'none'); } - + return $rawSign; } - static function getBrowserSign() + static function getBrowserSign(): string { - return md5(self::getRawSign()); } - function logout() { + function logout(): void { session_destroy(); } } diff --git a/src/Form/CheckBox.php b/src/Form/CheckBox.php index 6eb1619..fd1fa2a 100644 --- a/src/Form/CheckBox.php +++ b/src/Form/CheckBox.php @@ -5,8 +5,9 @@ use ctiso\Form\Field; class CheckBox extends Field { + /** @var bool */ public $checked = false; - function setValue($value) + function setValue($value): void { $this->value = $value; $this->checked = $value; diff --git a/src/Form/Field.php b/src/Form/Field.php index a76fbe2..cda2068 100644 --- a/src/Form/Field.php +++ b/src/Form/Field.php @@ -6,22 +6,31 @@ namespace ctiso\Form; class Field { + /** @var bool */ public $hidden = false; + /** @var string */ public $name; + /** @var string */ public $label; // Метка поля + public $value; // Значение поля + /** @var string */ public $type = ""; // Каждому типу элемента соответствует макрос TAL + /** @var ?string */ public $error_msg = null; public $default = null; public $error = false; public $require = false; public $hint = null; + /** @var ?int */ public $maxlength = null; public $fieldset = null; // Блоки (Убрать в отдельный класс!!!) - public $_title = array(); + public $_title = []; + /** @var string */ public $description = ""; - public $alias = array(); + /** @var array */ + public $alias = []; /** @phpstan-ignore-next-line */ public function __construct ($input = [], $factory = null) @@ -44,12 +53,12 @@ class Field /** * @param mixed $value */ - function setValue($value) + function setValue($value): void { $this->value = $value; } - function getId() + function getId(): string { return $this->name . '_label'; } diff --git a/src/Form/Form.php b/src/Form/Form.php index 30450d8..8d38943 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -16,18 +16,26 @@ use ctiso\Form\Field, * Форма для ввода */ class Form { + /** @var array */ public $field = []; //Поля формы + /** @var array */ public $fieldsets = []; //Группы полей (fieldset). Некоторые поля могут не принадлежать никаким группам + /** @var string */ public $action = ""; + /** @var string */ public $method = 'post'; + /** @var string */ public $header; protected $replace; protected $before; + /** @var array */ public $_title = []; + /** @var array */ public $alias = []; + /** @var class-string[] */ private $constructor = []; /** @@ -119,7 +127,6 @@ class Form { /** * Добавление массива fieldset на форму */ - public function addFieldSetList(array $list) { foreach ($list as $fieldset) { @@ -150,6 +157,11 @@ class Form { } } + /** + * Устанавливает ошибку для поля + * @param string $name + * @param string $message + */ function setFieldError($name, $message) { $this->field[$name]->error = true; diff --git a/src/Form/Hidden.php b/src/Form/Hidden.php index 535e21b..6e3df61 100644 --- a/src/Form/Hidden.php +++ b/src/Form/Hidden.php @@ -4,5 +4,6 @@ namespace ctiso\Form; use ctiso\Form\Input; class Hidden extends Input { + /** @var bool */ public $hidden = true; } diff --git a/src/Form/QuestionType.php b/src/Form/QuestionType.php index a2e7ae0..3a3a9a5 100644 --- a/src/Form/QuestionType.php +++ b/src/Form/QuestionType.php @@ -5,7 +5,7 @@ use ctiso\Form\Select; class QuestionType extends Select { - function setValue($value) + function setValue($value): void { // Установить selected у options $this->value = $value; diff --git a/src/Form/SelectMany.php b/src/Form/SelectMany.php index 86f4295..9ca752d 100644 --- a/src/Form/SelectMany.php +++ b/src/Form/SelectMany.php @@ -5,7 +5,7 @@ use ctiso\Form\Select; class SelectMany extends Select { - function setValue($value) + function setValue(mixed $value): void { // Установить selected у options if (!is_array($value)) { $value = [$value]; } diff --git a/src/Form/SelectOne.php b/src/Form/SelectOne.php index d2dc842..d631d81 100644 --- a/src/Form/SelectOne.php +++ b/src/Form/SelectOne.php @@ -8,7 +8,7 @@ use ctiso\Form\Select; class SelectOne extends Select { - function setValue($value) + function setValue($value): void { // Установить selected у options $this->value = $value; diff --git a/src/Form/TextArea.php b/src/Form/TextArea.php index 50ce417..01e60e0 100644 --- a/src/Form/TextArea.php +++ b/src/Form/TextArea.php @@ -1,13 +1,13 @@ value = $value; } diff --git a/src/Form/ViewState.php b/src/Form/ViewState.php index c9c6831..f22545d 100644 --- a/src/Form/ViewState.php +++ b/src/Form/ViewState.php @@ -1,6 +1,6 @@ values[$name] = $value; } - function get($_rest) + function get($_rest) { $args = func_get_args(); $result = $this->values; @@ -28,7 +34,7 @@ class ViewState // extends Collection return $result; } - function saveState() + function saveState(): string { return base64_encode(serialize($this->values)); } diff --git a/src/Functions.php b/src/Functions.php index 66e91f1..dc98a18 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -1,15 +1,10 @@ 0) && ($path['path'][0] != '/')) ? '/' : ''; @@ -231,7 +235,12 @@ class Path return $path->__toString(); } - // Вычисляет относительный путь в виде строки + /** + * Вычисляет относительный путь в виде строки + * @param string $rpath Путь относительно которого вычисляется относительный путь + * @param string $lpath Путь к которому вычисляется относительный путь + * @return string Относительный путь + */ static function relative($rpath, $lpath) { // Нужно проверять диск!! $self = new Path($rpath); @@ -259,6 +268,7 @@ class Path /** * @param string $path + * @return string */ public function append($path) { @@ -300,12 +310,12 @@ class Path } // Проверка структуры имени файла - static function checkName(string $name, string $extension) + static function checkName(string $name, string $extension): bool { return (strlen(pathinfo($name, PATHINFO_FILENAME)) > 0) && (pathinfo($name, PATHINFO_EXTENSION) == $extension); } - static function isCharName(string $char) + static function isCharName(string $char): bool { $ch = ord($char); return ((($ch >= ord('a')) && ($ch <= ord('z'))) || (strpos('-._', $char) !== false) || (($ch >= ord('0')) && ($ch <= ord('9')))); @@ -354,10 +364,10 @@ class Path /** * Список файлов в директории * - * @param ?array $allow массив расширений для файлов - * @param array $ignore массив имен пааок которые не нужно обрабатывать + * @param ?string[] $allow массив расширений для файлов + * @param string[] $ignore массив имен пааок которые не нужно обрабатывать * - * @returnarray + * @return string[] */ public function getContent(?array $allow = null, array $ignore = []) { @@ -368,10 +378,10 @@ class Path /** * Обьединяет строки в путь соединяя необходимым разделителем * - * @param ?array $allow массив расширений разрешеных для файлов - * @param array $ignore массив имен пааок которые не нужно обрабатывать + * @param ?string[] $allow массив расширений разрешеных для файлов + * @param string[] $ignore массив имен папок которые не нужно обрабатывать * - * @return array + * @return string[] */ function getContentRec(?array $allow = null, array $ignore = []) { @@ -381,7 +391,15 @@ class Path return $result; } - // Использовать SPL ??? + /** + * Список файлов в директории + * + * @param string $base Базовый путь + * @param ?string[] $allow массив расширений для файлов + * @param string[] $ignore массив имен папок которые не нужно обрабатывать + * + * @return string[] + */ protected static function fileList(string $base, ?array &$allow, array &$ignore): array { if ($base == '') $base = '.'; @@ -407,7 +425,7 @@ class Path return $result; } - protected static function fileListAll(array &$result, string $base, ?array &$allow, array &$ignore) + protected static function fileListAll(array &$result, string $base, ?array &$allow, array &$ignore): void { $files = self::fileList($base, $allow, $ignore); foreach ($files as $name) { diff --git a/src/Primitive.php b/src/Primitive.php index 4385c77..8a5a10d 100644 --- a/src/Primitive.php +++ b/src/Primitive.php @@ -3,7 +3,6 @@ /** * Преобразование типов !!! Пересмотреть использование классов!! * Класс преобразования типа значения поля класса в тип поля таблицы - * @package system */ namespace ctiso; diff --git a/src/Registry.php b/src/Registry.php index e2e1a5e..bab923c 100644 --- a/src/Registry.php +++ b/src/Registry.php @@ -5,8 +5,7 @@ use ctiso\File, Exception; class Registry { - public array $namespace = []; - public $data; + private array $namespace = []; function importFile(string $namespace, ?string $filePath = null) { $data = json_decode(File::getContents($filePath), true); diff --git a/src/Role/User.php b/src/Role/User.php index 44c5683..c9d68cc 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -1,8 +1,10 @@ executeQuery(); if ($result->next()) { @@ -56,7 +59,7 @@ class User implements UserInterface return $result->get('password'); } - public function getUserByLogin(string $login) + public function getUserByLogin(string $login): ?PDOStatement { $stmt = $this->db->prepareStatement("SELECT * FROM users WHERE login = ?"); $stmt->setString(1, $login); @@ -69,7 +72,7 @@ class User implements UserInterface return $result; } - public function getUserById(int $id) + public function getUserById(int $id): ?PDOStatement { $stmt = $this->db->prepareStatement("SELECT * FROM users WHERE id_user = ?"); $stmt->setInt(1, $_SESSION ['access']); diff --git a/src/Settings.php b/src/Settings.php index d87e266..b9b67fa 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -199,10 +199,20 @@ class Settings file_put_contents (($file) ? $file : $this->file, $result); } - public function set($key, $value) { + /** + * Установка значения ключа + * @param string $key Ключ + * @param mixed $value Значение + */ + public function set($key, $value): void { $this->data[$key] = $value; } + /** + * Получение значения ключа + * @param string $key Ключ + * @return mixed + */ public function get($key, $default = null) { return isset($this->data[$key]) && $this->data[$key] != '' ? $this->data[$key] : $default; @@ -218,6 +228,7 @@ class Settings /** * Список модулей/ключей + * @return array */ public function getKeys() { @@ -226,6 +237,8 @@ class Settings /** * Проверка наличия ключа + * @param string $name Ключ + * @return bool */ public function hasKey($name) { diff --git a/src/Setup.php b/src/Setup.php index 836579c..eac9518 100644 --- a/src/Setup.php +++ b/src/Setup.php @@ -13,28 +13,44 @@ use ctiso\Path; use SimpleXMLElement; class FakeZipArchive { + /** @var string */ public $base; - function open($path) { + + function open(string $path) { $this->base = $path; } + /** + * Возвращает содержимое файла + * @param string $file + * @return string + */ function getFromName($file) { - return file_get_contents(Path::join($this->base, $file)); + return file_get_contents(Path::join($this->base, $file)); } } class Setup { - protected $actions = array(); - public $context = array(); + /** @var array */ + protected $actions = []; + /** @var array */ + public $context = []; + /** @var string */ protected $file; + /** @var string */ protected $action; + /** @var SimpleXMLElement */ protected $node; - protected $stack = array(); + /** @var array */ + protected $stack = []; + /** @var FakeZipArchive */ public $zip; + /** @var string */ public $target; + /** @var string */ public $source; public function __construct($file) @@ -58,14 +74,18 @@ class Setup /** * Регистрация новых действия для установки + * @param string $name + * @param callable $action */ - public function registerAction(string $name, $action) + public function registerAction(string $name, $action): void { $this->actions[$name] = $action; } /** * Установка переменных для шаблона + * @param string $name + * @param mixed $value */ public function set(string $name, $value) { @@ -188,7 +208,7 @@ class Setup $setup->executeActions(); } - function targetPath($s) { + function targetPath(string $s): string { return $this->target . '/' . $s; } @@ -198,7 +218,7 @@ class Setup * * @param array{dst:string} $attributes */ - public function makeDirectory(array $attributes) + public function makeDirectory(array $attributes): void { $path = $this->targetPath($attributes['dst']); if (!file_exists($path)) { @@ -206,7 +226,7 @@ class Setup } } - function testWhen(array $attributes) + function testWhen(array $attributes): void { if (!isset($attributes['test']) || $attributes['test'] == $this->action) { $this->executeActions($this->action); @@ -218,7 +238,7 @@ class Setup * @param Database $conn * @param string $file */ - function batchSQLZip($conn, $file) + function batchSQLZip($conn, $file): void { $stmtList = SQLStatementExtractor::extract($this->zip->getFromName($file)); foreach ($stmtList as $stmt) { @@ -231,7 +251,7 @@ class Setup * @param Database $conn * @param string $file */ - static function batchSQL($conn, $file) + static function batchSQL($conn, $file): void { $stmtList = SQLStatementExtractor::extractFile($file); foreach ($stmtList as $stmt) { diff --git a/src/Tales.php b/src/Tales.php index 400bf24..214991b 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -13,12 +13,12 @@ use PHPTAL_Php_TalesInternal, class Tales_DateTime implements PHPTAL_Tales { - static public function date(string $expression, $nothrow = false): string + static public function date(string $expression, bool $nothrow = false): string { return "ctiso\\Tales::phptal_date(".PHPTAL_Php_TalesInternal::path($expression).")"; } - static public function time(string $expression, $nothrow = false): string + static public function time(string $expression, bool $nothrow = false): string { return "ctiso\\Tales::phptal_time(".PHPTAL_Php_TalesInternal::path($expression).")"; } @@ -26,7 +26,7 @@ class Tales_DateTime implements PHPTAL_Tales class Tales_Component implements PHPTAL_Tales { - static public function component(string $expression, $nothrow = false): string + static public function component(string $expression, bool $nothrow = false): string { $s = PHPTAL_Php_TalesInternal::string($expression); return "ctiso\\Tales::phptal_component(" . $s . ")"; @@ -35,7 +35,7 @@ class Tales_Component implements PHPTAL_Tales class Tales_Assets implements PHPTAL_Tales { - static public function assets(string $expression, $nothrow = false): string + static public function assets(string $expression, bool $nothrow = false): string { $s = PHPTAL_Php_TalesInternal::string($expression); return "ctiso\\Tales::phptal_asset(" . $s . ")"; diff --git a/src/Tools/Drawing.php b/src/Tools/Drawing.php index 56183b6..80bb92d 100644 --- a/src/Tools/Drawing.php +++ b/src/Tools/Drawing.php @@ -12,7 +12,15 @@ class Drawing const ALIGN_CENTER = "center"; const ALIGN_RIGHT = "right"; - static function drawrectnagle(GdImage &$image, int $left, int $top, int $width, int $height, array $rgb): void + /** + * @param GdImage $image + * @param int $left + * @param int $top + * @param int $width + * @param int $height + * @param array $rgb + */ + static function drawRectangle(GdImage &$image, int $left, int $top, int $width, int $height, array $rgb): void { $color = imagecolorallocate($image, $rgb[0], $rgb[1], $rgb[2]); $right = $left + $width; @@ -25,6 +33,19 @@ class Drawing /** * http://ru2.php.net/imagettftext + * + * @param GdImage $image + * @param int $size + * @param float $angle + * @param int $left + * @param int $top + * @param int $color + * @param string $font + * @param string $text + * @param int $max_width + * @param int $max_height + * @param string $align + * @param string $valign */ static function imagettftextbox( GdImage &$image, @@ -115,7 +136,6 @@ 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) { if ($spacing == 0) { diff --git a/src/Tools/Image.php b/src/Tools/Image.php index 31e1c7c..646c7d9 100644 --- a/src/Tools/Image.php +++ b/src/Tools/Image.php @@ -7,7 +7,7 @@ use GdImage; class Image { /** - * @param $uri + * @param string $uri * @return GdImage|false */ static function load($uri): GdImage|false diff --git a/src/Tools/StringUtil.php b/src/Tools/StringUtil.php index 661c14b..aba87c3 100644 --- a/src/Tools/StringUtil.php +++ b/src/Tools/StringUtil.php @@ -2,10 +2,16 @@ namespace ctiso\Tools; -class StringUtil { +class StringUtil +{ - // from creole - static function strToArray(string $str): array { + /** + * Преобразует строку в массив + * @param string $str + * @return array + */ + static function strToArray(string $str): array + { $str = substr($str, 1, -1); // remove { } $res = []; @@ -13,7 +19,7 @@ class StringUtil { $in_subarr = 0; $toks = explode(',', $str); - foreach($toks as $tok) { + foreach ($toks as $tok) { if ($in_subarr > 0) { // already in sub-array? $subarr[$in_subarr][] = $tok; if ('}' === substr($tok, -1, 1)) { // check to see if we just added last component @@ -21,7 +27,7 @@ class StringUtil { $in_subarr--; } } elseif ($tok[0] === '{') { // we're inside a new sub-array - if ('}' !== substr($tok, -1, 1)) { + if ('}' !== substr($tok, -1, 1)) { $in_subarr++; // if sub-array has more than one element $subarr[$in_subarr] = []; @@ -32,26 +38,37 @@ class StringUtil { } else { // not sub-array $val = trim($tok, '"'); // remove " (surrounding strings) // perform type castng here? - $res[] = $val; + $res[] = $val; } } return $res; } - //Нормализация строк на русском - static function normalizeRussian(string $str): string { - $result = preg_replace('/\s+/',' ', $str); + /** + * Нормализация строк на русском + * @param string $str + * @return string + */ + static function normalizeRussian(string $str): string + { + $result = preg_replace('/\s+/', ' ', $str); if (is_string($result)) { $result = trim($result); //Замена длинных пробелов на одинарные, пробелы по краям $result = mb_strtolower($result); - $result = preg_replace('/ё/','е', $str); //е на ё + $result = preg_replace('/ё/', 'е', $str); //е на ё } return $result; } - //Проверка равенства двух строк на русском языке. - static function equalRussianCheck($str1,$str2): bool { + /** + * Проверка равенства двух строк на русском языке. + * @param string $str1 + * @param string $str2 + * @return bool + */ + static function equalRussianCheck($str1, $str2): bool + { return self::normalizeRussian($str1) == self::normalizeRussian($str2); } @@ -61,33 +78,52 @@ class StringUtil { * output: true * input: $str="foo" $variants="foo1|foo2|foo3" * output: false - */ - static function compare_string_to_variants($str, string $variants){ + * + * @param string $str + * @param string $variants + * @return bool + */ + static function compare_string_to_variants($str, string $variants) + { $variants_array = explode('|', $variants); $founded = false; foreach ($variants_array as $variant) { - $founded = $founded || self::equalRussianCheck($variant, $str); + $founded = $founded || self::equalRussianCheck($variant, $str); } return $founded; } - static function mb_str_split(string $str): array|false { + /** + * Разбивает строку на массив символов + * @param string $str + * @return array|false + */ + static function mb_str_split(string $str): array|false + { return preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY); } - static function mb_strtr($str, $from, $to) { + /** + * Заменяет символы в строке на символы из другой строки + * @param string $str + * @param string $from + * @param string $to + * @return string + */ + static function mb_strtr($str, $from, $to) + { return str_replace(self::mb_str_split($from), self::mb_str_split($to), $str); } static function encodestring(string $st): string { - $st = self::mb_strtr($st,"абвгдеёзийклмнопрстуфхъыэ !+()", "abvgdeeziyklmnoprstufh_ie_____"); - $st = self::mb_strtr($st,"АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ", "ABVGDEEZIYKLMNOPRSTUFH_IE"); + $st = self::mb_strtr($st, "абвгдеёзийклмнопрстуфхъыэ !+()", "abvgdeeziyklmnoprstufh_ie_____"); + $st = self::mb_strtr($st, "АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ", "ABVGDEEZIYKLMNOPRSTUFH_IE"); $st = strtr($st, [ " " => '_', "." => '_', "," => '_', - "?" => '_', + "?" => '_', "\"" => '_', "'" => '_', "/" => '_', @@ -95,18 +131,38 @@ class StringUtil { "%" => '_', "#" => '_', "*" => '_', - "ж"=>"zh", "ц"=>"ts", "ч"=>"ch", "ш"=>"sh", - "щ"=>"shch","ь"=>"", "ю"=>"yu", "я"=>"ya", - "Ж"=>"ZH", "Ц"=>"TS", "Ч"=>"CH", "Ш"=>"SH", - "Щ"=>"SHCH","Ь"=>"", "Ю"=>"YU", "Я"=>"YA", - "Й"=>"i", "й"=>"ie", "ё"=>"Ye", - "№"=>"N" + "ж" => "zh", + "ц" => "ts", + "ч" => "ch", + "ш" => "sh", + "щ" => "shch", + "ь" => "", + "ю" => "yu", + "я" => "ya", + "Ж" => "ZH", + "Ц" => "TS", + "Ч" => "CH", + "Ш" => "SH", + "Щ" => "SHCH", + "Ь" => "", + "Ю" => "YU", + "Я" => "YA", + "Й" => "i", + "й" => "ie", + "ё" => "Ye", + "№" => "N" ]); return strtolower($st); } - static function validate_encoded_string(string $st): int|false { + /** + * Проверяет, является ли строка кодированной + * @param string $st + * @return int|false + */ + static function validate_encoded_string(string $st): int|false + { $enc_st = self::encodestring($st); return preg_match('/^[\w_-]+(\.[\w_-]+)?$/', $enc_st); } -} \ No newline at end of file +} diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index f6acfee..6407ab3 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -8,6 +8,13 @@ use Exception, ctiso\Validator\Rule\AbstractRule, ctiso\Collection; +/** + * @phpstan-type Rule array{ + * validate:string, // Описание правила см. формат правила ниже + * name:string, // Имя переменой для проверки + * context?:object + * } + */ class Validator { /** @var AbstractRule[] */ @@ -36,6 +43,9 @@ class Validator 'reg' => Rule\PregMatch::class, ]; + /** + * @param Rule[] $rules + */ function __construct($rules = []) { $this->addRuleList($rules); } @@ -51,9 +61,7 @@ class Validator /** * Добавление списка правил в специальном формате - * array(array('name' => fieldname, 'validate' => ruletext), ...) - * fieldname - Имя переменой для проверки - * ruletext - Описание правила см. формат правила ниже + * @param Rule[] $input */ public function addRuleList(array $input): void { diff --git a/src/View/Composite.php b/src/View/Composite.php index 5261ba4..3953c42 100644 --- a/src/View/Composite.php +++ b/src/View/Composite.php @@ -3,6 +3,7 @@ namespace ctiso\View; use ctiso\View\View, PHPTAL; +use PHPTAL_TranslationService; class Composite extends View { @@ -39,7 +40,7 @@ class Composite extends View return $this->tal->execute(); } - function setTranslator($t): void { + function setTranslator(PHPTAL_TranslationService $t): void { $this->tal->setTranslator($t); } } diff --git a/src/View/Top.php b/src/View/Top.php index 17f81f0..fbefed0 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -8,10 +8,13 @@ class Top extends Composite { /** * Общая строка заголовка + * @var int */ public $mid = 0; - public $require = array(); - public $deps = array(); + /** @var array */ + public $require = []; + /** @var array */ + public $deps = []; /** * Заголовок страницы diff --git a/src/View/View.php b/src/View/View.php index e35f147..dcdb8df 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -22,10 +22,14 @@ class View extends \stdClass public ?string $active_module = null; public string $module_action; + + /** @var string[] */ public array $prefix; + /** @var string[] */ public array $suggestions = []; //подсказки + /** @var string[] $alias */ public array $alias = []; public $codeGenerator = null; public $parent_view = null; From 530a3b931d1290bedd10de98601fd1ac8fcd776b Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 23 Oct 2025 11:24:33 +0300 Subject: [PATCH 102/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=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) { From 730a608f9b76188f0c607ad1612a3b22ffe3e9ad Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 23 Oct 2025 15:54:14 +0300 Subject: [PATCH 103/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Connection/HttpRequest.php | 38 ++++++++++---- src/Connection/HttpResponse.php | 16 +++--- src/Controller/Action.php | 66 ++++++++++++++++++++--- src/Controller/ActionInterface.php | 12 ++++- src/Controller/Component.php | 58 +++++++++++++++++++-- src/Controller/Front.php | 22 ++++---- src/Controller/Installer.php | 84 ++++++++++++++++++++++++------ src/Controller/Request.php | 8 +++ src/Controller/Service.php | 31 ++++++++--- src/Database.php | 71 ++++++++++++++++++++++--- src/Database/Manager.php | 2 +- src/Database/PDOStatement.php | 57 +++++++++++++++++--- src/Excel/Document.php | 11 ++-- src/Excel/Number.php | 9 ++-- src/Excel/Table.php | 35 +++++++------ src/File.php | 5 ++ src/Filter/ActionLogger.php | 7 ++- src/Filter/Authorization.php | 4 +- src/Filter/Filter.php | 9 +++- src/Form/Field.php | 2 + src/Functions.php | 18 ++++--- src/HttpRequest.php | 8 +++ src/Settings.php | 2 +- src/TableTree.php | 31 ++++++----- src/Tools/Drawing.php | 4 +- src/Tools/TemplateImage.php | 11 +++- src/View/Composite.php | 4 +- 27 files changed, 491 insertions(+), 134 deletions(-) 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); } From 89913de4fe278b4e39c899a81ad1704099e185d8 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Mon, 27 Oct 2025 16:39:44 +0300 Subject: [PATCH 104/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Adapter.php | 9 +++++++++ src/Arr.php | 6 ++++++ src/Collection.php | 5 +++++ src/ComponentRequest.php | 15 +++++++++++++++ src/Connection/HttpRequest.php | 14 ++++++++++---- src/Connection/HttpResponse.php | 16 +++++++++++----- src/Controller/Action.php | 4 ++++ src/Controller/Component.php | 5 +++++ src/Controller/Front.php | 9 ++++++++- src/Controller/Service.php | 1 + src/Database.php | 1 + src/Database/Manager.php | 2 -- src/Database/PDOStatement.php | 3 +++ src/Excel/Document.php | 15 ++++++++++----- src/Functions.php | 15 +++++++++++++++ src/Mail.php | 10 +++++++++- src/Primitive.php | 11 ++++++++++- src/Settings.php | 6 ++---- src/View/Composite.php | 1 - 19 files changed, 124 insertions(+), 24 deletions(-) diff --git a/src/Adapter.php b/src/Adapter.php index 2ba68f9..6ab0934 100644 --- a/src/Adapter.php +++ b/src/Adapter.php @@ -8,12 +8,21 @@ namespace ctiso; */ class Adapter { + /** @var array|object */ protected $adaptee; + + /** + * @param array|object $adaptee + */ public function __construct ($adaptee) { $this->adaptee = $adaptee; } + /** + * @param string $name + * @return mixed + */ public function get($name) { if (is_array ($this->adaptee)) { diff --git a/src/Arr.php b/src/Arr.php index 38cbb35..5d63ef8 100644 --- a/src/Arr.php +++ b/src/Arr.php @@ -4,6 +4,12 @@ namespace ctiso; class Arr { + /** + * @param array $data + * @param string $key + * @param mixed $default + * @return mixed + */ static function get($data, $key, $default = null) { return $data[$key] ?? $default; } diff --git a/src/Collection.php b/src/Collection.php index 58b725e..ca5e3ae 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -72,6 +72,11 @@ class Collection implements \ArrayAccess return (string)$this->get($key, $default); } + /** + * @param string $key + * @param int $default + * @return int + */ public function getNat($key, $default = 1) { $result = (int)$this->get($key, $default); diff --git a/src/ComponentRequest.php b/src/ComponentRequest.php index 6bc7dbc..9488184 100644 --- a/src/ComponentRequest.php +++ b/src/ComponentRequest.php @@ -6,15 +6,27 @@ use ctiso\HttpRequest, ctiso\Arr; class ComponentRequest { + /** @var string */ public $component_id; + /** @var string */ public $component_title; + /** @var HttpRequest */ public $r; + /** + * @param string $c + * @param HttpRequest $r + */ function __construct($c, HttpRequest $r) { $this->component_id = $c; $this->r = $r; } + /** + * @param string $key + * @param mixed $default + * @return mixed + */ function get($key, $default = null) { if ($key == 'active_page') { return $this->r->get($key); @@ -30,6 +42,9 @@ class ComponentRequest { return $default; } + /** + * @return string + */ function getAction() { return $this->r->getAction(); } diff --git a/src/Connection/HttpRequest.php b/src/Connection/HttpRequest.php index 0e2fcf3..c255f77 100644 --- a/src/Connection/HttpRequest.php +++ b/src/Connection/HttpRequest.php @@ -8,15 +8,21 @@ class HttpRequest const POST = "POST"; const GET = "GET"; - private $param = []; // Параметры запроса - public $data = null; // Содержание - public $url; // Адресс - public $method; // Метод + /** @var array Параметры запроса */ + private $param = []; + /** @var string Содержание */ + public $data = null; + /** @var string Адресс */ + public $url; + /** @var string Метод */ + public $method; /** @var int */ public $port = 80; /** @var string */ public $host = ""; + /** @var ?string */ public $proxy_host = null; + /** @var ?int */ public $proxy_port = null; /** @var string */ public $http_version = 'HTTP/1.1'; diff --git a/src/Connection/HttpResponse.php b/src/Connection/HttpResponse.php index 745091a..1dc2224 100644 --- a/src/Connection/HttpResponse.php +++ b/src/Connection/HttpResponse.php @@ -7,11 +7,17 @@ namespace ctiso\Connection; class HttpResponse { + /** @var int */ private $offset; + /** @var array */ private $param = []; + /** @var int */ private $code; + /** @var string */ public $response; + /** @var string */ public $version; + /** @var string */ public $data; public function __construct($response) @@ -28,7 +34,7 @@ class HttpResponse { $http = explode(" ", $this->getLine()); $this->version = $http[0]; - $this->code = $http[1]; + $this->code = (int)$http[1]; $line = $this->getLine(); while ($offset = strpos($line, ":")) { @@ -55,7 +61,7 @@ class HttpResponse /** * Обработка строки HTTP ответа */ - private function getLine() + private function getLine(): string { $begin = $this->offset; $offset = strpos($this->response, "\r\n", $this->offset); @@ -67,12 +73,12 @@ class HttpResponse /** * Значение параметра HTTP ответа */ - public function getParameter($name) + public function getParameter($name): string { return $this->param[$name]; } - public function getData() + public function getData(): string { return $this->data; } @@ -80,7 +86,7 @@ class HttpResponse /** * Состояние */ - public function getCode() + public function getCode(): int { return $this->code; } diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 480eb86..b6b26f6 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -288,6 +288,7 @@ class Action implements ActionInterface /** * Добавление помошника контроллера + * @param class-string $class */ public function addHelper($class) { @@ -345,6 +346,7 @@ class Action implements ActionInterface /** * Установка заголовка для отображения + * @param string $title */ public function setTitle($title): void { @@ -353,6 +355,8 @@ class Action implements ActionInterface /** * Добавление widget к отображению + * @param $section + * @param $node */ public function addChild($section, $node): void { diff --git a/src/Controller/Component.php b/src/Controller/Component.php index d9a3a84..4f9c76f 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -17,9 +17,14 @@ use PHPTAL; use PHPTAL_PreFilter_Normalize; class FakeTemplate { + /** @var array */ public $_data = []; + /** @var string */ public $_name = ''; + /** + * @param string $name + */ function __construct($name) { $this->_name = $name; } diff --git a/src/Controller/Front.php b/src/Controller/Front.php index e640c13..4aef444 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -22,6 +22,7 @@ class Front extends Action protected $_param; // Параметр по которому выбирается модуль protected $default; // Значение параметра по умолчанию + /** @var array */ protected $modules = []; public function __construct(Database $db, Registry $config, User $user, $default) { @@ -32,7 +33,13 @@ class Front extends Action $this->default = $default; } - public function isLoaded($name) { + /** + * Проверяет загружен ли модуль + * @param string $name Имя модуля + * @return bool + */ + public function isLoaded($name): bool + { return isset($this->modules[$name]); } diff --git a/src/Controller/Service.php b/src/Controller/Service.php index 1c572aa..8ea4b19 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -47,6 +47,7 @@ class Service /** * @param string $name Имя модели + * @return string */ private function getModelPath($name) { diff --git a/src/Database.php b/src/Database.php index 37d6bc1..c885b1e 100644 --- a/src/Database.php +++ b/src/Database.php @@ -114,6 +114,7 @@ namespace ctiso { /** * Создает подготовленный запрос * @param string $query - запрос + * @return Statement */ public function prepareStatement($query) { diff --git a/src/Database/Manager.php b/src/Database/Manager.php index d31527f..b357288 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -199,8 +199,6 @@ class Manager if (strtolower($type) == "serial") { $type = "integer"; } - //if (strtolower($type)=="boolean") - // $type = "integer"; } return $name . " " . $type . $references . $constraint; } diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index a8b42d8..2811df2 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -78,6 +78,9 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate return $this->cache[$this->cursorPos]; } + /** + * @return array|null + */ function getRow() { return $this->fields; } diff --git a/src/Excel/Document.php b/src/Excel/Document.php index 4b11eec..3086f56 100644 --- a/src/Excel/Document.php +++ b/src/Excel/Document.php @@ -27,7 +27,7 @@ class Document { * @param array $values array Параметры стиля * @param string $type Тип стиля */ - function setStyle ($name, array $values, $type = 'Interior') + function setStyle ($name, array $values, $type = 'Interior'): void { if(!isset($this->styles[$name])) { $this->styles[$name] = []; @@ -38,7 +38,8 @@ class Document { /** * Генерация стилей */ - private function createStyles (XMLWriter $doc) { + private function createStyles (XMLWriter $doc): void + { $doc->startElement('Styles'); foreach ($this->styles as $name => $sn) { $doc->startElement('Style'); @@ -70,18 +71,22 @@ class Document { /** * Преобразует переводы строки в спец символы + * @param string $s + * @return string */ function clean ($s) { - assert(is_string($s)); - return strtr($s, ["\n" => " "]); } /** * Сохраняет таблицу в формате Office 2003 XML * http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats + * + * @param string $filename + * @throws Exception + * @return void */ - function save($filename) + function save($filename): void { $doc = new XMLWriter(); if (!$doc->openUri($filename)) { diff --git a/src/Functions.php b/src/Functions.php index a681669..83b370b 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -6,9 +6,14 @@ namespace ctiso; * Эмуляция каррированой функции */ class right { + /** @var array */ protected $params; + /** @var callable */ protected $fn; + /** + * @param array $params + */ public function __construct($params) { $this->fn = array_shift($params); $this->params = $params; @@ -22,9 +27,14 @@ class right { } class left { + /** @var array */ protected $params; + /** @var callable */ protected $fn; + /** + * @param array $params + */ public function __construct($params) { $this->fn = array_shift($params); $this->params = $params; @@ -44,6 +54,9 @@ class partial { /** @var callable */ protected $fn; + /** + * @param array $params + */ public function __construct($params) { $this->fn = array_shift($params); $this->params = $params; @@ -294,6 +307,8 @@ class Functions { /** * Логическа операция && ко всем элементам массива + * @param array $array Массив + * @param callable $callback Функция * @return bool */ static function every(array $array, $callback) { diff --git a/src/Mail.php b/src/Mail.php index ca785a0..697895a 100644 --- a/src/Mail.php +++ b/src/Mail.php @@ -100,10 +100,12 @@ class Mail /** * Добавление вложения из файла + * @param string $filename + * @param string|false $name */ function addAttachment(string $filename, $name = false): void { - if (file_exists($filename)) { // assert ?? + if (file_exists($filename)) { $file = fopen($filename, "rb"); if (is_resource($file)) { $data = fread($file, filesize($filename)); @@ -112,6 +114,10 @@ class Mail } } + /** + * Установка типа содержимого + * @param string $type + */ function setType($type): void { $this->type = $type; @@ -119,6 +125,8 @@ class Mail /** * Добавление вложения из строки с указанием имени файла + * @param string $data + * @param string $name */ function addAttachmentRaw($data, string $name): void { diff --git a/src/Primitive.php b/src/Primitive.php index 7f0f92a..d43921d 100644 --- a/src/Primitive.php +++ b/src/Primitive.php @@ -25,12 +25,21 @@ class Primitive { return filter_var($value, FILTER_VALIDATE_BOOLEAN);//(int)((bool) $value); } + /** + * Преобразование значения в булевое значение + * @param string $value + * @return bool + */ public static function from_bool($value): bool { return ((bool) $value); } - // int + /** + * Преобразование значения в целое число + * @param string $value + * @return int + */ public static function to_int($value): int { return ((int) $value); diff --git a/src/Settings.php b/src/Settings.php index e99bb98..666532f 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -70,7 +70,6 @@ class Settings */ public function writeKey(array $key, $value) { -// assert(count($key) >= 1); $data = &$this->data; while (count($key) > 1) { @@ -78,7 +77,6 @@ class Settings $data = &$data[$name]; } -// assert(count($key) == 1); $name = array_shift($key); if (is_array($value)) { if (!isset($data[$name])) { @@ -92,6 +90,8 @@ class Settings /** * Обновляет массив в соответствии со значением + * @param array $data Массив + * @param mixed $value Значение */ protected function merge(array &$data, $value): void { @@ -122,7 +122,6 @@ class Settings */ protected function readKeyData(array $key, $data) { -// assert(count($key) >= 1); while (count($key) > 1) { $name = array_shift($key); if (isset($data[$name])) { @@ -132,7 +131,6 @@ class Settings } } -// assert(count($key) == 1); $name = array_shift($key); if (isset($data[$name])) { return $data[$name]; diff --git a/src/View/Composite.php b/src/View/Composite.php index 278f798..531f470 100644 --- a/src/View/Composite.php +++ b/src/View/Composite.php @@ -8,7 +8,6 @@ use PHPTAL_TranslationService; class Composite extends View { private PHPTAL $tal; - public $config; function __construct(string $file) { From 386a9272545ba67050bb11e5e0045bf89ed599b1 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 28 Oct 2025 12:26:00 +0300 Subject: [PATCH 105/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Arr.php | 2 +- src/Excel/Document.php | 2 ++ src/Excel/Table.php | 10 +++++++--- src/Form/ViewState.php | 22 ++++++++++++++++++--- src/Functions.php | 43 +++++++++++++++++++++++++++--------------- src/HttpRequest.php | 11 ++++++----- 6 files changed, 63 insertions(+), 27 deletions(-) diff --git a/src/Arr.php b/src/Arr.php index 5d63ef8..99ac0ba 100644 --- a/src/Arr.php +++ b/src/Arr.php @@ -5,7 +5,7 @@ namespace ctiso; class Arr { /** - * @param array $data + * @param array $data * @param string $key * @param mixed $default * @return mixed diff --git a/src/Excel/Document.php b/src/Excel/Document.php index 3086f56..4a9480c 100644 --- a/src/Excel/Document.php +++ b/src/Excel/Document.php @@ -8,9 +8,11 @@ use XMLWriter, Exception; class Document { + /** @var string */ static $ns = "urn:schemas-microsoft-com:office:spreadsheet"; /** @var list */ private $table = []; + /** @var array */ protected $styles = []; /** diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 95ab5db..41ff2b2 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -10,7 +10,9 @@ use XMLWriter, class TableCell { + /** @var string|false */ public $style = false; + /** @var string */ public $value; public $merge = false; @@ -25,17 +27,19 @@ class TableCell */ class TableRow { + /** @var string|false */ public $style = false; /** @var TableCell[] */ public $cells = []; + /** @var int|false */ public $height = false; - function setCell($y, $value) + function setCell($y, $value): void { $this->cells[$y] = new TableCell($value); } - function setCellStyle($y, $name) + function setCellStyle($y, $name): void { $this->cells[$y]->style = $name; } @@ -283,7 +287,7 @@ class Table } if ($this->rows[$i]->height) { - $doc->writeAttribute('ss:Height', $this->rows[$i]->height); + $doc->writeAttribute('ss:Height', (string)$this->rows[$i]->height); } /** @var TableRow $nrow */ $nrow = $this->rows[$i]; diff --git a/src/Form/ViewState.php b/src/Form/ViewState.php index f22545d..b315e6d 100644 --- a/src/Form/ViewState.php +++ b/src/Form/ViewState.php @@ -21,9 +21,13 @@ class ViewState // extends Collection $this->values[$name] = $value; } - function get($_rest) + /** + * Возвращает значение + * @param string ...$args + * @return mixed + */ + function get(...$args) { - $args = func_get_args(); $result = $this->values; foreach ($args as $name) { if (!isset($result[$name])) { @@ -34,16 +38,28 @@ class ViewState // extends Collection return $result; } + /** + * Сохраняет состояние + * @return string + */ function saveState(): string { return base64_encode(serialize($this->values)); } - function restoreState($value) + /** + * Восстанавливает состояние + * @param string $value + */ + function restoreState($value): void { $this->values = unserialize(base64_decode($value)); } + /** + * Возвращает состояние + * @return array + */ function export() { return $this->values; diff --git a/src/Functions.php b/src/Functions.php index 83b370b..700f893 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -62,8 +62,12 @@ class partial { $this->params = $params; } - function apply() { - $params = func_get_args(); + /** + * Применение функции + * @param mixed ...$params + * @return mixed + */ + function apply(...$params) { $result = []; $count = count($this->params); for($i = 0, $j = 0; $i < $count; $i++) { @@ -87,8 +91,12 @@ class compose { $this->fns = array_reverse($list); } - function apply () { - $params = func_get_args (); + /** + * Применение функций + * @param mixed ...$params + * @return mixed + */ + function apply (...$params) { $result = call_user_func_array($this->fns[0], $params); $count = count($this->fns); for ($i = 1; $i < $count; $i++) { @@ -100,39 +108,44 @@ class compose { class Functions { - static function partial($_rest) { - $closure = new partial(func_get_args()); + /** + * Частичное применение функции + * @param mixed ...$args + * @return mixed + */ + static function partial(...$args) { + $closure = new partial($args); return [$closure, 'apply']; } /** * Композиция функций - * @param array $_rest + * @param mixed ...$args * @return mixed */ - static function compose($_rest) { - $closure = new compose(func_get_args()); + static function compose(...$args) { + $closure = new compose($args); return [$closure, 'apply']; } /** * Карирование справа - * + * @param mixed ...$args * @return mixed */ - static function rcurry($_rest) { - $closure = new right(func_get_args ()); + static function rcurry(...$args) { + $closure = new right($args); return [$closure, 'apply']; } /** * Карирование слева - * + * @param mixed ...$args * @return mixed */ - static function lcurry($_rest) { - $closure = new left(func_get_args ()); + static function lcurry(...$args) { + $closure = new left($args); return [$closure, 'apply']; } diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 21ea3d2..3df3b05 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -4,13 +4,14 @@ * Неверный запрос */ namespace ctiso; -use Exception, - ArrayAccess, - ctiso\Collection, - ctiso\Session; + +use Exception; +use ArrayAccess; +use ctiso\Collection; +use ctiso\Session; /** - * @template T + * @template T=mixed */ class HttpRequest extends Collection { From 245b5c6c198d103db78f8fd992345f325b407a6b Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 28 Oct 2025 16:32:00 +0300 Subject: [PATCH 106/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Connection/HttpResponse.php | 3 +- src/Controller/Action.php | 55 +++++++++------ src/Controller/Component.php | 11 ++- src/Controller/Service.php | 3 + src/Controller/SiteInterface.php | 15 ++-- src/Database.php | 8 +-- src/Database/Manager.php | 2 +- src/Form/OptionsFactory.php | 2 +- src/Functions.php | 22 ++++-- src/Role/User.php | 7 ++ src/Setup.php | 6 +- src/Tales.php | 27 +++---- src/Tools/Drawing.php | 2 +- src/Tools/SQLStatementExtractor.php | 106 +++++++++++++++------------- src/Validator/Rule/AbstractRule.php | 5 ++ src/Validator/Validator.php | 17 +++-- src/View/Top.php | 1 - src/View/View.php | 3 + 18 files changed, 191 insertions(+), 104 deletions(-) diff --git a/src/Connection/HttpResponse.php b/src/Connection/HttpResponse.php index 1dc2224..d3cf5ac 100644 --- a/src/Connection/HttpResponse.php +++ b/src/Connection/HttpResponse.php @@ -30,7 +30,7 @@ class HttpResponse /** * Обработка HTTP ответа */ - private function parseMessage() + private function parseMessage(): void { $http = explode(" ", $this->getLine()); $this->version = $http[0]; @@ -72,6 +72,7 @@ class HttpResponse /** * Значение параметра HTTP ответа + * @param string $name Имя параметра */ public function getParameter($name): string { diff --git a/src/Controller/Action.php b/src/Controller/Action.php index b6b26f6..dcb69fe 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -1,16 +1,18 @@ modulePath, 'help', $name . '.suggest'); if (file_exists($file)) { @@ -188,6 +191,7 @@ class Action implements ActionInterface * 1. Можно переопределить действия * 2. Использовать наследование чтобы добавить к старому обработчику новое поведение * @param HttpRequest $request запроса + * @return View|string */ public function preProcess(HttpRequest $request) { @@ -203,6 +207,11 @@ class Action implements ActionInterface return $view; } + /** + * Выполнение действия + * @param HttpRequest $request + * @return View|string + */ public function execute(HttpRequest $request) { $result = $this->preProcess($request); @@ -227,7 +236,7 @@ class Action implements ActionInterface /** * Страница по умолчанию * @param HttpRequest $request - * @return string|\ctiso\View\View + * @return View|string */ public function actionIndex(HttpRequest $request) { return ""; @@ -355,14 +364,19 @@ class Action implements ActionInterface /** * Добавление widget к отображению - * @param $section - * @param $node + * @param string $section + * @param View $node */ public function addChild($section, $node): void { $this->childNodes[$section] = $node; } + /** + * Установка значения контроллера + * @param string $name + * @param mixed $value + */ public function setValue($name, $value): void { $this->ctrlValues[$name] = $value; @@ -370,6 +384,8 @@ class Action implements ActionInterface /** * Добавление дочернего отображения к текущему отображению + * @param string $section + * @param View $node */ public function addView($section, $node): void { @@ -379,6 +395,7 @@ class Action implements ActionInterface /** * Генерация содержания * Путаница c execute и render + * @return View|string */ public function render() { @@ -426,16 +443,14 @@ class Action implements ActionInterface return $result; } + /** + * @return State + */ function _getActionPath() { return new State('index'); } - // Тоже убрать в метод Controller_Model - function getActionPath(HttpRequest $request, $action = null) { - $this->_getActionPath()->getPath($this, ($action) ? $action : $request->getAction()); - } - - function redirect(string $action) { + function redirect(string $action): void { header('location: ' . $action); exit(); } diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 4f9c76f..5ebffc2 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -29,10 +29,17 @@ class FakeTemplate { $this->_name = $name; } - function __set($key, $value) { + /** + * @param string $key + * @param mixed $value + */ + function __set($key, $value): void { $this->_data[$key] = $value; } + /** + * @return string + */ function execute() { return json_encode($this->_data); } @@ -56,7 +63,7 @@ class Component public $component_id; /** @var string */ public $component_title; - + /** @var string */ public $COMPONENTS_WEB; public Registry $config; diff --git a/src/Controller/Service.php b/src/Controller/Service.php index 8ea4b19..923b4ad 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -20,8 +20,11 @@ class Service public $webPath = []; /** @var Registry */ public $config; + /** @var string */ public $template; + /** @var string */ public $templatePath; + /** @var string */ public $COMPONENTS_WEB; /** @var Database */ public $db; diff --git a/src/Controller/SiteInterface.php b/src/Controller/SiteInterface.php index d176e34..4fd6ff4 100644 --- a/src/Controller/SiteInterface.php +++ b/src/Controller/SiteInterface.php @@ -4,15 +4,22 @@ namespace ctiso\Controller; interface SiteInterface { function getResource(); + /** + * @return \ctiso\Database + */ function getDatabase(); function getConfig(); function getTheme(); - function addComponentConfig($config); - function addRequireJsPath(string $name, string $path, ?array $shim = null); - function addStyleSheet(string $url); + function addComponentConfig($config): void; + function addRequireJsPath(string $name, string $path, ?array $shim = null): void; + function addStyleSheet(string $url): void; + /** + * @param string $expression + * @return ?Component + */ function loadComponent(string $expression); function findTemplate(string $name); function replaceImg(string $src, int $width, int $height); - function updatePageTime(int $time); + function updatePageTime(int $time): void; } diff --git a/src/Database.php b/src/Database.php index c885b1e..35a56e9 100644 --- a/src/Database.php +++ b/src/Database.php @@ -124,8 +124,8 @@ namespace ctiso { /** * Извлекает из базы все элементы по запросу (Для совместимости со старым представлением баз данных CIS) * @param string $query - запрос - * @param array $values - значения - * @return array + * @param array $values - значения + * @return list> */ public function fetchAllArray($query, $values = null) { @@ -138,8 +138,8 @@ namespace ctiso { /** * Извлекает из базы первый элемент по запросу * @param string $query - запрос - * @param array $values - значения - * @return array|false + * @param array $values - значения + * @return array|false */ public function fetchOneArray($query, $values = null) { diff --git a/src/Database/Manager.php b/src/Database/Manager.php index b357288..91c6f64 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -294,7 +294,7 @@ class Manager /** * Возвращает все имена таблиц - * @return array + * @return list */ public function getAllTableNames() { diff --git a/src/Form/OptionsFactory.php b/src/Form/OptionsFactory.php index 8921b56..79be2e0 100644 --- a/src/Form/OptionsFactory.php +++ b/src/Form/OptionsFactory.php @@ -3,5 +3,5 @@ namespace ctiso\Form; interface OptionsFactory { - function create(Select $field, array $options); + function create(Select $field, array $options): void; } \ No newline at end of file diff --git a/src/Functions.php b/src/Functions.php index 700f893..cb38f96 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -217,15 +217,29 @@ class Functions { return ($a[$key] < $b[$key]) ? -1 : 1; } + /** + * @deprecated + * @param string $name Метод + * @param object $o + * + * @return mixed + */ static function __self($name, $o) { 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); } + /** + * @param mixed $x + * @return bool + */ static function __empty($x) { return empty($x); } @@ -235,7 +249,7 @@ class Functions { * @example key_values('a', array(1 => array('a' => 1, 'b' => 2))) => array(1) * * @param string $key - * @param array|\ArrayIterator $array + * @param list|\ArrayIterator $array * @return mixed */ static function key_values($key, $array) { @@ -249,7 +263,7 @@ class Functions { /** * @param string $key - * @param array|\ArrayIterator $array + * @param list|\ArrayIterator $array */ static function key_values_object($key, $array) { $result = []; diff --git a/src/Role/User.php b/src/Role/User.php index c9d68cc..174de9e 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -34,6 +34,9 @@ class User implements UserInterface return $this->name; } + /** + * @return bool + */ function isLogged() { return \ctiso\Filter\Authorization::isLogged(); } @@ -55,6 +58,10 @@ class User implements UserInterface return null; } + /** + * @param PDOStatement $result + * @return string + */ function getUserPassword($result) { return $result->get('password'); } diff --git a/src/Setup.php b/src/Setup.php index eac9518..935dabb 100644 --- a/src/Setup.php +++ b/src/Setup.php @@ -121,6 +121,8 @@ class Setup /** * Заменяет переменные на их значения в строке + * @param list $match массив совпадения + * @return string */ function replaceVariable(array $match) { @@ -132,12 +134,14 @@ class Setup /** * Для всех аттрибутов заменяет переменные на их значения + * @param SimpleXMLElement $attributes аттрибуты + * @return array */ function resolve(SimpleXMLElement $attributes): array { $result = []; foreach ($attributes as $key => $value) { - $result [$key] = preg_replace_callback("/\\\${(\w+)}/", [$this, 'replaceVariable'], $value); + $result[$key] = preg_replace_callback("/\\\${(\w+)}/", [$this, 'replaceVariable'], $value); } return $result; } diff --git a/src/Tales.php b/src/Tales.php index 214991b..2e3529f 100644 --- a/src/Tales.php +++ b/src/Tales.php @@ -4,12 +4,13 @@ * Расширения для PHPTAL для отображения времени и даты */ namespace ctiso; -use PHPTAL_Php_TalesInternal, - ctiso\Controller\SiteInterface, - ctiso\Controller\Component, - ctiso\HttpRequest, - PHPTAL_Tales, - PHPTAL_TalesRegistry; + +use PHPTAL_Php_TalesInternal; +use ctiso\Controller\SiteInterface; +use ctiso\Controller\Component; +use ctiso\HttpRequest; +use PHPTAL_Tales; +use PHPTAL_TalesRegistry; 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)); /** @var Component */ $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; /* Регистрация нового префикса для подключения компонента */ $tales = PHPTAL_TalesRegistry::getInstance(); - $tales->registerPrefix('component', ['ctiso\\Tales_Component', 'component']); - $tales->registerPrefix('date', ['ctiso\\Tales_DateTime', 'date']); - $tales->registerPrefix('time', ['ctiso\\Tales_DateTime', 'time']); - $tales->registerPrefix('assets', ['ctiso\\Tales_Assets', 'assets']); + $tales->registerPrefix('component', [\ctiso\Tales_Component::class, 'component']); + $tales->registerPrefix('date', [\ctiso\Tales_DateTime::class, 'date']); + $tales->registerPrefix('time', [\ctiso\Tales_DateTime::class, 'time']); + $tales->registerPrefix('assets', [\ctiso\Tales_Assets::class, 'assets']); } } diff --git a/src/Tools/Drawing.php b/src/Tools/Drawing.php index dbfcd8a..75b2eab 100644 --- a/src/Tools/Drawing.php +++ b/src/Tools/Drawing.php @@ -18,7 +18,7 @@ class Drawing * @param int $top * @param int $width * @param int $height - * @param array $rgb + * @param list $rgb */ static function drawRectangle(GdImage &$image, int $left, int $top, int $width, int $height, array $rgb): void { diff --git a/src/Tools/SQLStatementExtractor.php b/src/Tools/SQLStatementExtractor.php index 3759953..7ece534 100644 --- a/src/Tools/SQLStatementExtractor.php +++ b/src/Tools/SQLStatementExtractor.php @@ -26,10 +26,13 @@ * @version $Revision: 1.5 $ * @package creole.util.sql */ + namespace ctiso\Tools; + use Exception; -class SQLStatementExtractor { +class SQLStatementExtractor +{ protected static $delimiter = ';'; @@ -39,10 +42,11 @@ class SQLStatementExtractor { * @param string $filename Path to file to read. * @return array SQL statements */ - public static function extractFile($filename) { + public static function extractFile($filename) + { $buffer = file_get_contents($filename); if ($buffer !== false) { - return self::extractStatements(self::getLines($buffer)); + return self::extractStatements(self::getLines($buffer)); } throw new Exception("Unable to read file: " . $filename); } @@ -53,50 +57,53 @@ class SQLStatementExtractor { * @param string $buffer * @return array */ - public static function extract($buffer) { + public static function extract($buffer) + { return self::extractStatements(self::getLines($buffer)); } /** * Extract SQL statements from array of lines. * - * @param array $lines Lines of the read-in file. - * @return array + * @param list $lines Lines of the read-in file. + * @return list */ - protected static function extractStatements($lines) { + protected static function extractStatements($lines) + { $statements = []; $sql = ""; - foreach($lines as $line) { + foreach ($lines as $line) { + $line = trim($line); - $line = trim($line); - - if (self::startsWith("//", $line) || - self::startsWith("--", $line) || - self::startsWith("#", $line)) { - continue; - } - - if (strlen($line) > 4 && strtoupper(substr($line,0, 4)) == "REM ") { - continue; - } - - $sql .= " " . $line; - $sql = trim($sql); - - // SQL defines "--" as a comment to EOL - // and in Oracle it may contain a hint - // so we cannot just remove it, instead we must end it - if (strpos($line, "--") !== false) { - $sql .= "\n"; - } - - if (self::endsWith(self::$delimiter, $sql)) { - $statements[] = self::substring($sql, 0, strlen($sql)-1 - strlen(self::$delimiter)); - $sql = ""; - } + if ( + self::startsWith("//", $line) || + self::startsWith("--", $line) || + self::startsWith("#", $line) + ) { + continue; } + + if (strlen($line) > 4 && strtoupper(substr($line, 0, 4)) == "REM ") { + continue; + } + + $sql .= " " . $line; + $sql = trim($sql); + + // SQL defines "--" as a comment to EOL + // and in Oracle it may contain a hint + // so we cannot just remove it, instead we must end it + if (strpos($line, "--") !== false) { + $sql .= "\n"; + } + + if (self::endsWith(self::$delimiter, $sql)) { + $statements[] = self::substring($sql, 0, strlen($sql) - 1 - strlen(self::$delimiter)); + $sql = ""; + } + } return $statements; } @@ -110,7 +117,8 @@ class SQLStatementExtractor { * @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. */ - protected static function startsWith($check, $string) { + protected static function startsWith($check, $string) + { if ($check === "" || $check === $string) { return true; } else { @@ -124,7 +132,8 @@ class SQLStatementExtractor { * @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. */ - protected static function endsWith(string $check, string $string) { + protected static function endsWith(string $check, string $string) + { if ($check === "" || $check === $string) { return true; } else { @@ -136,21 +145,22 @@ class SQLStatementExtractor { * 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 */ - 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); - $endpos = (int) (($endpos === -1) ? $len-1 : $endpos); - if ($startpos > $len-1 || $startpos < 0) { + $endpos = (int) (($endpos === -1) ? $len - 1 : $endpos); + if ($startpos > $len - 1 || $startpos < 0) { trigger_error("substring(), Startindex out of bounds must be 0 $len-1 || $endpos < $startpos) { - trigger_error("substring(), Endindex out of bounds must be $startpos $len - 1 || $endpos < $startpos) { + trigger_error("substring(), Endindex out of bounds must be $startposerrorMsg; } + /** + * @param Collection $container + * @param bool|null $status + * @return bool + */ public function isValid(Collection $container, $status = null): bool { return true; diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 6407ab3..5d50dae 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -123,11 +123,17 @@ class Validator $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 = []; - if ($rule) { - $this->chain = $rule; + if ($rules) { + $this->chain = $rules; } foreach ($this->chain as $rule) { @@ -156,7 +162,10 @@ class Validator return empty($this->errorMsg); } - public function getErrorMsg() + /** + * @return array + */ + public function getErrorMsg(): array { return $this->errorMsg; } diff --git a/src/View/Top.php b/src/View/Top.php index fbefed0..e753401 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -147,5 +147,4 @@ class Top extends Composite { return $this->doTree('_stylesheet'); } - } \ No newline at end of file diff --git a/src/View/View.php b/src/View/View.php index 5ecfe7f..4ff81db 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -32,6 +32,7 @@ class View extends \stdClass /** @var string[] $alias */ public array $alias = []; public $codeGenerator = null; + /** @var View|null */ public $parent_view = null; function __construct() { @@ -191,6 +192,8 @@ class View extends \stdClass /** * @param string[][] $alias + * @param string[] $list + * @return string[] */ public function resolveAllNames($alias, array $list): array { $result = []; From 704e4e0bd50e87e3c4a25a8d545c017bc652942a Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 28 Oct 2025 20:09:21 +0300 Subject: [PATCH 107/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 12 ++++++++++++ src/Database.php | 6 +++--- src/Database/JsonInstall.php | 2 ++ src/Database/Manager.php | 34 ++++++++++++++++++++++++++++++++-- src/Excel/Number.php | 3 +++ src/Excel/Table.php | 10 ++++++++++ src/Filter/ActionAccess.php | 2 ++ src/Form/Form.php | 5 +++-- src/Functions.php | 8 +++++--- src/View/Pages.php | 2 +- 10 files changed, 73 insertions(+), 11 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 5ebffc2..a639ac4 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -104,6 +104,14 @@ class Component $callback, $text); } + /** + * Выполняет запрос компонента и возвращает результат + * Результат может быть строкой или View для обычных компонентов, или массивом для использования в сервисах + * + * @param HttpRequest $request + * @param bool $has_id + * @return mixed + */ function execute(HttpRequest $request, $has_id = true) { $crequest = new ComponentRequest($this->component_id, $request); @@ -125,6 +133,7 @@ class Component /** * Получить имя шаблона * @param Registry $_registry + * @return string */ public function getTemplateName($_registry) { return (isset($_COOKIE['with_template']) && preg_match('/^[\w\d-]{3,20}$/', $_COOKIE['with_template'])) @@ -486,7 +495,10 @@ class Component /** * @param ComponentRequest $request + * @return mixed */ function actionIndex($request) { + return null; } + } diff --git a/src/Database.php b/src/Database.php index 35a56e9..194d3b4 100644 --- a/src/Database.php +++ b/src/Database.php @@ -100,7 +100,7 @@ namespace ctiso { /** * Выполняет запрос к базе данных * @param string $query - запрос - * @param array $values - значения + * @param ?array $values - значения */ public function executeQuery($query, $values = null): PDOStatement|bool { @@ -124,7 +124,7 @@ namespace ctiso { /** * Извлекает из базы все элементы по запросу (Для совместимости со старым представлением баз данных CIS) * @param string $query - запрос - * @param array $values - значения + * @param ?array $values - значения * @return list> */ public function fetchAllArray($query, $values = null) @@ -138,7 +138,7 @@ namespace ctiso { /** * Извлекает из базы первый элемент по запросу * @param string $query - запрос - * @param array $values - значения + * @param ?array $values - значения * @return array|false */ public function fetchOneArray($query, $values = null) diff --git a/src/Database/JsonInstall.php b/src/Database/JsonInstall.php index 5dcfbd1..f7842fb 100644 --- a/src/Database/JsonInstall.php +++ b/src/Database/JsonInstall.php @@ -18,6 +18,7 @@ class JsonInstall { * Установить базу данных * @param string $dbinit_path * @param ?string $dbfill_path + * @return int */ function install($dbinit_path, $dbfill_path = null) { $dbinit_file = file_get_contents($dbinit_path); @@ -37,6 +38,7 @@ class JsonInstall { $this->fillDataBase($dbfill_path); } $this->makeConstraints($initActions); + return 1; } /** diff --git a/src/Database/Manager.php b/src/Database/Manager.php index 91c6f64..0ea3547 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -7,6 +7,36 @@ use ctiso\Tools\SQLStatementExtractor; use ctiso\Path; use Exception; +/** + * @phpstan-type Action array{ + * type:string, + * table_name:string, + * table:string, + * fields:array, + * field: ColumnProps, + * constraints:?array, + * references:?array, + * source:string, + * pgsql?:string, + * old_name?:string, + * new_name?:string, + * column?:string, + * column_name?:string, + * refTable?:string, + * refColumn?:string, + * values:array, + * view:string, + * select:string + * } + * + * @phpstan-type ColumnProps array{ + * name:string, + * type:string, + * not_null:bool, + * default:?string, + * references:?array{refTable:string,refColumn:string} + * } + */ class Manager { /** @var Database */ @@ -19,7 +49,7 @@ class Manager /** * Выполняет действие - * @param array $action + * @param Action $action * @param string $db_file * @throws Exception */ @@ -180,7 +210,7 @@ class Manager /** * Возвращает определение столбца * @param string $name - * @param array $data + * @param ColumnProps $data * @param bool $pg * @return string */ diff --git a/src/Excel/Number.php b/src/Excel/Number.php index 080fb74..3df78bb 100644 --- a/src/Excel/Number.php +++ b/src/Excel/Number.php @@ -7,6 +7,9 @@ class Number /** @var int */ public $value; + /** + * @param int|float $value + */ function __construct($value) { $this->value = (int)($value); diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 41ff2b2..3009c64 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -34,11 +34,21 @@ class TableRow /** @var int|false */ public $height = false; + /** + * Устанавливает значение для клетки + * @param int $y Номер столбца + * @param string $value Значение клетки + */ function setCell($y, $value): void { $this->cells[$y] = new TableCell($value); } + /** + * Устанавливает стиль для клетки + * @param int $y Номер столбца + * @param string $name Имя стиля + */ function setCellStyle($y, $name): void { $this->cells[$y]->style = $name; diff --git a/src/Filter/ActionAccess.php b/src/Filter/ActionAccess.php index 89f7326..db82044 100644 --- a/src/Filter/ActionAccess.php +++ b/src/Filter/ActionAccess.php @@ -10,7 +10,9 @@ use ctiso\Filter\UserAccess, class ActionAccess { + /** @var array */ public $access = []; + /** @var FilterInterface */ public $processor; /** @var User */ public $user; diff --git a/src/Form/Form.php b/src/Form/Form.php index 153f831..d072288 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -31,7 +31,7 @@ class Form { protected $replace; protected $before; - /** @var array */ + /** @var array */ public $_title = []; /** @var array */ public $alias = []; @@ -47,7 +47,6 @@ class Form { 'input' => Input::class, // input с проверкой на заполненность 'inputreq' => Input::class, - 'date' => Date::class, 'datereq' => Date::class, 'datetime' => DateTime::class, @@ -93,6 +92,8 @@ class Form { /** * Добавляет одно поле ввода на форму + * @param array{ type: string, name: string, hint?: string } $init + * @param OptionsFactory|null $factory */ public function addField(array $init, $factory = null): Field { diff --git a/src/Functions.php b/src/Functions.php index cb38f96..6921de5 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -277,7 +277,7 @@ class Functions { /** * @param string $key * @param string $value - * @param array|\ArrayIterator $array + * @param list>|\ArrayIterator $array */ static function assoc_key_values($key, $value, $array) { $result = []; @@ -289,7 +289,7 @@ class Functions { /** * @param string $key - * @param array|\ArrayIterator $array + * @param list>|\ArrayIterator $array */ static function assoc_key($key, $array) { $result = []; @@ -334,7 +334,7 @@ class Functions { /** * Логическа операция && ко всем элементам массива - * @param array $array Массив + * @param array $array Массив * @param callable $callback Функция * @return bool */ @@ -349,6 +349,8 @@ class Functions { /** * Логическа операция || ко всем элементам массива + * @param array $array Массив + * @param callable $callback Функция * @return mixed */ static function some(array $array, callable $callback) { diff --git a/src/View/Pages.php b/src/View/Pages.php index a5f2170..a64873d 100644 --- a/src/View/Pages.php +++ b/src/View/Pages.php @@ -14,7 +14,7 @@ class Pages * @param int $onpage количество страниц на странице * @param int $count количество всех страниц * @param string $prefix префикс - * @return array{'all': bool, 'list': array, 'first': string, 'last': string, 'next': string, 'prev': string} + * @return array{'all': bool, 'list': array, 'first': string, 'last': string, 'next': string|false, 'prev': string|false} */ static function getPages($page, $onpage, $count, $prefix = '?') { From 85881730792089af27a1daace59b612a95d46a37 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 29 Oct 2025 13:52:15 +0300 Subject: [PATCH 108/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Database/StatementIterator.php | 1 + src/Filter/FilterInterface.php | 4 ++++ src/Filter/Login.php | 35 ++++++++++++++++++------------ src/Functions.php | 25 +++++++++++++++------ src/HttpRequest.php | 4 ++++ src/Layout/Blank.php | 3 +++ src/Primitive.php | 14 +++++++++--- src/Registry.php | 11 ++++++++-- src/Role/User.php | 10 ++++++++- 9 files changed, 80 insertions(+), 27 deletions(-) diff --git a/src/Database/StatementIterator.php b/src/Database/StatementIterator.php index 8d0945b..b3c4152 100644 --- a/src/Database/StatementIterator.php +++ b/src/Database/StatementIterator.php @@ -6,6 +6,7 @@ use PDO; class StatementIterator implements \Iterator { + /** @var PDOStatement */ private $result; /** @var int */ private $pos = 0; diff --git a/src/Filter/FilterInterface.php b/src/Filter/FilterInterface.php index 075b80f..aee34a9 100644 --- a/src/Filter/FilterInterface.php +++ b/src/Filter/FilterInterface.php @@ -4,5 +4,9 @@ namespace ctiso\Filter; use ctiso\HttpRequest; interface FilterInterface { + /** + * @param HttpRequest $request + * @return mixed + */ function execute(HttpRequest $request); } \ No newline at end of file diff --git a/src/Filter/Login.php b/src/Filter/Login.php index d8b6fd1..d023db0 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -2,31 +2,34 @@ /** * Фильтр для проверки авторизации - * - * action: login(password, login) - * action: logout() */ +namespace ctiso\Filter; + +use ctiso\Filter\Filter; +use ctiso\HttpRequest; +use ctiso\Settings; +use ctiso\Registry; +use ctiso\Database; +use ctiso\Role\User; +use ctiso\Collection; +use ctiso\Path; +use ctiso\Database\PDOStatement; + // В класс авторизации передавать обьект для управления пользователем // Вынести в отдельный файл -namespace ctiso\Filter; -use ctiso\Filter\Filter, - ctiso\HttpRequest, - ctiso\Settings, - ctiso\Registry, - ctiso\Database, - ctiso\Role\User, - ctiso\Collection, - ctiso\Path; - class Login extends Filter { const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#'; const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; const AUTH_MAX_ATTEMPT = 10; const AUTH_LAST_ATTEMPT_TIMER = 600; + /** @var string */ public $mode = 'ajax'; + /** @var PDOStatement */ public $user; + /** @var User */ public $role; + /** @var Registry */ public $config; function __construct($processor, User $role, Registry $config) { @@ -125,11 +128,15 @@ class Login extends Filter return false; } + /** + * Вход в систему + * @param PDOStatement $result + */ private function enter($result): void { $this->user = $result; $random = rand(0, 1024 * 1024); - $this->role->setSID($random, $result); + $this->role->setSID((string)$random, $result); $_SESSION["group"] = $result->getInt('access'); $_SESSION["access"] = $result->getInt('id_user'); // id_user diff --git a/src/Functions.php b/src/Functions.php index 6921de5..812175f 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -19,8 +19,12 @@ class right { $this->params = $params; } - function apply() { - $params = func_get_args(); + /** + * Применение функции + * @param mixed ...$params + * @return mixed + */ + function apply(...$params) { array_splice($params, count($params), 0, $this->params); return call_user_func_array($this->fn, $params); } @@ -40,8 +44,12 @@ class left { $this->params = $params; } - function apply() { - $params = func_get_args(); + /** + * Применение функции + * @param mixed ...$params + * @return mixed + */ + function apply(...$params) { array_splice ($params, 0, 0, $this->params); return call_user_func_array ($this->fn, $params); } @@ -171,7 +179,7 @@ class Functions { /** * @deprecated - * @param array $value + * @param array $value * @param string $name * * @return mixed @@ -182,6 +190,9 @@ class Functions { /** * @deprecated + * @param mixed $value + * + * @return mixed */ static function identity($value) { return $value; @@ -191,7 +202,7 @@ class Functions { * @deprecated use fn and <=> operator * @param array $a * @param array $b - * @param $key + * @param string|int $key * * @return int */ @@ -206,7 +217,7 @@ class Functions { * @deprecated use fn and <=> operator * @param array $a * @param array $b - * @param $key + * @param string|int $key * * @return int */ diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 3df3b05..da5c547 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -80,6 +80,10 @@ class HttpRequest extends Collection parent::get('data')->set($key, $value); } + /** + * @param string $key + * @return array + */ function export(string $key = 'data') { return parent::get($key)->export(); diff --git a/src/Layout/Blank.php b/src/Layout/Blank.php index f731df3..8a0d0ff 100644 --- a/src/Layout/Blank.php +++ b/src/Layout/Blank.php @@ -9,6 +9,9 @@ use ctiso\Filter\Filter, class Blank extends Filter { + /** + * @return mixed + */ function execute(HttpRequest $request) { $text = $this->processor->execute($request); diff --git a/src/Primitive.php b/src/Primitive.php index d43921d..13dc67b 100644 --- a/src/Primitive.php +++ b/src/Primitive.php @@ -8,21 +8,29 @@ namespace ctiso; class Primitive { - // varchar + /** + * @param mixed $value + */ public static function to_varchar($value): string { return ((string) $value); } + /** + * @param mixed $value + * @return mixed + */ public static function from_varchar($value) { return $value; } - // int + /** + * @param mixed $value + */ public static function to_bool($value): bool { - return filter_var($value, FILTER_VALIDATE_BOOLEAN);//(int)((bool) $value); + return filter_var($value, FILTER_VALIDATE_BOOLEAN); } /** diff --git a/src/Registry.php b/src/Registry.php index bab923c..75924b4 100644 --- a/src/Registry.php +++ b/src/Registry.php @@ -5,9 +5,10 @@ use ctiso\File, Exception; class Registry { + /** @var array */ private array $namespace = []; - function importFile(string $namespace, ?string $filePath = null) { + function importFile(string $namespace, ?string $filePath = null): void { $data = json_decode(File::getContents($filePath), true); $data['_file'] = $filePath; $this->namespace[$namespace] = [ @@ -16,7 +17,7 @@ class Registry { ]; } - function importArray(string $namespace, array $data = []) { + function importArray(string $namespace, array $data = []): void { if (isset($this->namespace[$namespace])) { $data = array_merge($this->namespace[$namespace]['data'], $data); } @@ -26,6 +27,12 @@ class Registry { ]; } + /** + * @param string $ns + * @param string $key + * @return mixed + * @throws Exception + */ public function get(string $ns, string $key) { if (isset($this->namespace[$ns]['data'][$key])) { return $this->namespace[$ns]['data'][$key]; diff --git a/src/Role/User.php b/src/Role/User.php index 174de9e..972f35e 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -93,8 +93,16 @@ class User implements UserInterface return $result; } + /** + * @param string $random + * @param PDOStatement $result + * @return PDOStatement + */ function setSID(string $random, $result) { - return $this->db->executeQuery("UPDATE users SET sid = '$random', trie_count = 0 WHERE id_user = " . $result->getInt('id_user')); + return $this->db->executeQuery("UPDATE users SET sid = :sid, trie_count = 0 WHERE id_user = :user", [ + 'user' => $result->getInt('id_user'), + 'sid' => $random + ]); } function resetTries(string $login): void { From 2aac407c4d7c34d669ba423eec577c76c593b930 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 29 Oct 2025 15:21:10 +0300 Subject: [PATCH 109/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/View/Top.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/View/Top.php b/src/View/Top.php index e753401..0a34cb1 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -15,6 +15,8 @@ class Top extends Composite public $require = []; /** @var array */ public $deps = []; + /** @var \ctiso\Registry */ + public $config; /** * Заголовок страницы From 0267d3081f917fdc6f190de1bf267828821e4942 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 29 Oct 2025 17:38:30 +0300 Subject: [PATCH 110/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 7 ++++--- src/Database/Manager.php | 8 ++++---- src/Database/PDOStatement.php | 2 +- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index a639ac4..6cd5c66 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -232,13 +232,14 @@ class Component } /** + * FIXME: Передавать в модель имя класса, а не часть * Создает модель - * @param string $name + * @param class-string $modelName * @return mixed */ - public function getModel($name) + public function getModel($modelName) { - $modelName = "App\\Mapper\\" . $name; + // $modelName = "App\\Mapper\\" . $name; $model = new $modelName(); $model->config = $this->config; $model->db = $this->db; diff --git a/src/Database/Manager.php b/src/Database/Manager.php index 0ea3547..9f0fe05 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -12,10 +12,10 @@ use Exception; * type:string, * table_name:string, * table:string, - * fields:array, + * fields:array, * field: ColumnProps, - * constraints:?array, - * references:?array, + * constraints:?array, + * references:?array, * source:string, * pgsql?:string, * old_name?:string, @@ -24,7 +24,7 @@ use Exception; * column_name?:string, * refTable?:string, * refColumn?:string, - * values:array, + * values:array, * view:string, * select:string * } diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index 2811df2..3030723 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -11,7 +11,7 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate { /** @var int */ protected $cursorPos = 0; - /** @var array */ + /** @var array */ public $cache = []; /** @var ?array */ public $fields; From 5e8958969ff3feead75b64ab88de9cfd25ca9ad7 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 29 Oct 2025 20:43:32 +0300 Subject: [PATCH 111/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/ActionInterface.php | 6 +++++- src/Controller/Front.php | 15 ++++++++++++--- src/Filter/Filter.php | 9 +++++---- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/Controller/ActionInterface.php b/src/Controller/ActionInterface.php index d0113b4..b6551c9 100644 --- a/src/Controller/ActionInterface.php +++ b/src/Controller/ActionInterface.php @@ -6,6 +6,10 @@ use ctiso\Database; use ctiso\HttpRequest; interface ActionInterface { + /** + * @param HttpRequest $request + * @return mixed + */ function execute(HttpRequest $request); function getConnection(): Database; /** @@ -17,5 +21,5 @@ interface ActionInterface { * @param string $key * @param string $value */ - function addUrlPart($key, $value); + function addUrlPart($key, $value): void; } \ No newline at end of file diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 4aef444..affe522 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -19,12 +19,21 @@ use ctiso\Role\User; class Front extends Action { - protected $_param; // Параметр по которому выбирается модуль - protected $default; // Значение параметра по умолчанию + /** + * Параметр по которому выбирается модуль + * @var string + */ + protected $_param; + /** + * Значение параметра по умолчанию + * @var string + */ + protected $default; - /** @var array */ + /** @var array */ protected $modules = []; + public function __construct(Database $db, Registry $config, User $user, $default) { parent::__construct(); $this->config = $config; diff --git a/src/Filter/Filter.php b/src/Filter/Filter.php index 7aac567..57d8e7c 100644 --- a/src/Filter/Filter.php +++ b/src/Filter/Filter.php @@ -7,14 +7,15 @@ namespace ctiso\Filter; use ctiso\Database; use ctiso\HttpRequest; +use ctiso\Controller\ActionInterface; -class Filter implements \ctiso\Controller\ActionInterface +class Filter implements ActionInterface { - /** @var \ctiso\Controller\ActionInterface */ + /** @var ActionInterface */ public $processor; /** - * @param \ctiso\Controller\ActionInterface $processor + * @param ActionInterface $processor */ public function __construct($processor) { @@ -41,7 +42,7 @@ class Filter implements \ctiso\Controller\ActionInterface return $this->processor->getConnection(); } - public function addUrlPart($key, $value) { + public function addUrlPart($key, $value): void { $this->processor->addUrlPart($key, $value); } } From f964472e628cc91d01cce2e3e379367557275e62 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 30 Oct 2025 12:59:36 +0300 Subject: [PATCH 112/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Collection.php | 3 ++ src/Connection/HttpRequest.php | 5 +-- src/Connection/HttpResponse.php | 3 ++ src/Controller/Action.php | 5 +-- src/Controller/Component.php | 17 ++++++++-- src/Controller/Service.php | 3 ++ src/Database.php | 2 +- src/Excel/Table.php | 3 ++ src/Filter/ActionAccess.php | 10 ++++-- src/Filter/Login.php | 5 ++- src/Form/Field.php | 2 ++ src/Form/Form.php | 2 ++ src/Functions.php | 3 ++ src/Layout/Manager.php | 5 ++- src/Mail.php | 9 ++++-- src/Path.php | 7 +++-- src/Registry.php | 5 +++ src/Role/User.php | 2 +- src/Settings.php | 12 ++++++++ src/Setup.php | 5 +++ src/SortRecord.php | 2 +- src/Tools/SQLStatementExtractor.php | 5 +++ src/Tools/TemplateImage.php | 48 ++++++++++++++++++++--------- src/Validator/Rule/AbstractRule.php | 4 +++ src/Validator/Rule/Count.php | 4 +++ src/Validator/Rule/MatchRule.php | 1 + src/Validator/Validator.php | 2 +- src/View/View.php | 2 +- 28 files changed, 140 insertions(+), 36 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index ca5e3ae..1740ade 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -14,6 +14,7 @@ class Collection implements \ArrayAccess * Преобразование массива в коллекцию * * @param array $data + * @return bool */ public function import(array $data) { @@ -23,6 +24,8 @@ class Collection implements \ArrayAccess /** * Преобразование коллекции в массив + * + * @return array */ public function export() { diff --git a/src/Connection/HttpRequest.php b/src/Connection/HttpRequest.php index c255f77..5c71f1d 100644 --- a/src/Connection/HttpRequest.php +++ b/src/Connection/HttpRequest.php @@ -52,7 +52,7 @@ class HttpRequest * @param string $name * @param string $value */ - public function setParameter($name, $value) + public function setParameter($name, $value): void { $this->param[$name] = $value; } @@ -93,6 +93,7 @@ class HttpRequest /** * Посылает запрос и возвращает страницу + * @return string|null */ public function getPage() { @@ -105,7 +106,7 @@ class HttpRequest $header = $this->getHeader(); fwrite($socket, $header); - $result = null; + $result = ''; while (! feof($socket)) { $result .= fgets($socket, 128); } diff --git a/src/Connection/HttpResponse.php b/src/Connection/HttpResponse.php index d3cf5ac..9f0fe69 100644 --- a/src/Connection/HttpResponse.php +++ b/src/Connection/HttpResponse.php @@ -20,6 +20,9 @@ class HttpResponse /** @var string */ public $data; + /** + * @param string $response HTTP ответ + */ public function __construct($response) { $this->offset = 0; diff --git a/src/Controller/Action.php b/src/Controller/Action.php index dcb69fe..514b8cd 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -53,6 +53,7 @@ class Action implements ActionInterface // Для Widgets public $view = null; + public array $childNodes = []; public array $ctrlValues = []; public array $childViews = []; @@ -61,7 +62,7 @@ class Action implements ActionInterface $this->part = new Url(); } - public function setUp() { + public function setUp(): void { } /** @@ -338,7 +339,7 @@ class Action implements ActionInterface /** * Загрузка настроек - * @param $path + * @param string $path * @return array */ public function loadSettings($path) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 6cd5c66..a6e0e4d 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -13,6 +13,7 @@ use ctiso\Database; use ctiso\Collection; use ctiso\Registry; use ctiso\Controller\SiteInterface; +use ctiso\Database\PDOStatement; use PHPTAL; use PHPTAL_PreFilter_Normalize; @@ -249,7 +250,8 @@ class Component /** * @param string $key * @param string $val - * @param $res + * @param PDOStatement $res + * @return array{value: string, name: string}[] */ public function options(string $key, string $val, $res) { $result = []; @@ -262,7 +264,7 @@ class Component /** * @param array $list * @param bool $selected - * @return array + * @return array{value: string, name: string, selected: bool}[] */ public function optionsPair(array $list, $selected = false) { $result = []; @@ -288,6 +290,10 @@ class Component return null; } + /** + * Получить информацию о параметрах + * @return array + */ function getInfo() { $filename = Path::join($this->viewPath[count($this->viewPath) - 1], 'install.json'); if (file_exists($filename)) { @@ -502,4 +508,11 @@ class Component return null; } + /** + * @param HttpRequest $request + * @return array + */ + function getDefaultPageEnvironment($request) { + return []; + } } diff --git a/src/Controller/Service.php b/src/Controller/Service.php index 923b4ad..47607a9 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -98,6 +98,9 @@ class Service return $result; } + /** + * @return array + */ function getInfo() { $filename = Path::join($this->viewPath[0], 'install.json'); if (file_exists($filename)) { diff --git a/src/Database.php b/src/Database.php index 194d3b4..5de9e52 100644 --- a/src/Database.php +++ b/src/Database.php @@ -216,7 +216,7 @@ namespace ctiso { * @param array $values - значения * @param string $cond - условие */ - function updateQuery($table, array $values, $cond) + function updateQuery($table, array $values, $cond): void { $prep = $this->prepareValues($values); $sql = "UPDATE $table SET " . implode( diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 3009c64..2e8b7c4 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -16,6 +16,9 @@ class TableCell public $value; public $merge = false; + /** + * @param string $value Значение клетки + */ function __construct ($value) { $this->value = $value; diff --git a/src/Filter/ActionAccess.php b/src/Filter/ActionAccess.php index db82044..6dd44c3 100644 --- a/src/Filter/ActionAccess.php +++ b/src/Filter/ActionAccess.php @@ -4,9 +4,9 @@ * Фильтр действий */ namespace ctiso\Filter; -use ctiso\Filter\UserAccess, - ctiso\HttpRequest, - ctiso\Role\User; + +use ctiso\HttpRequest; +use ctiso\Role\User; class ActionAccess { @@ -39,6 +39,10 @@ class ActionAccess return (!isset($this->access[$action]) || in_array($this->user->access, $this->access[$action])); } + /** + * @param HttpRequest $request + * @return mixed + */ function execute(HttpRequest $request) { $action = $request->getAction(); if(! $this->checkAction($action)) { diff --git a/src/Filter/Login.php b/src/Filter/Login.php index d023db0..f2d0c4f 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -145,7 +145,10 @@ class Login extends Filter $_SESSION["time"] = time(); } - public function execute(HttpRequest $request): string + /** + * @return mixed + */ + public function execute(HttpRequest $request): mixed { $logged = $this->isLoggin($request); if ($request->get('action') == 'user_access') { diff --git a/src/Form/Field.php b/src/Form/Field.php index 30daf90..f7ae6f9 100644 --- a/src/Form/Field.php +++ b/src/Form/Field.php @@ -13,11 +13,13 @@ class Field /** @var string */ public $label; // Метка поля + /** @var mixed */ public $value; // Значение поля /** @var string */ public $type = ""; // Каждому типу элемента соответствует макрос TAL /** @var ?string */ public $error_msg = null; + /** @var ?mixed */ public $default = null; /** @var bool */ public $error = false; diff --git a/src/Form/Form.php b/src/Form/Form.php index d072288..4d0704f 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -28,7 +28,9 @@ class Form { /** @var string */ public $header; + /** @var array */ protected $replace; + /** @var array */ protected $before; /** @var array */ diff --git a/src/Functions.php b/src/Functions.php index 812175f..64fd100 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -289,6 +289,7 @@ class Functions { * @param string $key * @param string $value * @param list>|\ArrayIterator $array + * @return array */ static function assoc_key_values($key, $value, $array) { $result = []; @@ -301,6 +302,7 @@ class Functions { /** * @param string $key * @param list>|\ArrayIterator $array + * @return array */ static function assoc_key($key, $array) { $result = []; @@ -450,6 +452,7 @@ class Functions { * Сортировка двумерного массива по заданному ключу * @param array $array Массив * @param string $key Имя ключа по значению которого будет идти сравнение + * @param callable $fn Функция сравнения * @return array Отсортированный массив */ static function sortOn($array, $key, $fn = '\\ctiso\\Functions::__cmp') { diff --git a/src/Layout/Manager.php b/src/Layout/Manager.php index a3f9b26..c256afb 100644 --- a/src/Layout/Manager.php +++ b/src/Layout/Manager.php @@ -29,6 +29,8 @@ class Manager extends Filter /** * Условие для аякс запросов. Тоже самое что и addConditionGet но еще проверяется является ли запрос ajax + * @param array|true $get Ассоциативный массив ключей и значений для $_GET + * @param Filter $layout Макет */ public function addConditionXHR($get, Filter $layout): void { @@ -74,8 +76,9 @@ class Manager extends Filter /** * Выбирает и применяет макет для страницы + * @return mixed */ - public function execute(HttpRequest $request): string + public function execute(HttpRequest $request): mixed { foreach ($this->condition as $condition) { if (call_user_func($condition[0], $request)) { diff --git a/src/Mail.php b/src/Mail.php index 697895a..e965dfd 100644 --- a/src/Mail.php +++ b/src/Mail.php @@ -53,18 +53,21 @@ class Mail /** * Установка получателя */ - function to(string $name): void // recipient + function to(string $name): void { $this->_to = $name; } - function replyTo($name): void // recipient + /** + * @param string $name + */ + function replyTo($name): void {} /** * Установка получателей копии */ - function copy(string $name): void // recipient cc + function copy(string $name): void { $this->copy = $name; } diff --git a/src/Path.php b/src/Path.php index 787e2c7..8754f7f 100644 --- a/src/Path.php +++ b/src/Path.php @@ -55,8 +55,8 @@ class Path /** * Базовое имя - * @param $path - * @return mixed + * @param string $path + * @return string */ public static function basename($path) { @@ -120,6 +120,7 @@ class Path * Преобразует строку пути в массив * * @param string $path Путь + * @return array */ public static function listFromString(string $path): array { @@ -129,6 +130,8 @@ class Path /** * Преобразует относительный путь в абсолютный + * @param array $path Путь + * @return array */ public static function optimize($path) // { diff --git a/src/Registry.php b/src/Registry.php index 75924b4..5eda214 100644 --- a/src/Registry.php +++ b/src/Registry.php @@ -40,6 +40,11 @@ class Registry { throw new Exception('Unknown key ' . $ns . '::' . $key); } + /** + * @param string $ns + * @param string $key + * @return mixed|null + */ public function getOpt(string $ns, string $key) { if (isset($this->namespace[$ns]['data'][$key])) { return $this->namespace[$ns]['data'][$key]; diff --git a/src/Role/User.php b/src/Role/User.php index 972f35e..33cbc15 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -26,7 +26,7 @@ class User implements UserInterface $this->groups = $groups; } - public function setDB(Database $db) { + public function setDB(Database $db): void { $this->db = $db; } diff --git a/src/Settings.php b/src/Settings.php index 666532f..54491a9 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -67,6 +67,9 @@ class Settings /** * Запись ключа в реестр (Реестр это многомерный массив) + * @param array $key Путь к значению ключа + * @param mixed $value Значение + * @return void */ public function writeKey(array $key, $value) { @@ -216,10 +219,19 @@ class Settings return isset($this->data[$key]) && $this->data[$key] != '' ? $this->data[$key] : $default; } + /** + * Получение всех данных + * @return array + */ function export() { return $this->data; } + /** + * Импорт данных + * @param array $data Данные + * @return void + */ function import($data) { $this->data = $data; } diff --git a/src/Setup.php b/src/Setup.php index 935dabb..b520bd7 100644 --- a/src/Setup.php +++ b/src/Setup.php @@ -53,6 +53,9 @@ class Setup /** @var string */ public $source; + /** + * @param string $file + */ public function __construct($file) { $this->file = $file; @@ -150,6 +153,7 @@ class Setup * Выполняет список действий если для действия не указан аттрибут when то оно выполняется всегда * * @param string $action специальное действие + * @return void */ function executeActions($action = "install") { @@ -178,6 +182,7 @@ class Setup * dst Новый файл * * @param array{preserve?: string, template: string, src: string, dst: string} $attributes + * @return void */ public function copyFile(array $attributes) { diff --git a/src/SortRecord.php b/src/SortRecord.php index 855c85b..84604ea 100644 --- a/src/SortRecord.php +++ b/src/SortRecord.php @@ -44,7 +44,7 @@ class SortRecord return usort($list, [$this, 'compareKeys']); } - function group(array &$list, string $key, array $types) + function group(array &$list, string $key, array $types): void { $groups = []; foreach ($types as $name) { diff --git a/src/Tools/SQLStatementExtractor.php b/src/Tools/SQLStatementExtractor.php index 7ece534..c022ed8 100644 --- a/src/Tools/SQLStatementExtractor.php +++ b/src/Tools/SQLStatementExtractor.php @@ -34,6 +34,7 @@ use Exception; class SQLStatementExtractor { + /** @var string */ protected static $delimiter = ';'; /** @@ -144,6 +145,10 @@ class SQLStatementExtractor /** * 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 + * @param string $string The string to get the substring from. + * @param int $startpos The start position of the substring. + * @param int $endpos The end position of the substring. + * @return string The substring. */ protected static function substring(string $string, int $startpos, int $endpos = -1) { diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index 5d5bb06..01f3f99 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -3,7 +3,9 @@ /** * Формат для композиции изображений */ + namespace ctiso\Tools; + use ctiso\Tools\Drawing; use GdImage; @@ -27,7 +29,7 @@ class TemplateImage '' => 'arial.ttf', 'dejavu' => 'DejaVuCondensedSerif.ttf', 'dejavubd' => 'DejaVuCondensedSerifBold.ttf', - 'dejavuz' =>'DejaVuCondensedSerifBoldItalic.ttf', + 'dejavuz' => 'DejaVuCondensedSerifBoldItalic.ttf', 'dejavui' => 'DejaVuCondensedSerifItalic.ttf', 'miriad' => 'MyriadPro-Cond.ttf', 'miriadbd' => 'MyriadPro-BoldCond.ttf' @@ -47,7 +49,7 @@ class TemplateImage public string $resource; public string $filename; - function __construct (?array $template = null) + function __construct(?array $template = null) { if ($template) { $this->data = $template; @@ -70,9 +72,13 @@ class TemplateImage $this->base = $path; } + /** + * @param string $name + * @param mixed $value + */ function set(string $name, $value): void { - $this->context['['.$name.']'] = $value; + $this->context['[' . $name . ']'] = $value; } function setImage(string $name): void @@ -107,7 +113,7 @@ class TemplateImage function getFontFile(string $name): string { - if(array_key_exists(strtolower($name), self::$listfonts)) { + if (array_key_exists(strtolower($name), self::$listfonts)) { return $this->base . self::$listfonts[$name]; } return $this->base . 'arial.ttf'; @@ -115,15 +121,15 @@ class TemplateImage function fontSuffix(array $style): string { - if($style[0] && $style[1]) return "z"; + if ($style[0] && $style[1]) return "z"; - if($style[0]) return "bd"; - if($style[1]) return "i"; + if ($style[0]) return "bd"; + if ($style[1]) return "i"; return ""; } - function imageText(string $text, object $value) + function imageText(string $text, object $value): void { $text = strtr($text, $this->context); $size = $value->fontSize; @@ -140,15 +146,26 @@ class TemplateImage if ($value->valign[0]) { $valign = Drawing::ALIGN_TOP; - } elseif ($value->valign[1]) { + } elseif ($value->valign[1]) { $valign = Drawing::ALIGN_CENTER; } else { $valign = Drawing::ALIGN_BOTTOM; } - Drawing::imagettftextbox($this->image, $size, 0, $value->left, $value->top, $color, $fontfile, $text, - $value->width, $value->height, - $align, $valign); + Drawing::imagettftextbox( + $this->image, + $size, + 0, + $value->left, + $value->top, + $color, + $fontfile, + $text, + $value->width, + $value->height, + $align, + $valign + ); } /** @@ -171,12 +188,13 @@ class TemplateImage // Resample $image_p = imagecreatetruecolor($new_width, $new_height); imagecopyresampled($image_p, $this->image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); -// imagecopyresized($image_p, $this->image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); + // imagecopyresized($image_p, $this->image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); $this->image = $image_p; } - function prepare(): void { - if($this->_prepare) { + function prepare(): void + { + if ($this->_prepare) { $this->_prepare = false; foreach ($this->data as $value) { $this->imageText($value->text, $value); // break; diff --git a/src/Validator/Rule/AbstractRule.php b/src/Validator/Rule/AbstractRule.php index 0ca3438..fac4aad 100644 --- a/src/Validator/Rule/AbstractRule.php +++ b/src/Validator/Rule/AbstractRule.php @@ -7,6 +7,7 @@ abstract class AbstractRule { public string $field; protected ?string $errorMsg; + /** @var object */ protected $ctx; public function __construct(string $field, ?string $errorMsg = null) @@ -46,6 +47,9 @@ abstract class AbstractRule return true; } + /** + * @param object $ctx + */ public function setContext($ctx): void { $this->ctx = $ctx; diff --git a/src/Validator/Rule/Count.php b/src/Validator/Rule/Count.php index 7115587..fa650a8 100644 --- a/src/Validator/Rule/Count.php +++ b/src/Validator/Rule/Count.php @@ -17,6 +17,10 @@ class Count extends AbstractRule return "Количество записей должно быть не менне {$this->size} и не более {$this->max}"; } + /** + * @param string $s + * @return bool + */ function notEmpty($s): bool { return $s != ""; } diff --git a/src/Validator/Rule/MatchRule.php b/src/Validator/Rule/MatchRule.php index ab167d3..b0db64b 100644 --- a/src/Validator/Rule/MatchRule.php +++ b/src/Validator/Rule/MatchRule.php @@ -9,6 +9,7 @@ use ctiso\Validator\Rule\AbstractRule, class MatchRule extends AbstractRule { + /** @var string */ public $same; public function getErrorMsg(): string diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 5d50dae..7576ca8 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -147,7 +147,7 @@ class Validator return $this->isValid(); } - public function addError(string $name, string $message) + public function addError(string $name, string $message): void { $this->errorMsg[$name] = $message; } diff --git a/src/View/View.php b/src/View/View.php index 4ff81db..e4a091d 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -119,7 +119,7 @@ class View extends \stdClass return $result; } - /*abstract*/ public function set(string $key, mixed $value) + /*abstract*/ public function set(string $key, mixed $value): void { } From cf0bc435ceda9010ad94ca7301dd01d02a22362c Mon Sep 17 00:00:00 2001 From: Wizard Date: Sat, 1 Nov 2025 23:17:40 +0300 Subject: [PATCH 113/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D1=8F=20=D1=82=D0=B8=D0=BF=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Collection.php | 1 + src/Controller/Action.php | 31 +++++++++++++++--------------- src/Controller/ActionInterface.php | 1 + src/Controller/Component.php | 10 +++++++--- src/Controller/Front.php | 4 +++- src/Controller/Installer.php | 4 ++-- src/Database.php | 7 ++++++- src/Database/PDOStatement.php | 4 +++- src/Database/StatementIterator.php | 4 +++- src/Excel/Table.php | 15 +++++++++------ src/Form/Field.php | 12 +++++++++++- src/Form/Form.php | 7 ++++++- src/Functions.php | 7 +++++++ src/Numbers.php | 5 ++++- src/Primitive.php | 3 +++ src/Role/UserInterface.php | 2 +- src/Settings.php | 1 + src/Setup.php | 5 ++++- src/View/View.php | 10 ++++++++-- 19 files changed, 96 insertions(+), 37 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index 1740ade..0604a06 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -48,6 +48,7 @@ class Collection implements \ArrayAccess * Read stored "request data" by referencing a key. * * @param string $key + * @param mixed $default * @return mixed */ public function get($key, $default = null) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 514b8cd..6948166 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -31,27 +31,26 @@ class Action implements ActionInterface public string $viewPathPrefix = ''; // Путь к шаблонам контроллера - /** - * Соединение с базой данных - */ + /** Соединение с базой данных */ public Database $db; // Фильтры - /** @var ?\ctiso\Filter\ActionAccess */ - public $access = null; // Обьект хранит параметры доступа - /** @var ?\ctiso\Filter\ActionLogger */ - public $logger = null; // Обьект для ведения лога - + /** @var ?\ctiso\Filter\ActionAccess Обьект хранит параметры доступа */ + public $access = null; + /** @var ?\ctiso\Filter\ActionLogger Обьект для ведения лога */ + public $logger = null; + /** @var Factory Обьект для создания моделей */ private $factory = null; // Ссылка на обьект создания модели private array $helpers = []; // Помошники для действий - public $part = null; // Параметры для ссылки + /** @var ?Url Параметры для ссылки */ + public $part = null; - /** @var \ctiso\Registry */ - public $config; // Ссылка на настройки - /** @var \ctiso\Role\User */ - public $user; // Обьект пользователя + /** @var \ctiso\Registry Ссылка на настройки */ + public $config; + /** @var \ctiso\Role\User Обьект пользователя */ + public $user; - // Для Widgets + /** @var \ctiso\View\View Для Widgets */ public $view = null; public array $childNodes = []; @@ -307,6 +306,8 @@ class Action implements ActionInterface /** * Вызов помошников контроллера + * @param HttpRequest $request + * @return mixed */ public function callHelpers(HttpRequest $request) { @@ -430,7 +431,7 @@ class Action implements ActionInterface /** * Проверка идентификатора страницы - * @param $page int Идентификатор страницы + * @param int $page Идентификатор страницы * @return bool */ function checkPageId(HttpRequest $request, $page) diff --git a/src/Controller/ActionInterface.php b/src/Controller/ActionInterface.php index b6551c9..97d3251 100644 --- a/src/Controller/ActionInterface.php +++ b/src/Controller/ActionInterface.php @@ -15,6 +15,7 @@ interface ActionInterface { /** * @param string $name * @param class-string<\ctiso\View\View> $class + * @return \ctiso\View\View */ function getView($name, $class); /** diff --git a/src/Controller/Component.php b/src/Controller/Component.php index a6e0e4d..18d87ea 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -84,7 +84,7 @@ class Component */ public $site; - function before() { + function before(): void { } /** @@ -308,9 +308,9 @@ class Component /** * Генерация интерфейса для выбора галлереи фотографии * @param Composite $view - * @param \ctiso\Form\OptionsFactory $options + * @param ?\ctiso\Form\OptionsFactory $options */ - public function setParameters(Composite $view, $options = null) + public function setParameters(Composite $view, $options = null): void { $form = new Form(); @@ -322,6 +322,10 @@ class Component $view->component_title = $settings['title']; } + /** + * @param \ctiso\Form\OptionsFactory $options + * @return array + */ public function getFields($options = null) { $form = new Form(); $form->addFieldList($this->getInfo()['parameter'], $options); diff --git a/src/Controller/Front.php b/src/Controller/Front.php index affe522..1a64a65 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -33,7 +33,9 @@ class Front extends Action /** @var array */ protected $modules = []; - + /** + * @param string $default + */ public function __construct(Database $db, Registry $config, User $user, $default) { parent::__construct(); $this->config = $config; diff --git a/src/Controller/Installer.php b/src/Controller/Installer.php index f925697..6aefd18 100644 --- a/src/Controller/Installer.php +++ b/src/Controller/Installer.php @@ -15,7 +15,7 @@ class Installer /** @var callable */ protected $installPath; /** @var Settings */ - public $_registry; + public $_registry; public function __construct(Settings $_registry) { @@ -27,7 +27,7 @@ class Installer * @param Manager $db_manager * @param callable $installPath */ - public function setUp($db_manager, $installPath) + public function setUp($db_manager, $installPath): void { $this->db_manager = $db_manager; $this->installPath = $installPath; diff --git a/src/Database.php b/src/Database.php index 5de9e52..94fb840 100644 --- a/src/Database.php +++ b/src/Database.php @@ -1,6 +1,10 @@ cursorPos !== 0) { $this->seek(0); } return $this->next(); diff --git a/src/Database/StatementIterator.php b/src/Database/StatementIterator.php index b3c4152..7a8b76f 100644 --- a/src/Database/StatementIterator.php +++ b/src/Database/StatementIterator.php @@ -5,7 +5,6 @@ use PDO; class StatementIterator implements \Iterator { - /** @var PDOStatement */ private $result; /** @var int */ @@ -44,6 +43,9 @@ class StatementIterator implements \Iterator $this->pos++; } + /** + * @param int $index + */ function seek($index): void { $this->pos = $index; } diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 2e8b7c4..1a2a39b 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -82,6 +82,9 @@ class Table /** * Записать значение в клетку с заданными координатами + * @param int $x Номер ряда + * @param int $y Номер столбца + * @param string $value Значение клетки */ function setCell(int $x, int $y, $value): void { @@ -137,16 +140,15 @@ class Table /** * Обьединяет клетки в строке - * @param $row Номер ряда - * @param $cell Номер столбца - * @param $merge Количество клеток для обьединения + * @param int $x Номер ряда + * @param int $cell Номер столбца + * @param int $merge Количество клеток для обьединения */ function setCellMerge(int $x, int $cell, $merge): void { assert($x > 0); assert($cell > 0); - /** @var TableRow $row */ $row = $this->rows[$x]; $row->cells[$cell]->merge = $merge; } @@ -157,7 +159,7 @@ class Table * @param int $y Номер столбца * @param string $name Имя стиля */ - function setCellStyle ($row, $y, $name) + function setCellStyle ($row, $y, $name): void { if (isset($this->rows[$row])) { $this->rows[$row]->setCellStyle($y, $name); @@ -166,6 +168,7 @@ class Table /** * Добавляет строку к таблице + * @return int Номер добавленной строки */ function addRow(int $index = 1, array $data = [""]) { @@ -243,7 +246,7 @@ class Table * @param mixed $value Значение клетки * @param bool $setIndex Устанавливать индекс клетки в атрибут ss:Index */ - function createCell (TableCell $ncell, XMLWriter $doc, $j, mixed $value, $setIndex) { + function createCell (TableCell $ncell, XMLWriter $doc, $j, mixed $value, $setIndex): void { $doc->startElement("Cell"); if ($ncell->style) { diff --git a/src/Form/Field.php b/src/Form/Field.php index f7ae6f9..098003e 100644 --- a/src/Form/Field.php +++ b/src/Form/Field.php @@ -4,6 +4,8 @@ */ namespace ctiso\Form; +use ctiso\Form\OptionsFactory; + class Field { /** @var bool */ @@ -25,18 +27,26 @@ class Field public $error = false; /** @var bool */ public $require = false; + /** @var ?string */ public $hint = null; /** @var ?int */ public $maxlength = null; + /** @var ?string */ public $fieldset = null; // Блоки (Убрать в отдельный класс!!!) + /** @var array */ public $_title = []; /** @var string */ public $description = ""; /** @var array */ public $alias = []; - /** @phpstan-ignore-next-line */ + + /** + * @param array $input + * @param OptionsFactory|null $factory + * @phpstan-ignore-next-line + */ public function __construct ($input = [], $factory = null) { $this->default = null; diff --git a/src/Form/Form.php b/src/Form/Form.php index 4d0704f..7bfde94 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -16,7 +16,7 @@ use ctiso\HttpRequest; * Форма для ввода */ class Form { - /** @var array */ + /** @var array */ public $field = []; //Поля формы /** @var array */ public $fieldsets = []; //Группы полей (fieldset). Некоторые поля могут не принадлежать никаким группам @@ -137,6 +137,7 @@ class Form { /** * Добавляет список полей для формы * @param array $list + * @param OptionsFactory|null $factory */ public function addFieldList(array $list, $factory = null): void { @@ -191,6 +192,10 @@ class Form { } } + /** + * @param string $name + * @param mixed $value + */ public function set($name, $value): void { $this->field[$name]->setValue($value); diff --git a/src/Functions.php b/src/Functions.php index 64fd100..8f415f5 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -94,7 +94,12 @@ class partial { * Композиция функций */ class compose { + /** @var array */ protected $fns; + + /** + * @param array $list + */ function __construct($list) { $this->fns = array_reverse($list); } @@ -275,6 +280,7 @@ class Functions { /** * @param string $key * @param list|\ArrayIterator $array + * @return array */ static function key_values_object($key, $array) { $result = []; @@ -415,6 +421,7 @@ class Functions { * Поиск элемента в массиве * @param callable $cb сравнение с элементом массива * @param array $hs массив в котором ищется значение + * @param bool $strict * * @return int|string|null ключ найденого элемента в массиве */ diff --git a/src/Numbers.php b/src/Numbers.php index 368db12..f11678b 100644 --- a/src/Numbers.php +++ b/src/Numbers.php @@ -14,7 +14,10 @@ class Numbers return $i; } - static function prefix(callable $prefix, array $array, $key = false) + /** + * @param array $array + */ + static function prefix(callable $prefix, array $array) { $result = []; $count = count($array); diff --git a/src/Primitive.php b/src/Primitive.php index 13dc67b..746f868 100644 --- a/src/Primitive.php +++ b/src/Primitive.php @@ -53,6 +53,9 @@ class Primitive { return ((int) $value); } + /** + * @param mixed $value + */ public static function from_int($value): string { return ((string) $value); diff --git a/src/Role/UserInterface.php b/src/Role/UserInterface.php index 53e7150..5eb57d1 100644 --- a/src/Role/UserInterface.php +++ b/src/Role/UserInterface.php @@ -7,6 +7,6 @@ interface UserInterface { function getUserByQuery(Statement $stmt); function getUserByLogin(string $login); function getUserById(int $id); - function getName(); + function getName(): string; function setSID(string $random, $result); } \ No newline at end of file diff --git a/src/Settings.php b/src/Settings.php index 54491a9..1e75fc3 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -212,6 +212,7 @@ class Settings /** * Получение значения ключа * @param string $key Ключ + * @param mixed $default Значение по умолчанию * @return mixed */ public function get($key, $default = null) diff --git a/src/Setup.php b/src/Setup.php index b520bd7..4c83a9b 100644 --- a/src/Setup.php +++ b/src/Setup.php @@ -16,7 +16,7 @@ class FakeZipArchive { /** @var string */ public $base; - function open(string $path) { + function open(string $path): void { $this->base = $path; } @@ -95,6 +95,9 @@ class Setup $this->context[$name] = $value; } + /** + * @return string + */ function replaceFn(array $matches) { if (isset($this->context[$matches[2]])) { $v = $this->context[$matches[2]]; diff --git a/src/View/View.php b/src/View/View.php index e4a091d..45091a0 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -29,9 +29,9 @@ class View extends \stdClass /** @var string[] */ public array $suggestions = []; //подсказки - /** @var string[] $alias */ + /** @var array> */ public array $alias = []; - public $codeGenerator = null; + // public $codeGenerator = null; /** @var View|null */ public $parent_view = null; @@ -52,6 +52,9 @@ class View extends \stdClass } } + /** + * @param array $values + */ public function assignValues($values): void { $this->_values = $values; @@ -146,6 +149,9 @@ class View extends \stdClass return $title !== null; } + /** + * @param array> $alias + */ function setAlias($alias): void { $this->alias = $alias; From f07a668b30d0c6d2823dbe41343c45b2abf4075e Mon Sep 17 00:00:00 2001 From: Wizard Date: Sun, 2 Nov 2025 12:33:26 +0300 Subject: [PATCH 114/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D1=8F=20=D1=82=D0=B8=D0=BF=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Collection.php | 2 +- src/Controller/Action.php | 11 ++++++++--- src/Controller/Installer.php | 2 +- src/Controller/SiteInterface.php | 18 +++++++++++++++++- src/Database/PDOStatement.php | 3 +++ src/Database/StatementIterator.php | 3 +++ src/Excel/Table.php | 5 +++-- src/Functions.php | 8 ++++---- src/Numbers.php | 1 + src/Role/User.php | 5 +++-- src/Role/UserInterface.php | 13 ++++++++++--- src/Settings.php | 2 ++ src/Setup.php | 2 +- src/View/Plain.php | 6 +++++- 14 files changed, 62 insertions(+), 19 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index 0604a06..cf8b814 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -3,7 +3,7 @@ namespace ctiso; /** * Коллекция - * + * @implements \ArrayAccess */ class Collection implements \ArrayAccess { diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 6948166..20afb41 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -24,6 +24,7 @@ class Action implements ActionInterface // Параметры устанавливаются при создании контроллера public string $name = ''; // Имя модуля + /** @var \ctiso\Controller\Front */ public $front; public string $modulePath = ''; // Путь к модулю @@ -283,7 +284,7 @@ class Action implements ActionInterface /** * Генерация ссылки на действие контроллера * Ajax определяется автоматически mode = ajax используется для смены layout - * @param $name + * @param string $name * @param array $param * @return Url|null * @@ -299,7 +300,7 @@ class Action implements ActionInterface * Добавление помошника контроллера * @param class-string $class */ - public function addHelper($class) + public function addHelper($class): void { $this->helpers [] = $class; } @@ -323,10 +324,11 @@ class Action implements ActionInterface /** * Загрузка файла класса - * @deprecated + * @deprecated Веместо его нужно использовать автозагрузку * @param string $path * @param mixed $setup * @param string $prefix + * @return mixed */ public function loadClass($path, $setup = null, $prefix = '') { @@ -350,6 +352,9 @@ class Action implements ActionInterface return $result->export(); } + /** + * @param string $name + */ public function setView($name): void { $this->view = $this->getView($name); diff --git a/src/Controller/Installer.php b/src/Controller/Installer.php index 6aefd18..79b08f2 100644 --- a/src/Controller/Installer.php +++ b/src/Controller/Installer.php @@ -163,7 +163,7 @@ class Installer * @param string $dbinit_path * @param string|null $dbfill_path */ - function install($dbinit_path, $dbfill_path = null) + function install($dbinit_path, $dbfill_path = null): void { $json_installer = new JsonInstall($this->db_manager); $json_installer->install($dbinit_path, $dbfill_path); diff --git a/src/Controller/SiteInterface.php b/src/Controller/SiteInterface.php index 4fd6ff4..92c06a5 100644 --- a/src/Controller/SiteInterface.php +++ b/src/Controller/SiteInterface.php @@ -3,13 +3,26 @@ namespace ctiso\Controller; interface SiteInterface { + /** + * FIXME: Возвращает ресурс (но его тип опрделяется в App) + * @return mixed + */ function getResource(); /** * @return \ctiso\Database */ function getDatabase(); + /** + * @return \ctiso\Registry + */ function getConfig(); + /** + * @return \ctiso\Settings + */ function getTheme(); + /** + * @param array $config + */ function addComponentConfig($config): void; function addRequireJsPath(string $name, string $path, ?array $shim = null): void; function addStyleSheet(string $url): void; @@ -19,7 +32,10 @@ interface SiteInterface { * @return ?Component */ function loadComponent(string $expression); + /** + * @return array{string, string, string} + */ function findTemplate(string $name); - function replaceImg(string $src, int $width, int $height); + function replaceImg(string $src, int $width, int $height): string; function updatePageTime(int $time): void; } diff --git a/src/Database/PDOStatement.php b/src/Database/PDOStatement.php index 6fedc9e..69a1c49 100644 --- a/src/Database/PDOStatement.php +++ b/src/Database/PDOStatement.php @@ -7,6 +7,9 @@ use ctiso\Database\StatementIterator, PDO; use TheSeer\Tokenizer\Exception; +/** + * @implements \IteratorAggregate + */ class PDOStatement extends \PDOStatement implements \IteratorAggregate { /** @var int */ diff --git a/src/Database/StatementIterator.php b/src/Database/StatementIterator.php index 7a8b76f..43f82e9 100644 --- a/src/Database/StatementIterator.php +++ b/src/Database/StatementIterator.php @@ -3,6 +3,9 @@ namespace ctiso\Database; use PDO; +/** + * @implements \Iterator + */ class StatementIterator implements \Iterator { /** @var PDOStatement */ diff --git a/src/Excel/Table.php b/src/Excel/Table.php index 1a2a39b..bb15d3d 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -14,6 +14,7 @@ class TableCell public $style = false; /** @var string */ public $value; + /** @var bool */ public $merge = false; /** @@ -142,7 +143,7 @@ class Table * Обьединяет клетки в строке * @param int $x Номер ряда * @param int $cell Номер столбца - * @param int $merge Количество клеток для обьединения + * @param bool $merge Количество клеток для обьединения */ function setCellMerge(int $x, int $cell, $merge): void { @@ -254,7 +255,7 @@ class Table } if ($ncell->merge) { - $doc->writeAttribute('ss:MergeAcross', $ncell->merge); + $doc->writeAttribute('ss:MergeAcross', (string)$ncell->merge); } if ($setIndex) { diff --git a/src/Functions.php b/src/Functions.php index 8f415f5..3e040c4 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -265,7 +265,7 @@ class Functions { * @example key_values('a', array(1 => array('a' => 1, 'b' => 2))) => array(1) * * @param string $key - * @param list|\ArrayIterator $array + * @param list|\ArrayIterator $array * @return mixed */ static function key_values($key, $array) { @@ -279,7 +279,7 @@ class Functions { /** * @param string $key - * @param list|\ArrayIterator $array + * @param list|\ArrayIterator $array * @return array */ static function key_values_object($key, $array) { @@ -294,7 +294,7 @@ class Functions { /** * @param string $key * @param string $value - * @param list>|\ArrayIterator $array + * @param list>|\ArrayIterator $array * @return array */ static function assoc_key_values($key, $value, $array) { @@ -307,7 +307,7 @@ class Functions { /** * @param string $key - * @param list>|\ArrayIterator $array + * @param list>|\ArrayIterator $array * @return array */ static function assoc_key($key, $array) { diff --git a/src/Numbers.php b/src/Numbers.php index f11678b..5d92be2 100644 --- a/src/Numbers.php +++ b/src/Numbers.php @@ -16,6 +16,7 @@ class Numbers /** * @param array $array + * @return array */ static function prefix(callable $prefix, array $array) { diff --git a/src/Role/User.php b/src/Role/User.php index 33cbc15..1cca467 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -96,9 +96,10 @@ class User implements UserInterface /** * @param string $random * @param PDOStatement $result - * @return PDOStatement + * @return PDOStatement|bool */ - function setSID(string $random, $result) { + function setSID(string $random, $result) + { return $this->db->executeQuery("UPDATE users SET sid = :sid, trie_count = 0 WHERE id_user = :user", [ 'user' => $result->getInt('id_user'), 'sid' => $random diff --git a/src/Role/UserInterface.php b/src/Role/UserInterface.php index 5eb57d1..a69d9b7 100644 --- a/src/Role/UserInterface.php +++ b/src/Role/UserInterface.php @@ -2,11 +2,18 @@ namespace ctiso\Role; use ctiso\Database\Statement; +use ctiso\Database\PDOStatement; interface UserInterface { - function getUserByQuery(Statement $stmt); - function getUserByLogin(string $login); - function getUserById(int $id); + function getUserByQuery(Statement $stmt): ?PDOStatement; + function getUserByLogin(string $login): ?PDOStatement; + function getUserById(int $id): ?PDOStatement; function getName(): string; + + /** + * @param string $random + * @param PDOStatement $result + * @return PDOStatement|bool + */ function setSID(string $random, $result); } \ No newline at end of file diff --git a/src/Settings.php b/src/Settings.php index 1e75fc3..e678ea5 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -121,6 +121,7 @@ class Settings /** * Чтение ключа из реестра * @param array $key Путь к значению ключа + * @param array $data * @return mixed */ protected function readKeyData(array $key, $data) @@ -145,6 +146,7 @@ class Settings /** * Чтение ключа из реестра (Собирает все ключи с определенным значением во всех модулях) * @param mixed $key Путь к значению ключа внутри модуля + * @return array */ public function readKeyList(...$key) { diff --git a/src/Setup.php b/src/Setup.php index 4c83a9b..7f7874f 100644 --- a/src/Setup.php +++ b/src/Setup.php @@ -90,7 +90,7 @@ class Setup * @param string $name * @param mixed $value */ - public function set(string $name, $value) + public function set(string $name, $value): void { $this->context[$name] = $value; } diff --git a/src/View/Plain.php b/src/View/Plain.php index feb617c..f6fc13e 100644 --- a/src/View/Plain.php +++ b/src/View/Plain.php @@ -26,7 +26,7 @@ class Plain extends \stdClass * @param string $key ключ * @param mixed $value значение */ - public function set($key, $value) + public function set($key, $value): void { $this->values[$key] = $value; } @@ -40,6 +40,10 @@ class Plain extends \stdClass $this->values = array_merge($this->values, $list); } + /** + * @param string $key ключ + * @param mixed $value значение + */ public function __set($key, $value): void { $this->set($key, $value); From 540805ae35c10a796e8536d076a55c1ee9b280cf Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 5 Nov 2025 11:01:56 +0300 Subject: [PATCH 115/138] =?UTF-8?q?fix:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D0=B8=20=D0=BA=20=D1=82=D0=B8=D0=BF=D0=B0?= =?UTF-8?q?=D0=BC.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Database.php | 13 ++++++++----- src/Database/Statement.php | 2 +- src/Tools/TemplateImage.php | 15 +++++++++++++++ 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/Database.php b/src/Database.php index 94fb840..8d7807d 100644 --- a/src/Database.php +++ b/src/Database.php @@ -1,8 +1,8 @@ setAttribute(PDO::ATTR_STATEMENT_CLASS, [PDOStatement::class, []]); } - function prepare(string $sql, array $options = []): PDOStatement|false + /** + * prepare возвращает только PDOStatement т.к установлен PDO::ERRMODE_EXCEPTION + */ + function prepare(string $sql, array $options = []): PDOStatement { - /** @var PDOStatement $result */ + /** @var PDOStatement */ $result = parent::prepare($sql, $options); return $result; } @@ -106,7 +109,7 @@ namespace ctiso { * @param string $query - запрос * @param ?array $values - значения */ - public function executeQuery($query, $values = null): PDOStatement|bool + public function executeQuery($query, $values = null): PDOStatement { $stmt = $this->prepare($query); diff --git a/src/Database/Statement.php b/src/Database/Statement.php index 90b6619..e270822 100644 --- a/src/Database/Statement.php +++ b/src/Database/Statement.php @@ -71,7 +71,7 @@ class Statement } /** - * @return ?PDOStatement + * @return PDOStatement */ function executeQuery() { if ($this->limit) { diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index 01f3f99..66d5460 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -129,6 +129,21 @@ class TemplateImage return ""; } + /** + * @param string $text + * @param object{ + * fontFamily: string, + * fontSize: int, + * fontStyle: array{string, string}, + * color: string, + * align: array, + * valign: array, + * left: int, + * top: int, + * width: int, + * height: int + * } $value + */ function imageText(string $text, object $value): void { $text = strtr($text, $this->context); From 87fc94d700829355ea068b0323c174a420e2a5d4 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 6 Nov 2025 11:59:54 +0300 Subject: [PATCH 116/138] =?UTF-8?q?fix:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D1=86=D0=B8=D1=8F=20=D1=82=D0=B8=D0=BF=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Arr.php | 4 ++-- src/ComponentRequest.php | 8 ++++---- src/Controller/Component.php | 8 +++----- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/Arr.php b/src/Arr.php index 99ac0ba..2fa9187 100644 --- a/src/Arr.php +++ b/src/Arr.php @@ -5,8 +5,8 @@ namespace ctiso; class Arr { /** - * @param array $data - * @param string $key + * @param array $data + * @param string|int $key * @param mixed $default * @return mixed */ diff --git a/src/ComponentRequest.php b/src/ComponentRequest.php index 9488184..378c375 100644 --- a/src/ComponentRequest.php +++ b/src/ComponentRequest.php @@ -2,11 +2,11 @@ namespace ctiso; -use ctiso\HttpRequest, - ctiso\Arr; +use ctiso\HttpRequest; +use ctiso\Arr; class ComponentRequest { - /** @var string */ + /** @var int */ public $component_id; /** @var string */ public $component_title; @@ -14,7 +14,7 @@ class ComponentRequest { public $r; /** - * @param string $c + * @param int $c * @param HttpRequest $r */ function __construct($c, HttpRequest $r) { diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 18d87ea..d4fca32 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -60,7 +60,7 @@ class Component public $template = null; public string $templatePath; - /** @var string */ + /** @var int */ public $component_id; /** @var string */ public $component_title; @@ -359,12 +359,9 @@ class Component $path = Path::join ($config->get('site', 'components'), $name, $filename . '.php'); $className = implode("\\", ['Components', ucfirst($name), $filename]); - /** - * @var ?Component $component - */ $component = null; - if (file_exists($path)) { + /** @var Component $component */ $component = new $className(); $component->viewPath = [$config->get('site', 'components') . '/' . $name . '/']; @@ -372,6 +369,7 @@ class Component $component->COMPONENTS_WEB = $config->get('site', 'web') . '/components/'; } else { + /** @var Component $component */ $component = new $className(); $template = $component->getTemplateName($site->getConfig()); From 33565c9f7efe01b42f1a0a1a39e3902afc6a84a4 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 11 Nov 2025 16:22:01 +0300 Subject: [PATCH 117/138] =?UTF-8?q?fix:=20=D0=9F=D1=80=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D0=BA=D0=B0=20=D0=BD=D0=B0=20=D0=BF=D1=83=D1=81=D1=82?= =?UTF-8?q?=D0=BE=D0=B5=20=D0=B8=D0=BC=D1=8F=20=D0=BA=D0=BE=D0=BC=D0=BF?= =?UTF-8?q?=D0=BE=D0=BD=D0=B5=D0=BD=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index d4fca32..6cdb811 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -355,6 +355,12 @@ class Component $name = $path; $config = $site->getConfig(); + // FIXME: Если имя для компонента не задано то возвращаем пустой компонент + // Нужно дополнительно проверить и файл или в autoloader просто не найдет файл копонента + if (!$name) { + return new Component(); + } + $filename = ucfirst($name); $path = Path::join ($config->get('site', 'components'), $name, $filename . '.php'); $className = implode("\\", ['Components', ucfirst($name), $filename]); From b20ea0e7dc1f61cc3fc3fb0be3cbddb135551816 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 12 Nov 2025 19:41:24 +0300 Subject: [PATCH 118/138] =?UTF-8?q?fix:=20=D0=94=D0=BE=D0=BF.=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20=D0=B7=D0=BD=D0=B0?= =?UTF-8?q?=D1=87=D0=B5=D0=BD=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 30 +-------------------------- src/Session.php | 3 ++- src/Settings.php | 4 ++-- src/Tools/SQLStatementExtractor.php | 6 +++--- src/Validator/Rule/PregMatch.php | 2 +- src/View/Composite.php | 5 +++-- src/View/FakeTemplate.php | 32 +++++++++++++++++++++++++++++ src/View/Plain.php | 2 +- 8 files changed, 45 insertions(+), 39 deletions(-) create mode 100644 src/View/FakeTemplate.php diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 6cdb811..18d1320 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -16,35 +16,7 @@ use ctiso\Controller\SiteInterface; use ctiso\Database\PDOStatement; use PHPTAL; use PHPTAL_PreFilter_Normalize; - -class FakeTemplate { - /** @var array */ - public $_data = []; - /** @var string */ - public $_name = ''; - - /** - * @param string $name - */ - function __construct($name) { - $this->_name = $name; - } - - /** - * @param string $key - * @param mixed $value - */ - function __set($key, $value): void { - $this->_data[$key] = $value; - } - - /** - * @return string - */ - function execute() { - return json_encode($this->_data); - } -} +use ctiso\View\FakeTemplate; /** * Класс компонента diff --git a/src/Session.php b/src/Session.php index 028e190..bf17b0c 100644 --- a/src/Session.php +++ b/src/Session.php @@ -15,7 +15,8 @@ class Session function set(string|array $key, mixed $value): void { if (is_array($key)) { - $_SESSION[strtolower(get_class($key[0]))][$key[1]] = $value; + $className = get_class($key[0]); + $_SESSION[strtolower($className)][$key[1]] = $value; } else { $_SESSION[$key] = $value; } diff --git a/src/Settings.php b/src/Settings.php index e678ea5..d6958c3 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -184,7 +184,7 @@ class Settings /** * Запись настроек в файл (Может переименовать в store) * - * @param File $file + * @param string $file * @return void */ public function write($file = null) @@ -199,7 +199,7 @@ class Settings $result = var_export($this->data, true); $result = ""; } - file_put_contents (($file) ? $file : $this->file, $result); + file_put_contents(($file) ? $file : $this->file, $result); } /** diff --git a/src/Tools/SQLStatementExtractor.php b/src/Tools/SQLStatementExtractor.php index c022ed8..5041e69 100644 --- a/src/Tools/SQLStatementExtractor.php +++ b/src/Tools/SQLStatementExtractor.php @@ -66,8 +66,8 @@ class SQLStatementExtractor /** * Extract SQL statements from array of lines. * - * @param list $lines Lines of the read-in file. - * @return list + * @param string[] $lines Lines of the read-in file. + * @return string[] SQL statements */ protected static function extractStatements($lines) { @@ -177,6 +177,6 @@ class SQLStatementExtractor protected static function getLines(string $buffer): array { $lines = preg_split("/\r?\n|\r/", $buffer); - return $lines; + return $lines === false ? [] : $lines; } } diff --git a/src/Validator/Rule/PregMatch.php b/src/Validator/Rule/PregMatch.php index 6b7f75c..71e4252 100644 --- a/src/Validator/Rule/PregMatch.php +++ b/src/Validator/Rule/PregMatch.php @@ -15,6 +15,6 @@ class PregMatch extends AbstractRule public function isValid(Collection $container, $status = null): bool { - return preg_match($this->pattern, $container->get($this->field)); + return preg_match($this->pattern, $container->get($this->field)) !== false; } } diff --git a/src/View/Composite.php b/src/View/Composite.php index 531f470..edfaafb 100644 --- a/src/View/Composite.php +++ b/src/View/Composite.php @@ -1,8 +1,9 @@ _name = $name; + } + + /** + * @param string $key + * @param mixed $value + */ + function __set($key, $value): void { + $this->_data[$key] = $value; + } + + /** + * @return string + */ + function execute() { + return json_encode($this->_data); + } +} diff --git a/src/View/Plain.php b/src/View/Plain.php index f6fc13e..f070d3d 100644 --- a/src/View/Plain.php +++ b/src/View/Plain.php @@ -71,6 +71,6 @@ class Plain extends \stdClass include ($document); $content = ob_get_contents (); ob_clean (); - return $content; + return $content === false ? '' : $content; } } From 0473d410d125bcb22478d9fc82afeb06f59c88d9 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 13 Nov 2025 18:51:18 +0300 Subject: [PATCH 119/138] =?UTF-8?q?refactor:=20=D0=A3=D0=BF=D1=80=D0=BE?= =?UTF-8?q?=D1=89=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=BA=D0=BE=D0=BD=D1=82=D1=80?= =?UTF-8?q?=D0=BE=D0=BB=D0=BB=D0=B5=D1=80=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 86 +-------------------------------------- 1 file changed, 2 insertions(+), 84 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 20afb41..1c30a78 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -47,16 +47,10 @@ class Action implements ActionInterface public $part = null; /** @var \ctiso\Registry Ссылка на настройки */ - public $config; + public $config; /** @var \ctiso\Role\User Обьект пользователя */ public $user; - /** @var \ctiso\View\View Для Widgets */ - public $view = null; - - public array $childNodes = []; - public array $ctrlValues = []; - public array $childViews = []; function __construct() { $this->part = new Url(); @@ -216,11 +210,7 @@ class Action implements ActionInterface public function execute(HttpRequest $request) { $result = $this->preProcess($request); - if (!empty($result)) { - $this->view = $result; - } - $text = $this->render(); - return $text; + return $result; } /** @@ -352,78 +342,6 @@ class Action implements ActionInterface return $result->export(); } - /** - * @param string $name - */ - public function setView($name): void - { - $this->view = $this->getView($name); - } - - /** - * Установка заголовка для отображения - * @param string $title - */ - public function setTitle($title): void - { - $this->view->setTitle($title); - } - - /** - * Добавление widget к отображению - * @param string $section - * @param View $node - */ - public function addChild($section, $node): void - { - $this->childNodes[$section] = $node; - } - - /** - * Установка значения контроллера - * @param string $name - * @param mixed $value - */ - public function setValue($name, $value): void - { - $this->ctrlValues[$name] = $value; - } - - /** - * Добавление дочернего отображения к текущему отображению - * @param string $section - * @param View $node - */ - public function addView($section, $node): void - { - $this->childViews[$section] = $node; - } - - /** - * Генерация содержания - * Путаница c execute и render - * @return View|string - */ - public function render() - { - $view = $this->view; - if ($view instanceof View) { - $this->view->assignValues($this->ctrlValues); - - /** @var ?Composite $node */ - $node = null; - foreach ($this->childNodes as $name => $node) { - $node->make($this); - $this->view->setView($name, $node->view); - } - - foreach ($this->childViews as $name => $node) { - $this->view->setView($name, $node); - } - } - return $this->view; - } - /** * Установка идентификатора страницы * @return int From 3e0b99c3d212fc40ded6d39cf623f3298f7ea878 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 27 Nov 2025 13:45:45 +0300 Subject: [PATCH 120/138] =?UTF-8?q?chore:=20=D0=9C=D0=B5=D0=BB=D0=BA=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 7 +++---- src/Controller/Service.php | 17 +++-------------- src/Excel/Table.php | 4 ++-- src/View/FakeTemplate.php | 2 +- 4 files changed, 9 insertions(+), 21 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 18d1320..77a742a 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -205,14 +205,12 @@ class Component } /** - * FIXME: Передавать в модель имя класса, а не часть * Создает модель * @param class-string $modelName * @return mixed */ public function getModel($modelName) { - // $modelName = "App\\Mapper\\" . $name; $model = new $modelName(); $model->config = $this->config; $model->db = $this->db; @@ -300,7 +298,8 @@ class Component */ public function getFields($options = null) { $form = new Form(); - $form->addFieldList($this->getInfo()['parameter'], $options); + $settings = $this->getInfo(); + $form->addFieldList($settings['parameter'], $options); return $form->field; } @@ -485,7 +484,7 @@ class Component * @return mixed */ function actionIndex($request) { - return null; + return ""; } /** diff --git a/src/Controller/Service.php b/src/Controller/Service.php index 47607a9..7e00a06 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -48,25 +48,14 @@ class Service return Path::join($this->webPath[0], strtolower(get_class($this)), 'templates', 'modern'); } - /** - * @param string $name Имя модели - * @return string - */ - private function getModelPath($name) - { - return Path::join ($this->config->get('system', 'path'), "model", $name . ".php"); - } - /** * Создает модель - * @param string $name + * @param class-string $modelName * @return BaseMapper */ - public function getModel($name) + public function getModel($modelName) { - require_once ($this->getModelPath ($name)); - $modelName = $name . "Mapper"; - $model = new $modelName (); + $model = new $modelName(); $model->db = $this->db; return $model; } diff --git a/src/Excel/Table.php b/src/Excel/Table.php index bb15d3d..b6c7977 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -230,7 +230,7 @@ class Table /** * Кодирование строки - * @deprecated + * @deprecated Можно заменить на значение * @param string $s Строка * @return string */ @@ -275,7 +275,7 @@ class Table } else { $doc->writeAttribute('ss:Type', "Number"); } - $doc->writeCdata($this->encode($value)); + $doc->writeCdata($value); } $doc->endElement(); $doc->endElement(); diff --git a/src/View/FakeTemplate.php b/src/View/FakeTemplate.php index bd0f952..223fa46 100644 --- a/src/View/FakeTemplate.php +++ b/src/View/FakeTemplate.php @@ -27,6 +27,6 @@ class FakeTemplate extends \stdClass { * @return string */ function execute() { - return json_encode($this->_data); + return json_encode($this->_data) ?: ''; } } From 6fdc3eb46b637409ba82ca578760caedb3d0ba38 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Fri, 28 Nov 2025 17:44:08 +0300 Subject: [PATCH 121/138] =?UTF-8?q?chore:=20=D0=9C=D0=B5=D0=BB=D0=BA=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=BF=D1=80=D0=B0=D0=B2=D0=BA=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Component.php | 6 ++++-- src/Database/IdGenerator.php | 3 +++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 77a742a..85f54f2 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -206,8 +206,10 @@ class Component /** * Создает модель - * @param class-string $modelName - * @return mixed + * + * @template T + * @param class-string $modelName + * @return T */ public function getModel($modelName) { diff --git a/src/Database/IdGenerator.php b/src/Database/IdGenerator.php index 4cd3d3d..6cad31a 100644 --- a/src/Database/IdGenerator.php +++ b/src/Database/IdGenerator.php @@ -35,6 +35,9 @@ class IdGenerator { } else { $result = $this->db->fetchOneArray("SELECT last_insert_rowid() AS nextval"); } + if (!$result) { + throw new \Exception("nextval failed"); + } return (int)$result['nextval']; } } From 5d3fae4249bc2087529d069baef66b7d39399e4f Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Mon, 1 Dec 2025 16:19:28 +0300 Subject: [PATCH 122/138] =?UTF-8?q?chore:=20=D0=9F=D1=80=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D0=BA=D0=B8=20=D0=B4=D0=BB=D1=8F=20=D1=82=D0=B8=D0=BF?= =?UTF-8?q?=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Action.php | 2 +- src/Controller/Component.php | 9 ++--- src/Database.php | 8 ++++- src/Database/Manager.php | 70 ++++++++++++++++++++++++++++-------- src/Mail.php | 7 ++-- src/Primitive.php | 4 +-- src/Role/User.php | 5 ++- src/Session.php | 3 ++ src/Setup.php | 10 ++++-- src/Tools/Drawing.php | 2 +- src/Tools/Image.php | 5 ++- src/Tools/TemplateImage.php | 4 +-- src/Validator/Rule/Time.php | 1 + src/View/View.php | 30 ++++++++++++---- src/ZipFile.php | 7 ++-- 15 files changed, 125 insertions(+), 42 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 1c30a78..8c57a29 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -205,7 +205,7 @@ class Action implements ActionInterface /** * Выполнение действия * @param HttpRequest $request - * @return View|string + * @return View|string|false */ public function execute(HttpRequest $request) { diff --git a/src/Controller/Component.php b/src/Controller/Component.php index 85f54f2..a6916a5 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -96,11 +96,12 @@ class Component } $this->before(); - if (method_exists($this, $action)) { - return call_user_func([$this, $action], $crequest); - } else { - return $this->actionIndex($crequest); + $actionMethod = [$this, $action]; + if (is_callable($actionMethod)) { + return call_user_func($actionMethod, $crequest); } + + return $this->actionIndex($crequest); } /** diff --git a/src/Database.php b/src/Database.php index 8d7807d..a15b787 100644 --- a/src/Database.php +++ b/src/Database.php @@ -132,7 +132,7 @@ namespace ctiso { * Извлекает из базы все элементы по запросу (Для совместимости со старым представлением баз данных CIS) * @param string $query - запрос * @param ?array $values - значения - * @return list> + * @return array> */ public function fetchAllArray($query, $values = null) { @@ -212,6 +212,9 @@ namespace ctiso { return $result[$index]; } else { $result = $this->fetchOneArray("SELECT $index AS lastid FROM $table WHERE OID = last_insert_rowid()"); + if ($result === false) { + throw new \RuntimeException("Ошибка получения идентификатора"); + } return $result['lastid']; } } @@ -255,6 +258,9 @@ namespace ctiso { function getNextId($seq) { $result = $this->fetchOneArray("SELECT nextval('$seq')"); + if ($result === false) { + throw new \RuntimeException("Ошибка получения следующего идентификатора"); + } return $result['nextval']; } diff --git a/src/Database/Manager.php b/src/Database/Manager.php index 9f0fe05..19ed189 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -8,27 +8,67 @@ use ctiso\Path; use Exception; /** - * @phpstan-type Action array{ - * type:string, + * @phpstan-type DropAction array{ + * type:"dropTable", + * table_name:string + * } + * + * @phpstan-type CreateAction array{ + * type:"createTable", * table_name:string, - * table:string, - * fields:array, - * field: ColumnProps, * constraints:?array, - * references:?array, + * fields:array, + * } + * + * @phpstan-type AddColumnAction array{ + * type:"addColumn", + * table_name:string, + * column_name:string, + * field:ColumnProps + * } + * + * @phpstan-type AlterReferenceAction array{ + * type:"alterReference", + * table:string, + * column:string, + * refTable:string, + * refColumn:string + * } + * + * @phpstan-type RenameColumnAction array{ + * type:"renameColumn", + * table:string, + * old_name:string, + * new_name:string + * } + * + * @phpstan-type ExecuteFileAction array{ + * type:"executeFile", * source:string, - * pgsql?:string, - * old_name?:string, - * new_name?:string, - * column?:string, - * column_name?:string, - * refTable?:string, - * refColumn?:string, - * values:array, + * pgsql:?string + * } + * + * @phpstan-type CreateViewAction array{ + * type:"createView", * view:string, * select:string * } * + * @phpstan-type InsertAction array{ + * type:"insert", + * table_name:string, + * values:array + * } + * + * @phpstan-type Action DropAction + * | CreateAction + * | AddColumnAction + * | AlterReferenceAction + * | RenameColumnAction + * | ExecuteFileAction + * | CreateViewAction + * | InsertAction + * * @phpstan-type ColumnProps array{ * name:string, * type:string, @@ -266,7 +306,7 @@ class Manager * @example createTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']]) * @param string $table * @param array $fields - * @param array|string|null $constraints + * @param array{fields: array, type: string}|string|null $constraints */ public function createTableQuery($table, $fields, $constraints): void { diff --git a/src/Mail.php b/src/Mail.php index e965dfd..848c645 100644 --- a/src/Mail.php +++ b/src/Mail.php @@ -111,8 +111,11 @@ class Mail if (file_exists($filename)) { $file = fopen($filename, "rb"); if (is_resource($file)) { - $data = fread($file, filesize($filename)); - $this->attachment[] = ($name) ? [$data, $name] : [$data, basename($filename)]; + $size = filesize($filename); + if ($size !== false && $size > 0) { + $data = fread($file, $size); + $this->attachment[] = ($name) ? [$data, $name] : [$data, basename($filename)]; + } } } } diff --git a/src/Primitive.php b/src/Primitive.php index 746f868..ce1482a 100644 --- a/src/Primitive.php +++ b/src/Primitive.php @@ -81,7 +81,7 @@ class Primitive { if ($month != 0 && $day != 0 && $year != 0) { if (checkdate($month, $day, $year)) { - return mktime(0, 0, 0, $month, $day, $year); + return mktime(0, 0, 0, $month, $day, $year) ?: 0; } else { return 0; } @@ -102,7 +102,7 @@ class Primitive { $tmp = []; if (preg_match('/(\d+)-(\d+)-(\d+)T(\d+):(\d+)Z/', $value, $tmp)) { if (checkdate((int)$tmp[2], (int)$tmp[3], (int)$tmp[1])) { - $result = mktime((int)$tmp[4], (int)$tmp[5], 0, (int)$tmp[2], (int)$tmp[3], (int)$tmp[1]); + $result = mktime((int)$tmp[4], (int)$tmp[5], 0, (int)$tmp[2], (int)$tmp[3], (int)$tmp[1]) ?: 0; } } return $result; diff --git a/src/Role/User.php b/src/Role/User.php index 1cca467..fc96b8d 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -98,7 +98,7 @@ class User implements UserInterface * @param PDOStatement $result * @return PDOStatement|bool */ - function setSID(string $random, $result) + function setSID(string $random, $result) { return $this->db->executeQuery("UPDATE users SET sid = :sid, trie_count = 0 WHERE id_user = :user", [ 'user' => $result->getInt('id_user'), @@ -115,6 +115,9 @@ class User implements UserInterface function updateTries(string $login): void { $user = $this->db->fetchOneArray("SELECT id_user, trie_count FROM users WHERE login = :login", ['login' => $login]); + if ($user === false) { + return; + } $this->db->executeQuery( "UPDATE users SET trie_time = :cur_time, trie_count = :count WHERE id_user = :id_user", ['cur_time' => time(), 'count' => $user['trie_count']+1, 'id_user' => $user['id_user']] diff --git a/src/Session.php b/src/Session.php index bf17b0c..6085450 100644 --- a/src/Session.php +++ b/src/Session.php @@ -16,6 +16,9 @@ class Session { if (is_array($key)) { $className = get_class($key[0]); + /*if ($className === false) { + throw new \RuntimeException("Invalid class name " . $className); + }*/ $_SESSION[strtolower($className)][$key[1]] = $value; } else { $_SESSION[$key] = $value; diff --git a/src/Setup.php b/src/Setup.php index 7f7874f..09a428f 100644 --- a/src/Setup.php +++ b/src/Setup.php @@ -59,7 +59,11 @@ class Setup public function __construct($file) { $this->file = $file; - $this->node = simplexml_load_file($file); + $node = simplexml_load_file($file); + if ($node === false) { + throw new \RuntimeException("Can't load file $file"); + } + $this->node = $node; $this->target = ''; $this->source = ''; @@ -127,7 +131,7 @@ class Setup /** * Заменяет переменные на их значения в строке - * @param list $match массив совпадения + * @param array $match массив совпадения * @return string */ function replaceVariable(array $match) @@ -147,7 +151,7 @@ class Setup { $result = []; foreach ($attributes as $key => $value) { - $result[$key] = preg_replace_callback("/\\\${(\w+)}/", [$this, 'replaceVariable'], $value); + $result[$key] = preg_replace_callback("/\\\${(\w+)}/", $this->replaceVariable(...), $value); } return $result; } diff --git a/src/Tools/Drawing.php b/src/Tools/Drawing.php index 75b2eab..9758044 100644 --- a/src/Tools/Drawing.php +++ b/src/Tools/Drawing.php @@ -144,7 +144,7 @@ class Drawing $temp_x = $x; for ($i = 0; $i < mb_strlen($text); $i++) { $bbox = imagettftext($image, $size, $angle, $temp_x, $y, $color, $font, $text[$i]); - $temp_x += $spacing + ($bbox[2] - $bbox[0]); + $temp_x += $spacing + ($bbox !== false ? ($bbox[2] - $bbox[0]) : 0); } } } diff --git a/src/Tools/Image.php b/src/Tools/Image.php index 646c7d9..ee04dcb 100644 --- a/src/Tools/Image.php +++ b/src/Tools/Image.php @@ -25,8 +25,11 @@ class Image { $width = imagesx($image); $height = imagesy($image); + $percent = min($prewidth / $width, $preheight / $height); - if ($percent > 1 && !$force) $percent = 1; + if ($percent > 1 && !$force) { + $percent = 1; + } $new_width = $width * $percent; $new_height = $height * $percent; diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index 66d5460..a076a02 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -89,8 +89,8 @@ class TemplateImage /** * Создает пустое изображение - * @param int $width - * @param int $height + * @param int<1, max> $width + * @param int<1, max> $height */ function setEmptyImage($width, $height): void { diff --git a/src/Validator/Rule/Time.php b/src/Validator/Rule/Time.php index 34534b9..6b20161 100644 --- a/src/Validator/Rule/Time.php +++ b/src/Validator/Rule/Time.php @@ -9,6 +9,7 @@ use ctiso\Validator\Rule\AbstractRule, class Time extends AbstractRule { + /** @var non-empty-string */ private string $split = ":"; public function getErrorMsg(): string diff --git a/src/View/View.php b/src/View/View.php index 45091a0..c4d4106 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -5,12 +5,13 @@ use Exception; class View extends \stdClass { - protected array $_section = []; // Вложенные шаблоны - // Блоки - /** @var string[] $_stylesheet */ - protected array $_stylesheet = []; // Массив стилей текущего шаблона - /** @var string[] $_script */ - protected array $_script = []; // Массив скриптов текущего шаблона + /** @var array Вложенные шаблоны */ + protected array $_section = []; + + /** @var string[] $_stylesheet Массив стилей текущего шаблона */ + protected array $_stylesheet = []; + /** @var string[] $_script Массив скриптов текущего шаблона */ + protected array $_script = []; /** @var string[] $_scriptstring */ public array $_scriptstring = []; /** @var string[] $_startup */ @@ -46,7 +47,7 @@ class View extends \stdClass */ public function setView($section, $view): void { - $this->_section [$section] = $view; + $this->_section[$section] = $view; if (is_object($view)) { $view->parent_view = $this; } @@ -122,6 +123,14 @@ class View extends \stdClass return $result; } + /* + function getTitleArray(): array { + return array_reduce($this->_section, fn ($result, $item) => + is_object($item) ? array_merge($result, $item->getTitleArray()) : $result, []); + } + */ + + /*abstract*/ public function set(string $key, mixed $value): void { } @@ -208,4 +217,11 @@ class View extends \stdClass } return $result; } + + /** + * @return View|string|false + */ + function execute() { + return ''; + } } diff --git a/src/ZipFile.php b/src/ZipFile.php index 99ae70b..b6ecdf6 100644 --- a/src/ZipFile.php +++ b/src/ZipFile.php @@ -26,12 +26,15 @@ class ZipFile extends ZipArchive // Read all Files in Dir $dir = opendir($location); + if (!$dir) { + throw new \RuntimeException("Enable to open dir '$dir'"); + } while (($file = readdir($dir)) !== false) { if (in_array($file, $this->ignore)) continue; // Rekursiv, If dir: FlxZipArchive::addDir(), else ::File(); - $call = (is_dir($location . $file)) ? 'addDir' : 'addFile'; - call_user_func([$this, $call], $location . $file, $name . $file); + $call = (is_dir($location . $file)) ? $this->addDir(...) : $this->addFile(...); + call_user_func($call, $location . $file, $name . $file); } } From 8786e845680ba4a6011aff3ab6d4944778a36ce4 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Mon, 1 Dec 2025 19:44:22 +0300 Subject: [PATCH 123/138] =?UTF-8?q?chore:=20=D0=9F=D1=80=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D0=BA=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/Connection/HttpRequest.php | 6 +++++- src/Controller/Action.php | 34 ++++-------------------------- src/Controller/ActionInterface.php | 4 +++- src/Filter/Login.php | 5 ++++- src/Form/Form.php | 6 +++++- src/Layout/Manager.php | 4 ++-- src/Path.php | 6 +++--- src/Process.php | 6 +++++- src/Tools/Drawing.php | 3 +++ src/Tools/Image.php | 5 ++--- src/View/Top.php | 5 +++-- src/View/View.php | 4 ++-- 12 files changed, 41 insertions(+), 47 deletions(-) diff --git a/src/Connection/HttpRequest.php b/src/Connection/HttpRequest.php index 5c71f1d..368feda 100644 --- a/src/Connection/HttpRequest.php +++ b/src/Connection/HttpRequest.php @@ -73,7 +73,11 @@ class HttpRequest public function setUrl($url): void { $this->url = $url; - $this->host = parse_url($this->url, PHP_URL_HOST); + $host = parse_url($this->url, PHP_URL_HOST); + if (!$host) { + throw new \RuntimeException("Не удалось получить хост"); + } + $this->host = $host; } public function getUrl(): string diff --git a/src/Controller/Action.php b/src/Controller/Action.php index 8c57a29..e26b41e 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -41,8 +41,8 @@ class Action implements ActionInterface /** @var ?\ctiso\Filter\ActionLogger Обьект для ведения лога */ public $logger = null; /** @var Factory Обьект для создания моделей */ - private $factory = null; // Ссылка на обьект создания модели - private array $helpers = []; // Помошники для действий + private $factory = null; + /** @var ?Url Параметры для ссылки */ public $part = null; @@ -99,7 +99,6 @@ class Action implements ActionInterface * @param string $name */ public function addSuggest(View $view, $name): void { - $suggest = []; $file = Path::join($this->modulePath, 'help', $name . '.suggest'); if (file_exists($file)) { $view->suggestions = include($file); @@ -131,7 +130,8 @@ class Action implements ActionInterface $webPath = $this->config->get('system', 'web'); $list = [ - Path::join($this->modulePath, 'templates', $this->viewPathPrefix) => Path::join($webPath, "modules", $this->name, 'templates', $this->viewPathPrefix), + Path::join($this->modulePath, 'templates', $this->viewPathPrefix) + => Path::join($webPath, "modules", $this->name, 'templates', $this->viewPathPrefix), Path::join($basePath, "templates") => Path::join($webPath, "templates") ]; @@ -286,32 +286,6 @@ class Action implements ActionInterface return $this->nUrl($name, array_merge(['mode' => 'ajax'], $param)); } - /** - * Добавление помошника контроллера - * @param class-string $class - */ - public function addHelper($class): void - { - $this->helpers [] = $class; - } - - /** - * Вызов помошников контроллера - * @param HttpRequest $request - * @return mixed - */ - public function callHelpers(HttpRequest $request) - { - $action = self::ACTION_PREFIX . $request->getAction(); - foreach ($this->helpers as $helper) { - if (method_exists($helper, $action)) { - return call_user_func([$helper, $action], $request, $this); - } else { - return $helper->actionIndex($request, $this); // Вместо return response ??? - } - } - } - /** * Загрузка файла класса * @deprecated Веместо его нужно использовать автозагрузку diff --git a/src/Controller/ActionInterface.php b/src/Controller/ActionInterface.php index 97d3251..4c8dbf6 100644 --- a/src/Controller/ActionInterface.php +++ b/src/Controller/ActionInterface.php @@ -7,8 +7,10 @@ use ctiso\HttpRequest; interface ActionInterface { /** + * Действие может вернуть Шаблон или строку + * * @param HttpRequest $request - * @return mixed + * @return \ctiso\View\View|string|false */ function execute(HttpRequest $request); function getConnection(): Database; diff --git a/src/Filter/Login.php b/src/Filter/Login.php index f2d0c4f..d5195cb 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -63,6 +63,9 @@ class Login extends Filter $db = Database::getConnection($dsn); $user = $db->fetchOneArray("SELECT * FROM users WHERE login = :login", ['login' => $login]); + if ($user === false) { + return false; + } $userPassword = $user['password']; } /*else if (time() - $result->getInt('lastupdate') > 60*60*24*60) { // Проверить давность пароля, 60 дней @@ -184,7 +187,7 @@ class Login extends Filter } } else if (isset($_SERVER['HTTP_REFERER'])) { $arr = []; - parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY) ?? '', $arr); + parse_str(parse_url($_SERVER['HTTP_REFERER'] ?? '', PHP_URL_QUERY) ?? '', $arr); if (isset($arr['back_page']) && $request->get('mode') != 'ajax') { $request->redirect($arr['back_page']); } diff --git a/src/Form/Form.php b/src/Form/Form.php index 7bfde94..a425af1 100644 --- a/src/Form/Form.php +++ b/src/Form/Form.php @@ -188,7 +188,11 @@ class Form { { foreach ($schema as $key => $conv) { list($value, $type) = $conv; - $this->field [$key]->setValue(call_user_func([\ctiso\Primitive::class, 'from_' . $type], $data->$value)); + $convertFn = [\ctiso\Primitive::class, 'from_' . $type]; + if (!is_callable($convertFn)) { + throw new \Exception('Не найден метод преобразования ' . $type); + } + $this->field[$key]->setValue(call_user_func($convertFn, $data->$value)); } } diff --git a/src/Layout/Manager.php b/src/Layout/Manager.php index c256afb..45098d6 100644 --- a/src/Layout/Manager.php +++ b/src/Layout/Manager.php @@ -39,7 +39,7 @@ class Manager extends Filter /** * @param HttpRequest $request - * @param array $get + * @param array|true $get * @return bool */ public function checkGet($request, $get) @@ -85,7 +85,7 @@ class Manager extends Filter $layout = $condition[1]; $view = $layout->execute($request); if (is_object($view)) { - return $view->render(); + return $view->execute(); } else { return $view; } diff --git a/src/Path.php b/src/Path.php index 8754f7f..b9b386a 100644 --- a/src/Path.php +++ b/src/Path.php @@ -120,9 +120,9 @@ class Path * Преобразует строку пути в массив * * @param string $path Путь - * @return array + * @return list|false */ - public static function listFromString(string $path): array + public static function listFromString(string $path): array|false { $list = preg_split('#\\\\|/#s', $path); return $list; @@ -182,7 +182,7 @@ class Path . $path['host'] . (isset($path['port']) ? ':' . $path['port'] : '')) : '') . $slash - . $path['path'] + . ($path['path'] ?? '') . (isset($path['query']) ? '?' . $path['query'] : '') . (isset($path['fragment']) ? '#' . $path['fragment'] : ''); } diff --git a/src/Process.php b/src/Process.php index fd319f9..e0c9473 100644 --- a/src/Process.php +++ b/src/Process.php @@ -33,7 +33,11 @@ function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") function process_exists($pid) { if (PHP_OS == 'WINNT') { - $processes = explode("\n", shell_exec("tasklist.exe /NH /FO CSV")); + $content = shell_exec("tasklist.exe /NH /FO CSV"); + if (!$content) { + return false; + } + $processes = explode("\n", $content); foreach ($processes as $process) { if ($process != "") { $csv = str_getcsv($process); diff --git a/src/Tools/Drawing.php b/src/Tools/Drawing.php index 9758044..d950481 100644 --- a/src/Tools/Drawing.php +++ b/src/Tools/Drawing.php @@ -81,6 +81,9 @@ class Drawing for ($i = 0; $i < $count; $i++) { $item = $words[$i]; $dimensions = imagettfbbox($size, $angle, $font, $current_line . ($first_word ? '' : ' ') . $item); + if ($dimensions === false) { + continue; + } $line_width = $dimensions[2] - $dimensions[0]; $line_height = $dimensions[1] - $dimensions[7]; diff --git a/src/Tools/Image.php b/src/Tools/Image.php index ee04dcb..dd3ebd4 100644 --- a/src/Tools/Image.php +++ b/src/Tools/Image.php @@ -30,9 +30,8 @@ class Image if ($percent > 1 && !$force) { $percent = 1; } - $new_width = $width * $percent; - $new_height = $height * $percent; - + $new_width = max(1, (int)($width * $percent)); + $new_height = max(1, (int)($height * $percent)); $image_p = imagecreatetruecolor($new_width, $new_height); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); diff --git a/src/View/Top.php b/src/View/Top.php index 0a34cb1..2a7d7fe 100644 --- a/src/View/Top.php +++ b/src/View/Top.php @@ -45,7 +45,8 @@ class Top extends Composite * * @return string */ - public function render() + #[\Override] + public function execute(): string { $this->doTree('alias'); @@ -107,7 +108,7 @@ class Top extends Composite $this->set('title', $this->getTitle()); $this->set('jspath', $this->config->get('system', 'web')); // - return $this->execute(); // execute+phptal ?? + return parent::execute(); // execute+phptal ?? } /** diff --git a/src/View/View.php b/src/View/View.php index c4d4106..7d7776e 100644 --- a/src/View/View.php +++ b/src/View/View.php @@ -219,9 +219,9 @@ class View extends \stdClass } /** - * @return View|string|false + * Шаблон всегда возвращает строку */ - function execute() { + function execute(): string { return ''; } } From 18cc1cad01b0d60531717bc0302a3e61c3b7dc44 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 2 Dec 2025 13:16:02 +0300 Subject: [PATCH 124/138] =?UTF-8?q?chore:=20=D0=9F=D1=80=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D0=BA=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/Controller/Action.php | 6 +++++- src/Excel/Table.php | 10 ++++++---- src/Filter/Login.php | 10 +++++++--- src/Functions.php | 11 ----------- src/Layout/Manager.php | 2 +- src/Process.php | 6 +++--- src/Tools/Drawing.php | 11 +++++++---- src/Tools/TemplateImage.php | 6 +++++- 8 files changed, 34 insertions(+), 28 deletions(-) diff --git a/src/Controller/Action.php b/src/Controller/Action.php index e26b41e..fab01da 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -220,7 +220,11 @@ class Action implements ActionInterface * @return mixed */ public function forward($action, HttpRequest $args) { - $value = call_user_func([$this, $action], $args); + $actionFn = [$this, $action]; + if (!is_callable($actionFn)) { + return false; + } + $value = call_user_func($actionFn, $args); return $value; } diff --git a/src/Excel/Table.php b/src/Excel/Table.php index b6c7977..395253e 100644 --- a/src/Excel/Table.php +++ b/src/Excel/Table.php @@ -118,7 +118,7 @@ class Table /** * Устанавливает высоту ряда * @param int $row Номер ряда - * @param numeric $value Высота ряда + * @param int $value Высота ряда */ function setRowHeight (int $row, $value): void { @@ -187,8 +187,9 @@ class Table */ function getRows() { + // Высчитываем максимальный индекс, массив может быть разрежен поэтому используем array_keys $keys = array_keys($this->rows); - return max($keys); + return $keys === [] ? 0 : max($keys); } /** @@ -199,7 +200,7 @@ class Table function getRowCells(TableRow $row) { $keys = array_keys($row->cells); - return max($keys); + return $keys === [] ? 0 :max($keys); } /** @@ -225,7 +226,8 @@ class Table * @return int */ function getColumns() { - return max(array_map([$this, 'getRowCells'], $this->rows)); + $columns = array_map($this->getRowCells(...), $this->rows); + return $columns === [] ? 0 : max($columns); } /** diff --git a/src/Filter/Login.php b/src/Filter/Login.php index d5195cb..93df732 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -205,11 +205,15 @@ class Login extends Filter $action = $request->get('action'); $moduleDir = explode('\\',$module)[0]; + // TODO: Параметр для белого списка перенести в install.json $file = Path::join($this->config->get('system', 'path'), 'modules', $moduleDir, 'filters', 'white.json'); if (file_exists($file)) { - $whiteList = json_decode(file_get_contents($file), true); - - if (in_array($action, $whiteList)) { + $text = file_get_contents($file); + if (!$text) { + return false; + } + $whiteList = json_decode($text, true); + if (is_array($whiteList) && in_array($action, $whiteList, true)) { return true; } } diff --git a/src/Functions.php b/src/Functions.php index 3e040c4..1d7dd87 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -233,17 +233,6 @@ class Functions { return ($a[$key] < $b[$key]) ? -1 : 1; } - /** - * @deprecated - * @param string $name Метод - * @param object $o - * - * @return mixed - */ - static function __self($name, $o) { - return call_user_func([$o, $name]); - } - /** * @param string ...$args * @return string diff --git a/src/Layout/Manager.php b/src/Layout/Manager.php index 45098d6..26537b0 100644 --- a/src/Layout/Manager.php +++ b/src/Layout/Manager.php @@ -56,7 +56,7 @@ class Manager extends Filter /** * @param HttpRequest $request - * @param array $get + * @param array|true $get * @return bool */ public function checkXHR($request, $get): bool diff --git a/src/Process.php b/src/Process.php index e0c9473..ce1c177 100644 --- a/src/Process.php +++ b/src/Process.php @@ -8,13 +8,13 @@ namespace ctiso; * @param string $delimiter * @param string $enclosure * @param string $escape - * @return array + * @return array|false */ function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") { $fiveMBs = 1024; $fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+'); - $data = ''; + $data = []; if (is_resource($fp)) { fputs($fp, $input); rewind($fp); @@ -41,7 +41,7 @@ function process_exists($pid) foreach ($processes as $process) { if ($process != "") { $csv = str_getcsv($process); - if ($pid == $csv[1]) return true; + if ($csv && $pid == $csv[1]) return true; } } return false; diff --git a/src/Tools/Drawing.php b/src/Tools/Drawing.php index d950481..8a7568e 100644 --- a/src/Tools/Drawing.php +++ b/src/Tools/Drawing.php @@ -18,17 +18,20 @@ class Drawing * @param int $top * @param int $width * @param int $height - * @param list $rgb + * @param list> $rgb */ static function drawRectangle(GdImage &$image, int $left, int $top, int $width, int $height, array $rgb): void { $color = imagecolorallocate($image, $rgb[0], $rgb[1], $rgb[2]); + if ($color === false) { + throw new \RuntimeException("Can't allocate color"); + } $right = $left + $width; $bottom = $top + $height; - imageline($image, $left, $top, $right, $top, $color); - imageline($image, $right, $top, $right, $bottom, $color); + imageline($image, $left, $top, $right, $top, $color); + imageline($image, $right, $top, $right, $bottom, $color); imageline($image, $left, $bottom, $right, $bottom, $color); - imageline($image, $left, $top, $left, $bottom, $color); + imageline($image, $left, $top, $left, $bottom, $color); } /** diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index a076a02..690a4a4 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -106,7 +106,11 @@ class TemplateImage { $suffix = pathinfo($file, PATHINFO_EXTENSION); if (array_key_exists($suffix, self::$listfiles)) { - return call_user_func('imagecreatefrom' . self::$listfiles[$suffix], $file); + $imageFn = 'imagecreatefrom' . self::$listfiles[$suffix]; + if (!is_callable($imageFn)) { + return null; + } + return call_user_func($imageFn, $file); } return null; } From 5170ed8ed5a78c05a0f575a011a830b092b8a827 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 3 Dec 2025 17:12:40 +0300 Subject: [PATCH 125/138] feat: FakeTemplate -> JsonView --- src/Controller/Component.php | 6 +++--- src/View/{FakeTemplate.php => JsonView.php} | 10 +++++++++- 2 files changed, 12 insertions(+), 4 deletions(-) rename src/View/{FakeTemplate.php => JsonView.php} (73%) diff --git a/src/Controller/Component.php b/src/Controller/Component.php index a6916a5..fbf04b7 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -16,7 +16,7 @@ use ctiso\Controller\SiteInterface; use ctiso\Database\PDOStatement; use PHPTAL; use PHPTAL_PreFilter_Normalize; -use ctiso\View\FakeTemplate; +use ctiso\View\JsonView; /** * Класс компонента @@ -117,12 +117,12 @@ class Component /** * Получить шаблон * @param string $name - * @return PHPTAL|FakeTemplate + * @return PHPTAL|JsonView */ public function getView($name) { if ($this->output === 'json') { - return new FakeTemplate($name); + return new JsonView($name); } /** @var Registry $config */ diff --git a/src/View/FakeTemplate.php b/src/View/JsonView.php similarity index 73% rename from src/View/FakeTemplate.php rename to src/View/JsonView.php index 223fa46..3ba8fd4 100644 --- a/src/View/FakeTemplate.php +++ b/src/View/JsonView.php @@ -2,7 +2,7 @@ namespace ctiso\View; -class FakeTemplate extends \stdClass { +class JsonView extends \stdClass { /** @var array */ public $_data = []; /** @var string */ @@ -15,6 +15,14 @@ class FakeTemplate extends \stdClass { $this->_name = $name; } + /** + * @param string $key + * @param mixed $value + */ + function set($key, $value): void { + $this->_data[$key] = $value; + } + /** * @param string $key * @param mixed $value From 74aa44bdc02c161469f9dc37e62598cd090c8249 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 3 Dec 2025 18:32:21 +0300 Subject: [PATCH 126/138] =?UTF-8?q?feat:=20=D0=A1=D1=82=D1=80=D0=BE=D0=B3?= =?UTF-8?q?=D0=B8=D0=B5=20=D1=82=D0=B8=D0=BF=D1=8B=20=D0=B4=D0=BB=D1=8F=20?= =?UTF-8?q?HttpRequest?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Collection.php | 2 +- src/HttpRequest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index cf8b814..8e5328d 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -58,7 +58,7 @@ class Collection implements \ArrayAccess /** * @param string $key - * @param int $default + * @param int $default * @return int */ public function getInt($key, $default = 0) diff --git a/src/HttpRequest.php b/src/HttpRequest.php index da5c547..e688fe5 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -55,7 +55,7 @@ class HttpRequest extends Collection /** * @param string $key * @param mixed $default - * @return mixed + * @return null|string|array */ function get($key, $default = null) { From aa667d248942524d894a4cd9ee1748ea5bfd21c8 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 3 Dec 2025 20:58:24 +0300 Subject: [PATCH 127/138] fix: HttpRequest --- src/Collection.php | 4 ++-- src/HttpRequest.php | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index 8e5328d..85428ad 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -61,7 +61,7 @@ class Collection implements \ArrayAccess * @param int $default * @return int */ - public function getInt($key, $default = 0) + public function getInt(string $key, int $default = 0): int { return (int)$this->get($key, $default); } @@ -81,7 +81,7 @@ class Collection implements \ArrayAccess * @param int $default * @return int */ - public function getNat($key, $default = 1) + public function getNat(string $key, int $default = 1): int { $result = (int)$this->get($key, $default); return (($result > 0) ? $result : $default); diff --git a/src/HttpRequest.php b/src/HttpRequest.php index e688fe5..55b9bcc 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -67,6 +67,16 @@ class HttpRequest extends Collection return parent::get('data')->getString($key, $default); } + function getInt(string $key, int $default = 0): int + { + return parent::get('data')->getInt($key, $default); + } + + function getNat(string $key, int $default = 1): int + { + return parent::get('data')->getNat($key, $default); + } + function session(?Session $value = null): ?Session { if ($value) { From 088610946787007a73add55b8cb32cc7336172bd Mon Sep 17 00:00:00 2001 From: Wizard Date: Thu, 4 Dec 2025 00:46:30 +0300 Subject: [PATCH 128/138] =?UTF-8?q?feat:=20getArray=20=D0=B4=D0=BB=D1=8F?= =?UTF-8?q?=20HttpRequest?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/HttpRequest.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 55b9bcc..7192c09 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -85,6 +85,14 @@ class HttpRequest extends Collection return $this->_session; } + function getArray($key, $default = []) { + $result = parent::get('data')->get($key, $default); + if (is_array($result)) { + return $result; + } + return $default; + } + function set(string $key, mixed $value): void { parent::get('data')->set($key, $value); From 3169ea2032208efa8db608a69166160f65c99627 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 4 Dec 2025 13:43:22 +0300 Subject: [PATCH 129/138] =?UTF-8?q?chore:=20=D0=90=D0=BD=D0=BD=D0=BE=D1=82?= =?UTF-8?q?=D1=86=D0=B8=D1=8F=20=D1=82=D0=B8=D0=BF=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controller/Service.php | 1 + src/HttpRequest.php | 2 +- src/Model/BaseMapper.php | 3 +++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Controller/Service.php b/src/Controller/Service.php index 7e00a06..e4d7fb9 100644 --- a/src/Controller/Service.php +++ b/src/Controller/Service.php @@ -55,6 +55,7 @@ class Service */ public function getModel($modelName) { + /** @var BaseMapper */ $model = new $modelName(); $model->db = $this->db; return $model; diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 7192c09..62d024e 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -85,7 +85,7 @@ class HttpRequest extends Collection return $this->_session; } - function getArray($key, $default = []) { + function getArray(string $key, array $default = []): array { $result = parent::get('data')->get($key, $default); if (is_array($result)) { return $result; diff --git a/src/Model/BaseMapper.php b/src/Model/BaseMapper.php index 7e55e72..37831a0 100644 --- a/src/Model/BaseMapper.php +++ b/src/Model/BaseMapper.php @@ -2,6 +2,9 @@ namespace ctiso\Model; +/** + * @property \ctiso\Database $db + */ abstract class BaseMapper { function getAllAsOptions(): array { return []; From 08defbd046663fdc0bb42fe1a44040ef35be16d9 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 4 Dec 2025 16:39:24 +0300 Subject: [PATCH 130/138] =?UTF-8?q?chore:=20=D0=A2=D0=B8=D0=BF=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Connection/HttpResponse.php | 2 +- src/Controller/Component.php | 2 +- src/Controller/Front.php | 2 +- src/Database.php | 6 ++++++ src/Filter/Login.php | 6 +++--- 5 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/Connection/HttpResponse.php b/src/Connection/HttpResponse.php index 9f0fe69..a16120b 100644 --- a/src/Connection/HttpResponse.php +++ b/src/Connection/HttpResponse.php @@ -47,7 +47,7 @@ class HttpResponse if (isset($this->param['Transfer-Encoding']) && $this->param['Transfer-Encoding'] == 'chunked') { //$this->data = substr($this->response, $this->offset); - $index = hexdec($this->getLine()); + $index = (int)hexdec($this->getLine()); $chunk = []; while ($index > 0) { $chunk [] = substr($this->response, $this->offset, $index); diff --git a/src/Controller/Component.php b/src/Controller/Component.php index fbf04b7..124d4e5 100644 --- a/src/Controller/Component.php +++ b/src/Controller/Component.php @@ -135,7 +135,7 @@ class Component foreach ($this->viewPath as $index => $viewPath) { // Загружать шаблон по умолчанию если не найден текущий $dir = Path::join($this->viewPath[$index], 'templates', $template); - if(is_dir($dir)) { + if (is_dir($dir)) { $tpl = new PHPTAL(Path::join($this->viewPath[$index], 'templates', $template, $name)); $tpl->setPhpCodeDestination(PHPTAL_PHP_CODE_DESTINATION); $selected = $index; diff --git a/src/Controller/Front.php b/src/Controller/Front.php index 1a64a65..b799f40 100644 --- a/src/Controller/Front.php +++ b/src/Controller/Front.php @@ -111,7 +111,7 @@ class Front extends Action public function execute(HttpRequest $request) { - $name = $request->get('module', $this->default); + $name = $request->getString('module', $this->default); try { return $this->loadModule($name, $request); } catch (UserMessageException $ex) { //Исключение с понятным пользователю сообщением diff --git a/src/Database.php b/src/Database.php index a15b787..ab2a233 100644 --- a/src/Database.php +++ b/src/Database.php @@ -53,6 +53,12 @@ namespace ctiso { return $result; } + function query($query, $fetchMode = PDO::FETCH_INTO, mixed $_arg1 = null, mixed $_arg2 = null): PDOStatement { + /** @var PDOStatement */ + $result = parent::query($query, $fetchMode); + return $result; + } + /** * Возвращает DSN * @return DSN diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 93df732..2df43b7 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -41,7 +41,7 @@ class Login extends Filter /** * Проверка авторизации * @param HttpRequest $request - * @return Boolean Авторизовани пользователь или нет + * @return bool Авторизовани пользователь или нет */ public function isLoggin(HttpRequest $request) { @@ -50,8 +50,8 @@ class Login extends Filter switch ($request->getAction()) { // Авторизация по постоянному паролю case 'login': - $login = $request->get('login', '') ; - $password = $request->get('password'); + $login = $request->getString('login', '') ; + $password = $request->getString('password'); $result = $this->role->getUserByLogin($login); // Поиск по логину if ($result) { From b782af55a58e2668e8c3f01473e547165fa96cda Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 4 Dec 2025 19:44:02 +0300 Subject: [PATCH 131/138] =?UTF-8?q?chore:=20=D0=A2=D0=B8=D0=BF=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Filter/Login.php | 10 +++++----- src/Path.php | 6 +++--- src/Session.php | 5 +---- src/Setup.php | 3 ++- src/Tools/StringUtil.php | 6 +++--- src/Tools/TemplateImage.php | 8 ++++++-- 6 files changed, 20 insertions(+), 18 deletions(-) diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 2df43b7..78ac4b1 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -81,7 +81,7 @@ class Login extends Filter $request->set('timeout_error', true); break; } else { - $this->role->resetTries($request->get('login')); + $this->role->resetTries($request->getString('login')); } } // Извлечнеие пользователя из родительской CMS, для проверки пароля @@ -154,7 +154,7 @@ class Login extends Filter public function execute(HttpRequest $request): mixed { $logged = $this->isLoggin($request); - if ($request->get('action') == 'user_access') { + if ($request->getString('action') == 'user_access') { if ($logged) { $result = []; $result['fullname'] = $this->user->getString('patronymic') . " " . $this->user->getString('firstname'); @@ -166,7 +166,7 @@ class Login extends Filter } } - if ($request->get('action') == 'relogin') { + if ($request->getString('action') == 'relogin') { if ($logged) { return json_encode(['result' => 'ok', 'message' => "Авторизация успешна"]); } else { @@ -177,7 +177,7 @@ class Login extends Filter if (!$logged) { // Параметры при неправильной авторизации // Действия по умолчанию !! Возможно переход на форму регистрации - if ($request->get('mode') == 'ajax') { + if ($request->getString('mode') == 'ajax') { if (!$this->requestIsWhite($request)) { return json_encode(['result' => 'fail', 'message' =>"NOT_AUTHORIZED"]); } @@ -188,7 +188,7 @@ class Login extends Filter } else if (isset($_SERVER['HTTP_REFERER'])) { $arr = []; parse_str(parse_url($_SERVER['HTTP_REFERER'] ?? '', PHP_URL_QUERY) ?? '', $arr); - if (isset($arr['back_page']) && $request->get('mode') != 'ajax') { + if (isset($arr['back_page']) && $request->getString('mode') != 'ajax') { $request->redirect($arr['back_page']); } } diff --git a/src/Path.php b/src/Path.php index b9b386a..d9381ee 100644 --- a/src/Path.php +++ b/src/Path.php @@ -120,12 +120,12 @@ class Path * Преобразует строку пути в массив * * @param string $path Путь - * @return list|false + * @return list */ - public static function listFromString(string $path): array|false + public static function listFromString(string $path): array { $list = preg_split('#\\\\|/#s', $path); - return $list; + return $list ?: []; } /** diff --git a/src/Session.php b/src/Session.php index 6085450..ff2bba6 100644 --- a/src/Session.php +++ b/src/Session.php @@ -16,10 +16,7 @@ class Session { if (is_array($key)) { $className = get_class($key[0]); - /*if ($className === false) { - throw new \RuntimeException("Invalid class name " . $className); - }*/ - $_SESSION[strtolower($className)][$key[1]] = $value; + $_SESSION[strtolower($className ?: '')][$key[1]] = $value; } else { $_SESSION[$key] = $value; } diff --git a/src/Setup.php b/src/Setup.php index 09a428f..e3538be 100644 --- a/src/Setup.php +++ b/src/Setup.php @@ -10,6 +10,7 @@ namespace ctiso; use ctiso\Tools\SQLStatementExtractor; use ctiso\Path; +use ctiso\File; use SimpleXMLElement; class FakeZipArchive { @@ -26,7 +27,7 @@ class FakeZipArchive { * @return string */ function getFromName($file) { - return file_get_contents(Path::join($this->base, $file)); + return File::getContents(Path::join($this->base, $file)); } } diff --git a/src/Tools/StringUtil.php b/src/Tools/StringUtil.php index aba87c3..a5a37ce 100644 --- a/src/Tools/StringUtil.php +++ b/src/Tools/StringUtil.php @@ -96,11 +96,11 @@ class StringUtil /** * Разбивает строку на массив символов * @param string $str - * @return array|false + * @return array */ - static function mb_str_split(string $str): array|false + static function mb_str_split(string $str): array { - return preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY); + return preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY) ?: []; } /** diff --git a/src/Tools/TemplateImage.php b/src/Tools/TemplateImage.php index 690a4a4..cb0ad0d 100644 --- a/src/Tools/TemplateImage.php +++ b/src/Tools/TemplateImage.php @@ -196,12 +196,16 @@ class TemplateImage return $text; } - function setSize(int $new_width, int $new_height): void + /** + * @param int<1,max> $new_width + * @param ?int<1,max> $new_height + */ + function setSize(int $new_width, ?int $new_height = null): void { $width = imagesx($this->image); $height = imagesy($this->image); if ($new_height == null) { - $new_height = ceil($height * $new_width / $width); + $new_height = max(1, (int)ceil($height * $new_width / $width)); } // Resample From fbe5eb878e7de494ade163feaf02659db40c28a5 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 9 Dec 2025 17:05:00 +0300 Subject: [PATCH 132/138] =?UTF-8?q?chore:=20=D0=A2=D0=B8=D0=BF=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Filter/Login.php | 7 +++++-- src/Form/Select.php | 2 +- src/Functions.php | 4 ++-- src/Validator/Validator.php | 2 +- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/Filter/Login.php b/src/Filter/Login.php index 78ac4b1..50475ee 100644 --- a/src/Filter/Login.php +++ b/src/Filter/Login.php @@ -187,8 +187,11 @@ class Login extends Filter } } else if (isset($_SERVER['HTTP_REFERER'])) { $arr = []; - parse_str(parse_url($_SERVER['HTTP_REFERER'] ?? '', PHP_URL_QUERY) ?? '', $arr); - if (isset($arr['back_page']) && $request->getString('mode') != 'ajax') { + parse_str(parse_url($_SERVER['HTTP_REFERER'] ?? '', PHP_URL_QUERY) ?: '', $arr); + if (isset($arr['back_page']) + && is_string($arr['back_page']) + && $request->getString('mode') != 'ajax') + { $request->redirect($arr['back_page']); } } diff --git a/src/Form/Select.php b/src/Form/Select.php index 333691a..89ea70d 100644 --- a/src/Form/Select.php +++ b/src/Form/Select.php @@ -4,7 +4,7 @@ namespace ctiso\Form; use ctiso\Form\Field; /** - * @phpstan-type Option = array{value: string, name: string, selected: bool, class?: string|false} + * @phpstan-type Option = array{value: string, name: string, selected?: bool, class?: string|false} */ class Select extends Field { diff --git a/src/Functions.php b/src/Functions.php index 1d7dd87..fa4391b 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -268,7 +268,7 @@ class Functions { /** * @param string $key - * @param list|\ArrayIterator $array + * @param array|\ArrayIterator $array * @return array */ static function key_values_object($key, $array) { @@ -283,7 +283,7 @@ class Functions { /** * @param string $key * @param string $value - * @param list>|\ArrayIterator $array + * @param array>|\ArrayIterator $array * @return array */ static function assoc_key_values($key, $value, $array) { diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 7576ca8..2404d6a 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -10,7 +10,7 @@ use Exception, /** * @phpstan-type Rule array{ - * validate:string, // Описание правила см. формат правила ниже + * validate?:string, // Описание правила см. формат правила ниже * name:string, // Имя переменой для проверки * context?:object * } From 3d34ae4b84cd74d5afb31c525f740c98a33e6298 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Tue, 9 Dec 2025 19:46:55 +0300 Subject: [PATCH 133/138] =?UTF-8?q?chore:=20=D0=A2=D0=B8=D0=BF=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Connection/HttpResponse.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Connection/HttpResponse.php b/src/Connection/HttpResponse.php index a16120b..fad35ab 100644 --- a/src/Connection/HttpResponse.php +++ b/src/Connection/HttpResponse.php @@ -52,7 +52,7 @@ class HttpResponse while ($index > 0) { $chunk [] = substr($this->response, $this->offset, $index); $this->offset += $index; - $index = hexdec($this->getLine()); + $index = (int)hexdec($this->getLine()); } $this->data = implode("", $chunk); From f4d829119b0223ae440622fe789685feeaafd692 Mon Sep 17 00:00:00 2001 From: Wizard Date: Tue, 9 Dec 2025 23:25:13 +0300 Subject: [PATCH 134/138] =?UTF-8?q?chore:=20=D0=A2=D0=B8=D0=BF=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Path.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Path.php b/src/Path.php index d9381ee..b169d92 100644 --- a/src/Path.php +++ b/src/Path.php @@ -60,7 +60,7 @@ class Path */ public static function basename($path) { - $list = preg_split('#\\\\|/#s', $path); + $list = preg_split('#\\\\|/#s', $path) ?: ['']; return end($list); } @@ -96,7 +96,7 @@ class Path static function skipExtension(string $fileName): string { $path = pathinfo($fileName); - if ($path['dirname'] === ".") { + if (!isset($path['dirname']) || $path['dirname'] === ".") { return $path['filename']; } else { return self::join($path['dirname'], $path['filename']); From 233749f1ea5ba4d7afe160599f7f7d51e7e4d29e Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 10 Dec 2025 17:46:56 +0300 Subject: [PATCH 135/138] =?UTF-8?q?chore:=20=D0=A2=D0=B8=D0=BF=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Collection.php | 59 +++++++++++++++++++++++++++++++++++++-- src/Controller/Action.php | 2 +- src/HttpRequest.php | 25 +++++++++-------- src/Path.php | 22 +++++++-------- 4 files changed, 82 insertions(+), 26 deletions(-) diff --git a/src/Collection.php b/src/Collection.php index 85428ad..430cc69 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -63,7 +63,18 @@ class Collection implements \ArrayAccess */ public function getInt(string $key, int $default = 0): int { - return (int)$this->get($key, $default); + $value = $this->get($key); + + // Фильтруем как целое число + if (is_numeric($value)) { + // Приводим к int, но сначала проверим, что не float с дробной частью + $floatVal = (float)$value; + if (is_finite($floatVal) && floor($floatVal) === $floatVal) { + return (int)$floatVal; + } + } + + return $default; } /** @@ -73,9 +84,53 @@ class Collection implements \ArrayAccess */ public function getString(string $key, string $default = ''): string { - return (string)$this->get($key, $default); + $value = $this->get($key); + + if (is_string($value)) { + return $value; + } + + if (is_numeric($value)) { + return (string)$value; + } + + return $default; } + /** + * Получает булево значение + * Поддерживает: 1, '1', 'true', 'on', 'yes' → true + * Иначе → false + */ + public function getBool(string $key, bool $default = false): bool + { + $value = $this->get($key); + + if (is_bool($value)) { + return $value; + } + + if (is_string($value)) { + $value = strtolower(trim($value)); + return in_array($value, ['1', 'true', 'on', 'yes'], true); + } + + if (is_numeric($value)) { + return (bool)$value; + } + + return $default; + } + + function getArray(string $key, array $default = []): array { + $result = $this->get($key); + if (is_array($result)) { + return $result; + } + return $default; + } + + /** * @param string $key * @param int $default diff --git a/src/Controller/Action.php b/src/Controller/Action.php index fab01da..84cf844 100644 --- a/src/Controller/Action.php +++ b/src/Controller/Action.php @@ -231,7 +231,7 @@ class Action implements ActionInterface /** * Страница по умолчанию * @param HttpRequest $request - * @return View|string + * @return string|false */ public function actionIndex(HttpRequest $request) { return ""; diff --git a/src/HttpRequest.php b/src/HttpRequest.php index 62d024e..a24e60f 100644 --- a/src/HttpRequest.php +++ b/src/HttpRequest.php @@ -5,8 +5,7 @@ */ namespace ctiso; -use Exception; -use ArrayAccess; + use ctiso\Collection; use ctiso\Session; @@ -69,12 +68,22 @@ class HttpRequest extends Collection function getInt(string $key, int $default = 0): int { - return parent::get('data')->getInt($key, $default); + return parent::get('data')->getInt($key, $default); } function getNat(string $key, int $default = 1): int { - return parent::get('data')->getNat($key, $default); + return parent::get('data')->getNat($key, $default); + } + + function getBool(string $key, bool $default = false): bool + { + return parent::get('data')->getBool($key, $default); + } + + function getArray(string $key, array $default = []): array + { + return parent::get('data')->getArray($key, $default); } function session(?Session $value = null): ?Session @@ -85,14 +94,6 @@ class HttpRequest extends Collection return $this->_session; } - function getArray(string $key, array $default = []): array { - $result = parent::get('data')->get($key, $default); - if (is_array($result)) { - return $result; - } - return $default; - } - function set(string $key, mixed $value): void { parent::get('data')->set($key, $value); diff --git a/src/Path.php b/src/Path.php index b169d92..55a0022 100644 --- a/src/Path.php +++ b/src/Path.php @@ -21,7 +21,7 @@ class Path */ public function __construct($path = '') { - $this->url = parse_url($path); + $this->url = parse_url($path) ?: []; if (isset($this->url['path'])) { $path = $this->url['path']; @@ -174,17 +174,17 @@ class Path */ public static function makeUrl($path): string { - $slash = (isset($path['host']) && (strlen($path['path']) > 0) && ($path['path'][0] != '/')) ? '/' : ''; + $slash = (isset($path['host']) && isset($path['path']) && (strlen($path['path']) > 0) && ($path['path'][0] != '/')) ? '/' : ''; + $scheme = isset($path['scheme']) ? $path['scheme'] . ':/' : ''; + $user = isset($path['user']) ? $path['user'] . (isset($path['pass']) ? ':' . $path['pass'] : '') . '@' : ''; - return (isset($path['scheme']) ? $path['scheme'] . ':/' : '') - . (isset($path['host']) ? ('/' - . (isset($path['user']) ? $path['user'] . (isset($path['pass']) ? ':' . $path['pass'] : '') . '@' : '') - . $path['host'] - . (isset($path['port']) ? ':' . $path['port'] : '')) : '') - . $slash - . ($path['path'] ?? '') - . (isset($path['query']) ? '?' . $path['query'] : '') - . (isset($path['fragment']) ? '#' . $path['fragment'] : ''); + $port = isset($path['port']) ? ':' . $path['port'] : ''; + $host = isset($path['host']) ? ('/' . $user . $path['host'] . $port) : ''; + + $query = isset($path['query']) ? '?' . $path['query'] : ''; + $fragment = isset($path['fragment']) ? '#' . $path['fragment'] : ''; + + return $scheme . $host . $slash . ($path['path'] ?? '') . $query . $fragment; } /** From 1b6630e5f5766bd7d8760cae01ca1a29414b5e38 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Wed, 10 Dec 2025 19:50:04 +0300 Subject: [PATCH 136/138] =?UTF-8?q?chore:=20=D0=A2=D0=B8=D0=BF=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Database/Manager.php | 4 ++-- src/Functions.php | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Database/Manager.php b/src/Database/Manager.php index 19ed189..ff8211e 100644 --- a/src/Database/Manager.php +++ b/src/Database/Manager.php @@ -16,7 +16,7 @@ use Exception; * @phpstan-type CreateAction array{ * type:"createTable", * table_name:string, - * constraints:?array, + * constraints?:array{fields: array, type: string}|string, * fields:array, * } * @@ -277,7 +277,7 @@ class Manager * Добавляет столбец в таблицу * @param string $table_name * @param string $column_name - * @param array $field + * @param ColumnProps $field */ public function addColumn($table_name, $column_name, $field): void { diff --git a/src/Functions.php b/src/Functions.php index fa4391b..bd7fead 100644 --- a/src/Functions.php +++ b/src/Functions.php @@ -296,7 +296,7 @@ class Functions { /** * @param string $key - * @param list>|\ArrayIterator $array + * @param array>|\ArrayIterator $array * @return array */ static function assoc_key($key, $array) { From 481f76add4aa9b5916eb17421dcc93c6e802519f Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 11 Dec 2025 13:27:11 +0300 Subject: [PATCH 137/138] =?UTF-8?q?chore:=20=D0=A2=D0=B8=D0=BF=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Validator/Rule/AbstractRule.php | 5 +++-- src/Validator/Rule/Alpha.php | 5 +++-- src/Validator/Rule/RuleContext.php | 10 ++++++++++ src/Validator/Rule/Unique.php | 7 ++++--- src/Validator/Validator.php | 9 +++++---- 5 files changed, 25 insertions(+), 11 deletions(-) create mode 100644 src/Validator/Rule/RuleContext.php diff --git a/src/Validator/Rule/AbstractRule.php b/src/Validator/Rule/AbstractRule.php index fac4aad..706d8b6 100644 --- a/src/Validator/Rule/AbstractRule.php +++ b/src/Validator/Rule/AbstractRule.php @@ -1,13 +1,14 @@ ctx->isUnique($container->get($this->field), $status, $container); + return $this->ctx->isUnique($container->getString($this->field), $status, $container); } } diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 2404d6a..2225479 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -4,15 +4,16 @@ * Проверка коллекции */ namespace ctiso\Validator; -use Exception, - ctiso\Validator\Rule\AbstractRule, - ctiso\Collection; +use Exception; +use ctiso\Validator\Rule\AbstractRule; +use ctiso\Validator\Rule\RuleContext; +use ctiso\Collection; /** * @phpstan-type Rule array{ * validate?:string, // Описание правила см. формат правила ниже * name:string, // Имя переменой для проверки - * context?:object + * context?:RuleContext * } */ class Validator From 5988eca22b65841af866e13c4a80b9badc440c08 Mon Sep 17 00:00:00 2001 From: "origami11@yandex.ru" Date: Thu, 11 Dec 2025 16:08:16 +0300 Subject: [PATCH 138/138] =?UTF-8?q?chore:=20=D0=A2=D0=B8=D0=BF=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Role/User.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Role/User.php b/src/Role/User.php index fc96b8d..78f2923 100644 --- a/src/Role/User.php +++ b/src/Role/User.php @@ -74,7 +74,9 @@ class User implements UserInterface if ($result) { $time = time(); $id = $this->id; - $this->db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время входа + $this->db->executeQuery( + "UPDATE users SET lasttime = :time WHERE id_user = :id", + ['time' => $time, 'id' => $id]); // Время входа } return $result; }