fix: Определения типов

This commit is contained in:
origami11@yandex.ru 2025-10-01 12:37:39 +03:00
parent 9f6fd74b17
commit dd74a97894
28 changed files with 334 additions and 249 deletions

View file

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

View file

@ -35,6 +35,7 @@ class Action
public Database $db; public Database $db;
// Фильтры // Фильтры
/** @var ?ActionAccess */
public $access = null; // Обьект хранит параметры доступа public $access = null; // Обьект хранит параметры доступа
public $logger = null; // Обьект для ведения лога public $logger = null; // Обьект для ведения лога
@ -42,8 +43,10 @@ class Action
private $helpers = array(); // Помошники для действий private $helpers = array(); // Помошники для действий
public $part = null; // Параметры для ссылки public $part = null; // Параметры для ссылки
public $config/*: Registry*/; // Ссылка на настройки /** @var \ctiso\Registry */
public $user/*: User*/; // Обьект пользователя public $config; // Ссылка на настройки
/** @var \ctiso\Role\User */
public $user; // Обьект пользователя
// Для Widgets // Для Widgets
public $view = null; public $view = null;
@ -214,7 +217,7 @@ class Action
*/ */
public function nUrl($actionName, array $param = []) public function nUrl($actionName, array $param = [])
{ {
$access/*: ActionAccess*/ = $this->access; $access = $this->access;
$url = new Url(); $url = new Url();
//print_r([$name, $param]); //print_r([$name, $param]);
@ -337,7 +340,8 @@ class Action
if ($view instanceof View) { if ($view instanceof View) {
$this->view->assignValues($this->ctrlValues); $this->view->assignValues($this->ctrlValues);
$node/*: Composite*/ = null; /** @var ?Composite $node */
$node = null;
foreach ($this->childNodes as $name => $node) { foreach ($this->childNodes as $name => $node) {
$node->make($this); $node->make($this);
$this->view->setView($name, $node->view); $this->view->setView($name, $node->view);
@ -376,7 +380,7 @@ class Action
$this->_getActionPath()->getPath($this, ($action) ? $action : $request->getAction()); $this->_getActionPath()->getPath($this, ($action) ? $action : $request->getAction());
} }
function redirect($action/*: string*/) { function redirect(string $action) {
header('location: ' . $action); header('location: ' . $action);
exit(); exit();
} }

View file

@ -7,7 +7,10 @@ class Request {
public $r; public $r;
public $id; public $id;
function __construct($request/*: HttpRequest*/, $id) { /**
* @param HttpRequest $request
*/
function __construct($request, $id) {
$this->r = $request; $this->r = $request;
$this->id = $id; $this->id = $id;
} }

View file

@ -14,11 +14,12 @@ class Service
{ {
public $viewPath = []; public $viewPath = [];
public $webPath = []; public $webPath = [];
public $config/*: Registry*/; /** @var Registry */
public $config;
public $template; public $template;
public $templatePath; public $templatePath;
public $COMPONENTS_WEB; public $COMPONENTS_WEB;
public $db; public $db;
public function getTemplatePath($name) public function getTemplatePath($name)
@ -53,7 +54,12 @@ class Service
return $model; 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 = []; $result = [];
while($res->next()) { while($res->next()) {
$result[] = ['value' => $res->getInt($key), 'name' => $res->getString($val)]; $result[] = ['value' => $res->getInt($key), 'name' => $res->getString($val)];
@ -68,7 +74,7 @@ class Service
} }
return $result; return $result;
} }
function getInfo() { function getInfo() {
$filename = Path::join($this->viewPath[0], 'install.json'); $filename = Path::join($this->viewPath[0], 'install.json');
if (file_exists($filename)) { if (file_exists($filename)) {

View file

@ -31,7 +31,8 @@ namespace ctiso {
function prepare(string $sql, array $options = []): PDOStatement|false function prepare(string $sql, array $options = []): PDOStatement|false
{ {
$result/*: PDOStatement*/ = parent::prepare($sql, $options); /** @var PDOStatement $result */
$result = parent::prepare($sql, $options);
return $result; return $result;
} }
@ -49,10 +50,11 @@ namespace ctiso {
static function getConnection(array $dsn) static function getConnection(array $dsn)
{ {
/** @var ?Database */
$connection = null; $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 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') { if ($dsn['phptype'] == 'pgsql') {
$connection->query('SET client_encoding="UTF-8"'); $connection->query('SET client_encoding="UTF-8"');
} }
@ -64,9 +66,9 @@ namespace ctiso {
$connection = new self("{$dsn['phptype']}:"); $connection = new self("{$dsn['phptype']}:");
$connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1); $connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1);
} elseif ($dsn['phptype'] == 'sqlite') { } 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); $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->query("PRAGMA journal_mode=$mode");
$connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1); $connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1);
} }

View file

@ -42,8 +42,8 @@ class JsonInstall {
return $missingTables; return $missingTables;
} }
//Создать таблицы // Создать таблицы
function initDataBase($initActions/*: array*/, $dbinit_path) { function initDataBase(array $initActions, $dbinit_path) {
$pg = $this->db_manager->db->isPostgres(); $pg = $this->db_manager->db->isPostgres();
if (!$pg) { if (!$pg) {
$refs = []; $refs = [];

View file

@ -9,14 +9,15 @@ use Exception;
class Manager class Manager
{ {
public $db/*: Database*/; /** @var Database */
public $db;
public function __construct(Database $db) public function __construct(Database $db)
{ {
$this->db = $db; $this->db = $db;
} }
public function executeAction($action/*: array*/, $db_file = "") public function executeAction(array $action, $db_file = "")
{ {
switch($action["type"]) { switch($action["type"]) {
case "dropTable": case "dropTable":
@ -117,7 +118,7 @@ class Manager
return; return;
} }
$data/*: array*/ = $this->dumpTable($table); $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]; $table_info[$new_name] = $table_info[$old_name];
@ -169,7 +170,7 @@ class Manager
$this->db->query($q); $this->db->query($q);
} }
public function getConstraintDef($c/*: array*/) public function getConstraintDef(array $c)
{ {
if ($c['type'] == 'unique') { if ($c['type'] == 'unique') {
return "UNIQUE(" . implode(", ", $c['fields']) . ")"; return "UNIQUE(" . implode(", ", $c['fields']) . ")";
@ -209,7 +210,7 @@ class Manager
foreach ($table_fields as $name => $value) { foreach ($table_fields as $name => $value) {
$type = strtolower($value['type']); $type = strtolower($value['type']);
if ($type == "boolean") { if ($type == "boolean") {
foreach ($data as &$row) { foreach ($data as &$row) {
if (isset($row[$name])) { if (isset($row[$name])) {
$row[$name] = boolval($row[$name]); $row[$name] = boolval($row[$name]);
} }

View file

@ -16,7 +16,11 @@ class Statement
protected $conn; protected $conn;
protected $query; protected $query;
function __construct($query, $conn/*: Database*/) { /**
* @param string $query
* @param Database $conn
*/
function __construct($query, $conn) {
$this->query = $query; $this->query = $query;
$this->conn = $conn; $this->conn = $conn;
} }
@ -45,7 +49,7 @@ class Statement
if ($this->limit) { if ($this->limit) {
$this->query .= " LIMIT {$this->limit} OFFSET {$this->offset}"; $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) { foreach ($this->binds as $bind) {
list($n, $value, $type) = $bind; list($n, $value, $type) = $bind;
$stmt->bindValue($n, $value, (int) $type); $stmt->bindValue($n, $value, (int) $type);

View file

@ -10,7 +10,10 @@ class StatementIterator implements \Iterator
private $pos = 0; private $pos = 0;
private $row_count; private $row_count;
public function __construct($rs/*: PDOStatement*/) { /**
* @param PDOStatement $rs
*/
public function __construct($rs) {
$this->result = $rs; $this->result = $rs;
$this->row_count = $rs->getRecordCount(); $this->row_count = $rs->getRecordCount();
} }

View file

@ -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($x > 0);
assert(is_numeric($y) && $y > 0); assert($y > 0);
if(! isset($this->rows[$x])) { if(! isset($this->rows[$x])) {
$this->rows[$x] = new TableRow(); $this->rows[$x] = new TableRow();
} }
$row/*: TableRow*/ = $this->rows[$x]; /** @var TableRow $row */
$row = $this->rows[$x];
$row->setCell($y, $value); $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($index > 0);
assert(is_numeric($row) && $row > 0); assert($row > 0);
reset($data); reset($data);
for ($i = $index; $i < $index + count($data); $i++) { for ($i = $index; $i < $index + count($data); $i++) {
@ -90,20 +91,20 @@ class Table
/** /**
* Устанавливает высоту ряда * Устанавливает высоту ряда
* @param $row integer Номер ряда * @param int $row Номер ряда
* @parma $value real Высота ряда * @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; $this->rows[$row]->height = $value;
} }
/** /**
* Устанавливает стиль ряда * Устанавливает стиль ряда
* @param $row integer Номер ряда * @param int $row Номер ряда
* @parma $name string Имя стиля * @param string $name Имя стиля
*/ */
function setRowStyle ($row, $name) function setRowStyle ($row, $name)
{ {
@ -118,12 +119,13 @@ class Table
* @param $cell Номер столбца * @param $cell Номер столбца
* @param $merge Количество клеток для обьединения * @param $merge Количество клеток для обьединения
*/ */
function setCellMerge($x, $cell, $merge) function setCellMerge(int $x, int $cell, $merge)
{ {
assert(is_numeric($x) && $x > 0); assert($x > 0);
assert(is_numeric($cell) && $cell > 0); assert($cell > 0);
$row/*: TableRow*/ = $this->rows[$x]; /** @var TableRow $row */
$row = $this->rows[$x];
$row->cells[$cell]->merge = $merge; $row->cells[$cell]->merge = $merge;
} }
@ -135,14 +137,15 @@ class Table
*/ */
function setCellStyle ($row, $y, $name) function setCellStyle ($row, $y, $name)
{ {
if (isset($this->rows[$row])) if (isset($this->rows[$row])) {
$this->rows[$row]->setCellStyle($y, $name); $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); assert(is_numeric($index) && $index > 0);
$offset = $this->getRows() + 1; $offset = $this->getRows() + 1;
@ -158,7 +161,7 @@ class Table
*/ */
function getRows() function getRows()
{ {
$keys/*: array*/ = array_keys($this->rows); $keys = array_keys($this->rows);
return max($keys); return max($keys);
} }
@ -169,7 +172,7 @@ class Table
*/ */
function getRowCells(TableRow $row) function getRowCells(TableRow $row)
{ {
$keys/*: array*/ = array_keys($row->cells); $keys = array_keys($row->cells);
return max($keys); 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"); $doc->startElement("Cell");
if ($ncell->style) { if ($ncell->style) {
@ -266,8 +269,8 @@ class Table
if ($this->rows[$i]->height) { if ($this->rows[$i]->height) {
$doc->writeAttribute('ss:Height', $this->rows[$i]->height); $doc->writeAttribute('ss:Height', $this->rows[$i]->height);
} }
/** @var TableRow $nrow */
$nrow/*: TableRow*/ = $this->rows[$i]; $nrow = $this->rows[$i];
// Флаг индикатор подстановки номера столбца // Флаг индикатор подстановки номера столбца
$setIndex = false; $setIndex = false;
for ($j = 1; $j <= $columns; $j++) { for ($j = 1; $j <= $columns; $j++) {

View file

@ -1,7 +1,7 @@
<?php <?php
/** /**
* Фильтр действий * Фильтр действий
*/ */
namespace ctiso\Filter; namespace ctiso\Filter;
use ctiso\Filter\UserAccess, use ctiso\Filter\UserAccess,
@ -12,9 +12,13 @@ class ActionAccess
{ {
public $access = array(); public $access = array();
public $processor; public $processor;
public $user/*: User*/; /** @var User */
public $user;
function __construct($processor/*: Filter*/, $user) { /**
* @param Filter $processor
*/
function __construct($processor, $user) {
$this->processor = $processor; $this->processor = $processor;
$this->user = $user; $this->user = $user;
} }

View file

@ -6,14 +6,19 @@ use ctiso\Role\UserInterface,
/* Переделать формат Логов на список json */ /* Переделать формат Логов на список json */
class ActionLogger class ActionLogger
{ {
public $before = array(); public $before = array();
public $file; public $file;
public $user; public $user;
public $action; public $action;
public $processor; 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->processor = $processor;
$this->user = $user; $this->user = $user;

View file

@ -10,12 +10,17 @@ use ctiso\Controller\Action,
class Filter class Filter
{ {
/** @var Action */
public $processor; public $processor;
public function __construct($processor/*: Action*/)
/**
* @param Action $processor
*/
public function __construct($processor)
{ {
$this->processor = $processor; $this->processor = $processor;
} }
public function execute(HttpRequest $request) public function execute(HttpRequest $request)
{ {
return $this->processor->execute($request); return $this->processor->execute($request);

View file

@ -11,9 +11,9 @@ class Field
public $label; // Метка поля public $label; // Метка поля
public $value; // Значение поля public $value; // Значение поля
public $type = ""; // Каждому типу элемента соответствует макрос TAL public $type = ""; // Каждому типу элемента соответствует макрос TAL
public $error_msg = null; public $error_msg = null;
public $default = null; public $default = null;
public $error = false; public $error = false;
public $require = false; public $require = false;
public $hint = null; public $hint = null;
public $maxlength = null; public $maxlength = null;
@ -22,10 +22,10 @@ class Field
public $_title = array(); public $_title = array();
public $description = ""; public $description = "";
public $alias = array(); public $alias = array();
/** @phpstan-ignore-next-line */ /** @phpstan-ignore-next-line */
public function __construct ($input = [], $factory = null) public function __construct ($input = [], $factory = null)
{ {
$this->default = null; $this->default = null;
if (isset($input['validate'])) { if (isset($input['validate'])) {
$this->require = strpos($input['validate'], 'require') !== false; $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; $this->value = $value;
} }

View file

@ -11,25 +11,25 @@
namespace ctiso; namespace ctiso;
class right { class right {
protected $params; protected $params;
protected $fn; protected $fn;
public function __construct($params) { public function __construct($params) {
$this->fn = array_shift($params); $this->fn = array_shift($params);
$this->params = $params; $this->params = $params;
} }
function apply() { function apply() {
$params = func_get_args(); $params = func_get_args();
array_splice($params, count($params), 0, $this->params); array_splice($params, count($params), 0, $this->params);
return call_user_func_array($this->fn, $params); return call_user_func_array($this->fn, $params);
} }
} }
class left { class left {
protected $params; protected $params;
protected $fn; protected $fn;
public function __construct($params) { public function __construct($params) {
$this->fn = array_shift($params); $this->fn = array_shift($params);
$this->params = $params; $this->params = $params;
@ -44,9 +44,9 @@ class left {
define('__', '_ARGUMENT_PLACE_'); define('__', '_ARGUMENT_PLACE_');
class partial { class partial {
protected $params; protected $params;
protected $fn; protected $fn;
public function __construct($params) { public function __construct($params) {
$this->fn = array_shift($params); $this->fn = array_shift($params);
$this->params = $params; $this->params = $params;
@ -66,7 +66,7 @@ class partial {
} }
return call_user_func_array ($this->fn, $result); return call_user_func_array ($this->fn, $result);
} }
} }
/** /**
* Композиция функций * Композиция функций
@ -99,7 +99,7 @@ class Functions {
/** /**
* Композиция функций * Композиция функций
* @param array $_rest * @param array $_rest
* @return mixed * @return mixed
*/ */
static function compose($_rest) { static function compose($_rest) {
$closure = new compose(func_get_args()); $closure = new compose(func_get_args());
@ -109,7 +109,7 @@ class Functions {
/** /**
* Карирование справа * Карирование справа
* *
* @return mixed * @return mixed
*/ */
static function rcurry($_rest) { static function rcurry($_rest) {
$closure = new right(func_get_args ()); $closure = new right(func_get_args ());
@ -119,7 +119,7 @@ class Functions {
/** /**
* Карирование слева * Карирование слева
* *
* @return mixed * @return mixed
*/ */
static function lcurry($_rest) { static function lcurry($_rest) {
$closure = new left(func_get_args ()); $closure = new left(func_get_args ());
@ -129,9 +129,9 @@ class Functions {
/** /**
* Разделение массива на два по условию * Разделение массива на два по условию
* @param mixed $pred Условие по которому разделяется массив * @param mixed $pred Условие по которому разделяется массив
* @param array $lst * @param array $lst
* *
* @return mixed * @return mixed
*/ */
static function partition($pred, $lst) { static function partition($pred, $lst) {
$left = []; $left = [];
@ -148,24 +148,24 @@ class Functions {
/** /**
* @param array $value * @param array $value
* @param string $name * @param string $name
* *
* @return mixed * @return mixed
*/ */
static function __key($value, $name) { static function __key($value, $name) {
return $value[$name]; return $value[$name];
} }
static function identity($value) { static function identity($value) {
return $value; return $value;
} }
/** /**
* @param array $a * @param array $a
* @param array $b * @param array $b
* @param $key * @param $key
* *
* @return int * @return int
*/ */
static function __cmp($a, $b, $key) { static function __cmp($a, $b, $key) {
if ($a[$key] == $b[$key]) { if ($a[$key] == $b[$key]) {
@ -173,75 +173,81 @@ class Functions {
} }
return ($a[$key] > $b[$key]) ? -1 : 1; return ($a[$key] > $b[$key]) ? -1 : 1;
} }
static function __cmp_less($a, $b, $key) { static function __cmp_less($a, $b, $key) {
if ($a[$key] == $b[$key]) { if ($a[$key] == $b[$key]) {
return 0; return 0;
} }
return ($a[$key] < $b[$key]) ? -1 : 1; return ($a[$key] < $b[$key]) ? -1 : 1;
} }
// Сравнение по ключу массиве // Сравнение по ключу массиве
static function __index($n, $key, $row) { static function __index($n, $key, $row) {
return ($row[$key] == $n); return ($row[$key] == $n);
} }
static function __div($x, $y) { static function __div($x, $y) {
return $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]);
} }
static function concat(/* $args ...*/) { static function concat(/* $args ...*/) {
$args = func_get_args(); $args = func_get_args();
return implode("", $args); return implode("", $args);
} }
static function __empty($x) { static function __empty($x) {
return empty($x); return empty($x);
} }
// Отрицание // Отрицание
static function __not($x) { static function __not($x) {
return !$x; return !$x;
} }
// Не равно // Не равно
static function __neq($x, $y) { static function __neq($x, $y) {
return $x != $y; return $x != $y;
} }
// Равно // Равно
static function __eq($x, $y) { static function __eq($x, $y) {
return $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)
* *
* @param string $key
* @param array|ArrayIterator $array
* @return mixed * @return mixed
*/ */
static function key_values($key, $array/*: array|ArrayIterator*/) { static function key_values($key, $array) {
$result = []; $result = [];
foreach($array as $item) { foreach($array as $item) {
$result[] = $item[$key]; $result[] = $item[$key];
} }
return $result; 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 = []; $result = [];
foreach($array as $item) { foreach($array as $item) {
$result[] = $item->{$key}; $result[] = $item->{$key};
} }
return $result; return $result;
} }
static function assoc_key_values($key, $value, $array) { static function assoc_key_values($key, $value, $array) {
$result = []; $result = [];
foreach ($array as $item) { foreach ($array as $item) {
@ -249,7 +255,7 @@ class Functions {
} }
return $result; return $result;
} }
static function assoc_key($key, $array) { static function assoc_key($key, $array) {
$result = []; $result = [];
foreach ($array as $item) { foreach ($array as $item) {
@ -257,22 +263,28 @@ class Functions {
} }
return $result; 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) { foreach ($array as $item) {
if ($item[$key] == $value) return $item; if ($item[$key] == $value) return $item;
} }
return null; return null;
} }
static function _get_key($key, $value, $array) { static function _get_key($key, $value, $array) {
foreach ($array as $name => $item) { foreach ($array as $name => $item) {
if ($item[$key] == $value) return $name; if ($item[$key] == $value) return $name;
} }
return null; return null;
} }
/** /**
* Логическа операция && ко всем элементам массива * Логическа операция && ко всем элементам массива
* @return bool * @return bool
@ -285,17 +297,17 @@ class Functions {
} }
return true; return true;
} }
/** /**
* Логическа операция || ко всем элементам массива * Логическа операция || ко всем элементам массива
* @param array $array * @param array $array
* @param mixed $callback * @param mixed $callback
* *
* @return mixed * @return mixed
*/ */
static function some(array $array, $callback) { static function some(array $array, $callback) {
assert(is_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) {
return $key; return $key;
@ -303,10 +315,10 @@ class Functions {
} }
return false; return false;
} }
static function span($length, array $array) { static function span($length, array $array) {
assert(is_int($length)); assert(is_int($length));
$result = []; $result = [];
$count = count($array); $count = count($array);
for($i = 0; $i < $count; $i += $length) { for($i = 0; $i < $count; $i += $length) {
@ -314,17 +326,17 @@ class Functions {
} }
return $result; return $result;
} }
static function array_ref($data, $n) { static function array_ref($data, $n) {
return $data[$n]; return $data[$n];
} }
static function call() { static function call() {
$args = func_get_args(); $args = func_get_args();
$name = array_shift($args); $name = array_shift($args);
return call_user_func_array($name, $args); return call_user_func_array($name, $args);
} }
/** /**
* Поиск элемента в массиве * Поиск элемента в массиве
* @param mixed $cb сравнение с элементом массива * @param mixed $cb сравнение с элементом массива
@ -337,19 +349,19 @@ class Functions {
if (call_user_func_array($cb, [$value, $key, $strict])) return $key; if (call_user_func_array($cb, [$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)
* @end example * @end example
*/ */
static function key_unique_values ($name, $table) { static function key_unique_values ($name, $table) {
// Ищем уникальные значения для заданного ключа // Ищем уникальные значения для заданного ключа
$keys = []; $keys = [];
foreach ($table as $row) { foreach ($table as $row) {
if (!in_array ($row[$name], $keys)) if (!in_array ($row[$name], $keys))
@ -357,7 +369,7 @@ class Functions {
} }
return $keys; return $keys;
} }
/** /**
* Сортировка двумерного массива по заданному ключу * Сортировка двумерного массива по заданному ключу
* @param array $array Массив * @param array $array Массив
@ -371,16 +383,18 @@ class Functions {
} }
/** /**
* Преобразует ключи элементов для многомерного массива * Преобразует ключи элементов для многомерного массива
* @param string $key_name Имя ключа
* @param array $array Многомерный массив
* @return mixed * @return mixed
*/ */
static function hash_key ($key_name,$array/*: array */) { static function hash_key ($key_name, $array) {
$result = []; $result = [];
foreach($array as $value) { foreach($array as $value) {
$result[$value[$key_name]] = $value; $result[$value[$key_name]] = $value;
} }
return $result; return $result;
} }
} }

View file

@ -55,7 +55,7 @@ class HttpRequest extends Collection
return parent::get('data')->get($key, $default); return parent::get('data')->get($key, $default);
} }
function session(Session $value = null) function session(?Session $value = null)
{ {
if ($value) { if ($value) {
$this->_session = $value; $this->_session = $value;
@ -63,7 +63,7 @@ class HttpRequest extends Collection
return $this->_session; return $this->_session;
} }
function set($key, $value/*: any*/) function set($key, mixed $value)
{ {
parent::get('data')->set($key, $value); parent::get('data')->set($key, $value);
} }

View file

@ -18,7 +18,7 @@ class Manager extends Filter
* Функция которая добавляет условие для проверки параметров $_GET * Функция которая добавляет условие для проверки параметров $_GET
* @param $get array() | true Ассоциативный массив ключей и значений для $_GET * @param $get array() | true Ассоциативный массив ключей и значений для $_GET
* *
* @example * @example
* addConditionGet(array('module' => 'personal'), 'personal') * addConditionGet(array('module' => 'personal'), 'personal')
* addConditionGet(array('module' => 'login'), 'login') * addConditionGet(array('module' => 'login'), 'login')
*/ */
@ -28,14 +28,19 @@ class Manager extends Filter
} }
/** /**
* Условие для аякс запросов. Тоже самое что и addConditionGet но еще проверяется является ли запрос ajax * Условие для аякс запросов. Тоже самое что и addConditionGet но еще проверяется является ли запрос ajax
*/ */
public function addConditionXHR($get, Filter $layout) public function addConditionXHR($get, Filter $layout)
{ {
$this->addCondition(Functions::rcurry([$this, 'checkXHR'], $get), $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)) { if (is_array($get)) {
foreach ($get as $key => $value) { foreach ($get as $key => $value) {
@ -47,18 +52,23 @@ class Manager extends Filter
return true; 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); return $request->isAjax() && $this->checkGet($request, $get);
} }
/** /**
* Добавляет условие в общем виде * Добавляет условие в общем виде
* @parma $get function(HttpRequest) Функция * @parma $get function(HttpRequest) Функция
* @parma $layout Layout Макет * @parma $layout Layout Макет
*/ */
public function addCondition($get, Filter $layout) public function addCondition($get, Filter $layout)
{ {
$this->condition [] = [$get, $layout]; $this->condition [] = [$get, $layout];
} }

View file

@ -20,7 +20,7 @@ class MailAlt
function from($name) function from($name)
{ {
$this->mailer->setFrom($name); $this->mailer->setFrom($name);
} }
/** /**
* Установка получателя * Установка получателя
@ -37,12 +37,13 @@ class MailAlt
/** /**
* Установка получателей копии * Установка получателей копии
* @param string $name
*/ */
function copy($name) // recipient cc function copy($name) // recipient cc
{ {
$this->mailer->addCC($name); $this->mailer->addCC($name);
} }
function notify($notify) function notify($notify)
{ {
$this->_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; $this->mailer->Body = $text;
} }
function setType($text) function setType($text)
{ {
$this->mailer->isHTML($text == 'text/html'); $this->mailer->isHTML($text == 'text/html');
} }
/** /**
* Кодировка текста в письме * Кодировка текста в письме
*/ */
function setEncoding($encoding) function setEncoding($encoding)
{ {
$this->encoding = $encoding; $this->encoding = $encoding;
} }
@ -86,7 +89,7 @@ class MailAlt
} }
/** /**
* Отправка почты * Отправка почты
*/ */
function send() function send()
{ {

View file

@ -155,7 +155,10 @@ class Path
} }
// Сравнение двух путей на равентство // Сравнение двух путей на равентство
public function equal($path/*: Path*/) /**
* @param Path $path
*/
public function equal($path)
{ {
$count = count($this->path); $count = count($this->path);
if ($count == count($path->path)) { if ($count == count($path->path)) {
@ -199,11 +202,11 @@ class Path
/** /**
* Проверяет является ли папка родительской для другой папки * Проверяет является ли папка родительской для другой папки
* *
* @parma Path $path * @param Path $path
* *
* @return boolean * @return boolean
*/ */
public function isParent($path/*: Path*/) public function isParent($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; && ($this->url['host'] != $path->url['host'])) return false;

View file

@ -6,7 +6,7 @@
* $setup->set('target', 'dst'); * $setup->set('target', 'dst');
* $setup->executeActions('install'); * $setup->executeActions('install');
* </code> * </code>
*/ */
namespace ctiso; namespace ctiso;
use ctiso\Tools\SQLStatementExtractor; use ctiso\Tools\SQLStatementExtractor;
use ctiso\Path; use ctiso\Path;
@ -22,7 +22,7 @@ class FakeZipArchive {
} }
} }
class Setup class Setup
{ {
protected $actions = array(); protected $actions = array();
public $context = array(); public $context = array();
@ -30,7 +30,7 @@ class Setup
protected $action; protected $action;
protected $node; protected $node;
protected $stack = array(); protected $stack = array();
public $zip; public $zip;
public $target; public $target;
@ -56,7 +56,7 @@ class Setup
} }
/** /**
* Регистрация новых действия для установки * Регистрация новых действия для установки
*/ */
public function registerAction($name, $action) public function registerAction($name, $action)
{ {
@ -71,7 +71,7 @@ class Setup
$this->context[$name] = $value; $this->context[$name] = $value;
} }
function replaceFn($matches) { function replaceFn($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 {
@ -85,7 +85,7 @@ class Setup
} }
public function fileContent($file, array $tpl) public function fileContent($file, array $tpl)
{ {
$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;
@ -113,48 +113,49 @@ class Setup
* Для всех аттрибутов заменяет переменные на их значения * Для всех аттрибутов заменяет переменные на их значения
*/ */
function resolve($attributes) function resolve($attributes)
{ {
$result = []; $result = [];
foreach ($attributes as $key => $value) { 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; return $result;
} }
/** /**
* Выполняет список действий если для действия не указан аттрибут when то оно выполняется всегда * Выполняет список действий если для действия не указан аттрибут when то оно выполняется всегда
* *
* @param string $action специальное действие * @param string $action специальное действие
*/ */
function executeActions($action = "install") function executeActions($action = "install")
{ {
$this->action = $action; $this->action = $action;
if ($this->stack[count($this->stack) - 1] === false) { if ($this->stack[count($this->stack) - 1] === false) {
return; return;
} }
$item/*: \SimpleXMLElement*/ = $this->stack[count($this->stack) - 1]; /** @var \SimpleXMLElement */
$item = $this->stack[count($this->stack) - 1];
$root = $item->children(); $root = $item->children();
foreach ($root as $node) foreach ($root as $node)
{ {
$attributes = $node->attributes(); $attributes = $node->attributes();
array_push($this->stack, $node); array_push($this->stack, $node);
$this->callAction($node->getName(), [$this->resolve($attributes)]); $this->callAction($node->getName(), [$this->resolve($attributes)]);
array_pop($this->stack); array_pop($this->stack);
} }
} }
/** /**
* Копирования файла * Копирования файла
* preserve - Не переписывать файл если он существует * preserve - Не переписывать файл если он существует
* template Файл является шаблоном подставить параметры до копирования * template Файл является шаблоном подставить параметры до копирования
* src Исходный файл * src Исходный файл
* dst Новый файл * 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) public function copyFile(array $attributes)
{ {
$path = $this->targetPath($attributes['dst']); $path = $this->targetPath($attributes['dst']);
if (!(file_exists($path) && isset($attributes['preserve']))) { 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) public function makeLink(array $attributes)
{ {
@ -174,7 +175,7 @@ class Setup
} }
/** /**
* Подключение файла установки * Подключение файла установки
* @param array{file: string} $attributes Имя подключаемого файла * @param array{file: string} $attributes Имя подключаемого файла
*/ */
public function includeFile(array $attributes) public function includeFile(array $attributes)
@ -182,7 +183,7 @@ class Setup
$file = basename($this->file) . "/" . $attributes['file']; $file = basename($this->file) . "/" . $attributes['file'];
$setup = new Setup($file); $setup = new Setup($file);
$setup->context = $this->context; $setup->context = $this->context;
$setup->executeActions(); $setup->executeActions();
} }
@ -192,9 +193,9 @@ class Setup
/** /**
* Создает новую папку * Создает новую папку
* dst Имя папки * dst Имя папки
* *
* @param array{dst:string} $attributes * @param array{dst:string} $attributes
*/ */
public function makeDirectory(array $attributes) public function makeDirectory(array $attributes)
{ {
@ -202,7 +203,7 @@ class Setup
if (!file_exists($path)) { if (!file_exists($path)) {
mkdir($path); mkdir($path);
} }
} }
function testWhen(array $attributes) function testWhen(array $attributes)
{ {
@ -212,9 +213,11 @@ class Setup
} }
/** /**
* Выполнение Списка SQL команд * Выполнение Списка SQL команд из ZIP файла
*/ * @param Database $conn
function batchSQLZip($conn/*: Database*/, $file) * @param string $file
*/
function batchSQLZip($conn, $file)
{ {
$stmtList = SQLStatementExtractor::extract($this->zip->getFromName($file)); $stmtList = SQLStatementExtractor::extract($this->zip->getFromName($file));
foreach ($stmtList as $stmt) { 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); $stmtList = SQLStatementExtractor::extractFile($file);
foreach ($stmtList as $stmt) { foreach ($stmtList as $stmt) {

View file

@ -41,7 +41,8 @@ class Tales_Assets implements PHPTAL_Tales
} }
class Tales { class Tales {
static $site/*: SiteInterface*/; /** @var SiteInterface */
static $site;
static function phptal_date ($e) { static function phptal_date ($e) {
return date("d.m.Y", $e); return date("d.m.Y", $e);
@ -61,12 +62,11 @@ class Tales {
*/ */
static function phptal_component($expression) { static function phptal_component($expression) {
$begin = floatval(microtime(true)); $begin = floatval(microtime(true));
$component/*: Component*/ = null; /** @var Component */
$component = self::$site->loadComponent($expression); $component = self::$site->loadComponent($expression);
$req = new HttpRequest(); $req = new HttpRequest();
$result = $component->execute($req); $result = $component->execute($req);
echo "<!-- ", $expression, ", ", round(floatval(microtime(true)) - $begin, 4), "sec -->"; echo "<!-- ", $expression, ", ", round(floatval(microtime(true)) - $begin, 4), "sec -->";
return $result; return $result;
} }

View file

@ -18,7 +18,7 @@
* and is licensed under the LGPL. For more information please see * and is licensed under the LGPL. For more information please see
* <http://creole.phpdb.org>. * <http://creole.phpdb.org>.
*/ */
/** /**
* Static class for extracting SQL statements from a string or file. * Static class for extracting SQL statements from a string or file.
* *
@ -30,12 +30,12 @@ namespace ctiso\Tools;
use Exception; use Exception;
class SQLStatementExtractor { class SQLStatementExtractor {
protected static $delimiter = ';'; protected static $delimiter = ';';
/** /**
* Get SQL statements from file. * Get SQL statements from file.
* *
* @param string $filename Path to file to read. * @param string $filename Path to file to read.
* @return array SQL statements * @return array SQL statements
*/ */
@ -46,17 +46,17 @@ class SQLStatementExtractor {
} }
throw new Exception("Unable to read file: " . $filename); throw new Exception("Unable to read file: " . $filename);
} }
/** /**
* Extract statements from string. * Extract statements from string.
* *
* @param string $buffer * @param string $buffer
* @return array * @return array
*/ */
public static function extract($buffer) { public static function extract($buffer) {
return self::extractStatements(self::getLines($buffer)); return self::extractStatements(self::getLines($buffer));
} }
/** /**
* Extract SQL statements from array of lines. * Extract SQL statements from array of lines.
* *
@ -64,20 +64,20 @@ class SQLStatementExtractor {
* @return array * @return array
*/ */
protected static function extractStatements($lines) { protected static function extractStatements($lines) {
$statements = []; $statements = [];
$sql = ""; $sql = "";
foreach($lines as $line) { foreach($lines as $line) {
$line = trim($line); $line = trim($line);
if (self::startsWith("//", $line) || if (self::startsWith("//", $line) ||
self::startsWith("--", $line) || self::startsWith("--", $line) ||
self::startsWith("#", $line)) { self::startsWith("#", $line)) {
continue; continue;
} }
if (strlen($line) > 4 && strtoupper(substr($line,0, 4)) == "REM ") { if (strlen($line) > 4 && strtoupper(substr($line,0, 4)) == "REM ") {
continue; continue;
} }
@ -91,19 +91,19 @@ class SQLStatementExtractor {
if (strpos($line, "--") !== false) { if (strpos($line, "--") !== false) {
$sql .= "\n"; $sql .= "\n";
} }
if (self::endsWith(self::$delimiter, $sql)) { if (self::endsWith(self::$delimiter, $sql)) {
$statements[] = self::substring($sql, 0, strlen($sql)-1 - strlen(self::$delimiter)); $statements[] = self::substring($sql, 0, strlen($sql)-1 - strlen(self::$delimiter));
$sql = ""; $sql = "";
} }
} }
return $statements; return $statements;
} }
// //
// Some string helper methods // Some string helper methods
// //
/** /**
* Tests if a string starts with a given string. * Tests if a string starts with a given string.
* @param string $check The substring to check. * @param string $check The substring to check.
@ -117,24 +117,24 @@ class SQLStatementExtractor {
return (strpos($string, $check) === 0); return (strpos($string, $check) === 0);
} }
} }
/** /**
* Tests if a string ends with a given string. * Tests if a string ends with a given string.
* @param string $check The substring to check. * @param string $check The substring to check.
* @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($check/*: string*/, $string) { protected static function endsWith(string $check, $string) {
if ($check === "" || $check === $string) { if ($check === "" || $check === $string) {
return true; return true;
} else { } else {
return (strpos(strrev($string), strrev($check)) === 0); return (strpos(strrev($string), strrev($check)) === 0);
} }
} }
/** /**
* 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, $startpos, $endpos = -1) {
$len = strlen($string); $len = strlen($string);
@ -152,16 +152,16 @@ class SQLStatementExtractor {
} }
return substr($string, $startpos, $len+1); return substr($string, $startpos, $len+1);
} }
/** /**
* 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 array string[] lines of file.
*/ */
protected static function getLines($buffer) { protected static function getLines($buffer) {
$lines = preg_split("/\r?\n|\r/", $buffer); $lines = preg_split("/\r?\n|\r/", $buffer);
return $lines; return $lines;
} }
} }

View file

@ -41,9 +41,8 @@ class TemplateImage
public $resource; public $resource;
public $filename; public $filename;
function __construct ($template = null) function __construct (?string $template = null)
{ {
// assert(is_string($src));
if ($template) { if ($template) {
$this->data = $template; $this->data = $template;
} }
@ -52,27 +51,21 @@ class TemplateImage
/** /**
* Путь к изображению * Путь к изображению
*/ */
function resourcePath($path) function resourcePath(string $path)
{ {
assert(is_string($path));
$this->resource = $path; $this->resource = $path;
} }
/** /**
* Путь у шрифтам * Путь у шрифтам
*/ */
function fontPath($path) function fontPath(string $path)
{ {
assert(is_string($path));
$this->base = $path; $this->base = $path;
} }
function set($name, $value) function set(string $name, $value)
{ {
assert(is_string($name));
$this->context['['.$name.']'] = $this->encode($value); $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); $suffix = pathinfo($file, PATHINFO_EXTENSION);
if (array_key_exists($suffix, self::$listfiles)) { if (array_key_exists($suffix, self::$listfiles)) {
return call_user_func('imagecreatefrom' . self::$listfiles[$suffix], $file); return call_user_func('imagecreatefrom' . self::$listfiles[$suffix], $file);
@ -101,17 +92,15 @@ class TemplateImage
return null; return null;
} }
function getFontFile($name) function getFontFile(string $name)
{ {
assert(is_string($name));
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];
} }
return $this->base . 'arial.ttf'; return $this->base . 'arial.ttf';
} }
function fontSuffix($style) function fontSuffix(array $style)
{ {
if($style[0] && $style[1]) return "z"; if($style[0] && $style[1]) return "z";
@ -121,7 +110,11 @@ class TemplateImage
return ""; return "";
} }
function imageText($text, $value/*: \stdClass*/) /**
* @param string $text
* @param object $value
*/
function imageText($text, $value)
{ {
assert(is_string($text)); assert(is_string($text));
@ -130,29 +123,30 @@ class TemplateImage
$fontfile = $this->getFontFile($value->fontFamily . $this->fontSuffix($value->fontStyle)); $fontfile = $this->getFontFile($value->fontFamily . $this->fontSuffix($value->fontStyle));
$color = intval(substr($value->color, 1), 16); $color = intval(substr($value->color, 1), 16);
if ($value->align[0]) { if ($value->align[0]) {
$align = Drawing::ALIGN_LEFT; $align = Drawing::ALIGN_LEFT;
} elseif ($value->align[2]) { } elseif ($value->align[2]) {
$align = Drawing::ALIGN_RIGHT; $align = Drawing::ALIGN_RIGHT;
} else { } else {
$align = Drawing::ALIGN_CENTER; $align = Drawing::ALIGN_CENTER;
} }
if ($value->valign[0]) { if ($value->valign[0]) {
$valign = Drawing::ALIGN_TOP; $valign = Drawing::ALIGN_TOP;
} elseif ($value->valign[1]) { } elseif ($value->valign[1]) {
$valign = Drawing::ALIGN_CENTER; $valign = Drawing::ALIGN_CENTER;
} else { } else {
$valign = Drawing::ALIGN_BOTTOM; $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, $value->width, $value->height,
$align, $valign); $align, $valign);
} }
/** /**
* Перекодировка текста * Перекодировка текста
* @deprecated
*/ */
function encode($text) function encode($text)
{ {
@ -160,6 +154,10 @@ class TemplateImage
return $text; //iconv("WINDOWS-1251", "UTF-8", $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($new_width, $new_height)
{ {
$width = imagesx($this->image); $width = imagesx($this->image);

View file

@ -4,7 +4,8 @@ namespace ctiso;
class Url { class Url {
public $parts = []; public $parts = [];
public $parent/*: Url*/; /** @var Url */
public $parent;
function __construct() { function __construct() {
} }
@ -23,5 +24,5 @@ class Url {
function toString() { function toString() {
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

@ -83,7 +83,7 @@ class Validator
} }
} }
public function addRule($rule/*:z any*/) { public function addRule($rule) {
if (is_array($rule)) { if (is_array($rule)) {
$this->chain = array_merge($this->chain, $rule); $this->chain = array_merge($this->chain, $rule);
} else { } 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()) { if ($rule->skipEmpty()) {
$data = $container->get($rule->field); $data = $container->get($rule->field);

View file

@ -20,30 +20,30 @@ class Pages
} }
return [ return [
'all' => ($n > 1), 'all' => ($n > 1),
'list' => $result, 'list' => $result,
'first' => self::href($prefix, $url . 1), 'first' => self::href($prefix, $url . 1),
'last' => self::href($prefix, $url . $n), 'last' => self::href($prefix, $url . $n),
'next' => ($page == $n)? false : self::href($prefix, $url . ($page + 1)) , '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))];
} }
/** /**
* @deprecated * @deprecated
* @param $page int номер страницы * @param int $page номер страницы
* @param $onpage int количество элем на странице * @param int $onpage количество элем на странице
* @return string * @return string
*/ */
static function getLimit($page/*: number*/, $onpage/*: number*/) { static function getLimit(int $page, int $onpage) {
if ($page <= 0) { $page = 1; } if ($page <= 0) { $page = 1; }
return "LIMIT $onpage OFFSET " . ($page - 1) * $onpage; return "LIMIT $onpage OFFSET " . ($page - 1) * $onpage;
} }
/** /**
* @param $page int номер страницы * @param int $page номер страницы
* @param $onpage int количество элем на странице * @param int $onpage количество элем на странице
* @return array * @return array
*/ */
static function _getLimit($page, $onpage) { static function _getLimit(int $page, int $onpage) {
if ($page <= 0) { $page = 1; } if ($page <= 0) { $page = 1; }
return [ return [
'count' => $onpage, 'count' => $onpage,
@ -51,8 +51,8 @@ class Pages
]; ];
} }
static function href($prefix, $x) { static function href($prefix, $x) {
return $prefix . $x; return $prefix . $x;
} }
} }

View file

@ -68,11 +68,12 @@ class Top extends Composite
} }
$init = []; $init = [];
/** @var View $item */
foreach ($s->_section as $key => $item) { foreach ($s->_section as $key => $item) {
$ss /*: View*/= $item; if ($item->codeGenerator !== null) {
if ($ss->codeGenerator !== null) {
// функцию которая вычисляет а не результат // функцию которая вычисляет а не результат
$part = call_user_func($ss->codeGenerator, $this, $key, $value); $part = call_user_func($item->codeGenerator, $this, $key, $value);
$init[] = $part; $init[] = $part;
} }
} }
@ -89,14 +90,14 @@ class Top extends Composite
$this->set('title', $this->getTitle()); $this->set('title', $this->getTitle());
$this->set('jspath', $this->config->get('system', 'web')); $this->set('jspath', $this->config->get('system', 'web'));
// //
return $this->execute(); // execute+phptal ?? return $this->execute(); // execute+phptal ??
} }
/** /**
* Массив имен файлов скриптов * Массив имен файлов скриптов
* *
* return array * return array
*/ */
public function getScripts() public function getScripts()
{ {
@ -121,7 +122,7 @@ class Top extends Composite
/** /**
* Массив имен файлов стилей * Массив имен файлов стилей
* *
* return array * return array
*/ */
public function getStyleSheet() public function getStyleSheet()
{ {

View file

@ -160,7 +160,7 @@ class View extends \stdClass
} }
// FIXME: Префикс, конфликтует с протоколом // FIXME: Префикс, конфликтует с протоколом
function resolveName($alias, $file) { function resolveName($alias, $file): string {
list($type, $filename) = explode(":", $file, 2); list($type, $filename) = explode(":", $file, 2);
// Сделать поиск а не просто замену папки при совпадении имени // Сделать поиск а не просто замену папки при совпадении имени