fix: phpstan level=3

This commit is contained in:
origami11@yandex.ru 2024-01-22 19:56:45 +03:00
parent 277a297b8a
commit 4fc2e2ac7d
16 changed files with 69 additions and 54 deletions

4
config.php Normal file
View file

@ -0,0 +1,4 @@
<?php
define('PHPTAL_PHP_CODE_DESTINATION', '');
define('PHPTAL_TEMPLATE_REPOSITORY', '');
define('PHPTAL_DEFAULT_ENCODING', '');

10
phpstan.neon Normal file
View file

@ -0,0 +1,10 @@
parameters:
level: 3
editorUrl: 'vscode://file/%%file%%:%%line%%'
paths:
- src
universalObjectCratesClasses:
- ctiso\View\Composite
bootstrapFiles:
- config.php

View file

@ -100,7 +100,7 @@ class Action
/** /**
* Создает представление * Создает представление
* @param string * @param string $name
* @param string $viewClass * @param string $viewClass
* @return Composite * @return Composite
*/ */

View file

@ -49,9 +49,9 @@ class Component
public $COMPONENTS_WEB; public $COMPONENTS_WEB;
public $config/*: Registry*/; public Registry $config;
public $db/*: Database*/; public Database $db;
public $parameter/*: Collection*/; public Collection $parameter;
public $output = 'html'; public $output = 'html';
@ -104,6 +104,7 @@ class Component
$template = ($this->template) ? $this->template : $this->getTemplateName($config); $template = ($this->template) ? $this->template : $this->getTemplateName($config);
$selected = null; $selected = null;
$tpl = null;
foreach ($this->viewPath as $index => $viewPath) { foreach ($this->viewPath as $index => $viewPath) {
// Загружать шаблон по умолчанию если не найден текущий // Загружать шаблон по умолчанию если не найден текущий
$dir = Path::join($this->viewPath[$index], 'templates', $template); $dir = Path::join($this->viewPath[$index], 'templates', $template);
@ -147,7 +148,7 @@ class Component
} }
public function getTemplatePath($name) { public function getTemplatePath($name) {
$registry/*: \ctiso\Settings*/ = $this->config; $registry = $this->config;
// Брать настройки из куков если есть // Брать настройки из куков если есть
$template = ($this->template) ? $this->template : $this->getTemplateName($registry); $template = ($this->template) ? $this->template : $this->getTemplateName($registry);
foreach ($this->viewPath as $index => $viewPath) { foreach ($this->viewPath as $index => $viewPath) {
@ -167,7 +168,7 @@ class Component
/** /**
* Создает модель * Создает модель
* @param string $name * @param string $name
* @return model * @return mixed
*/ */
public function getModel($name) public function getModel($name)
{ {
@ -302,6 +303,7 @@ class Component
$component->component_id = $cid->getInt('id_component'); $component->component_id = $cid->getInt('id_component');
} else { } else {
$last = $db->getIdGenerator(); $last = $db->getIdGenerator();
$result = null;
if ($last->isBeforeInsert()) { if ($last->isBeforeInsert()) {
$result = $last->getId('component_id_component_seq'); $result = $last->getId('component_id_component_seq');

View file

@ -24,7 +24,7 @@ class Front extends Action
protected $modules = array(); protected $modules = array();
/** /**
* @param Settings $settings * @param Settings $config
*/ */
public function __construct($db, $config, $user, $default) { public function __construct($db, $config, $user, $default) {
parent::__construct(); parent::__construct();
@ -41,7 +41,7 @@ class Front extends Action
/** /**
* Создает экземпляр модуля и выполняет действия для него * Создает экземпляр модуля и выполняет действия для него
* @param string $name Имя модуля * @param string $name Имя модуля
* @param Request $request Имя модуля * @param Collection $request Имя модуля
* @return string * @return string
*/ */
public function loadModule($name, Collection $request) public function loadModule($name, Collection $request)

View file

@ -48,6 +48,7 @@ class Database/*<Database_PDOStatement>*/ extends PDO
static function getConnection(array $dsn) static function getConnection(array $dsn)
{ {
$connection = null;
if ($dsn['phptype'] == 'pgsql' || $dsn['phptype'] == 'mysql') { if ($dsn['phptype'] == 'pgsql' || $dsn['phptype'] == 'mysql') {
$port = (isset($dsn['port'])) ? "port={$dsn['port']};" : ""; $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 static("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']);
@ -107,11 +108,6 @@ class Database/*<Database_PDOStatement>*/ extends PDO
return $sth->fetch(PDO::FETCH_ASSOC); return $sth->fetch(PDO::FETCH_ASSOC);
} }
private static function assignQuote($x, $y)
{
return $x . "=" . $this->quote($y);
}
private function prepareValues($values) private function prepareValues($values)
{ {
if (!$values) { if (!$values) {

View file

@ -98,9 +98,7 @@ class Functions {
/** /**
* Композиция функций * Композиция функций
* @param mixed $a * @param array $_rest
* @param mixed $b
*
* @return mixed * @return mixed
*/ */
static function compose($_rest) { static function compose($_rest) {
@ -330,19 +328,21 @@ class Functions {
/** /**
* Поиск элемента в массиве * Поиск элемента в массиве
* @param mixed $cb сравнение с элементом массива * @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) { 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; return null;
} }
/** /**
* Выбирает все сроки из таблицы с уникальными значениями ключа * Выбирает все сроки из таблицы с уникальными значениями ключа
* @param string $name Имя ключа * @param string $name Имя ключа
* @param Array $table Двухмерный массив * @param array $table Двухмерный массив
* @example * @example
* key_unique_values ('name', array (array ('name' => 1), array ('name' => 2), array ('name' => 1))) * key_unique_values ('name', array (array ('name' => 1), array ('name' => 2), array ('name' => 1)))
=> array (1, 2) => array (1, 2)
@ -360,9 +360,9 @@ class Functions {
/** /**
* Сортировка двумерного массива по заданному ключу * Сортировка двумерного массива по заданному ключу
* @param Array $array Массив * @param array $array Массив
* @param string $key Имя ключа по значению которого будет идти сравнение * @param string $key Имя ключа по значению которого будет идти сравнение
* @return Array Отсортированный массив * @return array Отсортированный массив
*/ */
static function sortOn($array, $key, $fn = '\\ctiso\\Functions::__cmp') { static function sortOn($array, $key, $fn = '\\ctiso\\Functions::__cmp') {
usort ($array, Functions::rcurry($fn, $key)); usort ($array, Functions::rcurry($fn, $key));

View file

@ -59,7 +59,7 @@ class HttpRequest extends Collection
function set($key, $value/*: any*/) function set($key, $value/*: any*/)
{ {
return parent::get('data')->set($key, $value); parent::get('data')->set($key, $value);
} }
function export($key = 'data') function export($key = 'data')

View file

@ -471,12 +471,12 @@ class Path
/** /**
* Обновить относительную ссылку в файле при переносе папки * Обновить относительную ссылку в файле при переносе папки
* *
* @param String $relativePath - относительная ссылка до переноса * @param string $relativePath относительная ссылка до переноса
* @param String $fileDir - абсолютный путь к директории файла содержащего ссылку до переноса * @param string $fileDir абсолютный путь к директории файла содержащего ссылку до переноса
* @param String $srcDir - абсолютный путь к переносимой директории до переноса * @param string $srcDir абсолютный путь к переносимой директории до переноса
* @param String $dstDir - абсолютный путь к переносимой директории после переноса * @param string $dstDir абсолютный путь к переносимой директории после переноса
* *
* @return * @return string
*/ */
static function updateRelativePathOnDirectoryMove($relativePath, $fileDir, $srcDir, $dstDir) { static function updateRelativePathOnDirectoryMove($relativePath, $fileDir, $srcDir, $dstDir) {
$relativePath = self::normalize($relativePath); $relativePath = self::normalize($relativePath);

View file

@ -6,6 +6,7 @@ if (!function_exists('str_getcsv')) {
function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") { function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") {
$fiveMBs = 1024; $fiveMBs = 1024;
$fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+'); $fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');
$data = '';
if (is_resource($fp)) { if (is_resource($fp)) {
fputs($fp, $input); fputs($fp, $input);
rewind($fp); rewind($fp);

View file

@ -98,7 +98,7 @@ class Settings
/** /**
* Чтение ключа из реестра * Чтение ключа из реестра
* @param mixed $args Путь к значению ключа * @param array $key Путь к значению ключа
*/ */
public function readKey(array $key) public function readKey(array $key)
{ {
@ -130,9 +130,8 @@ class Settings
* Чтение ключа из реестра (Собирает все ключи с определенным значением во всех модулях) * Чтение ключа из реестра (Собирает все ключи с определенным значением во всех модулях)
* @param mixed $key Путь к значению ключа внутри модуля * @param mixed $key Путь к значению ключа внутри модуля
*/ */
public function readKeyList($_rest) public function readKeyList(...$key)
{ {
$key = func_get_args();
$result = array(); $result = array();
foreach ($this->data as $name => $value) { foreach ($this->data as $name => $value) {
$output = $this->readKeyData($key, $value); $output = $this->readKeyData($key, $value);

View file

@ -114,7 +114,7 @@ class Setup
/** /**
* Выполняет список действий если для действия не указан аттрибут when то оно выполняется всегда * Выполняет список действий если для действия не указан аттрибут when то оно выполняется всегда
* *
* @param $action специальное действие * @param string $action специальное действие
*/ */
function executeActions($action = "install") function executeActions($action = "install")
{ {
@ -136,10 +136,12 @@ class Setup
/** /**
* Копирования файла * Копирования файла
* @param preserve Не переписывать файл если он существует * preserver - Не переписывать файл если он существует
* @param template Файл является шаблоном подставить параметры до копирования * template Файл является шаблоном подставить параметры до копирования
* @param src Исходный файл * src Исходный файл
* @param dst Новый файл * dst Новый файл
*
* @param array{preserve: string, template: string, src: string, dst: string} $attributes
*/ */
public function copyFile(array $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) public function makeLink(array $attributes)
{ {
@ -163,7 +165,7 @@ class Setup
/** /**
* Подключение файла установки * Подключение файла установки
* @param file Имя подключаемого файла * @param array{file: string} $attributes Имя подключаемого файла
*/ */
public function includeFile(array $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) public function makeDirectory(array $attributes)
{ {

View file

@ -50,7 +50,7 @@ class SQLStatementExtractor {
/** /**
* Extract statements from string. * Extract statements from string.
* *
* @param string $txt * @param string $buffer
* @return array * @return array
*/ */
public static function extract($buffer) { public static function extract($buffer) {
@ -61,7 +61,7 @@ class SQLStatementExtractor {
* Extract SQL statements from array of lines. * Extract SQL statements from array of lines.
* *
* @param array $lines Lines of the read-in file. * @param array $lines Lines of the read-in file.
* @return string * @return array
*/ */
protected static function extractStatements($lines) { protected static function extractStatements($lines) {
@ -156,7 +156,7 @@ class SQLStatementExtractor {
/** /**
* Convert string buffer into array of lines. * Convert string buffer into array of lines.
* *
* @param string $filename * @param string $buffer
* @return array string[] lines of file. * @return array string[] lines of file.
*/ */
protected static function getLines($buffer) { protected static function getLines($buffer) {

View file

@ -38,9 +38,6 @@ class TemplateImage
protected $image; protected $image;
protected $_prepare = true; protected $_prepare = true;
public $debug = false; public $debug = false;
public $filename;
public $resource;
public $resource; public $resource;
public $filename; public $filename;

View file

@ -7,7 +7,7 @@ namespace ctiso\View;
class Pages class Pages
{ {
static $range = 5; static int $range = 5;
static function getPages($page, $onpage, $count, $prefix = '?') static function getPages($page, $onpage, $count, $prefix = '?')
{ {
$n = ceil($count / $onpage); $n = ceil($count / $onpage);

View file

@ -120,8 +120,6 @@ class View extends \stdClass
/** /**
* Обработка всех вложенных шаблонов * Обработка всех вложенных шаблонов
*
* @return string
*/ */
public function execute() public function execute()
{ {
@ -166,10 +164,12 @@ class View extends \stdClass
throw new Exception("file not found: $file"); throw new Exception("file not found: $file");
} }
// FIXME: Префикс, конфликтует с протоколом
function resolveName($alias, $file) { function resolveName($alias, $file) {
list($type, $filename) = explode(":", $file, 2); list($type, $filename) = explode(":", $file, 2);
// Сделать поиск а не просто замену папки при совпадении имени // Сделать поиск а не просто замену папки при совпадении имени
if (isset($alias[$type])) {
if (is_array($alias[$type])) { if (is_array($alias[$type])) {
$output = $this->find_file($alias[$type], $filename); $output = $this->find_file($alias[$type], $filename);
} else { } else {
@ -177,6 +177,8 @@ class View extends \stdClass
} }
return $output; return $output;
} }
return $file;
}
function loadImports($importFile) function loadImports($importFile)
{ {