fix: phpstan level=6

This commit is contained in:
origami11@yandex.ru 2025-10-06 12:49:36 +03:00
parent acbf2c847d
commit 48269bd424
41 changed files with 324 additions and 347 deletions

View file

@ -41,7 +41,7 @@ class Collection implements \ArrayAccess
* *
* @return void * @return void
*/ */
public function set($key, $value) public function set(string $key, mixed $value)
{ {
$this->data[$key] = $value; $this->data[$key] = $value;
} }

View file

@ -181,15 +181,6 @@ class Functions {
return ($a[$key] < $b[$key]) ? -1 : 1; 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) { static function __self($name, $o) {
return call_user_func([$o, $name]); return call_user_func([$o, $name]);
} }
@ -203,21 +194,6 @@ class Functions {
return 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) * @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 * @return mixed
*/ */
static function some(array $array, $callback) { static function some(array $array, callable $callback) {
assert(is_callable($callback));
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
if (call_user_func($callback, $value) === true) { if (call_user_func($callback, $value) === true) {
@ -316,8 +288,7 @@ class Functions {
return false; return false;
} }
static function span($length, array $array) { static function span(int $length, array $array) {
assert(is_int($length));
$result = []; $result = [];
$count = count($array); $count = count($array);
@ -327,7 +298,7 @@ class Functions {
return $result; return $result;
} }
static function array_ref($data, $n) { static function array_ref(array $data, string|int $n) {
return $data[$n]; return $data[$n];
} }

View file

@ -63,12 +63,12 @@ class HttpRequest extends Collection
return $this->_session; return $this->_session;
} }
function set($key, mixed $value) function set(string $key, mixed $value)
{ {
parent::get('data')->set($key, $value); parent::get('data')->set($key, $value);
} }
function export($key = 'data') function export(string $key = 'data')
{ {
return parent::get($key)->export(); return parent::get($key)->export();
} }
@ -85,7 +85,7 @@ class HttpRequest extends Collection
* @param string $key * @param string $key
* @return mixed * @return mixed
*/ */
public function getRawData($var, $key) public function getRawData(string $var, $key)
{ {
$data = parent::get(strtolower($var)); $data = parent::get(strtolower($var));
if ($data) { if ($data) {

View file

@ -17,7 +17,7 @@ class MailAlt
/** /**
* Установка отправителя * Установка отправителя
*/ */
function from($name) function from(string $name)
{ {
$this->mailer->setFrom($name); $this->mailer->setFrom($name);
} }
@ -25,12 +25,12 @@ class MailAlt
/** /**
* Установка получателя * Установка получателя
*/ */
function to($name) // recipient function to(string $name) // recipient
{ {
$this->mailer->addAddress($name); $this->mailer->addAddress($name);
} }
function replyTo($name) // recipient function replyTo(string $name) // recipient
{ {
$this->mailer->AddReplyTo($name); $this->mailer->AddReplyTo($name);
} }
@ -39,12 +39,12 @@ class MailAlt
* Установка получателей копии * Установка получателей копии
* @param string $name * @param string $name
*/ */
function copy($name) // recipient cc function copy(string $name) // recipient cc
{ {
$this->mailer->addCC($name); $this->mailer->addCC($name);
} }
function notify($notify) function notify(string $notify)
{ {
$this->_notify = $notify; $this->_notify = $notify;
} }
@ -53,7 +53,7 @@ class MailAlt
* Тема письма * Тема письма
* @param string $subject * @param string $subject
*/ */
function subject($subject) function subject(string $subject)
{ {
$this->mailer->Subject = $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); $this->mailer->addAttachment($filename, $name);
} }
@ -91,12 +91,12 @@ class MailAlt
/** /**
* Отправка почты * Отправка почты
*/ */
function send() function send(): bool
{ {
return $this->mailer->send(); return $this->mailer->send();
} }
function eml() { function eml(): string {
return $this->mailer->getSentMIMEMessage(); return $this->mailer->getSentMIMEMessage();
} }
} }

View file

@ -4,22 +4,22 @@ namespace ctiso;
class Numbers class Numbers
{ {
static function roman($i) static function roman(float $i): float
{ {
return 0; return 0;
} }
static function decimal($i) static function decimal(float $i): float
{ {
return $i; return $i;
} }
static function prefix($prefix, array $array, $key = false) static function prefix(callable $prefix, array $array, $key = false)
{ {
$result = []; $result = [];
$count = count($array); $count = count($array);
for ($i = 0; $i < $count; $i++) { 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; return $result;
} }

View file

@ -368,12 +368,12 @@ class Path
/** /**
* Список файлов в директории * Список файлов в директории
* *
* @param array $allow массив расширений для файлов * @param ?array $allow массив расширений для файлов
* @param array $ignore массив имен пааок которые не нужно обрабатывать * @param array $ignore массив имен пааок которые не нужно обрабатывать
* *
* @returnarray * @returnarray
*/ */
public function getContent($allow = null, $ignore = []) public function getContent(?array $allow = null, array $ignore = [])
{ {
$ignore = array_merge([".", ".."], $ignore); $ignore = array_merge([".", ".."], $ignore);
return self::fileList($this->__toString(), $allow, $ignore); return self::fileList($this->__toString(), $allow, $ignore);
@ -382,12 +382,12 @@ class Path
/** /**
* Обьединяет строки в путь соединяя необходимым разделителем * Обьединяет строки в путь соединяя необходимым разделителем
* *
* @param array $allow массив расширений разрешеных для файлов * @param ?array $allow массив расширений разрешеных для файлов
* @param array $ignore массив имен пааок которые не нужно обрабатывать * @param array $ignore массив имен пааок которые не нужно обрабатывать
* *
* @return array * @return array
*/ */
function getContentRec($allow = null, $ignore = []) function getContentRec(?array $allow = null, array $ignore = [])
{ {
$result = []; $result = [];
$ignore = array_merge([".", ".."], $ignore); $ignore = array_merge([".", ".."], $ignore);
@ -396,7 +396,7 @@ class Path
} }
// Использовать SPL ??? // Использовать SPL ???
protected static function fileList($base, &$allow, &$ignore) protected static function fileList(string $base, ?array &$allow, array &$ignore): array
{ {
if ($base == '') $base = '.'; if ($base == '') $base = '.';
$result = []; $result = [];
@ -441,7 +441,7 @@ class Path
* *
* @return void * @return void
*/ */
static function prepare($dst, $filename = true) static function prepare(string $dst, bool $filename = true)
{ {
if ($filename) { if ($filename) {
$path_dst = pathinfo($dst, PATHINFO_DIRNAME); $path_dst = pathinfo($dst, PATHINFO_DIRNAME);
@ -462,7 +462,7 @@ class Path
* *
* @return string * @return string
*/ */
static function updateRelativePathOnFileMove($relativePath, $srcFile, $dstFile) { static function updateRelativePathOnFileMove(string $relativePath, string $srcFile, string $dstFile) {
$srcToDst = self::relative($srcFile, $dstFile); $srcToDst = self::relative($srcFile, $dstFile);
return self::normalize(self::join($srcToDst, $relativePath)); return self::normalize(self::join($srcToDst, $relativePath));
} }
@ -477,7 +477,7 @@ class Path
* *
* @return string * @return string
*/ */
static function updateRelativePathOnDirectoryMove($relativePath, $fileDir, $srcDir, $dstDir) { static function updateRelativePathOnDirectoryMove(string $relativePath, string $fileDir, string $srcDir, string $dstDir) {
$relativePath = self::normalize($relativePath); $relativePath = self::normalize($relativePath);
$fileDir = self::normalize($fileDir); $fileDir = self::normalize($fileDir);
$srcDir = self::normalize($srcDir); $srcDir = self::normalize($srcDir);

View file

@ -10,7 +10,7 @@ namespace ctiso;
class Primitive { class Primitive {
// varchar // varchar
public static function to_varchar($value) public static function to_varchar($value): string
{ {
return ((string) $value); return ((string) $value);
} }
@ -26,28 +26,28 @@ class Primitive {
return filter_var($value, FILTER_VALIDATE_BOOLEAN);//(int)((bool) $value); 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); return ((bool) $value);
} }
// int // int
public static function to_int($value) public static function to_int($value): int
{ {
return ((int) $value); return ((int) $value);
} }
public static function from_int($value) public static function from_int($value): string
{ {
return ((string) $value); return ((string) $value);
} }
// date // date
public static function to_date($value) public static function to_date($value)
{ {
$result = 0; $result = 0;
$tmp = explode("/", $value ?? '', 3); $tmp = explode("/", $value ?? '', 3);
if (count($tmp) != 3) { if (count($tmp) != 3) {
return $result; return $result;
} }
@ -63,7 +63,7 @@ class Primitive {
return 0; return 0;
} }
} }
return $result; return $result;
} }
@ -110,7 +110,7 @@ class Primitive {
} }
// array // array
public static function to_array($value) public static function to_array($value)
{ {
return (is_array($value)) ? $value : []; return (is_array($value)) ? $value : [];
} }

View file

@ -5,47 +5,47 @@ use ctiso\File,
Exception; Exception;
class Registry { class Registry {
public $namespace = []; public array $namespace = [];
public $data; public $data;
function importFile($namespace, $filePath = null) { function importFile(string $namespace, ?string $filePath = null) {
$data = json_decode(File::getContents($filePath), true); $data = json_decode(File::getContents($filePath), true);
$data['_file'] = $filePath; $data['_file'] = $filePath;
$this->namespace[$namespace] = [ $this->namespace[$namespace] = [
'path' => $filePath, 'path' => $filePath,
'data' => $data 'data' => $data
]; ];
} }
function importArray($namespace, $data = []) { function importArray(string $namespace, array $data = []) {
if (isset($this->namespace[$namespace])) { if (isset($this->namespace[$namespace])) {
$data = array_merge($this->namespace[$namespace]['data'], $data); $data = array_merge($this->namespace[$namespace]['data'], $data);
} }
$this->namespace[$namespace] = [ $this->namespace[$namespace] = [
'path' => null, 'path' => null,
'data' => $data 'data' => $data
]; ];
} }
public function get($ns, $key) { public function get(string $ns, string $key) {
if (isset($this->namespace[$ns]['data'][$key])) { if (isset($this->namespace[$ns]['data'][$key])) {
return $this->namespace[$ns]['data'][$key]; return $this->namespace[$ns]['data'][$key];
} }
throw new Exception('Unknown key ' . $ns . '::' . $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])) { if (isset($this->namespace[$ns]['data'][$key])) {
return $this->namespace[$ns]['data'][$key]; return $this->namespace[$ns]['data'][$key];
} }
return null; return null;
} }
public function has($ns, $key) { public function has(string $ns, string $key): bool {
return isset($this->namespace[$ns]['data'][$key]); 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; $this->namespace[$ns]['data'][$key] = $value;
} }
} }

View file

@ -4,20 +4,20 @@ namespace ctiso\Role;
use ctiso\Database, use ctiso\Database,
ctiso\Database\Statement; ctiso\Database\Statement;
// Класс должен быть в библиотеке приложения // Класс должен быть в библиотеке приложения
class User implements UserInterface class User implements UserInterface
{ {
const LIFE_TIME = 1800; // = 30min * 60sec; const LIFE_TIME = 1800; // = 30min * 60sec;
public $fullname; public string $fullname;
public $name; public string $name;
public $access; public $access;
public $password; public string $password;
public $id; public $id;
public $db; public Database $db;
public $groups; public array $groups;
function __construct($db, $groups) { function __construct(Database $db, array $groups) {
$this->db = $db; $this->db = $db;
$this->groups = $groups; $this->groups = $groups;
} }
@ -26,7 +26,7 @@ class User implements UserInterface
$this->db = $db; $this->db = $db;
} }
public function getName() { public function getName(): string {
return $this->name; return $this->name;
} }
@ -35,7 +35,7 @@ class User implements UserInterface
} }
public function getUserByQuery(Statement $stmt) public function getUserByQuery(Statement $stmt)
{ {
$result = $stmt->executeQuery(); $result = $stmt->executeQuery();
if ($result->next()) { if ($result->next()) {
@ -44,8 +44,8 @@ class User implements UserInterface
$this->id = $result->getInt('id_user'); $this->id = $result->getInt('id_user');
$this->password = $result->getString('password'); $this->password = $result->getString('password');
$this->fullname = implode(' ', [ $this->fullname = implode(' ', [
$result->getString('surname'), $result->getString('surname'),
$result->getString('firstname'), $result->getString('firstname'),
$result->getString('patronymic')]); $result->getString('patronymic')]);
return $result; return $result;
} }
@ -56,12 +56,12 @@ class User implements UserInterface
return $result->get('password'); return $result->get('password');
} }
public function getUserByLogin($login) public function getUserByLogin(string $login)
{ {
$stmt = $this->db->prepareStatement("SELECT * FROM users WHERE login = ?"); $stmt = $this->db->prepareStatement("SELECT * FROM users WHERE login = ?");
$stmt->setString(1, $login); $stmt->setString(1, $login);
$result = $this->getUserByQuery($stmt); $result = $this->getUserByQuery($stmt);
if ($result) { if ($result) {
$time = time(); $time = time();
$id = $this->id; $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"); // Время входа
@ -69,7 +69,7 @@ class User implements UserInterface
return $result; return $result;
} }
public function getUserById($id) public function getUserById(int $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']); $stmt->setInt(1, $_SESSION ['access']);
@ -77,24 +77,24 @@ class User implements UserInterface
if ($result) { if ($result) {
$lasttime = $result->getInt('lasttime'); $lasttime = $result->getInt('lasttime');
$time = time(); $time = time();
if ($time - $lasttime > self::LIFE_TIME) return null; // Вышло время сессии if ($time - $lasttime > self::LIFE_TIME) return null; // Вышло время сессии
$id = $this->id; $id = $this->id;
} }
return $result; 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')); 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( $this->db->executeQuery(
"UPDATE users SET trie_count = :count WHERE login = :login", "UPDATE users SET trie_count = :count WHERE login = :login",
['count' => 0, '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]); $user = $this->db->fetchOneArray("SELECT id_user, trie_count FROM users WHERE login = :login", ['login' => $login]);
$this->db->executeQuery( $this->db->executeQuery(
"UPDATE users SET trie_time = :cur_time, trie_count = :count WHERE id_user = :id_user", "UPDATE users SET trie_time = :cur_time, trie_count = :count WHERE id_user = :id_user",

View file

@ -5,8 +5,8 @@ use ctiso\Database\Statement;
interface UserInterface { interface UserInterface {
function getUserByQuery(Statement $stmt); function getUserByQuery(Statement $stmt);
function getUserByLogin($login); function getUserByLogin(string $login);
function getUserById($id); function getUserById(int $id);
function getName(); function getName();
function setSID($random, $result); function setSID(string $random, $result);
} }

View file

@ -3,7 +3,7 @@
namespace ctiso; namespace ctiso;
class Security { class Security {
static function generatePassword($length = 9, $strength = 0) { static function generatePassword(int $length = 9, int $strength = 0): string {
$vowels = 'aeuy'; $vowels = 'aeuy';
$consonants = 'bdghjmnpqrstvz'; $consonants = 'bdghjmnpqrstvz';
if ($strength & 1) { if ($strength & 1) {
@ -18,7 +18,7 @@ class Security {
if ($strength & 8) { if ($strength & 8) {
$consonants .= '@#$%'; $consonants .= '@#$%';
} }
$password = ''; $password = '';
$alt = time() % 2; $alt = time() % 2;
for ($i = 0; $i < $length; $i++) { for ($i = 0; $i < $length; $i++) {

View file

@ -2,9 +2,9 @@
namespace ctiso; namespace ctiso;
class Session class Session
{ {
function get($key) function get(string $key): mixed
{ {
if (isset($_SESSION[$key])) { if (isset($_SESSION[$key])) {
return $_SESSION[$key]; return $_SESSION[$key];
@ -12,7 +12,7 @@ class Session
return null; return null;
} }
function set($key, $value) function set(string|array $key, mixed $value): void
{ {
if (is_array($key)) { if (is_array($key)) {
$_SESSION[strtolower(get_class($key[0]))][$key[1]] = $value; $_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]); unset($_SESSION[$key]);
} }
function start() function start(): void
{ {
@session_start(); @session_start();
} }
function stop() function stop(): void
{ {
session_destroy(); session_destroy();
} }

View file

@ -10,6 +10,7 @@
namespace ctiso; namespace ctiso;
use ctiso\Tools\SQLStatementExtractor; use ctiso\Tools\SQLStatementExtractor;
use ctiso\Path; use ctiso\Path;
use SimpleXMLElement;
class FakeZipArchive { class FakeZipArchive {
public $base; public $base;
@ -58,7 +59,7 @@ class Setup
/** /**
* Регистрация новых действия для установки * Регистрация новых действия для установки
*/ */
public function registerAction($name, $action) public function registerAction(string $name, $action)
{ {
$this->actions[$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; $this->context[$name] = $value;
} }
function replaceFn($matches) { function replaceFn(array $matches) {
if (isset($this->context[$matches[2]])) { if (isset($this->context[$matches[2]])) {
$v = $this->context[$matches[2]]; $v = $this->context[$matches[2]];
} else { } else {
@ -84,14 +85,14 @@ class Setup
return $v; return $v;
} }
public function fileContent($file, array $tpl) public function fileContent(string $file, array $tpl): string
{ {
$result = $this->zip->getFromName($file); $result = $this->zip->getFromName($file);
$result = preg_replace_callback('/\{\{\s*(\*?)(\w+)\s*\}\}/', [$this, 'replaceFn'], $result); $result = preg_replace_callback('/\{\{\s*(\*?)(\w+)\s*\}\}/', [$this, 'replaceFn'], $result);
return $result; return $result;
} }
function callAction($name, array $attributes) function callAction(string $name, array $attributes): void
{ {
if(isset($this->actions[$name])) { if(isset($this->actions[$name])) {
call_user_func_array($this->actions[$name], $attributes); call_user_func_array($this->actions[$name], $attributes);
@ -112,7 +113,7 @@ class Setup
/** /**
* Для всех аттрибутов заменяет переменные на их значения * Для всех аттрибутов заменяет переменные на их значения
*/ */
function resolve($attributes) function resolve(SimpleXMLElement $attributes): array
{ {
$result = []; $result = [];
foreach ($attributes as $key => $value) { foreach ($attributes as $key => $value) {
@ -167,7 +168,7 @@ class Setup
* Создает символическую ссылку на папку/файл * Создает символическую ссылку на папку/файл
* @param array{target: string, link: string} $attributes * @param array{target: string, link: string} $attributes
*/ */
public function makeLink(array $attributes) public function makeLink(array $attributes): void
{ {
if (function_exists('symlink')) { if (function_exists('symlink')) {
symlink($attributes['target'], $attributes['link']); symlink($attributes['target'], $attributes['link']);
@ -178,7 +179,7 @@ class Setup
* Подключение файла установки * Подключение файла установки
* @param array{file: string} $attributes Имя подключаемого файла * @param array{file: string} $attributes Имя подключаемого файла
*/ */
public function includeFile(array $attributes) public function includeFile(array $attributes): void
{ {
$file = basename($this->file) . "/" . $attributes['file']; $file = basename($this->file) . "/" . $attributes['file'];

View file

@ -2,20 +2,18 @@
namespace ctiso; namespace ctiso;
class SortRecord class SortRecord
{ {
public $key; public string $key;
public $mode; public int $order;
public $order;
function __construct($key, $mode, $order) function __construct(string $key, bool $order)
{ {
$this->key = $key; $this->key = $key;
$this->order = ((boolean)($order) === false) ? 1 : -1; $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]) { if($a[$this->key] == $b[$this->key]) {
return 0; return 0;
@ -23,7 +21,7 @@ class SortRecord
return ($a[$this->key] > $b[$this->key]) ? $this->order : -$this->order; 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}) { if($a->{$this->key} == $b->{$this->key}) {
return 0; return 0;
@ -31,17 +29,17 @@ class SortRecord
return ($a->{$this->key} > $b->{$this->key}) ? $this->order : -$this->order; return ($a->{$this->key} > $b->{$this->key}) ? $this->order : -$this->order;
} }
function sort(&$list) function sort(array &$list)
{ {
return usort($list, [$this, 'compare']); return usort($list, [$this, 'compare']);
} }
function sortKeys(&$list) function sortKeys(array &$list)
{ {
return usort($list, [$this, 'compareKeys']); return usort($list, [$this, 'compareKeys']);
} }
function group(&$list, $key, $types) function group(array &$list, string $key, array $types)
{ {
$groups = []; $groups = [];
foreach ($types as $name) { foreach ($types as $name) {
@ -59,6 +57,6 @@ class SortRecord
foreach ($groups as $value) { foreach ($groups as $value) {
$result = array_merge($result, $value); $result = array_merge($result, $value);
} }
$list = $result; $list = $result;
} }
} }

View file

@ -13,18 +13,20 @@ use PHPTAL_Php_TalesInternal,
class Tales_DateTime implements PHPTAL_Tales 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).")"; 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).")"; return "ctiso\\Tales::phptal_time(".PHPTAL_Php_TalesInternal::path($expression).")";
} }
} }
class Tales_Component implements PHPTAL_Tales 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); $s = PHPTAL_Php_TalesInternal::string($expression);
return "ctiso\\Tales::phptal_component(" . $s . ")"; return "ctiso\\Tales::phptal_component(" . $s . ")";
@ -33,7 +35,7 @@ class Tales_Component implements PHPTAL_Tales
class Tales_Assets 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); $s = PHPTAL_Php_TalesInternal::string($expression);
return "ctiso\\Tales::phptal_asset(" . $s . ")"; return "ctiso\\Tales::phptal_asset(" . $s . ")";
@ -44,15 +46,15 @@ class Tales {
/** @var SiteInterface */ /** @var SiteInterface */
static $site; static $site;
static function phptal_date ($e) { static function phptal_date ($e): string {
return date("d.m.Y", $e); return date("d.m.Y", $e);
} }
static function phptal_time ($e) { static function phptal_time ($e): string {
return date("H:i", $e); return date("H:i", $e);
} }
static function phptal_asset($s) { static function phptal_asset($s): string {
self::$site->addStyleSheet($s); self::$site->addStyleSheet($s);
return ""; return "";
} }

View file

@ -2,6 +2,8 @@
namespace ctiso\Tools; namespace ctiso\Tools;
use GdImage;
class Drawing class Drawing
{ {
const ALIGN_LEFT = "left"; const ALIGN_LEFT = "left";
@ -10,13 +12,13 @@ class Drawing
const ALIGN_CENTER = "center"; const ALIGN_CENTER = "center";
const ALIGN_RIGHT = "right"; 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]); $color = imagecolorallocate($image, $rgb[0], $rgb[1], $rgb[2]);
$right = $left + $width; $right = $left + $width;
$bottom = $top + $height; $bottom = $top + $height;
imageline($image, $left, $top, $right, $top, $color); 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, $bottom, $right, $bottom, $color);
imageline($image, $left, $top, $left, $bottom, $color); imageline($image, $left, $top, $left, $bottom, $color);
} }
@ -24,12 +26,23 @@ 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(
$max_width, $max_height, $align, $valign) GdImage &$image,
{ int $size,
// echo $left,"\n", $top, "\n"; float $angle,
// echo $max_width,"\n", $max_height, "\n"; $left,
// self::drawrectnagle($image, $left, $top, $max_width, $max_height, array(0xFF,0,0)); $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! $text_lines = explode("\n", $text); // Supports manual line breaks!
$lines = []; $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); imagettftext($image, $size, $angle, $x, $y, $color, $font, $text);
} } else {
else
{
$temp_x = $x; $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]); $bbox = imagettftext($image, $size, $angle, $temp_x, $y, $color, $font, $text[$i]);
$temp_x += $spacing + ($bbox[2] - $bbox[0]); $temp_x += $spacing + ($bbox[2] - $bbox[0]);
} }

View file

@ -2,9 +2,11 @@
namespace ctiso\Tools; namespace ctiso\Tools;
use GdImage;
class Image class Image
{ {
static function load($uri) static function load($uri): GdImage|false
{ {
$e = strtolower(pathinfo($uri, PATHINFO_EXTENSION)); $e = strtolower(pathinfo($uri, PATHINFO_EXTENSION));
switch ($e) { switch ($e) {
@ -12,9 +14,10 @@ class Image
case 'jpeg': case 'jpg': return imagecreatefromjpeg($uri); case 'jpeg': case 'jpg': return imagecreatefromjpeg($uri);
case 'gif': return imagecreatefromgif($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); $width = imagesx($image);
$height = imagesy($image); $height = imagesy($image);
@ -29,7 +32,7 @@ class Image
return $image_p; return $image_p;
} }
static function save($image, $uri) static function save($image, $uri): bool
{ {
$e = strtolower(pathinfo($uri, PATHINFO_EXTENSION)); $e = strtolower(pathinfo($uri, PATHINFO_EXTENSION));
switch ($e) { switch ($e) {
@ -37,5 +40,6 @@ class Image
case 'png': imagepng($image, $uri); break; case 'png': imagepng($image, $uri); break;
case 'gif': imagegif($image, $uri); break; case 'gif': imagegif($image, $uri); break;
} }
return false;
} }
} }

View file

@ -124,7 +124,7 @@ class SQLStatementExtractor {
* @param string $string The string to check in (haystack). * @param string $string The string to check in (haystack).
* @return boolean True if $string ends with $check, or they are equal, or $check is empty. * @return boolean True if $string ends with $check, or they are equal, or $check is empty.
*/ */
protected static function endsWith(string $check, $string) { protected static function endsWith(string $check, string $string) {
if ($check === "" || $check === $string) { if ($check === "" || $check === $string) {
return true; return true;
} else { } else {
@ -136,7 +136,7 @@ class SQLStatementExtractor {
* a natural way of getting a subtring, php's circular string buffer and strange * a natural way of getting a subtring, php's circular string buffer and strange
* return values suck if you want to program strict as of C or friends * return values suck if you want to program strict as of C or friends
*/ */
protected static function substring($string, $startpos, $endpos = -1) { protected static function substring(string $string, int $startpos, int $endpos = -1) {
$len = strlen($string); $len = strlen($string);
$endpos = (int) (($endpos === -1) ? $len-1 : $endpos); $endpos = (int) (($endpos === -1) ? $len-1 : $endpos);
if ($startpos > $len-1 || $startpos < 0) { if ($startpos > $len-1 || $startpos < 0) {
@ -157,9 +157,9 @@ class SQLStatementExtractor {
* Convert string buffer into array of lines. * Convert string buffer into array of lines.
* *
* @param string $buffer * @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); $lines = preg_split("/\r?\n|\r/", $buffer);
return $lines; return $lines;
} }

View file

@ -5,7 +5,7 @@ namespace ctiso\Tools;
class StringUtil { class StringUtil {
// from creole // from creole
static function strToArray($str) { static function strToArray(string $str): array {
$str = substr($str, 1, -1); // remove { } $str = substr($str, 1, -1); // remove { }
$res = []; $res = [];
@ -40,7 +40,7 @@ class StringUtil {
} }
//Нормализация строк на русском //Нормализация строк на русском
static function normalizeRussian($str) { static function normalizeRussian(string $str): string {
$result = preg_replace('/\s+/',' ', $str); $result = preg_replace('/\s+/',' ', $str);
if (is_string($result)) { if (is_string($result)) {
$result = trim($result); //Замена длинных пробелов на одинарные, пробелы по краям $result = trim($result); //Замена длинных пробелов на одинарные, пробелы по краям
@ -62,8 +62,8 @@ class StringUtil {
* output: true * output: true
* input: $str="foo" $variants="foo1|foo2|foo3" * input: $str="foo" $variants="foo1|foo2|foo3"
* output: false * output: false
*/ */
static function compare_string_to_variants($str, $variants){ static function compare_string_to_variants($str, string $variants){
$variants_array = explode('|', $variants); $variants_array = explode('|', $variants);
$founded = false; $founded = false;
foreach ($variants_array as $variant) { foreach ($variants_array as $variant) {
@ -72,7 +72,7 @@ class StringUtil {
return $founded; 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); 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); 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 = self::mb_strtr($st,"АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ", "ABVGDEEZIYKLMNOPRSTUFH_IE"); $st = self::mb_strtr($st,"АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ", "ABVGDEEZIYKLMNOPRSTUFH_IE");
$st = strtr($st, [ $st = strtr($st, [
" " => '_', " " => '_',
"." => '_', "." => '_',
"," => '_', "," => '_',
"?" => '_', "?" => '_',
"\"" => '_', "\"" => '_',
"'" => '_', "'" => '_',
"/" => '_', "/" => '_',
"\\" => '_', "\\" => '_',
"%" => '_', "%" => '_',
"#" => '_', "#" => '_',
"*" => '_', "*" => '_',
"ж"=>"zh", "ц"=>"ts", "ч"=>"ch", "ш"=>"sh", "ж"=>"zh", "ц"=>"ts", "ч"=>"ch", "ш"=>"sh",
"щ"=>"shch","ь"=>"", "ю"=>"yu", "я"=>"ya", "щ"=>"shch","ь"=>"", "ю"=>"yu", "я"=>"ya",
"Ж"=>"ZH", "Ц"=>"TS", "Ч"=>"CH", "Ш"=>"SH", "Ж"=>"ZH", "Ц"=>"TS", "Ч"=>"CH", "Ш"=>"SH",
"Щ"=>"SHCH","Ь"=>"", "Ю"=>"YU", "Я"=>"YA", "Щ"=>"SHCH","Ь"=>"", "Ю"=>"YU", "Я"=>"YA",
"Й"=>"i", "й"=>"ie", "ё"=>"Ye", "Й"=>"i", "й"=>"ie", "ё"=>"Ye",
""=>"N" ""=>"N"
]); ]);
return strtolower($st); return strtolower($st);
} }
static function validate_encoded_string($st) { static function validate_encoded_string(string $st): int|false {
$enc_st = self::encodestring($st); $enc_st = self::encodestring($st);
return preg_match('/^[\w_-]+(\.[\w_-]+)?$/', $enc_st); return preg_match('/^[\w_-]+(\.[\w_-]+)?$/', $enc_st);
} }

View file

@ -8,8 +8,8 @@ use ctiso\Tools\Drawing;
class TemplateImage class TemplateImage
{ {
static $listfiles = array('jpg' => 'jpeg', 'gif' => 'gif', 'png' => 'png', 'bmp' => 'wbmp'); static array $listfiles = array('jpg' => 'jpeg', 'gif' => 'gif', 'png' => 'png', 'bmp' => 'wbmp');
static $listfonts = array( static array $listfonts = array(
'georgia' => 'georgia.ttf', 'georgia' => 'georgia.ttf',
'georgiabd' => 'georgiab.ttf', 'georgiabd' => 'georgiab.ttf',
'georgiaz' => 'georgiaz.ttf', 'georgiaz' => 'georgiaz.ttf',
@ -32,16 +32,16 @@ class TemplateImage
); );
protected $src; protected $src;
protected $context = array(); protected array $context = [];
protected $data = array(); protected array $data = [];
protected $base = "c:\\windows\\fonts\\"; protected string $base = "c:\\windows\\fonts\\";
protected $image; protected $image;
protected $_prepare = true; protected $_prepare = true;
public $debug = false; public $debug = false;
public $resource; public $resource;
public $filename; public $filename;
function __construct (?string $template = null) function __construct (?array $template = null)
{ {
if ($template) { if ($template) {
$this->data = $template; $this->data = $template;
@ -51,7 +51,7 @@ class TemplateImage
/** /**
* Путь к изображению * Путь к изображению
*/ */
function resourcePath(string $path) function resourcePath(string $path): void
{ {
$this->resource = $path; $this->resource = $path;
} }
@ -59,7 +59,7 @@ class TemplateImage
/** /**
* Путь у шрифтам * Путь у шрифтам
*/ */
function fontPath(string $path) function fontPath(string $path): void
{ {
$this->base = $path; $this->base = $path;
} }
@ -69,13 +69,13 @@ class TemplateImage
$this->context['['.$name.']'] = $this->encode($value); $this->context['['.$name.']'] = $this->encode($value);
} }
function setImage($name) function setImage($name): void
{ {
$this->filename = $name; $this->filename = $name;
$this->image = $this->imagefromfile($name); $this->image = $this->imagefromfile($name);
} }
function setEmptyImage($width, $height) function setEmptyImage($width, $height): void
{ {
$this->image = imagecreatetruecolor($width, $height); $this->image = imagecreatetruecolor($width, $height);
} }
@ -92,7 +92,7 @@ class TemplateImage
return null; return null;
} }
function getFontFile(string $name) 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 . self::$listfonts[$name];
@ -100,7 +100,7 @@ class TemplateImage
return $this->base . 'arial.ttf'; return $this->base . 'arial.ttf';
} }
function fontSuffix(array $style) function fontSuffix(array $style): string
{ {
if($style[0] && $style[1]) return "z"; if($style[0] && $style[1]) return "z";
@ -110,14 +110,8 @@ class TemplateImage
return ""; return "";
} }
/** function imageText(string $text, object $value)
* @param string $text
* @param object $value
*/
function imageText($text, $value)
{ {
assert(is_string($text));
$text = strtr($text, $this->context); $text = strtr($text, $this->context);
$size = $value->fontSize; $size = $value->fontSize;
$fontfile = $this->getFontFile($value->fontFamily . $this->fontSuffix($value->fontStyle)); $fontfile = $this->getFontFile($value->fontFamily . $this->fontSuffix($value->fontStyle));
@ -148,17 +142,12 @@ class TemplateImage
* Перекодировка текста * Перекодировка текста
* @deprecated * @deprecated
*/ */
function encode($text) function encode(string $text): string
{ {
assert(is_string($text));
return $text; //iconv("WINDOWS-1251", "UTF-8", $text); return $text; //iconv("WINDOWS-1251", "UTF-8", $text);
} }
/** function setSize(int $new_width, int $new_height): void
* @param int $new_width
* @param int $new_height
*/
function setSize($new_width, $new_height)
{ {
$width = imagesx($this->image); $width = imagesx($this->image);
$height = imagesy($this->image); $height = imagesy($this->image);
@ -173,7 +162,7 @@ class TemplateImage
$this->image = $image_p; $this->image = $image_p;
} }
function prepare() { function prepare(): void {
if($this->_prepare) { if($this->_prepare) {
$this->_prepare = false; $this->_prepare = false;
foreach ($this->data as $value) { 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(); $this->prepare();
if ($file == null) { if ($file == null) {

View file

@ -2,13 +2,20 @@
namespace ctiso; namespace ctiso;
class UTF8 { class UTF8
static function str_split($str, $split_length = 1) { {
$split_length = (int) $split_length; /**
* @param string $str
* @param int $split_length
* @return list<string>
*/
static function str_split(string $str, int $split_length = 1): array
{
$split_length = (int) $split_length;
$matches = []; $matches = [];
preg_match_all('/.{'.$split_length.'}|[^\x00]{1,'.$split_length.'}$/us', $str, $matches); preg_match_all('/.{' . $split_length . '}|[^\x00]{1,' . $split_length . '}$/us', $str, $matches);
return $matches[0]; return $matches[0];
} }
} }

View file

@ -3,26 +3,23 @@
namespace ctiso; namespace ctiso;
class Url { class Url {
public $parts = []; /** @var array<string, string> */
/** @var Url */ public array $parts = [];
public $parent; public ?Url $parent;
function __construct() { function setParent($parent): void {
}
function setParent($parent) {
$this->parent = $parent; $this->parent = $parent;
} }
function setQuery($parts) { function setQuery($parts): void {
$this->parts = $parts; $this->parts = $parts;
} }
function addQueryParam($key, $value) { function addQueryParam(string $key, string $value): void {
$this->parts[$key] = $value; $this->parts[$key] = $value;
} }
function toString() { function toString(): string {
return '?' . http_build_query(array_merge($this->parts, $this->parent ? $this->parent->parts : [])); return '?' . http_build_query(array_merge($this->parts, $this->parent ? $this->parent->parts : []));
} }
} }

View file

@ -5,43 +5,43 @@ use ctiso\Collection;
abstract class AbstractRule abstract class AbstractRule
{ {
public $field; public string $field;
protected $errorMsg; protected $errorMsg;
protected $ctx; protected $ctx;
public function __construct($field, $errorMsg = null) public function __construct(string $field, $errorMsg = null)
{ {
$this->field = $field; $this->field = $field;
$this->errorMsg = $errorMsg; $this->errorMsg = $errorMsg;
} }
public function setName($field) public function setName(string $field): self
{ {
$this->field = $field; $this->field = $field;
return $this; return $this;
} }
public function setErrorMsg($errorMsg) public function setErrorMsg($errorMsg): self
{ {
$this->errorMsg = $errorMsg; $this->errorMsg = $errorMsg;
return $this; return $this;
} }
public function getErrorMsg() public function getErrorMsg(): string
{ {
return $this->errorMsg; return $this->errorMsg;
} }
public function isValid(Collection $container, $status = null) public function isValid(Collection $container, $status = null): bool
{ {
return true; return true;
} }
function skipEmpty() { function skipEmpty(): bool {
return true; return true;
} }
public function setContext($ctx) public function setContext($ctx): void
{ {
$this->ctx = $ctx; $this->ctx = $ctx;
} }

View file

@ -9,12 +9,12 @@ use ctiso\Validator\Rule\AbstractRule,
class Alpha extends AbstractRule class Alpha extends AbstractRule
{ {
public function getErrorMsg() public function getErrorMsg(): string
{ {
return "Поле должно содержать только буквы"; return "Поле должно содержать только буквы";
} }
public function isValid(Collection $container, $status = null) public function isValid(Collection $container, $status = null): bool
{ {
return ctype_alpha($container->get($this->field)); return ctype_alpha($container->get($this->field));
} }

View file

@ -13,7 +13,7 @@ class Code extends AbstractRule
return "Неправильно указан персональный код"; return "Неправильно указан персональный код";
} }
function checkCode($code): bool { function checkCode(array $code): bool {
foreach($code as $c) { foreach($code as $c) {
if (empty($c)) { if (empty($c)) {
return false; return false;

View file

@ -12,22 +12,22 @@ class Count extends AbstractRule
public $size = 1; public $size = 1;
public $max = null; public $max = null;
public function getErrorMsg() public function getErrorMsg(): string
{ {
return "Количество записей должно быть не менне {$this->size} и не более {$this->max}"; return "Количество записей должно быть не менне {$this->size} и не более {$this->max}";
} }
function not_empty($s) { function not_empty($s) {
return $s != ""; return $s != "";
} }
public function isValid(Collection $container, $status = null) public function isValid(Collection $container, $status = null): bool
{ {
if (!$this->max) { if (!$this->max) {
$this->max = $this->size; $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'])); explode(";", $container->get($this->field))), [$this, 'not_empty']));
return $count >= $this->size && $count <= ((int)$this->max); return $count >= $this->size && $count <= ((int)$this->max);

View file

@ -9,16 +9,16 @@ use ctiso\Validator\Rule\AbstractRule,
class Date extends AbstractRule class Date extends AbstractRule
{ {
public function getErrorMsg() public function getErrorMsg(): string
{ {
return "Неверный формат даты"; 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})$/"; $pattern = "/^([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})$/";
$matches = []; $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])); && checkdate((int)$matches[2], (int)$matches[1], (int)$matches[3]));
} }
} }

View file

@ -9,12 +9,12 @@ use ctiso\Validator\Rule\AbstractRule,
class Email extends AbstractRule class Email extends AbstractRule
{ {
public function getErrorMsg() public function getErrorMsg(): string
{ {
return "Неверный формат электронной почты"; return "Неверный формат электронной почты";
} }
public function isValid(Collection $container, $status = null) public function isValid(Collection $container, $status = null): bool
{ {
$emails = explode(",", $container->get($this->field)); $emails = explode(",", $container->get($this->field));
foreach ($emails as $email) { foreach ($emails as $email) {

View file

@ -9,20 +9,14 @@ use ctiso\Validator\Rule\AbstractRule,
class EmailList extends AbstractRule class EmailList extends AbstractRule
{ {
public function getErrorMsg() public function getErrorMsg(): string
{ {
return "Неверный формат электронной почты"; return "Неверный формат электронной почты";
} }
public function isValid(Collection $container, $status = null) { public function isValid(Collection $container, $status = null): bool {
$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 = $container->get($this->field); $emails = $container->get($this->field);
foreach ($emails as $email) { foreach ($emails as $email) {
// if (! preg_match("/^$user@($doIsValid|(\[($ipv4|$ipv6)\]))$/", $email)) return false;
if (! filter_var($email, FILTER_VALIDATE_EMAIL)) return false; if (! filter_var($email, FILTER_VALIDATE_EMAIL)) return false;
} }
return true; return true;

View file

@ -7,12 +7,12 @@ use ctiso\Validator\Rule\AbstractRule,
class FileName extends AbstractRule { class FileName extends AbstractRule {
public function getErrorMsg() public function getErrorMsg(): string
{ {
return 'Название файла может содержать только символы латиницы в нижнем регистре и цифры'; return 'Название файла может содержать только символы латиницы в нижнем регистре и цифры';
} }
public function isValid(Collection $container, $status = null) public function isValid(Collection $container, $status = null): bool
{ {
return Path::isName($container->get($this->field)); return Path::isName($container->get($this->field));
} }

View file

@ -9,42 +9,42 @@ use ctiso\Validator\Rule\AbstractRule,
class IsFile extends AbstractRule class IsFile extends AbstractRule
{ {
private $type = array(); private array $type = [];
private $maxsize = 1024; private int $maxsize = 1024;
function skipEmpty() { function skipEmpty(): bool {
return false; return false;
} }
function setSize($size) { function setSize(int $size): void {
$this->maxsize = $size; $this->maxsize = $size;
} }
function setType(array $type) { function setType(array $type): void {
$this->type = $type; $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) { if (!isset($_FILES[$this->field]) || $_FILES[$this->field]['error'] == UPLOAD_ERR_NO_FILE) {
$this->setErrorMsg('Файл не загружен'); $this->setErrorMsg('Файл не загружен');
return false; return false;
} }
if ($_FILES[$this->field]['error'] == UPLOAD_ERR_INI_SIZE) { if ($_FILES[$this->field]['error'] == UPLOAD_ERR_INI_SIZE) {
$this->setErrorMsg('Превышен размер файла'); $this->setErrorMsg('Превышен размер файла');
return false; return false;
} }
$tmp = $_FILES[$this->field]; $tmp = $_FILES[$this->field];
if (!in_array($tmp['type'], $this->type)) { if (!in_array($tmp['type'], $this->type)) {
$this->setErrorMsg('Неверный формат файла'); $this->setErrorMsg('Неверный формат файла');
return false; return false;
} }
if (((int)$tmp['size']) > $this->maxsize*1024) { if (((int)$tmp['size']) > $this->maxsize*1024) {
$this->setErrorMsg('Неверный размер файла'); $this->setErrorMsg('Неверный размер файла');
return false; return false;
} }
return true; return true;

View file

@ -11,12 +11,13 @@ class MatchRule extends AbstractRule
{ {
public $same; public $same;
public function getErrorMsg() public function getErrorMsg(): string
{ {
return "Поля не совпадают"; 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); return (strcmp($container->get($this->field), $container->get($this->same)) == 0);
} }
} }

View file

@ -6,16 +6,16 @@ use ctiso\Validator\Rule\AbstractRule,
class Notnull extends AbstractRule class Notnull extends AbstractRule
{ {
function skipEmpty() { function skipEmpty(): bool {
return false; return false;
} }
public function getErrorMsg() public function getErrorMsg(): string
{ {
return "Поле не должно быть пустым"; return "Поле не должно быть пустым";
} }
public function isValid(Collection $container, $status = null) public function isValid(Collection $container, $status = null): bool
{ {
$data = $container->get($this->field); $data = $container->get($this->field);
if (is_array($data)) { if (is_array($data)) {

View file

@ -9,12 +9,12 @@ use ctiso\Validator\Rule\AbstractRule,
class Numeric extends AbstractRule class Numeric extends AbstractRule
{ {
public function getErrorMsg() public function getErrorMsg(): string
{ {
return "Значение поля должно быть числом"; return "Значение поля должно быть числом";
} }
public function isValid(Collection $container, $status = null) public function isValid(Collection $container, $status = null): bool
{ {
return (is_numeric($container->get($this->field))); return (is_numeric($container->get($this->field)));
} }

View file

@ -1,21 +1,20 @@
<?php <?php
/**
*/
namespace ctiso\Validator\Rule; namespace ctiso\Validator\Rule;
use ctiso\Validator\Rule\AbstractRule, use ctiso\Validator\Rule\AbstractRule,
ctiso\Collection; ctiso\Collection;
class PregMatch extends AbstractRule class PregMatch extends AbstractRule
{ {
public $pattern; public string $pattern;
public function getErrorMsg() public function getErrorMsg(): string
{ {
return "Поле в неправильном формате"; return "Поле в неправильном формате";
} }
public function isValid(Collection $container, $status = null) 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));
} }
} }

View file

@ -11,19 +11,20 @@ class Time extends AbstractRule
{ {
private $split = ":"; private $split = ":";
public function getErrorMsg() public function getErrorMsg(): string
{ {
return "Неверный формат времени"; return "Неверный формат времени";
} }
static function checktime($hour, $minute) static function checktime(int $hour, int $minute): bool
{ {
if ($hour > -1 && $hour < 24 && $minute > -1 && $minute < 60) { if ($hour > -1 && $hour < 24 && $minute > -1 && $minute < 60) {
return true; return true;
} }
return false;
} }
public function isValid(Collection $container, $status = null) public function isValid(Collection $container, $status = null): bool
{ {
/** @var list<string> */ /** @var list<string> */
$tmp = explode($this->split, $container->get($this->field), 2); $tmp = explode($this->split, $container->get($this->field), 2);

View file

@ -8,12 +8,12 @@ use ctiso\Validator\Rule\AbstractRule,
class Unique extends AbstractRule class Unique extends AbstractRule
{ {
public function getErrorMsg() public function getErrorMsg(): string
{ {
return $this->ctx->getMessage(); 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); return $this->ctx->isUnique($container->get($this->field), $status, $container);
} }

View file

@ -1,7 +1,5 @@
<?php <?php
///<reference path="Rule/Notnull.php"/>
/** /**
* Проверка коллекции * Проверка коллекции
*/ */
@ -12,8 +10,10 @@ use Exception,
class Validator class Validator
{ {
protected $chain = []; // Массив правил /** @var AbstractRule[] */
protected $errorMsg = []; // Массив ошибок protected array $chain = []; // Массив правил
/** @var array<string, string> */
protected array $errorMsg = []; // Массив ошибок
/** /**
* Поля по умолчанию * Поля по умолчанию
@ -40,7 +40,12 @@ class Validator
$this->addRuleList($rules); $this->addRuleList($rules);
} }
function addRuleType($name, $className) { /**
* Добавление правила в список
* @param string $name
* @param class-string<Rule\AbstractRule> $className
*/
function addRuleType(string $name, string $className) {
$this->type[$name] = $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)) { if (is_array($rule)) {
$this->chain = array_merge($this->chain, $rule); $this->chain = array_merge($this->chain, $rule);
} else { } else {
@ -93,9 +98,8 @@ class Validator
/** /**
* @param AbstractRule $rule * @param AbstractRule $rule
* @param Collection $container
*/ */
public function skip($rule, $container) // -> Rule_Abstract public function skip($rule, Collection $container) // -> Rule_Abstract
{ {
if ($rule->skipEmpty()) { if ($rule->skipEmpty()) {
$data = $container->get($rule->field); $data = $container->get($rule->field);
@ -111,7 +115,7 @@ class Validator
$this->errorMsg = []; $this->errorMsg = [];
} }
public function validate(Collection $container, $rule = null, $status = null) public function validate(Collection $container, $rule = null, $status = null): bool
{ {
$fields = []; $fields = [];
if ($rule) { if ($rule) {

View file

@ -3,7 +3,7 @@
namespace ctiso\View; namespace ctiso\View;
use ctiso\View\View, use ctiso\View\View,
PHPTAL; PHPTAL;
class Composite extends View class Composite extends View
{ {
private $tal; private $tal;
@ -15,14 +15,14 @@ class Composite extends View
$this->tal = new PHPTAL($file); $this->tal = new PHPTAL($file);
$this->tal->setPhpCodeDestination(PHPTAL_PHP_CODE_DESTINATION); $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->setTemplateRepository(PHPTAL_TEMPLATE_REPOSITORY);
$this->tal->setOutputMode(PHPTAL::HTML5); $this->tal->setOutputMode(PHPTAL::HTML5);
$this->tal->stripComments(true); $this->tal->stripComments(true);
// $this->tal->addPreFilter(new PHPTAL_PreFilter_Normalize()); // $this->tal->addPreFilter(new PHPTAL_PreFilter_Normalize());
} }
function set($key, $val) { function set(string $key, mixed $val) {
if ($key == 'title') { if ($key == 'title') {
$this->setTitle($val); $this->setTitle($val);
} }

View file

@ -8,7 +8,7 @@ namespace ctiso\View;
class Plain extends \stdClass class Plain extends \stdClass
{ {
protected $document; protected $document;
protected $values = array(); protected $values = [];
public function __construct ($document) public function __construct ($document)
{ {
@ -36,10 +36,10 @@ class Plain extends \stdClass
return self::getTemplateContent ($this->document, $result); return self::getTemplateContent ($this->document, $result);
} }
static function getTemplateContent($document, $result) static function getTemplateContent(string $document, $result): string
{ {
ob_start (); ob_start ();
include ($document); include ($document);
$content = ob_get_contents (); $content = ob_get_contents ();
ob_clean (); ob_clean ();
return $content; return $content;

View file

@ -5,23 +5,23 @@ use Exception;
class View extends \stdClass class View extends \stdClass
{ {
protected $_section = array(); // Вложенные шаблоны protected array $_section = []; // Вложенные шаблоны
// Блоки // Блоки
protected $_stylesheet = array(); // Массив стилей текущего шаблона protected array $_stylesheet = []; // Массив стилей текущего шаблона
protected $_script = array(); // Массив скриптов текущего шаблона protected array $_script = []; // Массив скриптов текущего шаблона
public $_scriptstring = array(); public array $_scriptstring = [];
protected $_startup = array(); protected array $_startup = [];
protected $_values = array(); protected array $_values = [];
protected $_title = null; // Заголовок текущего шаблона protected ?string $_title = null; // Заголовок текущего шаблона
public $active_module; public string $active_module;
public $module_action; public string $module_action;
public $prefix; public array $prefix;
public $suggestions; //подсказки public array $suggestions; //подсказки
public $alias = []; public array $alias = [];
public $codeGenerator = null; public $codeGenerator = null;
public $parent_view = null; public $parent_view = null;
@ -53,7 +53,7 @@ class View extends \stdClass
* *
* @param string $name путь к скрипту * @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)); $output = $this->resolveName($this->alias, $name . '?' . http_build_query($this->prefix));
$this->_script [] = $output; $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) { if ($startup) {
$this->_startup [] = $name; $this->_startup [] = $code;
} else { } else {
$this->_scriptstring [] = $name; $this->_scriptstring [] = $code;
} }
} }
public function setPrefix($name, $val) { public function setPrefix(string $name, string $val): void {
$this->prefix[$name] = $val; $this->prefix[$name] = $val;
} }
@ -82,7 +82,7 @@ class View extends \stdClass
* *
* @param string $name путь к стилю * @param string $name путь к стилю
*/ */
public function addStyleSheet($name) public function addStyleSheet(string $name): void
{ {
$output = $this->resolveName($this->alias, $name . '?' . http_build_query($this->prefix)); $output = $this->resolveName($this->alias, $name . '?' . http_build_query($this->prefix));
$this->_stylesheet [] = $output; $this->_stylesheet [] = $output;
@ -92,9 +92,9 @@ class View extends \stdClass
* Рекурсивно извлекает из значение свойства обьекта * Рекурсивно извлекает из значение свойства обьекта
* *
* @param string $list Имя свойства * @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]; $result = ($flatten == true) ? $this->$list : [$this->$list];
foreach ($this->_section as $value) { foreach ($this->_section as $value) {
@ -109,7 +109,7 @@ class View extends \stdClass
return $result; 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; $this->_title = $title;
} }
@ -143,13 +141,16 @@ class View extends \stdClass
$this->alias = $alias; $this->alias = $alias;
} }
function addAlias($name, $path): void function addAlias(string $name, string $path): void
{ {
$this->alias[$name] = $path; $this->alias[$name] = $path;
$this->set($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) { foreach($pathlist as $key => $www) {
if (file_exists($key . '/' . $file)) { if (file_exists($key . '/' . $file)) {
@ -160,7 +161,7 @@ class View extends \stdClass
} }
// FIXME: Префикс, конфликтует с протоколом // FIXME: Префикс, конфликтует с протоколом
function resolveName($alias, $file): string { function resolveName($alias, string $file): string {
list($type, $filename) = explode(":", $file, 2); list($type, $filename) = explode(":", $file, 2);
// Сделать поиск а не просто замену папки при совпадении имени // Сделать поиск а не просто замену папки при совпадении имени
@ -175,7 +176,7 @@ class View extends \stdClass
return $file; return $file;
} }
public function resolveAllNames($alias, $list) { public function resolveAllNames($alias, array $list): array {
$result = []; $result = [];
foreach($list as $item) { foreach($list as $item) {
$result [] = $this->resolveName($alias, $item); $result [] = $this->resolveName($alias, $item);