Compare commits

..

No commits in common. "php8" and "master" have entirely different histories.
php8 ... master

120 changed files with 3279 additions and 5379 deletions

View file

@ -8,11 +8,8 @@
} }
], ],
"autoload": { "autoload": {
"psr-4": { "psr-0": {
"ctiso\\": "src/" "": "src/"
} }
},
"require": {
"phpmailer/phpmailer": "^6.8.0"
} }
} }

View file

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

View file

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

View file

@ -1,28 +1,16 @@
<?php <?php
namespace ctiso;
/** /**
* Интерфейс к массиву и обьекту как к коллекции * Интерфейс к массиву и обьекту как к коллекции
*/ */
class Adapter class Adapter
{ {
/** @var array|object */
protected $adaptee; protected $adaptee;
/**
* @param array|object $adaptee
*/
public function __construct ($adaptee) public function __construct ($adaptee)
{ {
$this->adaptee = $adaptee; $this->adaptee = $adaptee;
} }
/**
* @param string $name
* @return mixed
*/
public function get($name) public function get($name)
{ {
if (is_array ($this->adaptee)) { if (is_array ($this->adaptee)) {

View file

@ -1,16 +1,7 @@
<?php <?php
namespace ctiso;
class Arr { class Arr {
/**
* @param array<string|int, mixed> $data
* @param string|int $key
* @param mixed $default
* @return mixed
*/
static function get($data, $key, $default = null) { static function get($data, $key, $default = null) {
return $data[$key] ?? $default; return isset($data[$key]) ? $data[$key] : $default;
} }
} }

View file

@ -1,20 +1,21 @@
<?php <?php
namespace ctiso;
/** /**
* Коллекция * Коллекция
* @implements \ArrayAccess<string,mixed> *
*/ */
class Collection implements \ArrayAccess class Collection implements ArrayAccess
{ {
/** @var array */ /**
protected $data = []; * Holds collective request data
*
* @var array
*/
protected $data = array();
/** /**
* Преобразование массива в коллекцию * Преобразование массива в коллекцию
* *
* @param array $data * @param array $data
* @return bool
*/ */
public function import(array $data) public function import(array $data)
{ {
@ -24,8 +25,6 @@ class Collection implements \ArrayAccess
/** /**
* Преобразование коллекции в массив * Преобразование коллекции в массив
*
* @return array
*/ */
public function export() public function export()
{ {
@ -33,13 +32,14 @@ class Collection implements \ArrayAccess
} }
/** /**
* Store "request data" in GPC order.
*
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
* *
* @return void * @return void
*/ */
public function set(string $key, mixed $value) public function set($key/*: string*/, $value/*: any*/)
{ {
$this->data[$key] = $value; $this->data[$key] = $value;
} }
@ -48,7 +48,7 @@ class Collection implements \ArrayAccess
* Read stored "request data" by referencing a key. * Read stored "request data" by referencing a key.
* *
* @param string $key * @param string $key
* @param mixed $default *
* @return mixed * @return mixed
*/ */
public function get($key, $default = null) public function get($key, $default = null)
@ -56,114 +56,44 @@ class Collection implements \ArrayAccess
return isset($this->data[$key]) && $this->data[$key] != '' ? $this->data[$key] : $default; return isset($this->data[$key]) && $this->data[$key] != '' ? $this->data[$key] : $default;
} }
/** public function getInt($key, $default = 0)
* @param string $key
* @param int $default
* @return int
*/
public function getInt(string $key, int $default = 0): int
{ {
$value = $this->get($key); return (int)$this->get($key, $default);
// Фильтруем как целое число
if (is_numeric($value)) {
// Приводим к int, но сначала проверим, что не float с дробной частью
$floatVal = (float)$value;
if (is_finite($floatVal) && floor($floatVal) === $floatVal) {
return (int)$floatVal;
}
} }
return $default; public function getString($key, $default = '')
}
/**
* @param string $key
* @param string $default
* @return string
*/
public function getString(string $key, string $default = ''): string
{ {
$value = $this->get($key); return ((string) $this->get($key, $default));
if (is_string($value)) {
return $value;
} }
if (is_numeric($value)) { public function getNat($key, $default = 1)
return (string)$value;
}
return $default;
}
/**
* Получает булево значение
* Поддерживает: 1, '1', 'true', 'on', 'yes' true
* Иначе false
*/
public function getBool(string $key, bool $default = false): bool
{
$value = $this->get($key);
if (is_bool($value)) {
return $value;
}
if (is_string($value)) {
$value = strtolower(trim($value));
return in_array($value, ['1', 'true', 'on', 'yes'], true);
}
if (is_numeric($value)) {
return (bool)$value;
}
return $default;
}
function getArray(string $key, array $default = []): array {
$result = $this->get($key);
if (is_array($result)) {
return $result;
}
return $default;
}
/**
* @param string $key
* @param int $default
* @return int
*/
public function getNat(string $key, int $default = 1): int
{ {
$result = (int)$this->get($key, $default); $result = (int)$this->get($key, $default);
return (($result > 0) ? $result : $default); return (($result > 0) ? $result : $default);
} }
public function clear(): void public function clear()
{ {
$this->data = []; $this->data = array();
} }
public function offsetSet($key, $value): void public function offsetSet($key, $value)
{ {
$this->data[$key] = $value; $this->data[$key] = $value;
} }
public function offsetExists($key): bool public function offsetExists($key)
{ {
return isset($this->data[$key]); return isset($this->data[$key]);
} }
public function offsetUnset($key): void public function offsetUnset($key)
{ {
unset($this->data[$key]); unset($this->data[$key]);
} }
public function offsetGet($key): mixed public function offsetGet($key)
{ {
return $this->data[$key] ?? null; return isset($this->data[$key]) ? $this->data[$key] : null;
} }
} }

View file

@ -1,51 +0,0 @@
<?php
namespace ctiso;
use ctiso\HttpRequest;
use ctiso\Arr;
class ComponentRequest {
/** @var int */
public $component_id;
/** @var string */
public $component_title;
/** @var HttpRequest */
public $r;
/**
* @param int $c
* @param HttpRequest $r
*/
function __construct($c, HttpRequest $r) {
$this->component_id = $c;
$this->r = $r;
}
/**
* @param string $key
* @param mixed $default
* @return mixed
*/
function get($key, $default = null) {
if ($key == 'active_page') {
return $this->r->get($key);
}
$arr = $this->r->get($key);
if (!is_null($arr)) {
if (is_array($arr)) {
return Arr::get($arr, $this->component_id, $default);
} else {
return $arr;
}
}
return $default;
}
/**
* @return string
*/
function getAction() {
return $this->r->getAction();
}
}

View file

@ -1,30 +1,18 @@
<?php <?php
namespace ctiso\Connection; class Connection_HttpRequest
use ctiso\File;
class HttpRequest
{ {
const POST = "POST"; const POST = "POST";
const GET = "GET"; const GET = "GET";
/** @var array Параметры запроса */ private $param = array(); // Параметры запроса
private $param = []; public $data = null; // Содержание
/** @var string Содержание */ public $url; // Адресс
public $data = null; public $method; // Метод
/** @var string Адресс */
public $url;
/** @var string Метод */
public $method;
/** @var int */
public $port = 80; public $port = 80;
/** @var string */
public $host = ""; public $host = "";
/** @var ?string */
public $proxy_host = null; public $proxy_host = null;
/** @var ?int */
public $proxy_port = null; public $proxy_port = null;
/** @var string */
public $http_version = 'HTTP/1.1'; public $http_version = 'HTTP/1.1';
function __construct() { function __construct() {
@ -33,7 +21,6 @@ class HttpRequest
/** /**
* Возвращает заголовок соединения * Возвращает заголовок соединения
* @return string
*/ */
public function getHeader() public function getHeader()
{ {
@ -49,55 +36,44 @@ class HttpRequest
/** /**
* Установка параметров запроса * Установка параметров запроса
* @param string $name * @parma string $name
* @param string $value * @parma string $value
*/ */
public function setParameter($name, $value): void public function setParameter($name, $value)
{ {
$this->param[$name] = $value; $this->param[$name] = $value;
} }
/** /**
* Метод запроса GET или POST * Метод запроса GET или POST
* @param string $method
*/ */
public function setMethod($method): void public function setMethod($method)
{ {
$this->method = $method; $this->method = $method;
} }
/** public function setUrl($url)
* Установка URL
* @param string $url
*/
public function setUrl($url): void
{ {
$this->url = $url; $this->url = $url;
$host = parse_url($this->url, PHP_URL_HOST); $this->host = parse_url($this->url, PHP_URL_HOST);
if (!$host) {
throw new \RuntimeException("Не удалось получить хост");
}
$this->host = $host;
} }
public function getUrl(): string public function getUrl()
{ {
return $this->url; return $this->url;
} }
/** /**
* Содержание запроса * Содержание запроса
* @param string $data
*/ */
public function setContent($data): void public function setContent($data)
{ {
$this->setParameter("Content-length", (string)strlen($data)); $this->setParameter ("Content-length", strlen($data));
$this->data = $data; $this->data = $data;
} }
/** /**
* Посылает запрос и возвращает страницу * Посылает запрос и возвращает страницу
* @return string|null
*/ */
public function getPage() public function getPage()
{ {
@ -110,7 +86,7 @@ class HttpRequest
$header = $this->getHeader(); $header = $this->getHeader();
fwrite($socket, $header); fwrite($socket, $header);
$result = ''; $result = null;
while (! feof($socket)) { while (! feof($socket)) {
$result .= fgets($socket, 128); $result .= fgets($socket, 128);
} }
@ -120,12 +96,6 @@ class HttpRequest
return null; return null;
} }
/**
* Получение JSON
* @param string $url
* @param array $data
* @return array
*/
static function getJSON($url, $data) { static function getJSON($url, $data) {
$query = http_build_query($data); $query = http_build_query($data);
$q = $url . '?' . $query; $q = $url . '?' . $query;

View file

@ -3,26 +3,15 @@
/** /**
* Обрабатывает HTTP ответ * Обрабатывает HTTP ответ
*/ */
namespace ctiso\Connection; class Connection_HttpResponse
class HttpResponse
{ {
/** @var int */
private $offset; private $offset;
/** @var array */ private $param = array ();
private $param = [];
/** @var int */
private $code; private $code;
/** @var string */
public $response; public $response;
/** @var string */
public $version; public $version;
/** @var string */
public $data; public $data;
/**
* @param string $response HTTP ответ
*/
public function __construct($response) public function __construct($response)
{ {
$this->offset = 0; $this->offset = 0;
@ -33,11 +22,11 @@ class HttpResponse
/** /**
* Обработка HTTP ответа * Обработка HTTP ответа
*/ */
private function parseMessage(): void private function parseMessage()
{ {
$http = explode(" ", $this->getLine()); $http = explode(" ", $this->getLine());
$this->version = $http[0]; $this->version = $http[0];
$this->code = (int)$http[1]; $this->code = $http[1];
$line = $this->getLine(); $line = $this->getLine();
while ($offset = strpos($line, ":")) { while ($offset = strpos($line, ":")) {
@ -47,12 +36,12 @@ class HttpResponse
if (isset($this->param['Transfer-Encoding']) && $this->param['Transfer-Encoding'] == 'chunked') { if (isset($this->param['Transfer-Encoding']) && $this->param['Transfer-Encoding'] == 'chunked') {
//$this->data = substr($this->response, $this->offset); //$this->data = substr($this->response, $this->offset);
$index = (int)hexdec($this->getLine()); $nline = hexdec($this->getLine());
$chunk = []; $chunk = array();
while ($index > 0) { while ($nline > 0) {
$chunk [] = substr($this->response, $this->offset, $index); $chunk [] = substr($this->response, $this->offset, $nline);
$this->offset += $index; $this->offset += $nline;
$index = (int)hexdec($this->getLine()); $nline = hexdec($this->getLine());
} }
$this->data = implode("", $chunk); $this->data = implode("", $chunk);
@ -64,7 +53,7 @@ class HttpResponse
/** /**
* Обработка строки HTTP ответа * Обработка строки HTTP ответа
*/ */
private function getLine(): string private function getLine()
{ {
$begin = $this->offset; $begin = $this->offset;
$offset = strpos($this->response, "\r\n", $this->offset); $offset = strpos($this->response, "\r\n", $this->offset);
@ -75,14 +64,13 @@ class HttpResponse
/** /**
* Значение параметра HTTP ответа * Значение параметра HTTP ответа
* @param string $name Имя параметра
*/ */
public function getParameter($name): string public function getParameter($name)
{ {
return $this->param[$name]; return $this->param[$name];
} }
public function getData(): string public function getData()
{ {
return $this->data; return $this->data;
} }
@ -90,7 +78,7 @@ class HttpResponse
/** /**
* Состояние * Состояние
*/ */
public function getCode(): int public function getCode()
{ {
return $this->code; return $this->code;
} }

View file

@ -1,139 +1,112 @@
<?php <?php
namespace ctiso\Controller; function forceUrl($name)
{
use Exception; if (is_callable($name)) {
use ctiso\Path; return call_user_func($name);
use ctiso\Url; }
use ctiso\Model\Factory; return $name;
use ctiso\HttpRequest; }
use ctiso\Settings;
use ctiso\Database;
use ctiso\View\Composite;
use ctiso\View\View;
use App\Controller\State;
/** /**
* Контроллер страниц * Контроллер страниц
*/ */
class Action implements ActionInterface class Controller_Action
{ {
const TEMPLATE_EXTENSION = ".html"; // Расширение для шаблонов const TEMPLATE_EXTENSION = ".html"; // Расширение для шаблонов
const ACTION_PREFIX = "action"; // Префикс для функций действий const ACTION_PREFIX = "action"; // Префикс для функций действий
public $jsPath; // Глобальный путь к скриптам
public $themePath; // Глобальный путь к текущей теме
// Параметры устанавливаются при создании контроллера // Параметры устанавливаются при создании контроллера
public string $name = ''; // Имя модуля public $name = ''; // Имя модуля
/** @var \ctiso\Controller\Front */ public $viewPath = null; // Путь к шаблонам контроллера
public $front; public $viewPathPrefix = null; // Путь к шаблонам контроллера
public string $modulePath = ''; // Путь к модулю public $moduleTitle = "";
public string $moduleTitle = '';
public string $viewPathPrefix = ''; // Путь к шаблонам контроллера
/** Соединение с базой данных */
public Database $db;
// Фильтры
/** @var ?\ctiso\Filter\ActionAccess Обьект хранит параметры доступа */
public $access = null;
/** @var ?\ctiso\Filter\ActionLogger Обьект для ведения лога */
public $logger = null;
/** @var Factory Обьект для создания моделей */
private $factory = null;
/** @var ?Url Параметры для ссылки */
public $part = null;
/** @var \ctiso\Registry Ссылка на настройки */
public $config;
/** @var \ctiso\Role\User Обьект пользователя */
public $user;
function __construct() {
$this->part = new Url();
}
public function setUp(): void {
}
/** /**
* Загрузка файла настроек * Соединение с базой данных
* @param string $name
* @return array
*/ */
public function loadConfig($name) { public $db;
$basePath = $this->config->get('site', 'path');
$filename = Path::join($basePath, 'modules', $name); // Фильтры
public $access = null; // Обьект хранит параметры доступа
public $logger = null; // Обьект для ведения лога
private $factory = null; // Ссылка на обьект создания модели
private $helpers = array(); // Помошники для действий
public $param = array(); // Параметры для ссылки
public $_registry/*: Registry*/; // Ссылка на реестр
public $_shortcut;
public $modulePrefix = '';
public $iconPath = '';
// Для Widgets
public $view = null;
public $childNodes = array();
public $ctrlValues = array();
public $childViews = array();
function __construct() {
}
public function setUp() {
}
public function loadConfig($name) {
$filename = Shortcut::getUrl('config', $name);
$settings = []; $settings = [];
if (file_exists($filename)) { if (file_exists($filename)) {
$settings = include($filename); include($filename);
} else { } else {
throw new Exception('Невозможно загрузить файл настроек ' . $name); throw new Exception('Невозможно загрузить файл настроек ' . $name);
} }
return $settings; return $settings;
} }
public function getConnection(): Database public function getConnection()
{ {
return $this->db; return $this->db;
} }
/**
* Путь к установке модуля
* @param string $name
* @return string
*/
public function installPath($name) public function installPath($name)
{ {
$basePath = $this->config->get('system', 'path'); return Path::join(CMS_PATH, "modules", $name);
return Path::join($basePath, "modules", $name);
} }
/** public function addSuggest(View_View $view, $name)
* Добавляет подсказки {
* @param View $view $suggest = array();
* @param string $name $file = Path::join($this->viewPath, 'help', $name . '.suggest');
*/
public function addSuggest(View $view, $name): void {
$file = Path::join($this->modulePath, 'help', $name . '.suggest');
if (file_exists($file)) { if (file_exists($file)) {
$view->suggestions = include($file); include($file);
$view->suggestions = $suggest;
} }
} }
/** function findIcon($icon, $size)
* Поиск иконки {
* @param string $icon return Path::join($this->iconPath, $size . 'x' . $size, $icon . '.png');
* @param int $size
* @return string Путь к иконке
*/
function findIcon($icon, $size) {
$webPath = $this->config->get('site', 'web');
return Path::join($webPath, 'icons', $size . 'x' . $size, $icon . '.png');
} }
/** /**
* Создает представление * Создает представление
* @param string $name * @param $name String
* @param class-string $viewClass * @param $viewClass String
* @return Composite * @return View_Composite
*/ */
public function getView($name, $viewClass = Composite::class) public function getView($name, $viewClass = 'View_Composite')
{ {
$file = $name . self::TEMPLATE_EXTENSION; $file = $name . self::TEMPLATE_EXTENSION;
$basePath = $this->config->get('system', 'path'); $list = array(
$webPath = $this->config->get('system', 'web'); Path::join($this->viewPath, TEMPLATES, $this->viewPathPrefix) => Path::join(WWW_PATH, "modules", $this->name, TEMPLATES, $this->viewPathPrefix),
Path::join(CMS_PATH, "templates") => Path::join(WWW_PATH, "templates")
$list = [ );
Path::join($this->modulePath, 'templates', $this->viewPathPrefix)
=> Path::join($webPath, "modules", $this->name, 'templates', $this->viewPathPrefix),
Path::join($basePath, "templates") => Path::join($webPath, "templates")
];
// Поиск файла для шаблона // Поиск файла для шаблона
foreach($list as $ospath => $path) { foreach($list as $ospath => $path) {
@ -141,41 +114,34 @@ class Action implements ActionInterface
if(file_exists($template)) { break; } if(file_exists($template)) { break; }
} }
/** @var \ctiso\View\Composite */ $tpl/*: View_Composite*/ = new $viewClass($template);
$tpl = new $viewClass($template);
$tpl->config = $this->config;
$stylePath = Path::join($webPath, "assets", "css"); $assets = Path::join(enableHttps(WWW_PATH), "assets", "css");
$iconsPath = Path::join($webPath, 'icons'); $tpl->set('icons', $this->iconPath); // Путь к файлам текущей темы
$scriptPath = Path::join($webPath, 'assets'); $tpl->set('media', $this->themePath); // Путь к файлам текущей темы
$tpl->set('assets', $assets);
$tpl->set('icons', $iconsPath); // Путь к файлам текущей темы $tpl->set('script', $this->jsPath); // Путь к файлам скриптов
$tpl->set('assets', $stylePath);
$tpl->set('script', $scriptPath); // Путь к файлам скриптов
$tpl->set('template', $path); // Путь к файлам текущего шаблона $tpl->set('template', $path); // Путь к файлам текущего шаблона
$tpl->setAlias([ $tpl->setAlias(array(
'assets' => $stylePath, 'assets' => $assets,
'icons' => $iconsPath, 'icons' => $this->iconPath,
'script' => $scriptPath, 'script' => $this->jsPath,
// Для media и template поиск происходит как для файлов шаблонов // Для media и template поиск происходит как для файлов шаблонов
'media' => $list, 'media' => $list,
'template' => $list 'template' => $list
]); ));
$tpl->loadImports(Path::skipExtension($template) . ".import");
$this->addSuggest($tpl, $name); $this->addSuggest($tpl, $name);
return $tpl; return $tpl;
} }
/**
* @template T
* @param class-string<T> $name
* @return T
*/
public function getModel($name) public function getModel($name)
{ {
if (!$this->factory) { if (!$this->factory) {
$this->factory = new Factory($this->db, $this->config, $this->user); $this->factory = new Model_Factory($this->db, $this->_registry);
} }
return $this->factory->getModel($name); return $this->factory->getModel($name);
} }
@ -185,118 +151,125 @@ class Action implements ActionInterface
* Т.к действия являются методами класса то * Т.к действия являются методами класса то
* 1. Можно переопределить действия * 1. Можно переопределить действия
* 2. Использовать наследование чтобы добавить к старому обработчику новое поведение * 2. Использовать наследование чтобы добавить к старому обработчику новое поведение
* @param HttpRequest $request запроса * @param $request Обьект запроса
* @return View|string
*/ */
public function preProcess(HttpRequest $request) public function preprocess(HttpRequest $request)
{ {
$action = self::ACTION_PREFIX . ucfirst($request->getAction()); $action = self::ACTION_PREFIX . ucfirst($request->getAction());
if (!method_exists($this, $action)) { if (!method_exists($this, $action)) {
$action = "actionIndex"; $action = "actionIndex";
} }
$view = $this->forward($action, $request); $view = $this->forward($action, $request);
if ($view instanceof View) { if ($view instanceof View_View) {
$view->active_module = get_class($this); $view->active_module = get_class($this);
$view->module_action = $action; $view->module_action = $action;
} }
return $view; return $view;
} }
/**
* Выполнение действия
* @param HttpRequest $request
* @return View|string|false
*/
public function execute(HttpRequest $request) public function execute(HttpRequest $request)
{ {
$result = $this->preProcess($request); $result = $this->preprocess($request);
return $result; if (!empty($result)) {
$this->view = $result;
}
$text = $this->render();
return $text;
} }
/**
* Перенаправление на другой контроллер
* @param string $action
* @param HttpRequest $args
* @return mixed
*/
public function forward($action, HttpRequest $args) { public function forward($action, HttpRequest $args) {
$actionFn = [$this, $action]; $value = call_user_func(array($this, $action), $args);
if (!is_callable($actionFn)) {
return false;
}
$value = call_user_func($actionFn, $args);
return $value; return $value;
} }
/** /**
* Страница по умолчанию * Страница по умолчанию
* @param HttpRequest $request
* @return string|false
*/ */
public function actionIndex(HttpRequest $request) { public function actionIndex(HttpRequest $request) {
return ""; return "";
} }
/** public function postUrl($name, $param)
* Добавление части ссылки {
* @param string $key $uri = array_merge(array('module' =>
* @param string $value strtr($this->modulePrefix . strtolower(get_class($this)), array('module_' => '')), "action" => $name),
*/ $this->param, $param);
public function addUrlPart($key, $value): void {
$this->part->addQueryParam($key, $value); return "?" . http_build_query($uri);
} }
/** /**
* Генерация ссылки c учетом прав пользователя на ссылки * Генерация ссылки c учетом прав пользователя на ссылки
* @param string $actionName Действие * @param string $name Действие
* @param array $param Дополнительные параметры * @param array $param Дополнительные параметры
* 'mode' означает что элемент до отправки обрабатывается javascript * 'mode' означает что элемент до отправки обрабатывается javascript
* @return Url|null * @return array|null
*/ */
public function nUrl($actionName, array $param = []) public function nUrl($name, array $param = array())
{ {
$access = $this->access; $access/*: Filter_ActionAccess*/ = $this->access;
$url = new Url();
if ($access == null || $access->checkAction($actionName)) { if ($access == null || $access->checkAction($name)) {
$moduleName = explode("\\", strtolower(get_class($this))); return Functions::lcurry(array($this, 'postUrl'), $name, $param);
if (count($moduleName) > 2) {
array_shift($moduleName);
if ($moduleName[0] == $moduleName[1]) {
array_shift($moduleName);
} }
} return null;
$param = array_merge(['module' => implode("\\", $moduleName), "action" => $actionName], $param);
$url->setParent($this->part);
$url->setQuery($param);
} }
return $url; public function fUrl($name, array $param = array())
{
return forceUrl($this->nUrl($name, $param));
}
/**
* Добавляет параметр для всех ссылок создаваемых функцией nUrl, aUrl
*/
public function addParameter($name, $value)
{
if ($value) {
$this->param [$name] = $value;
}
} }
/** /**
* Генерация ссылки на действие контроллера * Генерация ссылки на действие контроллера
* Ajax определяется автоматически mode = ajax используется для смены layout * Ajax определяется автоматически mode = ajax используется для смены layout
* @param string $name * @param $name
* @param array $param * @param array $param
* @return Url|null * @return array|null
* *
* @example ?action=$name&mode=ajax * @example ?action=$name&mode=ajax
* {$param[i].key = $param[i].value} * {$param[i].key = $param[i].value}
*/ */
public function aUrl($name, array $param = []) public function aUrl($name, array $param = array())
{ {
return $this->nUrl($name, array_merge(['mode' => 'ajax'], $param)); return $this->nUrl($name, array_merge(array('mode' => 'ajax'), $param)); // FIXME
}
/**
* Добавление помошника контроллера
*/
public function addHelper($class)
{
$this->helpers [] = $class;
}
/**
* Вызов помошников контроллера
*/
public function callHelpers(HttpRequest $request)
{
$action = self::ACTION_PREFIX . $request->getAction();
foreach ($this->helpers as $helper) {
if (method_exists($helper, $action)) {
return call_user_func(array($helper, $action), $request, $this);
} else {
return $helper->actionIndex($request, $this); // Вместо return response ???
}
}
} }
/** /**
* Загрузка файла класса * Загрузка файла класса
* @deprecated Веместо его нужно использовать автозагрузку
* @param string $path
* @param mixed $setup
* @param string $prefix
* @return mixed
*/ */
public function loadClass($path, $setup = null, $prefix = '') public function loadClass($path, $setup = null, $prefix = '')
{ {
@ -308,11 +281,6 @@ class Action implements ActionInterface
throw new Exception("NO CLASS $path"); throw new Exception("NO CLASS $path");
} }
/**
* Загрузка настроек
* @param string $path
* @return array
*/
public function loadSettings($path) public function loadSettings($path)
{ {
$result = new Settings($path); $result = new Settings($path);
@ -320,21 +288,69 @@ class Action implements ActionInterface
return $result->export(); return $result->export();
} }
public function setView($name)
{
$this->view = $this->getView($name);
}
/** /**
* Установка идентификатора страницы * Установка заголовка для отображения
* @return int
*/ */
function getPageId(HttpRequest $request) { public function setTitle($title)
{
$this->view->setTitle($title);
}
/**
* Добавление widget к отображению
*/
public function addChild(/*Widget*/ $section, $node)
{
$this->childNodes[$section] = $node;
}
public function setValue(/*Widget*/ $name, $value)
{
$this->ctrlValues[$name] = $value;
}
/**
* Добавление дочернего отображения к текущему отображению
*/
public function addView(/*CompositeView*/ $section, $node)
{
$this->childViews[$section] = $node;
}
/**
* Генерация содержания
* Путаница c execute и render
*/
public function render()
{
if ($this->view instanceof View_View) {
$this->view->assignValues($this->ctrlValues);
$node/*: Widgets_Widget*/ = null;
foreach ($this->childNodes as $name => $node) {
$node->make($this);
$this->view->setView($name, $node->view);
}
foreach ($this->childViews as $name => $node) {
$this->view->setView($name, $node);
}
}
return $this->view;
}
function getPageId(HttpRequest $request)
{
$pageId = time(); $pageId = time();
$request->session()->set('page', $pageId); $request->session()->set('page', $pageId);
return $pageId; return $pageId;
} }
/**
* Проверка идентификатора страницы
* @param int $page Идентификатор страницы
* @return bool
*/
function checkPageId(HttpRequest $request, $page) function checkPageId(HttpRequest $request, $page)
{ {
if ($request->get('__forced__')) { if ($request->get('__forced__')) {
@ -346,15 +362,19 @@ class Action implements ActionInterface
return $result; return $result;
} }
/** function _getActionPath()
* @return State {
*/ return new Controller_State('index');
function _getActionPath() {
return new State('index');
} }
function redirect(string $action): void { // Тоже убрать в метод Controller_Model
header('location: ' . $action); function getActionPath(HttpRequest $request, $action = null)
{
$this->_getActionPath()->getPath($this, ($action) ? $action : $request->getAction());
}
function redirect($action) {
header('location: ' . $this->fUrl($action));
exit(); exit();
} }
} }

View file

@ -1,28 +0,0 @@
<?php
namespace ctiso\Controller;
use ctiso\Database;
use ctiso\HttpRequest;
interface ActionInterface {
/**
* Действие может вернуть Шаблон или строку
*
* @param HttpRequest $request
* @return \ctiso\View\View|string|false
*/
function execute(HttpRequest $request);
function getConnection(): Database;
/**
* @param string $name
* @param class-string<\ctiso\View\View> $class
* @return \ctiso\View\View
*/
function getView($name, $class);
/**
* @param string $key
* @param string $value
*/
function addUrlPart($key, $value): void;
}

View file

@ -1,90 +1,72 @@
<?php <?php
namespace ctiso\Controller; function replaceContent($match) {
$result = phptal_component(htmlspecialchars_decode($match[3]));
return $result;
}
use ctiso\HttpRequest; function applyComponents($text) {
use ctiso\ComponentRequest; return preg_replace_callback('/<(\w+)(\s+[a-zA-Z\-]+=\"[^\"]*\")*\s+tal:replace="structure\s+component:([^\"]*)"[^>]*>/u', 'replaceContent', $text);
use ctiso\Arr; }
use ctiso\Path;
use ctiso\File; class ComponentRequest {
use ctiso\Form\Form; public $component_id;
use ctiso\View\Composite; public $component_title;
use ctiso\Database; public $r;
use ctiso\Collection;
use ctiso\Registry; function __construct($c, HttpRequest $r) {
use ctiso\Controller\SiteInterface; $this->component_id = $c;
use ctiso\Database\PDOStatement; $this->r = $r;
use PHPTAL; }
use PHPTAL_PreFilter_Normalize;
use ctiso\View\JsonView; function get($key, $default = null) {
if ($key == 'active_page') {
return $this->r->get($key);
}
$arr = $this->r->get($key);
if ($arr !== NULL) {
if (is_array($arr)) {
return Arr::get($arr, $this->component_id, $default);
} else {
return $arr;
}
}
return $default;
}
function getAction() {
return $this->r->getAction();
}
}
/** /**
* Класс компонента * Класс компонента
*/ */
class Component class Controller_Component
{ {
/** @var string[] */ public $viewPath = array();
public $viewPath = []; public $webPath = array();
/** @var string[] */
public $webPath = [];
/** @var ?string */
public $template = null; public $template = null;
public string $templatePath; public $templatePath;
/** @var int */
public $component_id; public $component_id;
/** @var string */
public $component_title; public $component_title;
/** @var string */
public $COMPONENTS_WEB; public $COMPONENTS_WEB;
public Registry $config; public $registry/*: Settings*/;
public Database $db; public $db/*: Database*/;
public Collection $parameter; public $parameter/*: Collection*/;
/** @var string */
public $output = 'html';
/** @var string */
public $module; public $module;
/** @var string */
public $item_module; public $item_module;
/** function before() {
* @var SiteInterface $site
*/
public $site;
function before(): void {
} }
/** function get($request, $key, $default) {
* @param string $match
* @return string
*/
static function replaceContent($match) {
return \ctiso\Tales::phptal_component(htmlspecialchars_decode($match[3]));
} }
/**
* @param string $text
* @return string
*/
static function applyComponents($text) {
$callback = fn($x) => self::replaceContent($x);
return preg_replace_callback('/<(\w+)(\s+[a-zA-Z\-]+=\"[^\"]*\")*\s+tal:replace="structure\s+component:([^\"]*)"[^>]*>/u',
$callback, $text);
}
/**
* Выполняет запрос компонента и возвращает результат
* Результат может быть строкой или View для обычных компонентов, или массивом для использования в сервисах
*
* @param HttpRequest $request
* @param bool $has_id
* @return mixed
*/
function execute(HttpRequest $request, $has_id = true) { function execute(HttpRequest $request, $has_id = true) {
$crequest = new ComponentRequest($this->component_id, $request); $crequest = new ComponentRequest($this->component_id, $request);
@ -96,42 +78,25 @@ class Component
} }
$this->before(); $this->before();
$actionMethod = [$this, $action]; if (method_exists($this, $action)) {
if (is_callable($actionMethod)) { return call_user_func(array($this, $action), $crequest);
return call_user_func($actionMethod, $crequest); } else {
}
return $this->actionIndex($crequest); return $this->actionIndex($crequest);
} }
/**
* Получить имя шаблона
* @param Registry $_registry
* @return string
*/
public function getTemplateName($_registry) {
return (isset($_COOKIE['with_template']) && preg_match('/^[\w\d-]{3,20}$/', $_COOKIE['with_template']))
? $_COOKIE['with_template'] : ($_registry ? $_registry->get('site', 'template') : 'modern');
} }
/** public function getTemplateName($_registry/*: Settings*/) {
* Получить шаблон return (isset($_COOKIE['with_template']) && preg_match('/^[\w\d-]{3,20}$/', $_COOKIE['with_template']))
* @param string $name ? $_COOKIE['with_template'] : ($_registry ? $_registry->readKey(array('system', 'template')) : 'modern');
* @return PHPTAL|JsonView }
*/
public function getView($name) public function getView($name)
{ {
if ($this->output === 'json') { //
return new JsonView($name); $registry/*: Settings*/ = $this->registry;
} $template = ($this->template) ? $this->template : $this->getTemplateName($registry);
/** @var Registry $config */
$config = $this->config;
$default = $config->get('site', 'template');
$template = ($this->template) ? $this->template : $this->getTemplateName($config);
$selected = null; $selected = null;
$tpl = null;
foreach ($this->viewPath as $index => $viewPath) { foreach ($this->viewPath as $index => $viewPath) {
// Загружать шаблон по умолчанию если не найден текущий // Загружать шаблон по умолчанию если не найден текущий
$dir = Path::join($this->viewPath[$index], 'templates', $template); $dir = Path::join($this->viewPath[$index], 'templates', $template);
@ -152,16 +117,15 @@ class Component
} }
$tpl->stripComments(true); $tpl->stripComments(true);
$tpl->addPreFilter(new \PHPTAL_PreFilter_Normalize()); $tpl->addPreFilter(new PHPTAL_PreFilter_Normalize());
$tpl->set('common', Path::join($this->config->get('system', 'web'), '../', 'common')); $tpl->set('common', Path::join(WWW_PATH, '../', 'common'));
$tpl->set('script', Path::join($this->config->get('system', 'web'), 'js')); $tpl->set('script', Path::join(WWW_PATH, 'js'));
$tpl->set('media', Path::join($this->config->get('system', 'templates.web'), $template)); $tpl->set('media', Path::join(TEMPLATE_WEB, $template));
if ($registry) {
if ($default) { $tpl->set('site_template', SITE_WWW_PATH . '/templates/' . $registry->readKey(array('system', 'template')));
$tpl->set('site_template', Path::join($this->config->get('site', 'templates.web'), $default));
} }
$tpl->set('base', $this->config->get('site', 'web')); $tpl->set('base', SITE_WWW_PATH);
$tpl->set('component_base', $this->webPath[$selected]); $tpl->set('component_base', $this->webPath[$selected]);
$tpl->set('component', Path::join($this->webPath[$selected], 'templates', $template)); $tpl->set('component', Path::join($this->webPath[$selected], 'templates', $template));
@ -170,24 +134,15 @@ class Component
return $tpl; return $tpl;
} }
/**
* Возвращает путь к шаблону по умолчанию
* @return string
*/
function _getDefaultPath() { function _getDefaultPath() {
return $this->viewPath[count($this->viewPath) - 1]; return $this->viewPath[count($this->viewPath) - 1];
} }
/**
* Возвращает путь к шаблону
* @param string $name
* @return string
*/
public function getTemplatePath($name) { public function getTemplatePath($name) {
$registry = $this->config; $registry/*: Settings*/ = $this->registry;
// Брать настройки из куков если есть // Брать настройки из куков если есть
$template = ($this->template) ? $this->template : $this->getTemplateName($registry); $template = ($this->template) ? $this->template : $this->getTemplateName($registry);
foreach ($this->viewPath as $index => $_) { foreach ($this->viewPath as $index => $viewPath) {
if(is_dir(Path::join($this->viewPath[$index], 'templates', $template))) { if(is_dir(Path::join($this->viewPath[$index], 'templates', $template))) {
return Path::join($this->viewPath[$index], 'templates', $template, $name); return Path::join($this->viewPath[$index], 'templates', $template, $name);
} }
@ -196,10 +151,6 @@ class Component
return Path::join($this->viewPath[count($this->viewPath) - 1], 'templates', 'modern', $name); return Path::join($this->viewPath[count($this->viewPath) - 1], 'templates', 'modern', $name);
} }
/**
* Возвращает путь к шаблонам
* @return string
*/
public function getTemplateWebPath() public function getTemplateWebPath()
{ {
return Path::join($this->webPath[count($this->webPath) - 1], 'templates', 'modern'); return Path::join($this->webPath[count($this->webPath) - 1], 'templates', 'modern');
@ -207,85 +158,49 @@ class Component
/** /**
* Создает модель * Создает модель
* * @param string $name
* @template T * @return model
* @param class-string<T> $modelName
* @return T
*/ */
public function getModel($modelName) public function getModel($name)
{ {
$modelName = "Mapper_" . $name;
$model = new $modelName(); $model = new $modelName();
$model->config = $this->config;
$model->db = $this->db; $model->db = $this->db;
return $model; return $model;
} }
/** public function options($key, $val, $res/*: Database_PDOStatement*/) {
* @param string $key $result = array();
* @param string $val
* @param PDOStatement $res
* @return array{value: string, name: string}[]
*/
public function options(string $key, string $val, $res) {
$result = [];
while($res->next()) { while($res->next()) {
$result[] = ['value' => $res->getString($key), 'name' => $res->getString($val)]; $result[] = array('value' => $res->getString($key), 'name' => $res->getString($val));
} }
return $result; return $result;
} }
/** public function optionsPair($list, $selected = false) {
* @param array $list $result = array();
* @param bool $selected
* @return array{value: string, name: string, selected: bool}[]
*/
public function optionsPair(array $list, $selected = false) {
$result = [];
foreach ($list as $key => $value) { foreach ($list as $key => $value) {
$result [] = ['value' => $key, 'name' => $value, 'selected' => $key == $selected]; $result [] = array('value' => $key, 'name' => $value, 'selected' => $key == $selected);
} }
return $result; return $result;
} }
/**
* Найти файл по пути
* @param string[] $pathList
* @param string $name
* @return string|null
*/
function findFile(array $pathList, string $name) {
foreach($pathList as $item) {
$filename = Path::join($item, $name);
if (file_exists($filename)) {
return $filename;
}
}
return null;
}
/**
* Получить информацию о параметрах
* @return array<mixed>
*/
function getInfo() { function getInfo() {
$filename = Path::join($this->viewPath[count($this->viewPath) - 1], 'install.json'); $filename = Path::join($this->viewPath[count($this->viewPath) - 1], 'install.json');
if (file_exists($filename)) { if (file_exists($filename)) {
$settings = json_decode(File::getContents($filename), true); $settings = json_decode(File::getContents($filename), true);
if ($settings) {
return $settings; return $settings;
} }
} return array();
return ['parameter' => []];
} }
/** /**
* Генерация интерфейса для выбора галлереи фотографии * Генерация интерфейса для выбора галлереи фотографии
* @param Composite $view
* @param ?\ctiso\Form\OptionsFactory $options
*/ */
public function setParameters(Composite $view, $options = null): void public function setParameters($view/*: View_Composite*/)
{ {
$form = new Form(); $form = new Form_Form();
$options = new Form_OptionFactory($this->db, $this->registry);
$settings = $this->getInfo(); $settings = $this->getInfo();
$form->addFieldList($settings['parameter'], $options); $form->addFieldList($settings['parameter'], $options);
@ -295,93 +210,71 @@ class Component
$view->component_title = $settings['title']; $view->component_title = $settings['title'];
} }
/** static function loadComponent($expression, Database $db, $registry/*: Registry*/)
* @param \ctiso\Form\OptionsFactory $options
* @return array
*/
public function getFields($options = null) {
$form = new Form();
$settings = $this->getInfo();
$form->addFieldList($settings['parameter'], $options);
return $form->field;
}
/**
* Обьеденить с ComponentFactory
* @param string $expression
* @param SiteInterface $site
* @return Component
*/
static function loadComponent(string $expression, $site)
{ {
$expression = htmlspecialchars_decode($expression); $expression = htmlspecialchars_decode($expression);
$offset = strpos($expression, '?'); $offset = strpos($expression, '?');
$url = parse_url($expression); $url = parse_url($expression);
$arguments = []; $arguments = array();
if ($offset === false) {
$path = $expression; $path = $expression;
if (is_int($offset)) { } else if (is_int($offset)) {
$path = substr($expression, 0, $offset); $path = substr($expression, 0, $offset);
$query = substr($expression, $offset + 1); $query = substr($expression, $offset + 1);
parse_str($query, $arguments); parse_str($query, $arguments);
} }
$name = $path; $name = $path;
$config = $site->getConfig();
// FIXME: Если имя для компонента не задано то возвращаем пустой компонент $path = Path::join (BASE_PATH, 'components', $name, $name . '.php');
// Нужно дополнительно проверить и файл или в autoloader просто не найдет файл копонента $className = 'Component_' . $name;
if (!$name) {
return new Component();
}
$filename = ucfirst($name); $component/*: Controller_Component*/ = null;
$path = Path::join ($config->get('site', 'components'), $name, $filename . '.php');
$className = implode("\\", ['Components', ucfirst($name), $filename]);
$component = null;
if (file_exists($path)) { if (file_exists($path)) {
/** @var Component $component */ require_once ($path);
$component = new $className(); $component = new $className();
$component->viewPath = [$config->get('site', 'components') . '/' . $name . '/'];
$component->webPath = [$config->get('site', 'components.web') . '/' . $name];
$component->COMPONENTS_WEB = $config->get('site', 'web') . '/components/';
} else {
/** @var Component $component */
$component = new $className();
$template = $component->getTemplateName($site->getConfig());
$component->viewPath = [
// Сначало ищем локально
$config->get('site', 'templates') . '/'. $template . '/_components/' . $name . '/',
$config->get('site', 'components') . '/' . $name . '/',
// Потом в общем хранилище
$config->get('system', 'templates'). '/' . $template . '/_components/' . $name . '/',
$config->get('system', 'components') . '/' . $name . '/',
];
if (defined('COMPONENTS_WEB')) {
$component->webPath = [
// Сначало локально
$config->get('site', 'templates.web') . '/' . $template . '/_components/' . $name,
$config->get('site', 'components.web') . '/' . $name,
// Потом в общем хранилище
$config->get('system', 'templates.web') . '/' . $template . '/_components/' . $name,
$config->get('system', 'components.web') . '/' . $name,
];
$component->COMPONENTS_WEB = $config->get('system', 'components.web');
} else {
$component->webPath = ['', $config->get('site', 'components.web') . '/' . $name, '', ''];
}
}
// Вынести в отдельную функцию
$db = $site->getDatabase();
$component->db = $db; $component->db = $db;
$component->config = $site->getConfig(); $component->registry = $registry;
$component->site = $site;
$component->viewPath = array(BASE_PATH . '/components/' . $name . '/');
$component->webPath = array(SITE_WWW_PATH . '/components/' . $name);
$component->COMPONENTS_WEB = SITE_WWW_PATH . '/components/';
} else {
$path = Path::join (COMPONENTS, $name, $name . '.php');
require_once ($path);
$component = new $className();
$component->db = $db;
$component->registry = $registry;
$template = $component->getTemplateName($registry);
$component->viewPath = array(
// Сначало ищем локально
BASE_PATH . '/templates/' . $template . '/_components/' . $name . '/',
BASE_PATH . '/components/' . $name . '/',
// Потом в общем хранилище
CMS_PATH . '/../templates/' . $template . '/_components/' . $name . '/',
COMPONENTS . '/' . $name . '/',
);
if (defined('COMPONENTS_WEB')) {
$component->webPath = array(
// Сначало локально
SITE_WWW_PATH . '/templates/' . $template . '/_components/' . $name,
SITE_WWW_PATH . '/components/' . $name,
// Потом в общем хранилище
TEMPLATE_WEB . '/' . $template . '/_components/' . $name,
COMPONENTS_WEB . '/' . $name,
);
$component->COMPONENTS_WEB = COMPONENTS_WEB;
} else {
$component->webPath = array('', SITE_WWW_PATH . '/components/' . $name, '');
}
}
$stmt = $db->prepareStatement("SELECT * FROM component WHERE code = ?"); $stmt = $db->prepareStatement("SELECT * FROM component WHERE code = ?");
$stmt->setString(1, $expression); $stmt->setString(1, $expression);
@ -390,7 +283,6 @@ class Component
$component->component_id = $cid->getInt('id_component'); $component->component_id = $cid->getInt('id_component');
} else { } else {
$last = $db->getIdGenerator(); $last = $db->getIdGenerator();
$result = null;
if ($last->isBeforeInsert()) { if ($last->isBeforeInsert()) {
$result = $last->getId('component_id_component_seq'); $result = $last->getId('component_id_component_seq');
@ -410,40 +302,38 @@ class Component
$params = new Collection(); $params = new Collection();
$params->import(array_merge($_GET, $arguments)); $params->import(array_merge($_GET, $arguments));
$component->parameter = $params; $component->parameter = $params;
$component->template = $params->get('template', false); $component->template = $params->get('template', false);
$editor = $component->getEditUrl(); $editor = $component->getEditUrl();
if ($editor) { if ($editor) {
$site->addComponentConfig($editor); if(class_exists("Controller_Site")){ //Если мы в CMS2
$instance = Controller_Site::getInstance();
$instance->componentsConfig[] = $editor;
} else {
global $componentsConfig;
$componentsConfig[] = $editor;
}
} }
return $component; return $component;
} }
/**
* @return ?array{name: string, url: string}
*/
function getEditUrl() { function getEditUrl() {
return null; return null;
} }
/** function raw_query($request/*: ComponentRequest*/)
* @param ComponentRequest $request
* @return array
*/
function raw_query($request)
{ {
$arr = $request->r->export('get'); $arr = $request->r->export('get');
$param = []; $param = array();
$parameter = $this->parameter; $parameter/*: Collection*/ = $this->parameter;
foreach($parameter->export() as $key => $value) { foreach($parameter->export() as $key => $value) {
$param[$key] = $value; $param[$key] = $value;
} }
$data = []; $data = array();
foreach($arr as $key => $value) { foreach($arr as $key => $value) {
if (is_array($value)) { if (is_array($value)) {
$data[$key] = Arr::get($value, $this->component_id); $data[$key] = Arr::get($value, $this->component_id);
@ -456,12 +346,7 @@ class Component
} }
/** function query($request/*: ComponentRequest*/, $list)
* @param ComponentRequest $request
* @param array $list
* @return string
*/
function query($request, $list)
{ {
$arr = $request->r->export('get'); $arr = $request->r->export('get');
@ -474,27 +359,14 @@ class Component
} }
/** /**
* @param string $name * @deprecated В CMS2 перенесено в контроллер сайта!
* @param string $path
* @param array $shim
*/ */
function addRequireJsPath($name, $path, $shim = null): void {
$this->site->addRequireJsPath($name, $path, $shim); function addRequireJsPath($name, $path, $shim = null) {
Controller_Site::addRequireJsPath($name, $path, $shim);
} }
/** function actionIndex($request/*: ComponentRequest*/) {
* @param ComponentRequest $request }
* @return mixed
*/
function actionIndex($request) {
return "";
} }
/**
* @param HttpRequest $request
* @return array
*/
function getDefaultPageEnvironment($request) {
return [];
}
}

View file

@ -4,52 +4,32 @@
* Первичный контроллер контроллер страниц * Первичный контроллер контроллер страниц
* @package system.controller * @package system.controller
*/ */
namespace ctiso\Controller; class Controller_Front extends Controller_Action
use ctiso\Controller\Action;
use ctiso\Registry;
use ctiso\Database;
use ctiso\Filter\ActionAccess;
use ctiso\Filter\ActionLogger;
use ctiso\Path;
use ctiso\UserMessageException;
use ctiso\HttpRequest;
use ctiso\Role\User;
class Front extends Action
{ {
/** /** @var Shortcut */
* Параметр по которому выбирается модуль protected $shortcut; // Ярлык к модулю
* @var string protected $_param; // Параметр по которому выбирается модуль
*/ protected $default; // Значение параметра по умолчанию
protected $_param;
/**
* Значение параметра по умолчанию
* @var string
*/
protected $default;
/** @var array<string, Action> */ protected $modules = array();
protected $modules = [];
/** /**
* @param string $default * @param Settings $_registry
* @param Shortcut $_shortcut
*/ */
public function __construct(Database $db, Registry $config, User $user, $default) { public function __construct(Settings $_registry, $_shortcut) // $db, $installer, $shortcut
{
parent::__construct(); parent::__construct();
$this->config = $config; $registry = $_registry;
$this->db = $db; $this->_registry = $_registry;
$this->user = $user; $this->_shortcut = $_shortcut; // $cc->newShortcut();
$this->default = $default;
$dsn = $registry->readKey(array('system', 'dsn'));
$this->db = Database::getConnection($dsn); // $cc->newConnection();
} }
/** public function isLoaded($name)
* Проверяет загружен ли модуль
* @param string $name Имя модуля
* @return bool
*/
public function isLoaded($name): bool
{ {
return isset($this->modules[$name]); return isset($this->modules[$name]);
} }
@ -57,49 +37,43 @@ class Front extends Action
/** /**
* Создает экземпляр модуля и выполняет действия для него * Создает экземпляр модуля и выполняет действия для него
* @param string $name Имя модуля * @param string $name Имя модуля
* @param HttpRequest $request * @param request $request Имя модуля
* @return string * @return string
*/ */
public function loadModule($name, HttpRequest $request) public function loadModule($name, Collection $request, $controller = false)
{ {
if ($this->isLoaded($name)) { if ($this->isLoaded($name)) {
$module = $this->modules[$name]; $module = $this->modules[$name];
return $module->access->execute($request); return $module->access->execute($request);
} }
$parts = explode('\\', $name); $suffix = ($controller) ? $controller : $name;
$moduleFile = Shortcut::getUrl($this->shortcut, $name, $suffix); // ModuleLoader (2)
$config = $this->config;
$moulesPath = Path::join($config->get('system', 'path'), 'modules');
$logPath = Path::join($config->get('site', 'path'), $config->get('system', 'access.log'));
$first = $parts[0];
$second = (count($parts) >= 2) ? $parts[1] : $parts[0];
$ucname = ucfirst($first);
$ucpart = ucfirst($second);
$moduleClass = "Modules\\$ucname\\$ucpart";
/** @var Action $module */
$module = new $moduleClass();
$module = $this->loadClass($moduleFile, null, 'Module_');
if ($module) {
// Инициализация модуля // Инициализация модуля
$modPath = Path::join($moulesPath, $first);
$module->modulePath = $modPath;
$module->name = $name;
//
$module->config = $this->config;
$module->db = $this->db;
$module->user = $this->user;
$module->front = $this; $module->front = $this;
$module->viewPath = Shortcut::getUrl('modulepath', $name);
$module->name = $name;
$module->param = $this->param;
//
$module->_registry = $this->_registry;
$module->_shortcut = $this->_shortcut;
$module->iconPath = $this->iconPath; // -> Registry
$module->themePath = $this->themePath; // -> Registry
$module->jsPath = $this->jsPath; // -> Registry
$module->db = $this->db;
// Не для всех приложений нужно вести лог действий
// Ведение лога // Ведение лога
$logger = new ActionLogger($module, $logPath, $this->user); $logger = $this->loadClass(__DIR__ . '/../Filter/ActionLogger.php', $module, 'Filter_');
$filename = Path::join($modPath, 'filters', 'logger.json'); $logger->before = $this->loadSettings(Shortcut::getUrl('logger', $name));
$logger->before = $this->loadSettings($filename);
// Управление доступом // Управление доступом
$module->access = new ActionAccess($logger, $this->user); $module->access = $this->loadClass(__DIR__ . '/../Filter/ActionAccess.php', $logger, 'Filter_');
$module->access->access = $this->loadSettings(Path::join($modPath, 'filters', 'access.json')); $module->access->name = $suffix;
$module->access->access = $this->loadSettings(Shortcut::getUrl('access', $name));
$module->setUp(); $module->setUp();
@ -107,13 +81,27 @@ class Front extends Action
$result = $module->access->execute($request); $result = $module->access->execute($request);
return $result; return $result;
} }
return null; // throw new FileNotFoundException();
}
public function setParameter($shortcut, $param, $name)
{
$this->shortcut = $shortcut;
// Параметр
$this->_param = $param;
$this->default = $name;
}
public function execute(HttpRequest $request) public function execute(HttpRequest $request)
{ {
$name = $request->getString('module', $this->default); $name = explode("_", $request->get($this->_param, $this->default));
if (count($name) >= 2) {
$controller = $name[1];
} else {
$controller = false;
}
try{ try{
return $this->loadModule($name, $request); return $this->loadModule($name[0], $request, $controller);
} catch (UserMessageException $ex) { //Исключение с понятным пользователю сообщением } catch (UserMessageException $ex) { //Исключение с понятным пользователю сообщением
$mode = $request->get('mode'); $mode = $request->get('mode');
if($mode == 'ajax' || $mode == 'json'){ if($mode == 'ajax' || $mode == 'json'){

View file

@ -1,20 +1,9 @@
<?php <?php
namespace ctiso\Controller; class Controller_Installer
use ctiso\Settings;
use ctiso\Path;
use ctiso\Database\JsonInstall;
use ctiso\Database\Manager;
class Installer
{ {
/** @var Manager */
protected $db_manager; protected $db_manager;
/** @var callable */
protected $installPath; protected $installPath;
/** @var Settings */
public $_registry; public $_registry;
public function __construct(Settings $_registry) public function __construct(Settings $_registry)
@ -22,46 +11,26 @@ class Installer
$this->_registry = $_registry; $this->_registry = $_registry;
} }
/** public function setUp($db_manager, $installPath)
* Устанавливает параметры
* @param Manager $db_manager
* @param callable $installPath
*/
public function setUp($db_manager, $installPath): void
{ {
$this->db_manager = $db_manager; $this->db_manager = $db_manager;
$this->installPath = $installPath; $this->installPath = $installPath;
} }
/**
* Получение пути к файлу install.json
* @param string $name
* @return string
*/
function getSetupFile($name) function getSetupFile($name)
{ {
$setup = Path::join(call_user_func($this->installPath, $name), "install.json"); $setup = Path::join(call_user_func($this->installPath, $name), "install.json");
return $setup; return $setup;
} }
/** function getUninstallFile($name){
* Получение пути к файлу unisntall.json
* @param string $name
* @return string
*/
function getUninstallFile($name)
{
return Path::join(call_user_func($this->installPath, $name), "sql", "uninstall.json"); return Path::join(call_user_func($this->installPath, $name), "sql", "uninstall.json");
} }
/** // Проверка версии обновления
* Проверка версии обновления
* @param string $name
* @return bool
*/
function isChanged($name) // Информация о модулях function isChanged($name) // Информация о модулях
{ {
$item = $this->_registry->get($name); $item = $this->_registry->readKey(array($name));
if ($item) { if ($item) {
$setup = $this->getSetupFile($name); $setup = $this->getSetupFile($name);
if (file_exists($setup) && (filemtime($setup) > $item['time'])) { if (file_exists($setup) && (filemtime($setup) > $item['time'])) {
@ -72,18 +41,10 @@ class Installer
return true; return true;
} }
/**
* Устанавливает SQL
* @param array $sql
* @param string $version_new
* @param string $version_old
* @param string $name
* @return array
*/
function installSQL(array $sql, $version_new, $version_old, $name) function installSQL(array $sql, $version_new, $version_old, $name)
{ {
$result = []; $result = [];
$json_installer = new JsonInstall($this->db_manager); $json_installer = new Database_JsonInstall($this->db_manager);
foreach ($sql as $version => $install) { foreach ($sql as $version => $install) {
if (version_compare($version, $version_new, "<=") && version_compare($version, $version_old, ">")) { if (version_compare($version, $version_new, "<=") && version_compare($version, $version_old, ">")) {
$file = Path::join(call_user_func($this->installPath, $name), "sql", $install); $file = Path::join(call_user_func($this->installPath, $name), "sql", $install);
@ -94,46 +55,35 @@ class Installer
return $result; return $result;
} }
/** function uninstall($name){
* @param string $name
* @return void
*/
function uninstall($name): void
{
$uninstall = $this->getUninstallFile($name); $uninstall = $this->getUninstallFile($name);
if (file_exists($uninstall)) { if (file_exists($uninstall)) {
$json_installer = new JsonInstall($this->db_manager); $json_installer = new Database_JsonInstall($this->db_manager);
$json_installer->install($uninstall,null); $json_installer->install($uninstall,null);
} }
$this->_registry->removeKey($name); $this->_registry->removeKey($name);
$this->_registry->write(); $this->_registry->write();
} }
/** // Устанавливает обновления если есть
* Устанавливает обновления если есть function doUpdates($name, $force = false) // Установка модуля
* @param string $name
* @param bool $force
* @return array
*/
function doUpdates($name, $force = false)
{ {
$result = []; $result = array();
$setup = $this->getSetupFile($name); $setup = $this->getSetupFile($name);
if (file_exists($setup) && ($this->isChanged($name) || $force)) { if (file_exists($setup) && ($this->isChanged($name) || $force)) {
$registry = $this->_registry; $registry = $this->_registry;
$settings = new Settings($setup); $settings = new Settings($setup);
$settings->read(); $settings->read();
$item = $registry->get($name); $item = $registry->readKey(array($name));
$version_new = $settings->get('version'); $version_new = $settings->get('version');
if ($item) { if ($item) {
$version_old = $item['version']; $version_old = $item['version'];
} else { } else {
$version_old = "0.0"; $version_old = "0.0";
$registry->writeKey([$name], []); $registry->writeKey(array($name), array());
} }
if (version_compare($version_old, $settings->get('version'), "!=")) { if (version_compare($version_old, $settings->get('version'), "!=")) {
$sql = $settings->get('sql'); $sql = $settings->get('sql');
@ -143,29 +93,22 @@ class Installer
$result[]=$res; $result[]=$res;
} }
} }
}
// Обновление версии меню // Обновление версии меню
$registry->removeKey($name); $registry->removeKey($name);
$registry->set($name, [ $registry->writeKey(array($name), $settings->get('settings'));
'version' => $version_new, $registry->writeKey(array($name),
'time' => filemtime($setup) array('version' => $version_new,
]); 'time' => filemtime($setup)));
// $registry->writeKey([$name], $settings->export()); }
$registry->write(); $registry->write();
} }
return $result; return $result;
} }
/** function install($dbinit_path, $dbfill_path = null) {
* Устанавливает базу данных $json_installer = new Database_JsonInstall($this->db_manager);
* @param string $dbinit_path
* @param string|null $dbfill_path
*/
function install($dbinit_path, $dbfill_path = null): void
{
$json_installer = new JsonInstall($this->db_manager);
$json_installer->install($dbinit_path, $dbfill_path); $json_installer->install($dbinit_path, $dbfill_path);
} }
} }

View file

@ -1,33 +1,19 @@
<?php <?php
namespace ctiso\Controller; class Controller_Request {
use ctiso\HttpRequest;
class Request {
/** @var HttpRequest */
public $r; public $r;
/** @var string */
public $id; public $id;
/**
* @param HttpRequest $request
* @param string $id
*/
function __construct($request, $id) { function __construct($request, $id) {
$this->r = $request; $this->r = $request;
$this->id = $id; $this->id = $id;
} }
/**
* @param string $name
* @param mixed $def
* @return mixed
*/
function get($name, $def = null) { function get($name, $def = null) {
$v = $this->r->get($name); $v = $this->r->get($name);
$id = $this->id; $id = $this->id;
if ($id && is_array($v)) { if ($id && is_array($v)) {
return $v[$id] ?? $def; return isset($v[$id]) ? $v[$id] : $def;
} }
return $v; return $v;
} }

View file

@ -3,101 +3,72 @@
/** /**
* Класс сервиса = Упрощенный компонент * Класс сервиса = Упрощенный компонент
*/ */
namespace ctiso\Controller; class Controller_Service
use ctiso\Path;
use ctiso\Model\BaseMapper;
use ctiso\File;
use ctiso\Registry;
use ctiso\Database\PDOStatement;
use ctiso\Database;
class Service
{ {
/** @var array */
public $viewPath = []; public $viewPath = [];
/** @var array */
public $webPath = []; public $webPath = [];
/** @var Registry */ public $registry; // Registry->getInstance
public $config;
/** @var string */
public $template; public $template;
/** @var string */
public $templatePath; public $templatePath;
/** @var string */
public $COMPONENTS_WEB; public $COMPONENTS_WEB;
/** @var Database */
public $db; public $db;
/**
* Возвращает путь к шаблонам
* @param string $name Имя шаблона
* @return string
*/
public function getTemplatePath($name) public function getTemplatePath($name)
{ {
return Path::join($this->viewPath[0], 'templates', 'modern', $name); return Path::join($this->viewPath[0], 'templates', 'modern', $name);
} }
/**
* Возвращает путь к шаблонам
* @return string
*/
public function getTemplateWebPath() public function getTemplateWebPath()
{ {
return Path::join($this->webPath[0], strtolower(get_class($this)), 'templates', 'modern'); return Path::join($this->webPath[0], strtolower(get_class($this)), 'templates', 'modern');
} }
/** /**
* Создает модель * @param $name Имя модели
* @param class-string $modelName
* @return BaseMapper
*/ */
public function getModel($modelName) private function getModelPath($name)
{ {
/** @var BaseMapper */ return Path::join (CMS_PATH, "model", $name . ".php");
}
/**
* Создает модель
* @param string $name
* @return model
*/
public function getModel($name)
{
require_once ($this->getModelPath ($name));
$modelName = $name . "Mapper";
$model = new $modelName (); $model = new $modelName ();
$model->db = $this->db; $model->db = $this->db;
return $model; return $model;
} }
/**
* @param string $key
* @param string $val
* @param PDOStatement $res
* @return array
*/
public function options($key, $val, $res) { public function options($key, $val, $res) {
$result = []; $result = array();
while($res->next()) { while($res->next()) {
$result[] = ['value' => $res->getInt($key), 'name' => $res->getString($val)]; $result[] = array('value' => $res->getInt($key), 'name' => $res->getString($val));
} }
return $result; return $result;
} }
/**
* @param array $list
* @param bool $selected
* @return array
*/
public function optionsPair($list, $selected = false) { public function optionsPair($list, $selected = false) {
$result = []; $result = array();
foreach ($list as $key => $value) { foreach ($list as $key => $value) {
$result [] = ['value' => $key, 'name' => $value, 'selected' => $key == $selected]; $result [] = array('value' => $key, 'name' => $value, 'selected' => $key == $selected);
} }
return $result; return $result;
} }
/**
* @return array
*/
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)) {
$settings = json_decode(File::getContents($filename), true); $settings = json_decode(File::getContents($filename), true);
return $settings; return $settings;
} }
return []; return array();
} }
} }

View file

@ -1,41 +0,0 @@
<?php
namespace ctiso\Controller;
interface SiteInterface {
/**
* FIXME: Возвращает ресурс (но его тип опрделяется в App)
* @return mixed
*/
function getResource();
/**
* @return \ctiso\Database
*/
function getDatabase();
/**
* @return \ctiso\Registry
*/
function getConfig();
/**
* @return \ctiso\Settings
*/
function getTheme();
/**
* @param array $config
*/
function addComponentConfig($config): void;
function addRequireJsPath(string $name, string $path, ?array $shim = null): void;
function addStyleSheet(string $url): void;
/**
* @param string $expression
* @return ?Component
*/
function loadComponent(string $expression);
/**
* @return array{string, string, string}
*/
function findTemplate(string $name);
function replaceImg(string $src, int $width, int $height): string;
function updatePageTime(int $time): void;
}

70
src/Controller/State.php Normal file
View file

@ -0,0 +1,70 @@
<?php
class Controller_State
{
public $action = '';
public $states = array();
public $titles = array();
public function __construct($action)
{
$this->action = $action;
}
static function make($action)
{
return new Controller_State($action);
}
public function addTitle($name, $url = array())
{
$this->titles [] = array($name, $url);
return $this;
}
public function addState(Controller_State $state)
{
$this->states [$state->getAction()] = $state;
return $this;
}
public function getAction()
{
return $this->action;
}
function checkAction($action, &$list)
{
if ($this->action == $action) {
array_push($list, $this);
return true;
} else {
foreach ($this->states as $state) {
if ($state->checkAction($action, $list)) {
array_push($list, $this);
return true;
}
}
}
return false;
}
function makeTitle(Controller_Action $module)
{
foreach ($this->titles as $item) {
$module->path->addMenuItem($module->nUrl($this->action, $item[1]), $item[0]);
}
}
function getPath($module, $action)
{
$list = array();
if ($this->checkAction($action, $list)) {
foreach (array_reverse($list) as $item) {
$item->makeTitle($module);
}
} else {
$this->makeTitle($module);
}
}
}

View file

@ -1,94 +1,43 @@
<?php <?php
namespace { ///<reference path="Database/PDOStatement.php" />
if (!function_exists('sqliteLower')) { require_once "Database/PDOStatement.php";
/**
* @param string $str
* @return string
*/
function sqliteLower($str)
{
return mb_strtolower($str, 'UTF-8');
}
}
}
namespace ctiso {
use PDO;
use ctiso\Database\Statement;
use ctiso\Database\PDOStatement;
use ctiso\Database\IdGenerator;
/** /**
* Класс оболочка для PDO для замены Creole * Класс оболочка для PDO для замены Creole
* @phpstan-type DSN = array{phptype: string, hostspec: string, database: string, username: string, password: string}
*/ */
class Database extends PDO class Database/*<Database_PDOStatement>*/ extends PDO
{ {
/** @var DSN */
public $dsn; public $dsn;
/**
* Создает соединение с базой данных
* @param string $dsn - DSN
* @param string|null $username - имя пользователя
* @param string|null $password - пароль
*/
public function __construct($dsn, $username = null, $password = null) public function __construct($dsn, $username = null, $password = null)
{ {
parent::__construct($dsn, $username, $password); parent::__construct($dsn, $username, $password);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $this->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->setAttribute(PDO::ATTR_STATEMENT_CLASS, [PDOStatement::class, []]); $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('Database_PDOStatement', array()));
} }
/** function prepare($sql, $args = []) {
* prepare возвращает только PDOStatement т.к установлен PDO::ERRMODE_EXCEPTION $result = parent::prepare($sql, $args);
*/
function prepare(string $sql, array $options = []): PDOStatement
{
/** @var PDOStatement */
$result = parent::prepare($sql, $options);
return $result; return $result;
} }
function query($query, $fetchMode = PDO::FETCH_INTO, mixed $_arg1 = null, mixed $_arg2 = null): PDOStatement {
/** @var PDOStatement */
$result = parent::query($query, $fetchMode);
return $result;
}
/**
* Возвращает DSN
* @return DSN
*/
public function getDSN() public function getDSN()
{ {
return $this->dsn; return $this->dsn;
} }
public function isPostgres(){
/**
* Возвращает true, если база данных Postgres
* @return bool
*/
public function isPostgres()
{
return ($this->dsn["phptype"] == "pgsql"); return ($this->dsn["phptype"] == "pgsql");
} }
/** /**
* Создает соединение с базой данных * Создает соединение с базой данных
* @param array $dsn - DSN
* @return Database|null
*/ */
static function getConnection(array $dsn) static function getConnection(array $dsn)
{ {
/** @var ?Database */
$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 = new self("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']); $connection/*: Database*/ = new static("{$dsn['phptype']}:host={$dsn['hostspec']}; $port dbname={$dsn['database']}", $dsn['username'], $dsn['password']);
if ($dsn['phptype'] == 'pgsql') { if ($dsn['phptype'] == 'pgsql') {
$connection->query('SET client_encoding="UTF-8"'); $connection->query('SET client_encoding="UTF-8"');
} }
@ -96,53 +45,45 @@ namespace ctiso {
if (isset($dsn['schema'])) { if (isset($dsn['schema'])) {
$connection->query('SET search_path TO ' . $dsn['schema']); $connection->query('SET search_path TO ' . $dsn['schema']);
} }
} elseif ($dsn['phptype'] == 'sqlite::memory') { }
$connection = new self("{$dsn['phptype']}:"); if ($dsn['phptype'] == 'sqlite') {
$connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1); $connection/*: Database*/ = new static("{$dsn['phptype']}:{$dsn['database']}");
} elseif ($dsn['phptype'] == 'sqlite') {
$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");
if(!function_exists('sqliteLower')){
function sqliteLower($str) {
return mb_strtolower($str, 'UTF-8');
}
$connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1); $connection->sqliteCreateFunction('LOWER', 'sqliteLower', 1);
} }
}
$connection->dsn = $dsn; $connection->dsn = $dsn;
return $connection; return $connection;
} }
/** public function executeQuery($query, $values=null)
* Выполняет запрос к базе данных
* @param string $query - запрос
* @param ?array<string, mixed> $values - значения
*/
public function executeQuery($query, $values = null): PDOStatement
{ {
$stmt = $this->prepare($query); $stmt/*: Database_PDOStatement*/ = $this->prepare($query);
$stmt->execute($values); $stmt->execute($values);
$stmt->cache = $stmt->fetchAll(PDO::FETCH_ASSOC); $stmt->cache = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $stmt; return $stmt;
} }
/**
* Создает подготовленный запрос
* @param string $query - запрос
* @return Statement
*/
public function prepareStatement($query) public function prepareStatement($query)
{ {
return new Statement($query, $this); return new Database_Statement($query, $this);
} }
// Для совместимости со старым представлением баз данных CIS
/** /**
* Извлекает из базы все элементы по запросу (Для совместимости со старым представлением баз данных CIS) * Извлекает из базы все элементы по запросу
* @param string $query - запрос
* @param ?array<string, mixed> $values - значения
* @return array<array<string, mixed>>
*/ */
public function fetchAllArray($query, $values = null) public function fetchAllArray($query, $values = null)
{ {
$sth = $this->prepare($query); $sth/*: Database_PDOStatement*/ = $this->prepare($query);
$prep = $this->prepareValues($values); $prep = $this->prepareValues($values);
$sth->execute($prep); $sth->execute($prep);
return $sth->fetchAll(PDO::FETCH_ASSOC); return $sth->fetchAll(PDO::FETCH_ASSOC);
@ -150,30 +91,27 @@ namespace ctiso {
/** /**
* Извлекает из базы первый элемент по запросу * Извлекает из базы первый элемент по запросу
* @param string $query - запрос
* @param ?array<string, mixed> $values - значения
* @return array<string, mixed>|false
*/ */
public function fetchOneArray($query, $values = null) public function fetchOneArray($query, $values = null)
{ {
$sth = $this->prepare($query); $sth/*: Database_PDOStatement*/ = $this->prepare($query);
$prep = $this->prepareValues($values); $prep = $this->prepareValues($values);
$sth->execute($prep); $sth->execute($prep);
return $sth->fetch(PDO::FETCH_ASSOC); return $sth->fetch(PDO::FETCH_ASSOC);
} }
/** private static function assignQuote($x, $y)
* Преобразует значения в подготовленные значения {
* @param array $values - значения return $x . "=" . $this->quote($y);
* @return ?array<string, string> }
*/
private function prepareValues($values) private function prepareValues($values)
{ {
if (!$values) { if (!$values) {
return null; return null;
} }
$pg = $this->isPostgres(); $pg = $this->isPostgres();
$prep = []; $prep = array();
foreach ($values as $key => $value) { foreach ($values as $key => $value) {
$result = null; $result = null;
if(is_bool($value)) { if(is_bool($value)) {
@ -189,14 +127,8 @@ namespace ctiso {
} }
return $prep; return $prep;
} }
/** /**
* Создает INSERT запрос * Создает INSERT запрос
* @param string $table - таблица
* @param array $values - значения
* @param bool $return_id - возвращать id
* @param string $index - индекс
* @return int|null
*/ */
function insertQuery($table, array $values, $return_id = false, $index = null) function insertQuery($table, array $values, $return_id = false, $index = null)
{ {
@ -206,7 +138,7 @@ namespace ctiso {
. ") VALUES (" . implode(",", array_keys($prep)). ")"; . ") VALUES (" . implode(",", array_keys($prep)). ")";
if ($return_id) { if ($return_id) {
if ($this->isPostgres()){ if ($this->isPostgres()){
$sql .= " RETURNING $index"; $sql = $sql." RETURNING $index";
} }
} }
$stmt = $this->prepare($sql); $stmt = $this->prepare($sql);
@ -218,42 +150,27 @@ namespace ctiso {
return $result[$index]; return $result[$index];
} else { } else {
$result = $this->fetchOneArray("SELECT $index AS lastid FROM $table WHERE OID = last_insert_rowid()"); $result = $this->fetchOneArray("SELECT $index AS lastid FROM $table WHERE OID = last_insert_rowid()");
if ($result === false) {
throw new \RuntimeException("Ошибка получения идентификатора");
}
return $result['lastid']; return $result['lastid'];
} }
} }
return null;
} }
/** /**
* Создает UPDATE запрос * Создает UPDATE запрос
* @param string $table - таблица
* @param array $values - значения
* @param string $cond - условие
*/ */
function updateQuery($table, array $values, $cond): void function updateQuery($table, array $values, $cond)
{ {
$prep = $this->prepareValues($values); $prep = $this->prepareValues($values);
$sql = "UPDATE $table SET " . implode( $sql = "UPDATE $table SET " . implode(",",
",", array_map(function($k,$v){return $k."=".$v;}, array_keys($values), array_keys($prep))) . " WHERE $cond";
array_map(function ($k, $v) {
return $k . "=" . $v; }, array_keys($values), array_keys($prep))
) . " WHERE $cond";
$stmt = $this->prepare($sql); $stmt = $this->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC); $stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute($prep); $stmt->execute($prep);
} }
/** function getIdGenerator() {
* Создает генератор идентификаторов return new Database_IdGenerator($this);
* @return IdGenerator
*/
function getIdGenerator()
{
return new IdGenerator($this);
} }
/** /**
@ -261,20 +178,13 @@ namespace ctiso {
* @param string $seq Имя последовательности для ключа таблицы * @param string $seq Имя последовательности для ключа таблицы
* @return int Идентефикатор следующей записи * @return int Идентефикатор следующей записи
*/ */
function getNextId($seq) function getNextId($seq) {
{
$result = $this->fetchOneArray("SELECT nextval('$seq')"); $result = $this->fetchOneArray("SELECT nextval('$seq')");
if ($result === false) {
throw new \RuntimeException("Ошибка получения следующего идентификатора");
}
return $result['nextval']; return $result['nextval'];
} }
/** function close()
* Закрывает соединение с базой данных
*/
function close(): void
{ {
} return null;
} }
} }

View file

@ -1,43 +1,26 @@
<?php <?php
namespace ctiso\Database; class Database_IdGenerator {
use ctiso\Database;
class IdGenerator {
/** @var Database */
private $db; private $db;
function __construct(Database $db) { function __construct(Database $db) {
$this->db = $db; $this->db = $db;
} }
/**
* @return bool
*/
function isBeforeInsert() { function isBeforeInsert() {
return false; return false;
} }
/**
* @return bool
*/
function isAfterInsert() { function isAfterInsert() {
return true; return true;
} }
/**
* @param string $seq
* @return int
*/
function getId($seq) { function getId($seq) {
if ($this->db->isPostgres()) { if ($this->db->isPostgres()) {
$result = $this->db->fetchOneArray("SELECT nextval('$seq') AS nextval"); $result = $this->db->fetchOneArray("SELECT nextval('$seq') AS nextval");
} else { } else {
$result = $this->db->fetchOneArray("SELECT last_insert_rowid() AS nextval"); $result = $this->db->fetchOneArray("SELECT last_insert_rowid() AS nextval");
} }
if (!$result) { return intval($result['nextval']);
throw new \Exception("nextval failed");
}
return (int)$result['nextval'];
} }
} }

View file

@ -1,25 +1,14 @@
<?php <?php
//Действия с базой данных согласно json файлу. //Действия с базой данных согласно json файлу.
namespace ctiso\Database; class Database_JsonInstall {
use ctiso\Database\Manager;
class JsonInstall {
/** @var Manager */
public $db_manager; public $db_manager;
/** @var array */
public $serialColumns; public $serialColumns;
public function __construct(Manager $db_manager) { public function __construct(Database_Manager $db_manager) {
$this->db_manager = $db_manager; $this->db_manager = $db_manager;
} }
/**
* Установить базу данных
* @param string $dbinit_path
* @param ?string $dbfill_path
* @return int
*/
function install($dbinit_path, $dbfill_path = null) { function install($dbinit_path, $dbfill_path = null) {
$dbinit_file = file_get_contents($dbinit_path); $dbinit_file = file_get_contents($dbinit_path);
if (is_string($dbinit_file)) { if (is_string($dbinit_file)) {
@ -38,16 +27,10 @@ class JsonInstall {
$this->fillDataBase($dbfill_path); $this->fillDataBase($dbfill_path);
} }
$this->makeConstraints($initActions); $this->makeConstraints($initActions);
return 1;
} }
/**
* Получить список таблиц, которые не существуют в базе данных
* @param array $tables
* @return array
*/
function missingTables($tables) { function missingTables($tables) {
$actual_tables = $this->db_manager->getAllTableNames(); $actual_tables = $this->db_manager->GetAllTableNames();
$missingTables = []; $missingTables = [];
foreach ($tables as $table) { foreach ($tables as $table) {
if (!in_array($table, $actual_tables)) if (!in_array($table, $actual_tables))
@ -56,13 +39,8 @@ class JsonInstall {
return $missingTables; return $missingTables;
} }
/** //Создать таблицы
* Создать таблицы function initDataBase($initActions/*: array*/, $dbinit_path) {
* @param array $initActions
* @param string $dbinit_path
* @return void
*/
function initDataBase(array $initActions, $dbinit_path) {
$pg = $this->db_manager->db->isPostgres(); $pg = $this->db_manager->db->isPostgres();
if (!$pg) { if (!$pg) {
$refs = []; $refs = [];
@ -82,17 +60,15 @@ class JsonInstall {
$table_name = $action["table_name"]; $table_name = $action["table_name"];
if (isset($refs[$table_name])) { if (isset($refs[$table_name])) {
foreach ($refs[$table_name] as $value) { foreach ($refs[$table_name] as $value) {
$action['fields'][$value['column']]['references'] = [ $action['fields'][$value['column']]['references'] =
"refTable" => $value['refTable'], $value['refTable']."(".$value['refColumn'].")";
'refColumn' => $value['refColumn']
];
} }
} }
} }
} }
if ($action["type"] != "alterReference") { if ($action["type"] != "alterReference") {
$this->db_manager->executeAction($action, $dbinit_path); $this->db_manager->ExecuteAction($action, $dbinit_path);
} }
} }
@ -114,11 +90,7 @@ class JsonInstall {
} }
} }
/** //Заполнить данными
* Заполнить данными
* @param string $dbfill_file_path
* @return void
*/
function fillDataBase($dbfill_file_path) { function fillDataBase($dbfill_file_path) {
$dbfill_file = file_get_contents($dbfill_file_path); $dbfill_file = file_get_contents($dbfill_file_path);
if (is_string($dbfill_file)) { if (is_string($dbfill_file)) {
@ -141,7 +113,7 @@ class JsonInstall {
//Выполнение действий //Выполнение действий
foreach ($actions as $action) { foreach ($actions as $action) {
$this->db_manager->executeAction($action, $dbfill_file_path); $this->db_manager->ExecuteAction($action, $dbfill_file_path);
} }
} else { } else {
echo "Invalid dbfill.json"; echo "Invalid dbfill.json";
@ -151,22 +123,18 @@ class JsonInstall {
} }
} }
/** //Обновить ключи serial и создать ограничения
* Обновить ключи serial и создать ограничения
* @param array $initActions
* @return void
*/
function makeConstraints($initActions) { function makeConstraints($initActions) {
$pg = $this->db_manager->db->isPostgres(); $pg = $this->db_manager->db->isPostgres();
if ($pg) { if ($pg) {
foreach ($this->serialColumns as $serialColumn) { foreach ($this->serialColumns as $serialColumn) {
$this->db_manager->updateSerial($serialColumn["table"], $serialColumn["column"]); $this->db_manager->UpdateSerial($serialColumn["table"], $serialColumn["column"]);
} }
foreach ($initActions as $action) { foreach ($initActions as $action) {
if ($action["type"] == "alterReference") { if ($action["type"] == "alterReference") {
$this->db_manager->executeAction($action); $this->db_manager->ExecuteAction($action);
} }
} }
} }

View file

@ -1,122 +1,33 @@
<?php <?php
namespace ctiso\Database; class Database_Manager
use ctiso\Database;
use ctiso\Tools\SQLStatementExtractor;
use ctiso\Path;
use Exception;
/**
* @phpstan-type DropAction array{
* type:"dropTable",
* table_name:string
* }
*
* @phpstan-type CreateAction array{
* type:"createTable",
* table_name:string,
* constraints?:array{fields: array<string>, type: string}|string,
* fields:array<mixed>,
* }
*
* @phpstan-type AddColumnAction array{
* type:"addColumn",
* table_name:string,
* column_name:string,
* field:ColumnProps
* }
*
* @phpstan-type AlterReferenceAction array{
* type:"alterReference",
* table:string,
* column:string,
* refTable:string,
* refColumn:string
* }
*
* @phpstan-type RenameColumnAction array{
* type:"renameColumn",
* table:string,
* old_name:string,
* new_name:string
* }
*
* @phpstan-type ExecuteFileAction array{
* type:"executeFile",
* source:string,
* pgsql:?string
* }
*
* @phpstan-type CreateViewAction array{
* type:"createView",
* view:string,
* select:string
* }
*
* @phpstan-type InsertAction array{
* type:"insert",
* table_name:string,
* values:array<mixed>
* }
*
* @phpstan-type Action DropAction
* | CreateAction
* | AddColumnAction
* | AlterReferenceAction
* | RenameColumnAction
* | ExecuteFileAction
* | CreateViewAction
* | InsertAction
*
* @phpstan-type ColumnProps array{
* name:string,
* type:string,
* not_null:bool,
* default:?string,
* references:?array{refTable:string,refColumn:string}
* }
*/
class Manager
{ {
/** @var Database */ public $db/*: Database*/;
public $db;
public function __construct(Database $db) function __construct(Database $db) {
{
$this->db = $db; $this->db = $db;
} }
/** public function ExecuteAction($action/*: array*/, $db_file = "") {
* Выполняет действие
* @param Action $action
* @param string $db_file
* @throws Exception
*/
public function executeAction(array $action, $db_file = ""): void
{
switch($action["type"]) { switch($action["type"]) {
case "dropTable": case "dropTable":
$this->dropTableQuery($action["table_name"], true); $this->DropTableQuery($action["table_name"], true);
break; break;
case "createTable": case "createTable":
$constraints = $action["constraints"] ?? null; $constraints = isset($action["constraints"]) ? $action["constraints"] : NULL;
$this->createTableQuery($action["table_name"], $action["fields"], $constraints); $this->CreateTableQuery($action["table_name"], $action["fields"], $constraints);
break; break;
case "addColumn": case "addColumn":
$this->addColumn($action["table_name"], $action["column_name"], $action["field"]); $this->AddColumn($action["table_name"], $action["column_name"], $action["field"]);
break; break;
case "insert": case "insert":
$this->db->insertQuery($action["table_name"], $action["values"]); $this->db->insertQuery($action["table_name"], $action["values"]);
break; break;
case "alterReference": case "alterReference":
$this->alterReference($action["table"], $action["column"], $action["refTable"], $action["refColumn"]); $this->AlterReference($action["table"], $action["column"], $action["refTable"], $action["refColumn"]);
break; break;
case "renameColumn": case "renameColumn":
$this->renameColumn($action["table"], $action["old_name"], $action["new_name"]); $this->RenameColumn($action["table"], $action["old_name"], $action["new_name"]);
break;
case "createView":
$this->recreateView($action["view"], $action["select"]);
break; break;
case "executeFile": case "executeFile":
if ($this->db->isPostgres() && isset($action["pgsql"])) { if ($this->db->isPostgres() && isset($action["pgsql"])) {
@ -125,7 +36,7 @@ class Manager
$file = $action["source"]; $file = $action["source"];
} }
$stmtList = SQLStatementExtractor::extractFile(Path::join(dirname($db_file), $file)); $stmtList = Tools_SQLStatementExtractor::extractFile(Path::join(dirname($db_file), $file));
foreach($stmtList as $stmt) { foreach($stmtList as $stmt) {
$this->db->executeQuery($stmt); $this->db->executeQuery($stmt);
} }
@ -136,50 +47,20 @@ class Manager
} }
} }
/** public function DropTableQuery($table, $cascade=false) {
* Дропает и создаёт SQL VIEW
* @param string $viewName
* @param string $selectStatement
*/
public function recreateView($viewName, $selectStatement): void
{
$this->db->query("DROP VIEW " . $viewName);
$this->db->query("CREATE VIEW " . $viewName . " AS " . $selectStatement);
}
/**
* Дропает таблицу
* @param string $table
* @param bool $cascade
*/
public function dropTableQuery($table, $cascade = false): void
{
$statement = "DROP TABLE IF EXISTS ".$table; $statement = "DROP TABLE IF EXISTS ".$table;
if ($this->db->isPostgres()&&$cascade) { if ($this->db->isPostgres()&&$cascade) {
$statement .= " CASCADE"; $statement = $statement." CASCADE";
} }
$this->db->query($statement); $this->db->query($statement);
} }
/** public function AlterReference($table,$column,$refTable,$refColumn) {
* Добавляет ссылку на другую таблицу $this->db->query("ALTER TABLE ".$table." ADD CONSTRAINT ".$table."_".$column."fk"." FOREIGN KEY (".$column.") REFERENCES ".$refTable." (".$refColumn.")");
* @param string $table
* @param string $column
* @param string $refTable
* @param string $refColumn
*/
public function alterReference($table, $column, $refTable, $refColumn): void
{
$this->db->query("ALTER TABLE " . $table . " ADD CONSTRAINT " . $table . "_" . $column . "fk" . " FOREIGN KEY (" . $column . ") REFERENCES " . $refTable . " (" . $refColumn . ") ON DELETE CASCADE ON UPDATE CASCADE");
} }
/** //Извлечение информации о полях таблицы
* Извлечение информации о полях таблицы public function TableInfo($table) {
* @param string $table
* @return array{type:string,not_null:bool,constraint:?string}[]|null
*/
public function tableInfo($table)
{
$pg = $this->db->isPostgres(); $pg = $this->db->isPostgres();
if ($pg) { if ($pg) {
throw new Exception("Not implemented for postgres"); throw new Exception("Not implemented for postgres");
@ -193,39 +74,32 @@ class Manager
$fields[$result["name"]] = [ $fields[$result["name"]] = [
"type"=> $result["type"], "type"=> $result["type"],
"not_null"=> boolval($result["notnull"]), "not_null"=> boolval($result["notnull"]),
"constraint" => ((bool) $result["pk"]) ? "PRIMARY KEY" : null "constraint"=> ((boolean) $result["pk"]) ? "PRIMARY KEY" : null
]; ];
} }
return $fields; return $fields;
} }
} }
/** public function RenameColumn($table, $old_name, $new_name) {
* Переименование столбца в таблице
* @param string $table
* @param string $old_name
* @param string $new_name
*/
public function renameColumn($table, $old_name, $new_name): void
{
$pg = $this->db->isPostgres(); $pg = $this->db->isPostgres();
if ($pg) { if ($pg) {
$this->db->query("ALTER TABLE ".$table." RENAME COLUMN ".$old_name." TO ".$new_name); $this->db->query("ALTER TABLE ".$table." RENAME COLUMN ".$old_name." TO ".$new_name);
} else { } else {
$tmp_table = "tmp_" . $table; $tmp_table = "tmp_" . $table;
$this->dropTableQuery($tmp_table); $this->DropTableQuery($tmp_table);
$table_info = $this->tableInfo($table); $table_info = $this->TableInfo($table);
if (isset($table_info[$new_name])) { if (isset($table_info[$new_name])) {
return; return;
} }
$data = $this->dumpTable($table); $data/*: array*/ = $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];
unset($table_info[$old_name]); unset($table_info[$old_name]);
$this->createTableQuery($table, $table_info, null); $this->CreateTableQuery($table,$table_info,null);
foreach ($data as $row) { foreach ($data as $row) {
$values = $row['values']; $values = $row['values'];
@ -233,83 +107,49 @@ class Manager
unset($values[$old_name]); unset($values[$old_name]);
$this->db->insertQuery($table, $values); $this->db->insertQuery($table, $values);
} }
$this->dropTableQuery($tmp_table); $this->DropTableQuery($tmp_table);
} }
} }
/** //Обновление ключа serial после ручной вставки
* Обновление ключа serial после ручной вставки public function UpdateSerial($table,$column) {
* @param string $table
* @param string $column
*/
public function updateSerial($table, $column): void
{
$this->db->query("SELECT setval(pg_get_serial_sequence('".$table."', '".$column."'), coalesce(max(".$column."),0) + 1, false) FROM ".$table); $this->db->query("SELECT setval(pg_get_serial_sequence('".$table."', '".$column."'), coalesce(max(".$column."),0) + 1, false) FROM ".$table);
} }
/** public function Column_Definition($name,$data,$pg){
* Возвращает определение столбца
* @param string $name
* @param ColumnProps $data
* @param bool $pg
* @return string
*/
public function columnDefinition($name, $data, $pg)
{
$constraint = isset($data['constraint'])?" ".$data['constraint']:""; $constraint = isset($data['constraint'])?" ".$data['constraint']:"";
$references = ""; $references = "";
if (isset($data['references'])) { if (isset($data['references'])) {
$references = " REFERENCES " . $data['references']['refTable'] . '(' . $data['references']['refColumn'] . ')'; $references = " REFERENCES ".$data['references'];
} }
if (isset($data["not_null"]) && $data["not_null"]) { if (isset($data["not_null"]) && $data["not_null"])
$constraint .=" NOT NULL"; $constraint .=" NOT NULL";
}
$type = $data['type']; $type = $data['type'];
if (!$pg) { if (!$pg) {
if (strtolower($type) == "serial") { if (strtolower($type)=="serial")
$type = "integer"; $type = "integer";
} //if (strtolower($type)=="boolean")
// $type = "integer";
} }
return $name." ".$type.$references.$constraint; return $name." ".$type.$references.$constraint;
} }
/** public function AddColumn($table_name,$column_name,$field){
* Добавляет столбец в таблицу
* @param string $table_name
* @param string $column_name
* @param ColumnProps $field
*/
public function addColumn($table_name, $column_name, $field): void
{
$pg = $this->db->isPostgres(); $pg = $this->db->isPostgres();
$q = "ALTER TABLE ".$table_name." ADD COLUMN ". $q = "ALTER TABLE ".$table_name." ADD COLUMN ".
$this->columnDefinition($column_name, $field, $pg); $this->Column_Definition($column_name, $field, $pg);
$this->db->query($q); $this->db->query($q);
} }
/** function getConstraintDef($c/*: array*/) {
* Возвращает определение ограничения
* @param array{fields: string[], type: string} $c
* @return string
*/
public function getConstraintDef(array $c)
{
if ($c['type'] == 'unique') { if ($c['type'] == 'unique') {
return "UNIQUE(" . implode(", ", $c['fields']) . ")"; return "UNIQUE(" . implode(", ", $c['fields']) . ")";
} }
return ""; return "";
} }
//CreateTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']])
/** public function CreateTableQuery($table, $fields, $constraints) {
* Создает таблицу
* @example createTableQuery('users',['id'=>['type'=>'integer','constraint'=>'PRIMARY KEY']])
* @param string $table
* @param array $fields
* @param array{fields: array<string>, type: string}|string|null $constraints
*/
public function createTableQuery($table, $fields, $constraints): void
{
$pg = $this->db->isPostgres(); $pg = $this->db->isPostgres();
if ($constraints) { if ($constraints) {
if (is_array($constraints)) { if (is_array($constraints)) {
@ -318,33 +158,27 @@ class Manager
$constraints = ", " . $constraints; $constraints = ", " . $constraints;
} }
$statement = "CREATE TABLE $table (" . implode( $statement = "CREATE TABLE $table (" . implode(",",
",",
array_map(function($name,$data) use ($pg) { array_map(function($name,$data) use ($pg) {
return $this->columnDefinition($name, $data, $pg); return $this->Column_Definition($name,$data,$pg);
}, array_keys($fields), array_values($fields)) }, array_keys($fields), array_values($fields))
) . " " . $constraints . ")"; ) . " " . $constraints . ")";
$this->db->query($statement); $this->db->query($statement);
} }
/** public function DumpTable($table_name) {
* Возвращает дамп таблицы
* @param string $table_name
* @return array
*/
public function dumpTable($table_name)
{
$pg = $this->db->isPostgres(); $pg = $this->db->isPostgres();
$result = []; $result/*: array*/ = array();
$data = $this->db->fetchAllArray("SELECT * FROM " . $table_name . ";"); $data/*: array*/ = $this->db->fetchAllArray("SELECT * FROM ".$table_name.";");
if (!$pg) { if (!$pg) {
$table_fields = $this->tableInfo($table_name); $table_fields = $this->TableInfo($table_name);
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) {
$row/*: array*/ = $row;
if (isset($row[$name])) { if (isset($row[$name])) {
$row[$name] = boolval($row[$name]); $row[$name] = boolval($row[$name]);
} }
@ -353,21 +187,16 @@ class Manager
} }
} }
foreach ($data as $r) { foreach ($data as $r) {
$result[] = [ $result[] = array(
"type" => "insert", "type" => "insert",
"table_name" => $table_name, "table_name" => $table_name,
"values" => $r "values" => $r
]; );
} }
return $result; return $result;
} }
/** public function GetAllTableNames() {
* Возвращает все имена таблиц
* @return list<string>
*/
public function getAllTableNames()
{
$result = []; $result = [];
if ($this->db->isPostgres()) { if ($this->db->isPostgres()) {
$query = "SELECT table_name as name FROM information_schema.tables WHERE table_schema='public'"; $query = "SELECT table_name as name FROM information_schema.tables WHERE table_schema='public'";
@ -381,16 +210,11 @@ class Manager
return $result; return $result;
} }
/** public function DumpInserts() {
* Возвращает дамп всех таблиц $table_names = $this->GetAllTableNames();
* @return array $result = array();
*/
public function dumpInserts()
{
$table_names = $this->getAllTableNames();
$result = [];
foreach ($table_names as $table_name) { foreach ($table_names as $table_name) {
$result = array_merge($result, $this->dumpTable($table_name)); $result = array_merge($result, $this->DumpTable($table_name));
} }
return $result; return $result;
} }

View file

@ -1,40 +1,23 @@
<?php <?php
namespace ctiso\Database; class Database_PDOStatement extends PDOStatement implements IteratorAggregate
use ctiso\Database\StatementIterator,
ctiso\Tools\StringUtil,
PDO;
use TheSeer\Tokenizer\Exception;
/**
* @implements \IteratorAggregate<int, array>
*/
class PDOStatement extends \PDOStatement implements \IteratorAggregate
{ {
/** @var int */
protected $cursorPos = 0; protected $cursorPos = 0;
/** @var array<int, mixed> */ public $cache = array();
public $cache = [];
/** @var ?array */
public $fields; public $fields;
function getIterator(): \Iterator { function getIterator(): Iterator {
return new StatementIterator($this); return new Database_StatementIterator($this);
} }
protected function __construct() { protected function __construct() {
} }
function rewind(): void { function rewind() {
$this->cursorPos = 0; $this->cursorPos = 0;
} }
/** public function seek($rownum) {
* @param int $rownum
* @return bool
*/
public function seek($rownum): bool {
if ($rownum < 0) { if ($rownum < 0) {
return false; return false;
} }
@ -45,19 +28,17 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate
return true; return true;
} }
function valid(): bool { function valid() {
return true; return true;
} }
/**
* @return bool
*/
public function first() { public function first() {
if($this->cursorPos !== 0) { $this->seek(0); } if($this->cursorPos !== 0) { $this->seek(0); }
return $this->next(); return $this->next();
} }
function next(): bool{ function next() {
if ($this->getRecordCount() > $this->cursorPos) { if ($this->getRecordCount() > $this->cursorPos) {
if (!isset($this->cache[$this->cursorPos])) { if (!isset($this->cache[$this->cursorPos])) {
$this->cache[$this->cursorPos] = $this->fetch(PDO::FETCH_ASSOC); $this->cache[$this->cursorPos] = $this->fetch(PDO::FETCH_ASSOC);
@ -72,87 +53,50 @@ class PDOStatement extends \PDOStatement implements \IteratorAggregate
} }
} }
function key(): int { function key() {
return $this->cursorPos; return $this->cursorPos;
} }
/**
* @return mixed
*/
function current() { function current() {
return $this->cache[$this->cursorPos]; return $this->cache[$this->cursorPos];
} }
/**
* @return array|null
*/
function getRow() { function getRow() {
return $this->fields; return $this->fields;
} }
/** function getInt($name) {
* @param string $name
* @return int
*/
function getInt($name): int {
if (!$this->fields) { if (!$this->fields) {
throw new \Exception('no fields'); throw new Error('no fields');
} }
return (int)$this->fields[$name]; return (int)$this->fields[$name];
} }
/**
* @param string $name
* @return string
*/
function getBlob($name) { function getBlob($name) {
return $this->fields[$name]; return $this->fields[$name];
} }
/**
* @param string $name
* @return string
*/
function getString($name) { function getString($name) {
return $this->fields[$name] ?? null; return isset($this->fields[$name]) ? $this->fields[$name]: null;
} }
/**
* @param string $name
* @return bool
*/
function getBoolean($name) { function getBoolean($name) {
return (bool)$this->fields[$name]; return (bool)$this->fields[$name];
} }
/**
* @param string $name
* @return mixed
*/
function get($name) { function get($name) {
return $this->fields[$name]; return $this->fields[$name];
} }
/**
* @param string $name
* @return array
*/
function getArray($name) { function getArray($name) {
return StringUtil::strToArray($this->fields[$name]); return Tools_String::strToArray($this->fields[$name]);
} }
/**
* @return int
*/
function getRecordCount() { function getRecordCount() {
return count($this->cache); return count($this->cache);
} }
/** function execute($args = null) {
* @param array $args
* @return bool
*/
function execute($args = null): bool {
$result = parent::execute($args); $result = parent::execute($args);
return $result; return $result;
} }

View file

@ -3,81 +3,45 @@
/** /**
* Класс оболочка для PDOStatement для замены Creole * Класс оболочка для PDOStatement для замены Creole
*/ */
namespace ctiso\Database; class Database_Statement
use PDO;
use ctiso\Database;
class Statement
{ {
/** @var ?int */
protected $limit = null; protected $limit = null;
/** @var ?int */
protected $offset = null; protected $offset = null;
/** @var never */
protected $statement = null; protected $statement = null;
/** @var array{int|string, mixed, int}[] */ protected $binds = array();
protected $binds = [];
/** @var Database */
protected $conn; protected $conn;
/** @var string */
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;
} }
/** function setInt($n, $value) {
* @param int|string $n $this->binds [] = array($n, $value, PDO::PARAM_INT);
* @param int $value
*/
function setInt($n, $value): void {
$this->binds [] = [$n, $value, PDO::PARAM_INT];
} }
/** function setString($n, $value) {
* @param int|string $n $this->binds [] = array($n, $value, PDO::PARAM_STR);
* @param string $value
*/
function setString($n, $value): void {
$this->binds [] = [$n, $value, PDO::PARAM_STR];
} }
/** function setBlob($n, $value) {
* @param int|string $n $this->binds [] = array($n, $value, PDO::PARAM_LOB);
* @param mixed $value
*/
function setBlob($n, $value): void {
$this->binds [] = [$n, $value, PDO::PARAM_LOB];
} }
/** function setLimit($limit) {
* @param int $limit
*/
function setLimit($limit): void {
$this->limit = $limit; $this->limit = $limit;
} }
/** function setOffset($offset) {
* @param int $offset
*/
function setOffset($offset): void {
$this->offset = $offset; $this->offset = $offset;
} }
/**
* @return PDOStatement
*/
function executeQuery() { function executeQuery() {
if ($this->limit) { if ($this->limit) {
$this->query .= " LIMIT {$this->limit} OFFSET {$this->offset}"; $this->query .= " LIMIT {$this->limit} OFFSET {$this->offset}";
} }
$stmt = $this->conn->prepare($this->query); $stmt/*: Database_PDOStatement*/ = $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

@ -1,59 +1,46 @@
<?php <?php
namespace ctiso\Database; class Database_StatementIterator implements Iterator
use PDO;
/**
* @implements \Iterator<array>
*/
class StatementIterator implements \Iterator
{ {
/** @var PDOStatement */
private $result; private $result;
/** @var int */
private $pos = 0; private $pos = 0;
/** @var int */ private $fetchmode;
private $row_count; private $row_count;
/** public function __construct($rs/*: Database_PDOStatement*/) {
* @param PDOStatement $rs
*/
public function __construct($rs) {
$this->result = $rs; $this->result = $rs;
$this->row_count = $rs->getRecordCount(); $this->row_count = $rs->getRecordCount();
} }
function rewind(): void{ function rewind() {
$this->pos = 0; $this->pos = 0;
} }
function valid(): bool { function valid() {
return ($this->pos < $this->row_count); return ($this->pos < $this->row_count);
} }
function key(): mixed { function key() {
return $this->pos; return $this->pos;
} }
function current(): mixed{ function current() {
if (!isset($this->result->cache[$this->pos])) { if (!isset($this->result->cache[$this->pos])) {
$this->result->cache[$this->pos] = $this->result->fetch(PDO::FETCH_ASSOC); $this->result->cache[$this->pos] = $this->result->fetch(PDO::FETCH_ASSOC);
} }
return $this->result->cache[$this->pos]; return $this->result->cache[$this->pos];
} }
function next(): void { function next() {
$this->pos++; $this->pos++;
} }
/** function seek($index) {
* @param int $index
*/
function seek($index): void {
$this->pos = $index; $this->pos = $index;
} }
function count(): int { function count() {
return $this->row_count; return $this->row_count;
} }
} }

View file

@ -1,21 +1,15 @@
<?php <?php
namespace ctiso\Excel; class Excel_DateTime
class DateTime
{ {
/** @var int */
public $value; public $value;
/**
* @param int $value
*/
function __construct($value) function __construct($value)
{ {
$this->value = (int)$value; $this->value = intval($value);
} }
function getString(): string function getString()
{ {
return date('Y-m-d\TH:i:s.u', $this->value); return date('Y-m-d\TH:i:s.u', $this->value);
} }

View file

@ -3,36 +3,25 @@
/** /**
* Документ * Документ
*/ */
namespace ctiso\Excel; class Excel_Document {
use XMLWriter,
Exception;
class Document {
/** @var string */
static $ns = "urn:schemas-microsoft-com:office:spreadsheet"; static $ns = "urn:schemas-microsoft-com:office:spreadsheet";
/** @var list<Table|callable> */ private $table = array ();
private $table = []; protected $styles = array();
/** @var array<string, array> */
protected $styles = [];
/** function addTable($table) {
* Добавление таблицы в документ
* @param Table|callable $table Таблица или функция, возвращающая таблицу
*/
function addTable($table): void {
$this->table [] = $table; $this->table [] = $table;
} }
/** /**
* Добавление стиля к документу * Добавление стиля к документу
* @param string $name string Имя стиля * @param $name string Имя стиля
* @param array $values array Параметры стиля * @param $values array Параметры стиля
* @param string $type Тип стиля * @param $type Тип стиля
*/ */
function setStyle ($name, array $values, $type = 'Interior'): void function setStyle ($name, array $values, $type = 'Interior')
{ {
if(!isset($this->styles[$name])) { if(!isset($this->styles[$name])) {
$this->styles[$name] = []; $this->styles[$name] = array();
} }
$this->styles[$name][$type] = $values; $this->styles[$name][$type] = $values;
} }
@ -40,8 +29,7 @@ class Document {
/** /**
* Генерация стилей * Генерация стилей
*/ */
private function createStyles (XMLWriter $doc): void private function createStyles (XMLWriter $doc) {
{
$doc->startElement('Styles'); $doc->startElement('Styles');
foreach ($this->styles as $name => $sn) { foreach ($this->styles as $name => $sn) {
$doc->startElement('Style'); $doc->startElement('Style');
@ -51,6 +39,7 @@ class Document {
if ($type == 'Borders') { if ($type == 'Borders') {
$doc->startElement('Borders'); $doc->startElement('Borders');
foreach ($s as $border) { foreach ($s as $border) {
$border/*: array*/ = $border;
$doc->startElement('Border'); $doc->startElement('Border');
foreach ($border as $key => $value) { foreach ($border as $key => $value) {
$doc->writeAttribute('ss:' . $key, $value); $doc->writeAttribute('ss:' . $key, $value);
@ -73,25 +62,21 @@ class Document {
/** /**
* Преобразует переводы строки в спец символы * Преобразует переводы строки в спец символы
* @param string $s
* @return string
*/ */
function clean ($s) { function clean ($s) {
return strtr($s, ["\n" => "&#10;"]); assert(is_string($s));
return strtr($s, array ("\n" => "&#10;"));
} }
/** /**
* Сохраняет таблицу в формате Office 2003 XML * Сохраняет таблицу в формате Office 2003 XML
* http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats * http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats
*
* @param string $filename
* @throws Exception
* @return void
*/ */
function save($filename): void function save($filename)
{ {
$doc = new XMLWriter(); $doc = new XMLWriter();
if (!$doc->openUri($filename)) { if (!$doc->openURI($filename)) {
throw new Exception("unknown file " . $filename); throw new Exception("unknown file " . $filename);
} }
$doc->setIndent(false); $doc->setIndent(false);
@ -103,7 +88,7 @@ class Document {
$this->createStyles($doc); $this->createStyles($doc);
foreach ($this->table as $table) { foreach ($this->table as $table) {
if ($table instanceof Table) { if ($table instanceof Excel_Table) {
$table->createTable($doc); $table->createTable($doc);
} else { } else {
$table_data = call_user_func($table); $table_data = call_user_func($table);

View file

@ -1,23 +1,17 @@
<?php <?php
namespace ctiso\Excel; class Excel_Number
class Number
{ {
/** @var int */
public $value; public $value;
/**
* @param int|float $value
*/
function __construct($value) function __construct($value)
{ {
$this->value = (int)($value); $this->value = (int)($value);
} }
function getString(): string function getString()
{ {
return (string) $this->value; return $this->value;
} }
} }

View file

@ -3,23 +3,12 @@
/** /**
* Клетка таблицы * Клетка таблицы
*/ */
namespace ctiso\Excel;
use XMLWriter,
ctiso\Excel\DateTime as Excel_DateTime,
ctiso\Excel\Number as Excel_Number;
class TableCell class TableCell
{ {
/** @var string|false */
public $style = false; public $style = false;
/** @var string */
public $value; public $value;
/** @var bool */
public $merge = false; public $merge = false;
/**
* @param string $value Значение клетки
*/
function __construct ($value) function __construct ($value)
{ {
$this->value = $value; $this->value = $value;
@ -31,29 +20,16 @@ class TableCell
*/ */
class TableRow class TableRow
{ {
/** @var string|false */
public $style = false; public $style = false;
/** @var TableCell[] */ public $cells = array();
public $cells = [];
/** @var int|false */
public $height = false; public $height = false;
/** function setCell($y, $value)
* Устанавливает значение для клетки
* @param int $y Номер столбца
* @param string $value Значение клетки
*/
function setCell($y, $value): void
{ {
$this->cells[$y] = new TableCell($value); $this->cells[$y] = new TableCell($value);
} }
/** function setCellStyle($y, $name)
* Устанавливает стиль для клетки
* @param int $y Номер столбца
* @param string $name Имя стиля
*/
function setCellStyle($y, $name): void
{ {
$this->cells[$y]->style = $name; $this->cells[$y]->style = $name;
} }
@ -62,51 +38,43 @@ class TableRow
/** /**
* Таблица * Таблица
*/ */
class Table class Excel_Table
{ {
/** @var int */
static $index; static $index;
/** @var string */
private $name; private $name;
/** @var TableRow[] */ private $style;
protected $rows = []; protected $rows = array();
/** @var int|false */
protected $_splitVertical = false; protected $_splitVertical = false;
/** @var int|false */
protected $_splitHorizontal = false; protected $_splitHorizontal = false;
function __construct() function __construct()
{ {
$this->name = "Page " . ((int)self::$index ++); $this->name = "Page " . intval(self::$index ++);
} }
/** /**
* Записать значение в клетку с заданными координатами * Записать значение в клетку с заданными координатами
* @param int $x Номер ряда
* @param int $y Номер столбца
* @param string $value Значение клетки
*/ */
function setCell(int $x, int $y, $value): void function setCell($x, $y, $value)
{ {
assert($x > 0); assert(is_numeric($x) && $x > 0);
assert($y > 0); assert(is_numeric($y) && $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];
$row = $this->rows[$x];
$row->setCell($y, $value); $row->setCell($y, $value);
} }
/** /**
* Заполняет ряд начиная с указанного столбца значениями из массива * Заполняет ряд начиная с указанного столбца значениями из массива
*/ */
function setRow(int $row, int $index, array $data): void function setRow($row, $index, array $data)
{ {
assert($index > 0); assert(is_numeric($index) && $index > 0);
assert($row > 0); assert(is_numeric($row) && $row > 0);
reset($data); reset($data);
for ($i = $index; $i < $index + count($data); $i++) { for ($i = $index; $i < $index + count($data); $i++) {
@ -117,63 +85,61 @@ class Table
/** /**
* Устанавливает высоту ряда * Устанавливает высоту ряда
* @param int $row Номер ряда * @param $row integer Номер ряда
* @param int $value Высота ряда * @parma $value real Высота ряда
*/ */
function setRowHeight (int $row, $value): void function setRowHeight ($row, $value)
{ {
assert($row > 0); assert(is_numeric($row) && $row > 0);
$this->rows[$row]->height = $value; $this->rows[$row]->height = $value;
} }
/** /**
* Устанавливает стиль ряда * Устанавливает стиль ряда
* @param int $row Номер ряда * @param $row integer Номер ряда
* @param string $name Имя стиля * @parma $name string Имя стиля
*/ */
function setRowStyle(int $row, $name): void function setRowStyle ($row, $name)
{ {
assert($row > 0); assert(is_numeric($row) && $row > 0);
$this->rows[$row]->style = $name; $this->rows[$row]->style = $name;
} }
/** /**
* Обьединяет клетки в строке * Обьединяет клетки в строке
* @param int $x Номер ряда * @param $row Номер ряда
* @param int $cell Номер столбца * @param $cell Номер столбца
* @param bool $merge Количество клеток для обьединения * @param $merge Количество клеток для обьединения
*/ */
function setCellMerge(int $x, int $cell, $merge): void function setCellMerge($x, $cell, $merge)
{ {
assert($x > 0); assert(is_numeric($x) && $x > 0);
assert($cell > 0); assert(is_numeric($cell) && $cell > 0);
$row = $this->rows[$x]; $row/*: TableRow*/ = $this->rows[$x];
$row->cells[$cell]->merge = $merge; $row->cells[$cell]->merge = $merge;
} }
/** /**
* Устанавливает стиль для клеток ряда * Устанавливает стиль для клеток ряда
* @param int $row Номер ряда * @param $row integer Номер ряда
* @param int $y Номер столбца * @param $y integer Номер столбца
* @param string $name Имя стиля * @parma $name string Имя стиля
*/ */
function setCellStyle ($row, $y, $name): void 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);
} }
}
/** /**
* Добавляет строку к таблице * Добавляет строку к таблице
* @return int Номер добавленной строки
*/ */
function addRow(int $index = 1, array $data = [""]) function addRow($index = 1, array $data = array(""))
{ {
assert($index > 0); assert(is_numeric($index) && $index > 0);
$offset = $this->getRows() + 1; $offset = $this->getRows() + 1;
$this->setRow($offset, $index, $data); $this->setRow($offset, $index, $data);
@ -187,9 +153,8 @@ class Table
*/ */
function getRows() function getRows()
{ {
// Высчитываем максимальный индекс, массив может быть разрежен поэтому используем array_keys $keys/*: array*/ = array_keys($this->rows);
$keys = array_keys($this->rows); return max($keys);
return $keys === [] ? 0 : max($keys);
} }
/** /**
@ -199,23 +164,23 @@ class Table
*/ */
function getRowCells(TableRow $row) function getRowCells(TableRow $row)
{ {
$keys = array_keys($row->cells); $keys/*: array*/ = array_keys($row->cells);
return $keys === [] ? 0 :max($keys); return max($keys);
} }
/** /**
* Разделяет таблицу на две части по вертикали * Разделяет таблицу на две части по вертикали
* @param int $n Количество столбцов слева * @param $n integer Количество столбцов слева
*/ */
function splitVertical($n): void { function splitVertical($n) {
$this->_splitVertical = $n; $this->_splitVertical = $n;
} }
/** /**
* Разделяет таблицу на две части по горизонтали * Разделяет таблицу на две части по горизонтали
* @param int $n Количество столбцов сверху * @param $n integer Количество столбцов сверху
*/ */
function splitHorizontal($n): void { function splitHorizontal($n) {
$this->_splitHorizontal = $n; $this->_splitHorizontal = $n;
} }
@ -226,16 +191,9 @@ class Table
* @return int * @return int
*/ */
function getColumns() { function getColumns() {
$columns = array_map($this->getRowCells(...), $this->rows); return max(array_map(array($this, 'getRowCells'), $this->rows));
return $columns === [] ? 0 : max($columns);
} }
/**
* Кодирование строки
* @deprecated Можно заменить на значение
* @param string $s Строка
* @return string
*/
function encode($s) function encode($s)
{ {
return $s; return $s;
@ -243,13 +201,8 @@ class Table
/** /**
* Генерация клетки таблицы (Переработать) * Генерация клетки таблицы (Переработать)
* @param TableCell $ncell Клетка таблицы
* @param XMLWriter $doc XMLWriter
* @param int $j Индекс клетки
* @param mixed $value Значение клетки
* @param bool $setIndex Устанавливать индекс клетки в атрибут ss:Index
*/ */
function createCell (TableCell $ncell, XMLWriter $doc, $j, mixed $value, $setIndex): void { function createCell (TableCell $ncell, XMLWriter $doc, $j, $value/*: any*/, $setIndex) {
$doc->startElement("Cell"); $doc->startElement("Cell");
if ($ncell->style) { if ($ncell->style) {
@ -257,11 +210,11 @@ class Table
} }
if ($ncell->merge) { if ($ncell->merge) {
$doc->writeAttribute('ss:MergeAcross', (string)$ncell->merge); $doc->writeAttribute('ss:MergeAcross', $ncell->merge);
} }
if ($setIndex) { if ($setIndex) {
$doc->writeAttribute('ss:Index', (string)$j); $doc->writeAttribute('ss:Index', $j);
} }
$doc->startElement("Data"); $doc->startElement("Data");
@ -277,7 +230,7 @@ class Table
} else { } else {
$doc->writeAttribute('ss:Type', "Number"); $doc->writeAttribute('ss:Type', "Number");
} }
$doc->writeCdata($value); $doc->writeCData($this->encode($value));
} }
$doc->endElement(); $doc->endElement();
$doc->endElement(); $doc->endElement();
@ -286,7 +239,7 @@ class Table
/** /**
* Генерация таблицы * Генерация таблицы
*/ */
public function createTable (XMLWriter $doc): void { public function createTable (XMLWriter $doc) {
$doc->startElement('Worksheet'); $doc->startElement('Worksheet');
$doc->writeAttribute('ss:Name', $this->name); $doc->writeAttribute('ss:Name', $this->name);
@ -294,8 +247,8 @@ class Table
$rows = $this->getRows(); $rows = $this->getRows();
$doc->startElement('Table'); $doc->startElement('Table');
$doc->writeAttribute('ss:ExpandedColumnCount', (string)$columns); $doc->writeAttribute('ss:ExpandedColumnCount', $columns);
$doc->writeAttribute('ss:ExpandedRowCount', (string)$rows); $doc->writeAttribute('ss:ExpandedRowCount', $rows);
// Переписать цыкл !!!!!!! // Переписать цыкл !!!!!!!
for ($i = 1; $i <= $rows; $i++) { for ($i = 1; $i <= $rows; $i++) {
@ -306,10 +259,10 @@ class Table
} }
if ($this->rows[$i]->height) { if ($this->rows[$i]->height) {
$doc->writeAttribute('ss:Height', (string)$this->rows[$i]->height); $doc->writeAttribute('ss:Height', $this->rows[$i]->height);
} }
/** @var TableRow $nrow */
$nrow = $this->rows[$i]; $nrow/*: TableRow*/ = $this->rows[$i];
// Флаг индикатор подстановки номера столбца // Флаг индикатор подстановки номера столбца
$setIndex = false; $setIndex = false;
for ($j = 1; $j <= $columns; $j++) { for ($j = 1; $j <= $columns; $j++) {
@ -334,24 +287,25 @@ class Table
$doc->endElement(); $doc->endElement();
} }
protected function splitPane (XMLWriter $doc): void { protected function splitPane (XMLWriter $doc) {
$doc->startElement('WorksheetOptions'); $doc->startElement('WorksheetOptions');
$doc->writeAttribute('xmlns', 'urn:schemas-microsoft-com:office:excel'); $doc->writeAttribute('xmlns', 'urn:schemas-microsoft-com:office:excel');
$doc->writeElement('FrozenNoSplit'); $doc->writeElement('FrozenNoSplit');
if ($this->_splitVertical) { if ($this->_splitVertical) {
$doc->writeElement('SplitVertical', (string) $this->_splitVertical); $doc->writeElement('SplitVertical', $this->_splitVertical);
$doc->writeElement('LeftColumnRightPane', (string) $this->_splitVertical); $doc->writeElement('LeftColumnRightPane', $this->_splitVertical);
} }
if ($this->_splitHorizontal) { if ($this->_splitHorizontal) {
$doc->writeElement('SplitHorizontal', (string) $this->_splitHorizontal); $doc->writeElement('SplitHorizontal', $this->_splitHorizontal);
$doc->writeElement('TopRowBottomPane', (string) $this->_splitHorizontal); $doc->writeElement('TopRowBottomPane', $this->_splitHorizontal);
} }
if ($this->_splitHorizontal && $this->_splitVertical) { if ($this->_splitHorizontal && $this->_splitVertical) {
$doc->writeElement('ActivePane', (string) 0); $doc->writeElement('ActivePane', 0);
} else if($this->_splitHorizontal) { } else if($this->_splitHorizontal) {
$doc->writeElement('ActivePane', (string) 2); $doc->writeElement('ActivePane', 2);
} }
$doc->endElement(); $doc->endElement();
} }
} }

View file

@ -1,16 +1,8 @@
<?php <?php
namespace ctiso;
use Exception;
class File { class File {
/**
* @param string $filename
* @return string
* @throws Exception
*/
static function getContents($filename) { static function getContents($filename) {
$buffer = @file_get_contents($filename); $buffer = file_get_contents($filename);
if ($buffer !== false) { if ($buffer !== false) {
return $buffer; return $buffer;
} }

View file

@ -3,46 +3,27 @@
/** /**
* Фильтр действий * Фильтр действий
*/ */
namespace ctiso\Filter; class Filter_ActionAccess
use ctiso\HttpRequest;
use ctiso\Role\User;
class ActionAccess
{ {
/** @var array */ public $access = array();
public $access = [];
/** @var FilterInterface */
public $processor; public $processor;
/** @var User */ public $name;
public $user;
/** function __construct($processor/*: Filter_Filter*/) {
* @param FilterInterface $processor
* @param User $user
*/
function __construct($processor, $user) {
$this->processor = $processor; $this->processor = $processor;
$this->user = $user;
} }
/** /**
* Проверка доступных действий для пользователя * Проверка доступных действий для пользователя
* !! Реализация класса проверки действий не должна быть внутри Контроллера!!! * !! Реализация класса проверки действий не должна быть внутри Контроллера!!!
* Информация о доступе может быть в файле, базе данных и т.д. * Информация о доступе может быть в файле, базе данных и т.д.
*
* @param string $action
* @return bool
*/ */
function checkAction($action) { function checkAction($action) {
// Импликация !! http://ru.wikipedia.org/wiki/Импликация // Импликация !! http://ru.wikipedia.org/wiki/Импликация
return (!isset($this->access[$action]) || in_array($this->user->access, $this->access[$action])); $name = $this->name;
return (!isset($this->access[$name][$action]) || in_array(Filter_UserAccess::$access, $this->access[$name][$action]));
} }
/**
* @param HttpRequest $request
* @return mixed
*/
function execute(HttpRequest $request) { function execute(HttpRequest $request) {
$action = $request->getAction(); $action = $request->getAction();
if(! $this->checkAction($action)) { if(! $this->checkAction($action)) {

View file

@ -1,44 +1,21 @@
<?php <?php
namespace ctiso\Filter; class Filter_ActionLogger
use ctiso\Role\UserInterface,
ctiso\HttpRequest;
/* Переделать формат Логов на список json */
class ActionLogger implements FilterInterface
{ {
/** @var array */ public $before = array();
public $before = [];
/** @var resource */
public $file; public $file;
/** @var UserInterface */
public $user;
/** @var string */
public $action; public $action;
/** @var \ctiso\Controller\ActionInterface */
public $processor; public $processor;
/** function __construct($processor/*: Filter_Filter*/) {
* @param \ctiso\Controller\ActionInterface $processor
* @param string $logPath
* @param UserInterface $user
*/
function __construct($processor, $logPath, $user) {
$this->processor = $processor; $this->processor = $processor;
$this->user = $user; $this->file = fopen(Shortcut::getUrl('access.log'), "a");
$file = fopen($logPath, "a");
if (is_resource($file)) {
$this->file = $file;
} else {
throw new \Exception('Ошибка открытия файла ' . $logPath);
}
} }
function execute(HttpRequest $request) { function execute(HttpRequest $request) {
$action = $request->getAction(); $action = $request->getAction();
if(in_array($action, $this->before)) { if(in_array($action, $this->before)) {
$line = ['time' => time(), 'user' => $this->user->getName(), 'sid' => session_id(), 'query' => array_merge($_POST, $_GET)]; $line = ['time' => time(), 'user' => Filter_UserAccess::$name, 'sid' => session_id(), 'query' => array_merge($_POST, $_GET)];
fwrite($this->file, json_encode($line) . "\n"); fwrite($this->file, json_encode($line) . "\n");
} }
return $this->processor->execute($request); return $this->processor->execute($request);

View file

@ -1,24 +1,10 @@
<?php <?php
namespace ctiso\Filter; class Filter_Authorization {
class Authorization {
const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#'; const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#';
const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign';
/** @var string */
public $group;
/** static function isLogged($group = 'access') {
* @param string $group
*/
function __construct($group) {
$this->group = $group;
}
/**
* @param string $group
*/
static function isLogged($group = 'access'): bool {
// echo session_status(); // echo session_status();
if (session_status() == PHP_SESSION_NONE) { if (session_status() == PHP_SESSION_NONE) {
session_start(); session_start();
@ -36,39 +22,31 @@ class Authorization {
return false; return false;
} }
/** static function enter($id, $group = 'access')
* @param int $id {
* @param string $group
*/
static function enter($id, $group = 'access'): void {
// $db->executeQuery("UPDATE visitor SET sid = '' WHERE id_visitor = " . $result->getInt('id_user')); // $db->executeQuery("UPDATE visitor SET sid = '' WHERE id_visitor = " . $result->getInt('id_user'));
// session_register("access"); // session_register("access");
// session_register("time"); // session_register("time");
$_SESSION [$group] = $id; // $_SESSION ["group"] = $result->getInt('access');
$_SESSION [$group] = $id; // id_user
$_SESSION [self::SESSION_BROWSER_SIGN_KEYNAME] = self::getBrowserSign(); $_SESSION [self::SESSION_BROWSER_SIGN_KEYNAME] = self::getBrowserSign();
$_SESSION ["sign"] = self::getRawSign();
$_SESSION ["time"] = time(); $_SESSION ["time"] = time();
} }
static function getRawSign(): string private static function getBrowserSign()
{ {
$rawSign = self::SESSION_BROWSER_SIGN_SECRET; $rawSign = self::SESSION_BROWSER_SIGN_SECRET;
$signParts = ['HTTP_USER_AGENT']; // $signParts = array('HTTP_USER_AGENT', 'HTTP_ACCEPT_ENCODING');
$signParts = array();
foreach ($signParts as $signPart) { foreach ($signParts as $signPart) {
$rawSign .= '::' . ($_SERVER[$signPart] ?? 'none'); $rawSign .= '::' . (isset($_SERVER[$signPart]) ? $_SERVER[$signPart] : 'none');
}
return md5($rawSign);
} }
return $rawSign; static function logout() {
}
static function getBrowserSign(): string
{
return md5(self::getRawSign());
}
function logout(): void {
session_destroy(); session_destroy();
} }
} }

View file

@ -3,21 +3,10 @@
/** /**
* Попытка реализовать фильтр для запросов * Попытка реализовать фильтр для запросов
*/ */
namespace ctiso\Filter; class Filter_Filter
use ctiso\Database;
use ctiso\HttpRequest;
use ctiso\Controller\ActionInterface;
class Filter implements ActionInterface
{ {
/** @var ActionInterface */
public $processor; public $processor;
public function __construct($processor/*: Controller_Action*/)
/**
* @param ActionInterface $processor
*/
public function __construct($processor)
{ {
$this->processor = $processor; $this->processor = $processor;
} }
@ -27,22 +16,13 @@ class Filter implements ActionInterface
return $this->processor->execute($request); return $this->processor->execute($request);
} }
/** public function getView($name, $class = 'View_Top')
* @param string $name
* @param class-string<\ctiso\View\View> $class
* @return \ctiso\View\View
*/
public function getView($name, $class = \ctiso\View\Top::class)
{ {
return $this->processor->getView($name, $class); return $this->processor->getView($name, $class);
} }
public function getConnection(): Database public function getConnection()
{ {
return $this->processor->getConnection(); return $this->processor->getConnection();
} }
public function addUrlPart($key, $value): void {
$this->processor->addUrlPart($key, $value);
}
} }

View file

@ -1,12 +0,0 @@
<?php
namespace ctiso\Filter;
use ctiso\HttpRequest;
interface FilterInterface {
/**
* @param HttpRequest $request
* @return mixed
*/
function execute(HttpRequest $request);
}

View file

@ -2,70 +2,48 @@
/** /**
* Фильтр для проверки авторизации * Фильтр для проверки авторизации
*
* action: login(password, login)
* action: logout()
*/ */
namespace ctiso\Filter;
use ctiso\Filter\Filter;
use ctiso\HttpRequest;
use ctiso\Settings;
use ctiso\Registry;
use ctiso\Database;
use ctiso\Role\User;
use ctiso\Collection;
use ctiso\Path;
use ctiso\Database\PDOStatement;
// В класс авторизации передавать обьект для управления пользователем // В класс авторизации передавать обьект для управления пользователем
// Вынести в отдельный файл // Вынести в отдельный файл
class Login extends Filter class Filter_Login extends Filter_Filter
{ {
const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#'; const SESSION_BROWSER_SIGN_SECRET = '@w3dsju45Msk#';
const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign'; const SESSION_BROWSER_SIGN_KEYNAME = 'session.app.browser.sign';
const AUTH_MAX_ATTEMPT = 10; const AUTH_MAX_ATTEMPT = 10;
const AUTH_LAST_ATTEMPT_TIMER = 600; const AUTH_LAST_ATTEMPT_TIMER = 600;
/** @var string */
public $mode = 'ajax'; public $mode = 'ajax';
/** @var PDOStatement */
public $user; public $user;
/** @var User */
public $role;
/** @var Registry */
public $config;
function __construct($processor, User $role, Registry $config) {
parent::__construct($processor);
$this->role = $role;
$this->config = $config;
}
/** /**
* Проверка авторизации * Проверка авторизации
* @param HttpRequest $request * @return Boolean Авторизовани пользователь или нет
* @return bool Авторизовани пользователь или нет
*/ */
public function isLoggin(HttpRequest $request) public function isLoggin(HttpRequest $request)
{ {
// Авторизация // Авторизация
session_start(); session_start();
$db = $this->getConnection();
Filter_UserAccess::setUp($db); // Соединение
switch ($request->getAction()) { switch ($request->getAction()) {
// Авторизация по постоянному паролю // Авторизация по постоянному паролю
case 'login': case 'login':
$login = $request->getString('login', '') ; $login = $request->get('login');
$password = $request->getString('password'); $password = $request->get('password');
$result = $this->role->getUserByLogin($login); // Поиск по логину $result = Filter_UserAccess::getUserByLogin($login); // Поиск по логину
if ($result) { if ($result) {
$userPassword = $this->role->getUserPassword($result); $userPassword = $result->getString('password');
if ($this->role->access == 'site_root' && defined('PARENT_PATH')) { if (Filter_UserAccess::$access == 'site_root' && defined('PARENT_PATH')) {
$s = new Settings(PARENT_PATH . '/settings.json'); $s = new Settings(PARENT_PATH . '/settings.json');
$s->read(); $s->read();
$dsn = $s->readKey(['system', 'dsn']); $dsn = $s->readKey(array('system', 'dsn'));
$db = Database::getConnection($dsn); $db = Database::getConnection($dsn);
$user = $db->fetchOneArray("SELECT * FROM users WHERE login = :login", ['login' => $login]); $user = $db->fetchOneArray("SELECT * FROM users WHERE login = :login", ['login' => $login]);
if ($user === false) {
return false;
}
$userPassword = $user['password']; $userPassword = $user['password'];
} /*else if (time() - $result->getInt('lastupdate') > 60*60*24*60) { } /*else if (time() - $result->getInt('lastupdate') > 60*60*24*60) {
// Проверить давность пароля, 60 дней // Проверить давность пароля, 60 дней
@ -74,23 +52,30 @@ class Login extends Filter
return false; return false;
}*/ }*/
// Проверка на количества попыток авторизации // Проверка на количества попыток авторизации
$lastAttempt = $result; $lastAttempt = $db->fetchOneArray(
"SELECT trie_count, trie_time FROM users WHERE login = :login", ['login' => $request->get('login')]);
if ($lastAttempt->get('trie_count') >= self::AUTH_MAX_ATTEMPT /*&& time() - $lastAttempt['trie_time'] < self::AUTH_LAST_ATTEMPT_TIMER*/) { if ($lastAttempt['trie_count'] >= self::AUTH_MAX_ATTEMPT /*&& time() - $lastAttempt['trie_time'] < self::AUTH_LAST_ATTEMPT_TIMER*/) {
if (time() - $lastAttempt->get('trie_time') < self::AUTH_LAST_ATTEMPT_TIMER) { if (time() - $lastAttempt['trie_time'] < self::AUTH_LAST_ATTEMPT_TIMER) {
$request->set('timeout_error', true); $request->set('timeout_error', true);
break; break;
} else { } else {
$this->role->resetTries($request->getString('login')); $db->executeQuery(
"UPDATE users SET trie_count = :count WHERE login = :login",
['count' => 0, 'login' => $request->get('login')]
);
} }
} }
// Извлечнеие пользователя из родительской CMS, для проверки пароля // Извлечнеие пользователя из родительской CMS, для проверки пароля
if (md5($password) == $userPassword) { // password if (md5($password) == $userPassword) { // password
$this->enter($result); $this->enter($db, $result);
return true; return true;
} else { } else {
// Обновление количества неудачных попыток входа // Обновление количества неудачных попыток входа
$this->role->updateTries($login); $user = $db->fetchOneArray("SELECT id_user, trie_count FROM users WHERE login = :login", ['login' => $login]);
$db->executeQuery(
"UPDATE users SET trie_time = :cur_time, trie_count = :count WHERE id_user = :id_user",
['cur_time' => time(), 'count' => $user['trie_count']+=1, 'id_user' => $user['id_user']]
);
} }
} }
$request->set('error', true); $request->set('error', true);
@ -103,22 +88,22 @@ class Login extends Filter
case 'enter': case 'enter':
$login = $request->get('login'); $login = $request->get('login');
$password = $request->get('sid'); $password = $request->get('sid');
$result = $this->role->getUserByLogin($login); // Поиск по логину $result = Filter_UserAccess::getUserByLogin($login); // Поиск по логину
if ($result) { if ($result) {
$temp = md5($result->getString('password') . $result->getString('login') . $result->getString('sid')); $temp = md5($result->getString('password') . $result->getString('login') . $result->getString('sid'));
if ($password == $temp) { if ($password == $temp) {
$this->enter($result); $this->enter($db, $result);
return true; return true;
} }
} }
break; break;
*/ */
default: default:
$hash = Authorization::getBrowserSign(); $hash = $this->getBrowserSign();
// Если $hash не совпадает $_SESSION['hash'] то удаляем сессию // Если $hash не совпадает $_SESSION['hash'] то удаляем сессию
if (isset($_SESSION ['access']) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) { if (isset($_SESSION ['access']) && isset($_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME])) {
if ($hash == $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME]) { if ($hash == $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME]) {
$this->user = $user = $this->role->getUserById($_SESSION['access']); // Поиск по идентификатору $this->user = $user = Filter_UserAccess::getUserById($_SESSION['access']); // Поиск по идентификатору
if ($user && isset($_SESSION['random']) && ($user->get('sid') == $_SESSION['random'])) { if ($user && isset($_SESSION['random']) && ($user->get('sid') == $_SESSION['random'])) {
return true; return true;
} }
@ -131,34 +116,40 @@ class Login extends Filter
return false; return false;
} }
/** private function getBrowserSign()
* Вход в систему {
* @param PDOStatement $result $rawSign = self::SESSION_BROWSER_SIGN_SECRET;
*/ //$signParts = array('HTTP_USER_AGENT', 'HTTP_ACCEPT_ENCODING');
private function enter($result): void $signParts = array();
foreach ($signParts as $signPart) {
$rawSign .= '::' . (isset($_SERVER[$signPart]) ? $_SERVER[$signPart] : 'none');
}
return md5($rawSign);
}
private function enter($db, $result)
{ {
$this->user = $result; $this->user = $result;
$random = rand(0, 1024 * 1024); $random = rand(0, 1024 * 1024);
$this->role->setSID((string)$random, $result); $db->executeQuery("UPDATE users SET sid = '$random', trie_count = 0 WHERE id_user = " . $result->getInt('id_user'));
$_SESSION["group"] = $result->getInt('access'); $_SESSION["group"] = $result->getInt('access');
$_SESSION["access"] = $result->getInt('id_user'); // id_user $_SESSION["access"] = $result->getInt('id_user'); // id_user
$_SESSION["random"] = $random; // id_user $_SESSION["random"] = $random; // id_user
$_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME] = Authorization::getBrowserSign(); $_SESSION[self::SESSION_BROWSER_SIGN_KEYNAME] = $this->getBrowserSign();
$_SESSION["time"] = time(); $_SESSION["time"] = time();
} }
/** public function execute(HttpRequest $request)
* @return mixed
*/
public function execute(HttpRequest $request): mixed
{ {
$logged = $this->isLoggin($request); $logged = $this->isLoggin($request);
if ($request->getString('action') == 'user_access') { if ($request->get('action') == 'user_access') {
if ($logged) { if ($logged) {
$result = []; $result = array();
$result['fullname'] = $this->user->getString('patronymic') . " " . $this->user->getString('firstname'); $result['fullname'] = $this->user->getString('patronymic') . " " . $this->user->getString('firstname');
$result['email'] = $this->user->getString('email'); $result['email'] = $this->user->getString('email');
$result['site'] = 187;
$result['hash'] = sha1(self::SESSION_BROWSER_SIGN_SECRET . $this->user->getString('email')); $result['hash'] = sha1(self::SESSION_BROWSER_SIGN_SECRET . $this->user->getString('email'));
return json_encode($result); return json_encode($result);
} else { } else {
@ -166,32 +157,29 @@ class Login extends Filter
} }
} }
if ($request->getString('action') == 'relogin') { if ($request->get('action') == 'relogin') {
if ($logged) { if ($logged) {
return json_encode(['result' => 'ok', 'message' => "Авторизация успешна"]); return json_encode(array('result' => 'ok', 'message' => "Авторизация успешна"));
} else { } else {
return json_encode(['result' => 'fail', 'message' => "Неправильное имя пользователя или пароль"]); return json_encode(array('result' => 'fail', 'message' => "Неправильное имя пользователя или пароль"));
} }
} }
if (!$logged) { if (!$logged) {
// Параметры при неправильной авторизации // Параметры при неправильной авторизации
// Действия по умолчанию !! Возможно переход на форму регистрации // Действия по умолчанию !! Возможно переход на форму регистрации
if ($request->getString('mode') == 'ajax') { if ($request->get('mode') == 'ajax') {
if (!$this->requestIsWhite($request)) { if (!$this->requestIsWhite($request)) {
return json_encode(['result' => 'fail', 'message' =>"NOT_AUTHORIZED"]); return json_encode(array('result' => 'fail', 'message' =>"NOT_AUTHORIZED"));
} }
} else { } else {
$request->set('module', 'login'); $request->set('module', 'login');
$request->set('mode', $this->mode); $request->set('mode', $this->mode);
} }
} else if (isset($_SERVER['HTTP_REFERER'])) { } else if (isset($_SERVER['HTTP_REFERER'])) {
$arr = []; $arr = array();
parse_str(parse_url($_SERVER['HTTP_REFERER'] ?? '', PHP_URL_QUERY) ?: '', $arr); parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $arr);
if (isset($arr['back_page']) if (isset($arr['back_page']) && $request->get('mode') != 'ajax') {
&& is_string($arr['back_page'])
&& $request->getString('mode') != 'ajax')
{
$request->redirect($arr['back_page']); $request->redirect($arr['back_page']);
} }
} }
@ -200,23 +188,20 @@ class Login extends Filter
return $text; return $text;
} }
/** /* ---------------------
* Проверка на попадание реквеста в белый список * Проверка на попадание реквеста в белый список
*/ */
public function requestIsWhite(Collection $request): bool {
public function requestIsWhite(Collection $request) {
$module = $request->get('module'); $module = $request->get('module');
$action = $request->get('action'); $action = $request->get('action');
$moduleDir = explode('\\',$module)[0]; $moduleDir = explode('_',$module)[0];
// TODO: Параметр для белого списка перенести в install.json $file = Path::join(CMS_PATH, 'modules', $moduleDir, 'filters', 'white.json');
$file = Path::join($this->config->get('system', 'path'), 'modules', $moduleDir, 'filters', 'white.json');
if (file_exists($file)) { if (file_exists($file)) {
$text = file_get_contents($file); $whiteList = json_decode(file_get_contents($file), true);
if (!$text) {
return false; if (in_array($action, $whiteList)) {
}
$whiteList = json_decode($text, true);
if (is_array($whiteList) && in_array($action, $whiteList, true)) {
return true; return true;
} }
} }

69
src/Filter/UserAccess.php Normal file
View file

@ -0,0 +1,69 @@
<?php
// Класс должен быть в библиотеке приложения
class Filter_UserAccess
{
const LIFE_TIME = 1800; // = 30min * 60sec;
static $fullname;
static $name;
static $access;
static $password;
static $id;
static $db;
protected function __construct()
{
}
public static function setUp(Database $db)
{
self::$db = $db;
}
public static function getUserByQuery(Database_Statement $stmt)
{
global $GROUPS;
$result = $stmt->executeQuery();
if ($result->next()) {
self::$access = $GROUPS[$result->getString('access')];
self::$name = $result->getString('login');
self::$id = $result->getInt('id_user');
self::$password = $result->getString('password');
self::$fullname = implode(' ', array(
$result->getString('surname'),
$result->getString('firstname'),
$result->getString('patronymic')));
return $result;
}
return null;
}
public static function getUserByLogin($login)
{
$stmt = self::$db->prepareStatement("SELECT * FROM users WHERE login = ?");
$stmt->setString(1, $login);
$result = self::getUserByQuery($stmt);
if ($result) {
$time = time();
$id = self::$id;
self::$db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время входа
}
return $result;
}
public static function getUserById($id)
{
$stmt = self::$db->prepareStatement("SELECT * FROM users WHERE id_user = ?");
$stmt->setInt(1, $_SESSION ['access']);
$result = self::getUserByQuery($stmt);
if ($result) {
$lasttime = $result->getInt('lasttime');
$time = time();
if ($time - $lasttime > self::LIFE_TIME) return null; // Вышло время сессии
$id = self::$id;
// self::$db->executeQuery("UPDATE users SET lasttime = $time WHERE id_user = $id"); // Время последнего обращения входа
}
return $result;
}
}

View file

@ -1,6 +0,0 @@
<?php
namespace ctiso\Form;
use ctiso\Form\Input;
class BrowserInput extends Input {
}

View file

@ -1,15 +0,0 @@
<?php
namespace ctiso\Form;
use ctiso\Form\Field;
class CheckBox extends Field
{
/** @var bool */
public $checked = false;
function setValue($value): void
{
$this->value = $value;
$this->checked = $value;
}
}

View file

@ -3,9 +3,6 @@
/** /**
* Поле с цветом * Поле с цветом
*/ */
namespace ctiso\Form; class Form_Color extends Form_Field
use ctiso\Form\Field;
class Color extends Field
{ {
} }

View file

@ -2,8 +2,5 @@
/** /**
* Поле с датой * Поле с датой
*/ */
namespace ctiso\Form; class Form_Date extends Form_Field {
use ctiso\Form\Field;
class Date extends Field {
} }

View file

@ -1,7 +0,0 @@
<?php
namespace ctiso\Form;
use ctiso\Form\Input;
class DateTime extends Input {
}

View file

@ -2,53 +2,27 @@
/** /**
* Элемент формы * Элемент формы
*/ */
namespace ctiso\Form; class Form_Field
use ctiso\Form\OptionsFactory;
class Field
{ {
/** @var bool */
public $hidden = false; public $hidden = false;
/** @var string */
public $name; public $name;
/** @var string */
public $label; // Метка поля public $label; // Метка поля
/** @var mixed */
public $value; // Значение поля public $value; // Значение поля
/** @var string */
public $type = ""; // Каждому типу элемента соответствует макрос TAL public $type = ""; // Каждому типу элемента соответствует макрос TAL
/** @var ?string */
public $error_msg = null; public $error_msg = null;
/** @var ?mixed */
public $default = null; public $default = null;
/** @var bool */
public $error = false; public $error = false;
/** @var bool */
public $require = false; public $require = false;
/** @var ?string */
public $hint = null; public $hint = null;
/** @var ?int */
public $maxlength = null;
/** @var ?string */
public $fieldset = null; public $fieldset = null;
// Блоки (Убрать в отдельный класс!!!) // Блоки (Убрать в отдельный класс!!!)
/** @var array */ public $_title = array();
public $_title = [];
/** @var string */
public $description = ""; public $description = "";
/** @var array */ public $alias = array();
public $alias = [];
public function __construct ($input = array(), $factory = null)
/**
* @param array $input
* @param OptionsFactory|null $factory
* @phpstan-ignore-next-line
*/
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;
@ -57,22 +31,19 @@ class Field
$this->fieldset = $input['fieldset']; $this->fieldset = $input['fieldset'];
} }
// Инициализация свойст обьетка // Инициализация свойст обьетка
foreach (['label', 'name', 'type', 'description', 'maxlength'] as $name) { foreach (array('label', 'name', 'type', 'description') as $name) {
if (isset($input[$name])) { if (isset($input[$name])) {
$this->$name = $input[$name]; $this->$name = $input[$name];
} }
} }
} }
/** function setValue($value/*: any*/)
* @param mixed $value
*/
function setValue($value): void
{ {
$this->value = $value; $this->value = $value;
} }
function getId(): string function getId()
{ {
return $this->name . '_label'; return $this->name . '_label';
} }

View file

@ -4,100 +4,119 @@
* При рендеринге каждому классу соответствует шаблон (см. themes/maxim/templates/macros.html) * При рендеринге каждому классу соответствует шаблон (см. themes/maxim/templates/macros.html)
*/ */
namespace ctiso\Form; class TCheckbox extends Form_Field
{
public $checked = false;
function setValue($value)
{
$this->value = $value;
$this->checked = $value;
}
}
use ctiso\Form\Field; class TQuestionType extends Form_Select
use ctiso\Form\Select; {
use ctiso\Form\Input; function setValue($value)
use ctiso\Validator\Validator; {
use ctiso\HttpRequest; // Установить selected у options
$this->value = $value;
foreach ($this->options as &$option) {
$option['selected'] = ($option['value'] == $value);
}
}
}
class TDateTime extends Form_Input {
}
/**
* Поле для ввода пароля
*/
class TSecret extends Form_Field {
}
class TUpload extends Form_Field {
}
class THidden extends Form_Input {
public $hidden = true;
}
class TComponentBrowserInput extends Form_Input {
}
// вставка простого html
class Html_Text extends Form_Field {
}
/** /**
* Форма для ввода * Форма для ввода
*/ */
class Form { class Form_Form extends View_View {
/** @var array<Field> */ public $field = array(); //Поля формы
public $field = []; //Поля формы public $fieldsets = array(); //Группы полей (fieldset). Некоторые поля могут не принадлежать никаким группам
/** @var array */
public $fieldsets = []; //Группы полей (fieldset). Некоторые поля могут не принадлежать никаким группам
/** @var string */
public $action = ""; public $action = "";
/** @var string */
public $method = 'post'; public $method = 'post';
/** @var string */
public $header; public $header;
/** @var array */
protected $replace; protected $replace;
/** @var array */
protected $before; protected $before;
/** @var array<string> */ public $_title = array();
public $_title = []; public $alias = array();
/** @var array */ public $constructor = array();
public $alias = [];
/** @var class-string<Field>[] */
private $constructor = [];
/** /**
* Строим форму по ее структуре. Каждому типу соответствует определенный класс. * Строим форму по ее структуре. Каждому типу соответствует определенный класс.
*/ */
public function __construct() public function __construct()
{ {
$this->constructor = [ $this->constructor = array(
'input' => Input::class, 'input' => 'Form_Input',
// input с проверкой на заполненность 'inputreq' => 'Form_Input', // input с проверкой на заполненность
'inputreq' => Input::class,
'date' => Date::class,
'datereq' => Date::class,
'datetime' => DateTime::class,
'color' => Color::class, 'date' => 'Form_Date',
'textarea' => TextArea::class, 'datereq' => 'Form_Date',
'text' => TextArea::class, 'datetime' => 'TDateTime',
'multiselect' => SelectMany::class,
'select1' => SelectOne::class,
'select' => SelectOne::class,
'questiontype'=> QuestionType::class, 'color' => 'Form_Color',
'secret' => Secret::class, 'textarea' => 'Form_TextArea',
'upload' => Upload::class, 'text' => 'Form_TextArea',
'image' => Upload::class, 'multiselect' => 'Form_SelectMany',
'checkbox' => CheckBox::class, // 'selectmany' => 'TSelectMany',
'checkmany' => SelectMany::class, 'select1' => 'Form_SelectOne',
'hidden' => Hidden::class, 'select' => 'Form_SelectOne',
'radio' => SelectOne::class, 'questiontype'=> 'TQuestionType',
'filebrowser' => BrowserInput::class, 'secret' => 'TSecret',
'documents' => BrowserInput::class, 'upload' => 'TUpload',
'chooser' => Input::class, 'image' => 'TUpload',
'select_chooser' => SelectOne::class, 'checkbox' => 'TCheckbox',
'html_text' => HtmlText::class 'checkmany' => 'Form_SelectMany',
]; 'hidden' => 'THidden',
'radio' => 'Form_SelectOne',
'filebrowser' => 'TComponentBrowserInput',
'documents' => 'TComponentBrowserInput',
'chooser' => 'Form_Input',
'select_chooser' => 'Form_SelectOne',
'html_text' => 'Html_Text'
);
} }
function getId(): string function getId()
{ {
return '_form_edit'; return '_form_edit';
} }
/** public function addFieldClass($name, $class)
* Добавление конструкторя для поля формы
* @param string $name Краткое название поля
* @param class-string<Field> $class
*/
public function addFieldClass($name, $class): void
{ {
$this->constructor [$name] = $class; $this->constructor [$name] = $class;
} }
/** /**
* Добавляет одно поле ввода на форму * Добавляет одно поле ввода на форму
* @param array{ type: string, name: string, hint?: string } $init
* @param OptionsFactory|null $factory
*/ */
public function addField(array $init, $factory = null): Field public function addField(array $init, $factory = null)
{ {
assert(isset($init['type'])); assert(isset($init['type']));
assert(isset($init['name'])); assert(isset($init['name']));
@ -119,7 +138,8 @@ class Form {
/** /**
* Добавление fieldset на форму * Добавление fieldset на форму
*/ */
public function addFieldSet(array $fieldset): void
public function addFieldSet(array $fieldset)
{ {
$this->fieldsets[$fieldset['name']] = $fieldset; $this->fieldsets[$fieldset['name']] = $fieldset;
} }
@ -127,7 +147,8 @@ class Form {
/** /**
* Добавление массива fieldset на форму * Добавление массива fieldset на форму
*/ */
public function addFieldSetList(array $list): void
public function addFieldSetList(array $list)
{ {
foreach ($list as $fieldset) { foreach ($list as $fieldset) {
$this->addFieldSet($fieldset); $this->addFieldSet($fieldset);
@ -137,9 +158,8 @@ class Form {
/** /**
* Добавляет список полей для формы * Добавляет список полей для формы
* @param array $list * @param array $list
* @param OptionsFactory|null $factory
*/ */
public function addFieldList(array $list, $factory = null): void public function addFieldList(array $list, $factory = null)
{ {
foreach ($list as $init) { foreach ($list as $init) {
$this->addField($init, $factory); $this->addField($init, $factory);
@ -149,7 +169,7 @@ class Form {
/** /**
* Устанавливает ошибки после проверки * Устанавливает ошибки после проверки
*/ */
function setError(Validator $validator): void function setError(Validator_Validator $validator)
{ {
foreach ($validator->getErrorMsg() as $name => $error) foreach ($validator->getErrorMsg() as $name => $error)
{ {
@ -158,12 +178,7 @@ class Form {
} }
} }
/** function setFieldError($name, $message)
* Устанавливает ошибку для поля
* @param string $name
* @param string $message
*/
function setFieldError($name, $message): void
{ {
$this->field[$name]->error = true; $this->field[$name]->error = true;
$this->field[$name]->error_msg = $message; $this->field[$name]->error_msg = $message;
@ -172,8 +187,8 @@ class Form {
/** /**
* Устанавливает значения из масива * Устанавливает значения из масива
*/ */
function setValues(HttpRequest $request): void { function setValues(HttpRequest $request) {
foreach ($this->field as $key => $_) { foreach ($this->field as $key => $el) {
$value = $request->getRawData($this->method, $key); $value = $request->getRawData($this->method, $key);
$this->field[$key]->setValue($value); $this->field[$key]->setValue($value);
} }
@ -184,28 +199,20 @@ class Form {
* @param object $data * @param object $data
* @param array $schema Связь между элементами формы и свойствами обьекта * @param array $schema Связь между элементами формы и свойствами обьекта
*/ */
public function fill($data, array $schema): void public function fill($data, array $schema)
{ {
foreach ($schema as $key => $conv) { foreach ($schema as $key => $conv) {
list($value, $type) = $conv; list($value, $type) = $conv;
$convertFn = [\ctiso\Primitive::class, 'from_' . $type]; $this->field [$key]->setValue(call_user_func(array('Primitive', 'from_' . $type), $data->$value));
if (!is_callable($convertFn)) {
throw new \Exception('Не найден метод преобразования ' . $type);
}
$this->field[$key]->setValue(call_user_func($convertFn, $data->$value));
} }
} }
/** public function set($name, $value)
* @param string $name
* @param mixed $value
*/
public function set($name, $value): void
{ {
$this->field[$name]->setValue($value); $this->field[$name]->setValue($value);
} }
function execute(): self function execute()
{ {
return $this; return $this;
} }

View file

@ -1,9 +0,0 @@
<?php
namespace ctiso\Form;
use ctiso\Form\Input;
class Hidden extends Input {
/** @var bool */
public $hidden = true;
}

View file

@ -1,8 +0,0 @@
<?php
namespace ctiso\Form;
use ctiso\Form\Field;
// вставка простого html
class HtmlText extends Field {
}

View file

@ -3,8 +3,5 @@
/** /**
* Поле ввода Input * Поле ввода Input
*/ */
namespace ctiso\Form; class Form_Input extends Form_Field {
use ctiso\Form\Field;
class Input extends Field {
} }

View file

@ -0,0 +1,87 @@
<?php
class Form_OptionFactory {
public $db;
public $registry;
function __construct($db, $registry = null) {
$this->db = $db;
$this->registry = $registry;
}
function create(Form_Select $field, $input) {
if (isset($input['options.resid'])) {
$type = $input['options.resid'];
$res = new Model_Resources($this->db);
$field->options = $this->optionsArray('id_section', 'title', $res->getSubsections('', $type));
} else if (isset($input['options.res'])) {
$type = $input['options.res'];
$res = new Model_Resources($this->db);
$field->options = $this->optionsArray('path', 'title', $res->getSubsections('', $type));
} else if (isset($input['options.all_res'])) {
$type = $input['options.all_res'];
$res = new Model_Resources($this->db);
$field->options = $this->optionsArray('id_resource', 'subtitle', $res->getAllResource($type));
} else if (isset($input['options.db'])) {
list($table, $keyvalue) = explode(":", $input['options.db']);
list($key, $value) = explode(",", $keyvalue);
try {
$query_result = $this->db->executeQuery("SELECT * FROM $table");
$field->options = $this->optionsDB($key, $value, $query_result);
} catch(Exception $ex) {
$field->options = [];
}
} elseif (isset($input['options.pair'])) {
$field->options = $this->optionsPair($input['options.pair']);
} elseif (isset($input['options.model'])) {
$factory = new Model_Factory($this->db, $this->registry);
$model = $factory->getModel($input['options.model']);
$field->options = $model->getAllAsOptions();
} else {
$field->options = $input['options'];
}
if (isset($input['default'])) {
array_unshift($field->options, ['value' => 0, 'name' => $input['default']]);
}
// Ставим корневой каталог в начало списка (скорее всего он будет в конце массива)
if ($field->options)
{
$root_elem = array_pop($field->options);
if ($root_elem['value'] == '/')
array_unshift($field->options, $root_elem);
else
array_push($field->options, $root_elem);
}
}
public function optionsDB($key, $val, $res) {
$result = array();
while($res->next()) {
$result[] = array('value' => $res->getInt($key), 'name' => $res->getString($val));
}
return $result;
}
public function optionsArray($key, $val, $res) {
$result = array();
foreach($res as $item) {
$result[] = array('value' => $item->{$key}, 'name' => $item->{$val});
}
return $result;
}
public function optionsPair($list, $selected = false) {
$result = array();
foreach ($list as $key => $value) {
$result [] = array('value' => $key, 'name' => $value, 'selected' => $key == $selected);
}
return $result;
}
}

View file

@ -1,7 +0,0 @@
<?php
namespace ctiso\Form;
interface OptionsFactory {
function create(Select $field, array $options): void;
}

View file

@ -1,16 +0,0 @@
<?php
namespace ctiso\Form;
use ctiso\Form\Select;
class QuestionType extends Select
{
function setValue($value): void
{
// Установить selected у options
$this->value = $value;
foreach ($this->options as &$option) {
$option['selected'] = ($option['value'] == $value);
}
}
}

View file

@ -1,10 +0,0 @@
<?php
namespace ctiso\Form;
use ctiso\Form\Field;
/**
* Поле для ввода пароля
*/
class Secret extends Field {
}

View file

@ -1,22 +1,11 @@
<?php <?php
namespace ctiso\Form; class Form_Select extends Form_Field
use ctiso\Form\Field;
/**
* @phpstan-type Option = array{value: string, name: string, selected?: bool, class?: string|false}
*/
class Select extends Field
{ {
/** @var Option[] */ public $options = array();
public $options = [];
/**
* @param array{ options?: Option[], 'options.pair'?: array } $input
* @param OptionsFactory $factory
*/
public function __construct ($input, $factory) { public function __construct ($input, $factory) {
parent::__construct($input); parent::__construct($input, $factory);
if ($factory != null) { if ($factory != null) {
$factory->create($this, $input); $factory->create($this, $input);
@ -32,15 +21,10 @@ class Select extends Field
} }
} }
/**
* @param string[] $list
* @param bool $selected
* @return Option[]
*/
public function optionsPair($list, $selected = false) { public function optionsPair($list, $selected = false) {
$result = []; $result = array();
foreach ($list as $key => $value) { foreach ($list as $key => $value) {
$result [] = ['value' => $key, 'name' => $value, 'selected' => $key == $selected]; $result [] = array('value' => $key, 'name' => $value, 'selected' => $key == $selected);
} }
return $result; return $result;
} }

View file

@ -1,14 +1,11 @@
<?php <?php
namespace ctiso\Form; class Form_SelectMany extends Form_Select
use ctiso\Form\Select;
class SelectMany extends Select
{ {
function setValue(mixed $value): void function setValue($value)
{ {
// Установить selected у options // Установить selected у options
if (!is_array($value)) { $value = [$value]; } if (!is_array($value)) { $value = array($value); }
$this->value = $value; $this->value = $value;
foreach ($this->options as &$option) { foreach ($this->options as &$option) {
$option['selected'] = (in_array($option['value'], $value)); $option['selected'] = (in_array($option['value'], $value));

View file

@ -3,12 +3,9 @@
/** /**
* Выбор из одного элемента * Выбор из одного элемента
*/ */
namespace ctiso\Form; class Form_SelectOne extends Form_Select
use ctiso\Form\Select;
class SelectOne extends Select
{ {
function setValue($value): void function setValue($value)
{ {
// Установить selected у options // Установить selected у options
$this->value = $value; $this->value = $value;

View file

@ -3,11 +3,8 @@
/** /**
* Текстовое поле * Текстовое поле
*/ */
namespace ctiso\Form; class Form_TextArea extends Form_Field {
use ctiso\Form\Field; function setValue($value)
class TextArea extends Field {
function setValue($value): void
{ {
$this->value = $value; $this->value = $value;
} }

View file

@ -1,7 +0,0 @@
<?php
namespace ctiso\Form;
use ctiso\Form\Field;
class Upload extends Field {
}

View file

@ -4,30 +4,18 @@
* http://www.alternateinterior.com/2006/09/a-viewstate-for-php.html * http://www.alternateinterior.com/2006/09/a-viewstate-for-php.html
* Управление состоянием между страницами * Управление состоянием между страницами
*/ */
namespace ctiso\Form; class Form_ViewState // extends Collection
class ViewState // extends Collection
{ {
/** @var array */ private $values = array();
private $values = [];
/** function set($name, $value)
* Устанавливает значение
* @param string $name
* @param mixed $value
*/
function set($name, $value): void
{ {
$this->values[$name] = $value; $this->values[$name] = $value;
} }
/** function get($_rest)
* Возвращает значение
* @param string ...$args
* @return mixed
*/
function get(...$args)
{ {
$args = func_get_args();
$result = $this->values; $result = $this->values;
foreach ($args as $name) { foreach ($args as $name) {
if (!isset($result[$name])) { if (!isset($result[$name])) {
@ -38,28 +26,16 @@ class ViewState // extends Collection
return $result; return $result;
} }
/** function saveState()
* Сохраняет состояние
* @return string
*/
function saveState(): string
{ {
return base64_encode(serialize($this->values)); return base64_encode(serialize($this->values));
} }
/** function restoreState($value)
* Восстанавливает состояние
* @param string $value
*/
function restoreState($value): void
{ {
$this->values = unserialize(base64_decode($value)); $this->values = unserialize(base64_decode($value));
} }
/**
* Возвращает состояние
* @return array
*/
function export() function export()
{ {
return $this->values; return $this->values;

View file

@ -1,84 +1,59 @@
<?php <?php
namespace ctiso; /**
* Функциональное программирование в PHP
* package functional
*/
/** /**
* Эмуляция каррированой функции * Эмуляция каррированой функции
*/ */
class right { class __right {
/** @var array<mixed> */
protected $params; protected $params;
/** @var callable */
protected $fn; protected $fn;
/**
* @param array $params
*/
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() {
* Применение функции $params = func_get_args();
* @param mixed ...$params
* @return mixed
*/
function apply(...$params) {
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 {
/** @var array<mixed> */
protected $params; protected $params;
/** @var callable */
protected $fn; protected $fn;
/**
* @param array $params
*/
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() {
* Применение функции $params = func_get_args();
* @param mixed ...$params
* @return mixed
*/
function apply(...$params) {
array_splice ($params, 0, 0, $this->params); array_splice ($params, 0, 0, $this->params);
return call_user_func_array ($this->fn, $params); return call_user_func_array ($this->fn, $params);
} }
} }
define('__', '_ARGUMENT_PLACE_'); define('__', '_ARGUMENT_PLACE_');
class partial { class __partial {
/** @var array<mixed> */
protected $params; protected $params;
/** @var callable */
protected $fn; protected $fn;
/**
* @param array $params
*/
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() {
* Применение функции $params = func_get_args();
* @param mixed ...$params $result = array();
* @return mixed for($i = 0, $j = 0; $i < count($this->params); $i++) {
*/
function apply(...$params) {
$result = [];
$count = count($this->params);
for($i = 0, $j = 0; $i < $count; $i++) {
if ($this->params[$i] == __) { if ($this->params[$i] == __) {
$result [] = $params[$j]; $result [] = $params[$j];
$j++; $j++;
@ -93,26 +68,16 @@ class partial {
/** /**
* Композиция функций * Композиция функций
*/ */
class compose { class __compose {
/** @var array<callable> */
protected $fns; protected $fns;
/**
* @param array<callable> $list
*/
function __construct($list) { function __construct($list) {
$this->fns = array_reverse($list); $this->fns = array_reverse($list);
} }
/** function apply () {
* Применение функций $params = func_get_args ();
* @param mixed ...$params
* @return mixed
*/
function apply (...$params) {
$result = call_user_func_array($this->fns[0], $params); $result = call_user_func_array($this->fns[0], $params);
$count = count($this->fns); for ($i = 1; $i < count($this->fns); $i++) {
for ($i = 1; $i < $count; $i++) {
$result = call_user_func($this->fns[$i], $result); $result = call_user_func($this->fns[$i], $result);
} }
return $result; return $result;
@ -121,45 +86,42 @@ class compose {
class Functions { class Functions {
/** static function partial() {
* Частичное применение функции $closure = new __partial(func_get_args());
* @param mixed ...$args return array($closure, 'apply');
* @return mixed
*/
static function partial(...$args) {
$closure = new partial($args);
return [$closure, 'apply'];
} }
/** /**
* Композиция функций * Композиция функций
* @param mixed ...$args * @param mixed $a
* @return mixed * @param mixed $b
*
* @return array[int]mixed
*/ */
static function compose(...$args) { static function compose() {
$closure = new compose($args); $closure = new __compose(func_get_args());
return [$closure, 'apply']; return array($closure, 'apply');
} }
/** /**
* Карирование справа * Карирование справа
* @param mixed ...$args *
* @return mixed * @return array[int]mixed
*/ */
static function rcurry(...$args) { static function rcurry($_rest) {
$closure = new right($args); $closure = new __right(func_get_args ());
return [$closure, 'apply']; return array($closure, 'apply');
} }
/** /**
* Карирование слева * Карирование слева
* @param mixed ...$args *
* @return mixed * @return array[int]mixed
*/ */
static function lcurry(...$args) { static function lcurry($_rest) {
$closure = new left($args); $closure = new __left(func_get_args ());
return [$closure, 'apply']; return array($closure, 'apply');
} }
/** /**
@ -167,11 +129,11 @@ class Functions {
* @param mixed $pred Условие по которому разделяется массив * @param mixed $pred Условие по которому разделяется массив
* @param array $lst * @param array $lst
* *
* @return mixed * @return array[int]mixed
*/ */
static function partition($pred, $lst) { static function partition($pred, $lst) {
$left = []; $left = array ();
$right = []; $right = array ();
foreach ($lst as $n) { foreach ($lst as $n) {
if (call_user_func($pred, $n) !== false) { if (call_user_func($pred, $n) !== false) {
$left [] = $n; $left [] = $n;
@ -179,12 +141,11 @@ class Functions {
$right [] = $n; $right [] = $n;
} }
} }
return [$left, $right]; return array ($left, $right);
} }
/** /**
* @deprecated * @param array $value
* @param array<string, mixed> $value
* @param string $name * @param string $name
* *
* @return mixed * @return mixed
@ -193,21 +154,14 @@ class Functions {
return $value[$name]; return $value[$name];
} }
/**
* @deprecated
* @param mixed $value
*
* @return mixed
*/
static function identity($value) { static function identity($value) {
return $value; return $value;
} }
/** /**
* @deprecated use fn and <=> operator
* @param array $a * @param array $a
* @param array $b * @param array $b
* @param string|int $key * @param $key
* *
* @return int * @return int
*/ */
@ -218,14 +172,6 @@ class Functions {
return ($a[$key] > $b[$key]) ? -1 : 1; return ($a[$key] > $b[$key]) ? -1 : 1;
} }
/**
* @deprecated use fn and <=> operator
* @param array $a
* @param array $b
* @param string|int $key
*
* @return int
*/
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;
@ -233,32 +179,51 @@ class Functions {
return ($a[$key] < $b[$key]) ? -1 : 1; return ($a[$key] < $b[$key]) ? -1 : 1;
} }
/** // Сравнение по ключу массиве
* @param string ...$args static function __index($n, $key, $row) {
* @return string return ($row[$key] == $n);
*/ }
static function concat(...$args) {
static function __div($x, $y) {
return $x / $y;
}
static function __self($name, $o) {
return call_user_func(array($o, $name));
}
static function concat(/* $args ...*/) {
$args = func_get_args();
return implode("", $args); return implode("", $args);
} }
/**
* @param mixed $x
* @return bool
*/
static function __empty($x) { static function __empty($x) {
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)
* *
* @param string $key
* @param list<array>|\ArrayIterator<int, array> $array
* @return mixed * @return mixed
*/ */
static function key_values($key, $array) { static function key_values($key, /*array|ArrayIterator*/ $array) {
$result = []; $result = array();
foreach($array as $item) { foreach($array as $item) {
$result[] = $item[$key]; $result[] = $item[$key];
@ -266,13 +231,8 @@ class Functions {
return $result; return $result;
} }
/** static function key_values_object($key, /*array|ArrayIterator*/ $array) {
* @param string $key $result = array();
* @param array<object>|\ArrayIterator<int, object> $array
* @return array<mixed>
*/
static function key_values_object($key, $array) {
$result = [];
foreach($array as $item) { foreach($array as $item) {
$result[] = $item->{$key}; $result[] = $item->{$key};
@ -280,61 +240,32 @@ class Functions {
return $result; return $result;
} }
/**
* @param string $key
* @param string $value
* @param array<array<string, mixed>>|\ArrayIterator<int, array> $array
* @return array<string, mixed>
*/
static function assoc_key_values($key, $value, $array) { static function assoc_key_values($key, $value, $array) {
$result = []; $result = array();
foreach ($array as $item) { foreach ($array as $item) {
$result[$item[$key]] = $item[$value]; $result[$item[$key]] = $item[$value];
} }
return $result; return $result;
} }
/**
* @param string $key
* @param array<array<string, mixed>>|\ArrayIterator<int, array> $array
* @return array<string, mixed>
*/
static function assoc_key($key, $array) { static function assoc_key($key, $array) {
$result = []; $result = array();
foreach ($array as $item) { foreach ($array as $item) {
$result[$item[$key]] = $item; $result[$item[$key]] = $item;
} }
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) { if ($item[$key] == $value) return $item;
return $item;
}
} }
return null; return null;
} }
/**
* Возвращает ключ по значению
* @param string $key
* @param mixed $value
* @param array $array
* @return mixed
*/
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) { if ($item[$key] == $value) return $name;
return $name;
}
} }
return null; return null;
} }
@ -342,8 +273,6 @@ class Functions {
/** /**
* Логическа операция && ко всем элементам массива * Логическа операция && ко всем элементам массива
* @param array<mixed> $array Массив
* @param callable $callback Функция
* @return bool * @return bool
*/ */
static function every(array $array, $callback) { static function every(array $array, $callback) {
@ -357,11 +286,14 @@ class Functions {
/** /**
* Логическа операция || ко всем элементам массива * Логическа операция || ко всем элементам массива
* @param array<mixed> $array Массив * @param array $array
* @param callable $callback Функция * @param mixed $callback
*
* @return mixed * @return mixed
*/ */
static function some(array $array, callable $callback) { static function some(array $array, $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;
@ -370,88 +302,63 @@ class Functions {
return false; return false;
} }
/** static function span($length, array $array) {
* Разбивает массив на массивы определенной длины assert(is_int($length));
* @template T
* @param int $length Длина массива $result = array();
* @param T[] $array Массив for($i = 0; $i < count($array); $i += $length) {
* @return T[][]
*/
static function span(int $length, array $array) {
$result = [];
$count = count($array);
for($i = 0; $i < $count; $i += $length) {
$result [] = array_slice($array, $i, $length); $result [] = array_slice($array, $i, $length);
} }
return $result; return $result;
} }
/** static function array_ref($data, $n) {
* Возвращает значение массива
* @param array $data Массив
* @param string|int $n Ключ
* @return mixed
*/
static function array_ref(array $data, string|int $n) {
return $data[$n]; return $data[$n];
} }
/** static function call() {
* Вызывает функцию с аргументами $args = func_get_args();
* @param mixed ...$args Аргументы
* @return mixed
*/
static function call(...$args) {
$name = array_shift($args); $name = array_shift($args);
return call_user_func_array($name, $args); return call_user_func_array($name, $args);
} }
/** /**
* Поиск элемента в массиве * Поиск элемента в массиве
* @param callable $cb сравнение с элементом массива * @param function $cb сравнение с элементом массива
* @param array $hs массив в котором ищется значение * @param array $hs массив в котором ищется значение
* @param bool $strict
* *
* @return int|string|null ключ найденого элемента в массиве * @return int|string ключ найденого элемента в массиве
*/ */
static function array_usearch($cb, array $hs, $strict = false) { static function array_usearch($cb, array $hs, $strict = false) {
foreach($hs as $key => $value) { foreach($hs as $key => $value) if (call_user_func_array($cb, array($value, $key, $strict))) return $key;
if (call_user_func_array($cb, [$value, $key, $strict])) {
return $key;
}
}
return null;
} }
/** /**
* Выбирает все сроки из таблицы с уникальными значениями ключа * Выбирает все сроки из таблицы с уникальными значениями ключа
* @param $name Имя ключа
* @param $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
* @param string $name Имя ключа
* @param array $table Двухмерный массив
* @return array Массив с уникальными значениями ключа
*/ */
static function key_unique_values ($name, $table) { static function key_unique_values ($name, $table) {
// Ищем уникальные значения для заданного ключа // Ищем уникальные значения для заданного ключа
$keys = []; $keys = array ();
foreach ($table as $row) { foreach ($table as $row) {
if (!in_array ($row[$name], $keys)) { if (!in_array ($row[$name], $keys))
$keys[] = $row[$name]; $keys[] = $row[$name];
} }
}
return $keys; return $keys;
} }
/** /**
* Сортировка двумерного массива по заданному ключу * Сортировка двумерного массива по заданному ключу
* @param array $array Массив * @param $array Массив
* @param string $key Имя ключа по значению которого будет идти сравнение * @param $key Имя ключа по значению которого будет идти сравнение
* @param callable $fn Функция сравнения * @return Отсортированный массив
* @return array Отсортированный массив
*/ */
static function sortOn($array, $key, $fn = '\\ctiso\\Functions::__cmp') { static function sortOn($array, $key, $fn = 'Functions::__cmp') {
usort ($array, Functions::rcurry($fn, $key)); usort ($array, Functions::rcurry($fn, $key));
//usort ($array, create_function ('$x,$y', 'return __cmp ($x, $y, "'.$key.'");')); //usort ($array, create_function ('$x,$y', 'return __cmp ($x, $y, "'.$key.'");'));
return $array; return $array;
@ -459,12 +366,10 @@ class Functions {
/** /**
* Преобразует ключи элементов для многомерного массива * Преобразует ключи элементов для многомерного массива
* @param string $key_name Имя ключа
* @param array $array Многомерный массив
* @return mixed * @return mixed
*/ */
static function hash_key ($key_name, $array) { static function hash_key ($key_name,$array/*: array*/) {
$result = []; $result = array();
foreach($array as $value) { foreach($array as $value) {
$result[$value[$key_name]] = $value; $result[$value[$key_name]] = $value;

View file

@ -3,20 +3,15 @@
/** /**
* Неверный запрос * Неверный запрос
*/ */
namespace ctiso; class WrongRequestException extends Exception
use ctiso\Collection;
use ctiso\Session;
/**
* @template T=mixed
*/
class HttpRequest extends Collection
{ {
/** @var Session */ }
public $_session;
// HTTPRequest = ArrayAccess
class HttpRequest extends Collection implements ArrayAccess
{
public $_session;
/** /**
* Constructor * Constructor
* Stores "request data" in GPC order. * Stores "request data" in GPC order.
@ -42,51 +37,17 @@ class HttpRequest extends Collection
parent::set('files', $data); parent::set('files', $data);
} }
/**
* @param string $key
* @return Collection
*/
function _get($key) function _get($key)
{ {
return parent::get($key); return parent::get($key);
} }
/**
* @param string $key
* @param mixed $default
* @return null|string|array
*/
function get($key, $default = null) function get($key, $default = null)
{ {
return parent::get('data')->get($key, $default); return parent::get('data')->get($key, $default);
} }
function getString(string $key, string $default = ''): string function session(Session $value = null)
{
return parent::get('data')->getString($key, $default);
}
function getInt(string $key, int $default = 0): int
{
return parent::get('data')->getInt($key, $default);
}
function getNat(string $key, int $default = 1): int
{
return parent::get('data')->getNat($key, $default);
}
function getBool(string $key, bool $default = false): bool
{
return parent::get('data')->getBool($key, $default);
}
function getArray(string $key, array $default = []): array
{
return parent::get('data')->getArray($key, $default);
}
function session(?Session $value = null): ?Session
{ {
if ($value) { if ($value) {
$this->_session = $value; $this->_session = $value;
@ -94,25 +55,19 @@ class HttpRequest extends Collection
return $this->_session; return $this->_session;
} }
function set(string $key, mixed $value): void function set($key, $value/*: any*/)
{ {
parent::get('data')->set($key, $value); return parent::get('data')->set($key, $value);
} }
/** function export($key = 'data')
* @param string $key
* @return array<mixed>
*/
function export(string $key = 'data')
{ {
return parent::get($key)->export(); return parent::get($key)->export();
} }
function clear(): void function clear()
{ {
/** @var Collection */ return parent::get('data')->clear();
$collection = parent::get('data');
$collection->clear();
} }
/** /**
@ -122,7 +77,7 @@ class HttpRequest extends Collection
* @param string $key * @param string $key
* @return mixed * @return mixed
*/ */
public function getRawData(string $var, $key) public function getRawData($var, $key)
{ {
$data = parent::get(strtolower($var)); $data = parent::get(strtolower($var));
if ($data) { if ($data) {
@ -131,12 +86,6 @@ class HttpRequest extends Collection
return null; return null;
} }
/**
* @param string $var
* @param string $key
* @param mixed $val
* @return mixed
*/
public function setRawData($var, $key, $val) public function setRawData($var, $key, $val)
{ {
$data = parent::get(strtolower($var)); $data = parent::get(strtolower($var));
@ -145,34 +94,37 @@ class HttpRequest extends Collection
} }
} }
/** public function setAction($name)
* @param string $name
*/
public function setAction($name): void
{ {
$this->setRawData('get', 'action', $name); $this->setRawData('get', 'action', $name);
} }
public function getAction(): string public function getAction()
{ {
$result = $this->getRawData('get', 'action'); $result = $this->getRawData('get', 'action');
return ($result) ? $result : 'index'; return ($result) ? $result : 'index';
} }
public function isAjax(): bool public function isAjax()
{ {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'); return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest');
} }
/** public function redirect($url) {
* @param string $url
*/
public function redirect($url): void {
header('location: ' . $url); header('location: ' . $url);
exit(); exit();
} }
static function getProtocol(): string {
return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; public function offsetSet($key, $value) {
}
public function offsetExists($key) {
}
public function offsetUnset($key) {
}
public function offsetGet($key) {
} }
} }

View file

@ -3,15 +3,8 @@
/** /**
* Самый простой макет * Самый простой макет
*/ */
namespace ctiso\Layout; class Layout_Empty extends Filter_Filter
use ctiso\Filter\Filter,
ctiso\HttpRequest;
class Blank extends Filter
{ {
/**
* @return mixed
*/
function execute(HttpRequest $request) function execute(HttpRequest $request)
{ {
$text = $this->processor->execute($request); $text = $this->processor->execute($request);

View file

@ -4,44 +4,32 @@
* Выбор макета страницы. * Выбор макета страницы.
* Выбор оформления страницы осуществляется если было совпадение с каким либо условием * Выбор оформления страницы осуществляется если было совпадение с каким либо условием
*/ */
namespace ctiso\Layout; class Layout_Manager extends Filter_Filter
use ctiso\Filter\Filter;
use ctiso\HttpRequest;
class Manager extends Filter
{ {
/** // Массив условий с их макетами
* Массив условий с их макетами protected $condition = array();
* @var list<array{callable, Filter}>
*/
protected $condition = [];
/** /**
* Функция которая добавляет условие для проверки параметров $_GET * Функция которая добавляет условие для проверки параметров $_GET
* @param array|true $get Ассоциативный массив ключей и значений для $_GET * @param $get array() | true Ассоциативный массив ключей и значений для $_GET
* @param Filter $layout Макет *
* @example
* addConditionGet(array('module' => 'personal'), 'personal')
* addConditionGet(array('module' => 'login'), 'login')
*/ */
public function addConditionGet($get, Filter $layout): void public function addConditionGet($get, Filter_Filter $layout)
{ {
$this->addCondition(fn(HttpRequest $request) => $this->checkGet($request, $get), $layout); $this->addCondition(Functions::rcurry(array($this, 'checkGet'), $get), $layout);
} }
/** /**
* Условие для аякс запросов. Тоже самое что и addConditionGet но еще проверяется является ли запрос ajax * Условие для аякс запросов. Тоже самое что и addConditionGet но еще проверяется является ли запрос ajax
* @param array|true $get Ассоциативный массив ключей и значений для $_GET
* @param Filter $layout Макет
*/ */
public function addConditionXHR($get, Filter $layout): void public function addConditionXHR($get, Filter_Filter $layout)
{ {
$this->addCondition(fn(HttpRequest $request) => $this->checkXHR($request, $get), $layout); $this->addCondition(Functions::rcurry(array($this, 'checkXHR'), $get), $layout);
} }
/**
* @param HttpRequest $request
* @param array|true $get
* @return bool
*/
public function checkGet($request, $get) public function checkGet($request, $get)
{ {
if (is_array($get)) { if (is_array($get)) {
@ -54,44 +42,38 @@ class Manager extends Filter
return true; return true;
} }
/** public function checkXHR($request, $get)
* @param HttpRequest $request
* @param array|true $get
* @return bool
*/
public function checkXHR($request, $get): bool
{ {
return $request->isAjax() && $this->checkGet($request, $get); return $request->isAjax() && $this->checkGet($request, $get);
} }
/** /**
* Добавляет условие в общем виде * Добавляет условие в общем виде
* @param callable $get Функция * @parma $get function(HttpRequest) Функция
* @param Filter $layout Макет * @parma $layout Layout Макет
*/ */
public function addCondition($get, Filter $layout): void public function addCondition($get, Filter_Filter $layout)
{ {
$this->condition [] = [$get, $layout]; $this->condition [] = array($get, $layout);
} }
/** /**
* Выбирает и применяет макет для страницы * Выбирает и применяет макет для страницы
* @return mixed
*/ */
public function execute(HttpRequest $request): mixed public function execute(HttpRequest $request)
{ {
foreach ($this->condition as $condition) { foreach ($this->condition as $condition) {
if (call_user_func($condition[0], $request)) { if (call_user_func($condition[0], $request)) {
$layout = $condition[1]; $layout = $condition[1];
$view = $layout->execute($request); $view = $layout->execute($request);
if (is_object($view)) { if (is_object($view)) {
return $view->execute(); echo $view->render();
} else { } else {
return $view; echo $view;
}
return null;
} }
} }
} }
return '';
}
} }

View file

@ -4,75 +4,55 @@
* Класс для работы с почтой * Класс для работы с почтой
* http://en.wikipedia.org/wiki/MIME * http://en.wikipedia.org/wiki/MIME
*/ */
namespace ctiso;
use ctiso\Path,
Exception;
class Mail class Mail
{ {
/** @var string */
public $_from; public $_from;
/** @var string */
public $_to; public $_to;
/** @var string */
public $_subject; public $_subject;
/** @var string */
public $content; public $content;
/** @var string */
public $copy; public $copy;
/** @var string */
private $encoding; private $encoding;
/** @var string */
private $_notify = null; private $_notify = null;
/** @var array */
protected $attachment = array (); protected $attachment = array ();
/** @var string */
protected $uniqid; protected $uniqid;
/** @var string */
protected $type = "text/plain"; protected $type = "text/plain";
function __construct() function __construct() {
{
$this->setEncoding("UTF-8"); $this->setEncoding("UTF-8");
$this->uniqid = strtoupper(uniqid((string)time())); // Идентефикатор разделителя $this->uniqid = strtoupper(uniqid(time())); // Идентефикатор разделителя
} }
/** /**
* Установка отправителя * Установка отправителя
*/ */
function from(string $name): void function from($name)
{ {
// filter_var($name, FILTER_VALIDATE_EMAIL);
$this->_from = $name; $this->_from = $name;
} }
/** /**
* Установка получателя * Установка получателя
*/ */
function to(string $name): void function to($name) // recipient
{ {
$this->_to = $name; $this->_to = $name;
} }
/** function replyTo($name) // recipient
* @param string $name {
*/ }
function replyTo($name): void
{}
/** /**
* Установка получателей копии * Установка получателей копии
*/ */
function copy(string $name): void function copy($name) // recipient cc
{ {
$this->copy = $name; $this->copy = $name;
} }
function notify(string $notify): void function notify($notify)
{ {
$this->_notify = $notify; $this->_notify = $notify;
} }
@ -80,7 +60,7 @@ class Mail
/** /**
* Тема письма * Тема письма
*/ */
function subject(string $subject): void function subject($subject)
{ {
$this->_subject = $subject; $this->_subject = $subject;
} }
@ -88,7 +68,7 @@ class Mail
/** /**
* Текст письма * Текст письма
*/ */
function setContent(string $text): void function setContent($text)
{ {
$this->content = $text; $this->content = $text;
} }
@ -96,54 +76,43 @@ class Mail
/** /**
* Кодировка текста в письме * Кодировка текста в письме
*/ */
function setEncoding(string $encoding): void function setEncoding($encoding)
{ {
$this->encoding = $encoding; $this->encoding = $encoding;
} }
/** /**
* Добавление вложения из файла * Добавление вложения из файла
* @param string $filename
* @param string|false $name
*/ */
function addAttachment(string $filename, $name = false): void function addAttachment($filename, $name = false)
{ {
if (file_exists($filename)) { assert(is_string($filename));
if(file_exists($filename)) { // assert ??
$file = fopen($filename, "rb"); $file = fopen($filename, "rb");
if (is_resource($file)) { if (is_resource($file)) {
$size = filesize($filename); $data = fread($file, filesize($filename));
if ($size !== false && $size > 0) { $this->attachment [] = ($name) ? array($data, $name) : array($data, basename($filename));
$data = fread($file, $size);
$this->attachment[] = ($name) ? [$data, $name] : [$data, basename($filename)];
}
} }
} }
} }
/** function setType($type)
* Установка типа содержимого
* @param string $type
*/
function setType($type): void
{ {
$this->type = $type; $this->type = $type;
} }
/** /**
* Добавление вложения из строки с указанием имени файла * Добавление вложения из строки с указанием имени файла
* @param string $data
* @param string $name
*/ */
function addAttachmentRaw($data, string $name): void function addAttachmentRaw($data, $name)
{ {
$this->attachment[] = [$data, $name]; assert(is_string($name));
$this->attachment [] = array($data, $name);
} }
/** function quote($var, $val)
* @param string $var
* @param string $val
*/
function quote($var, $val): string
{ {
return ";" . PHP_EOL . "\t" . $var . "=\"" . $val . "\""; return ";" . PHP_EOL . "\t" . $var . "=\"" . $val . "\"";
} }
@ -151,24 +120,20 @@ class Mail
/** /**
* Общий формат тегов MIME * Общий формат тегов MIME
* @see http://tools.ietf.org/html/rfc2045 * @see http://tools.ietf.org/html/rfc2045
*
* @param string $name
* @param string $value
* @param array $args
*/ */
function mimeTag($name, $value, array $args = []): string function mimeTag($name, $value, array $args = array())
{ {
assert (is_string($name)); assert (is_string($name));
assert (is_string($value)); assert (is_string($value));
return $name . ": " . $value . implode("", array_map([$this, 'quote'], array_keys($args), array_values($args))) . PHP_EOL; return $name . ": " . $value . implode("", array_map(array($this, 'quote'), array_keys($args), array_values($args))) . PHP_EOL;
} }
/** /**
* *
* @see http://tools.ietf.org/html/rfc2047 * @see http://tools.ietf.org/html/rfc2047
*/ */
function encodedWord(string $text, string $encoding = 'B'): string function encodedWord($text, $encoding = 'B')
{ {
return "=?{$this->encoding}?$encoding?".base64_encode($text)."?="; return "=?{$this->encoding}?$encoding?".base64_encode($text)."?=";
} }
@ -176,10 +141,10 @@ class Mail
/** /**
* Тело сообщения * Тело сообщения
*/ */
function getMessage(): string function getMessage()
{ {
$message = "--".$this->uniqid . PHP_EOL; $message = "--".$this->uniqid . PHP_EOL;
$message .= $this->mimeTag("Content-Type", $this->type, ['charset' => $this->encoding]); $message .= $this->mimeTag("Content-Type", $this->type, array ('charset' => $this->encoding));
$message .= $this->mimeTag("Content-Transfer-Encoding", "8bit"); $message .= $this->mimeTag("Content-Transfer-Encoding", "8bit");
$message .= PHP_EOL . $this->content . PHP_EOL . PHP_EOL; $message .= PHP_EOL . $this->content . PHP_EOL . PHP_EOL;
@ -190,9 +155,9 @@ class Mail
foreach ($this->attachment as $value) { foreach ($this->attachment as $value) {
list($data, $name) = $value; list($data, $name) = $value;
$message .= "--" . $this->uniqid . PHP_EOL; $message .= "--" . $this->uniqid . PHP_EOL;
$message .= $this->mimeTag("Content-Type", "application/octet-stream", ['name' => basename($name)]); $message .= $this->mimeTag("Content-Type", "application/octet-stream", array ('name' => basename($name)));
$message .= $this->mimeTag("Content-Transfer-Encoding", "base64"); $message .= $this->mimeTag("Content-Transfer-Encoding", "base64");
$message .= $this->mimeTag("Content-Disposition", "attachment", ['filename' => basename($name)]); $message .= $this->mimeTag("Content-Disposition", "attachment", array ('filename' => basename($name)));
$message .= PHP_EOL . chunk_split(base64_encode($data)) . PHP_EOL; $message .= PHP_EOL . chunk_split(base64_encode($data)) . PHP_EOL;
} }
@ -202,7 +167,7 @@ class Mail
/** /**
* Заголовок сообщения * Заголовок сообщения
*/ */
function getHeader(): string function getHeader()
{ {
$head = $this->mimeTag("MIME-Version", "1.0"); $head = $this->mimeTag("MIME-Version", "1.0");
$head .= $this->mimeTag("From", $this->_from); $head .= $this->mimeTag("From", $this->_from);
@ -211,7 +176,7 @@ class Mail
if (is_string($this->_notify)) { if (is_string($this->_notify)) {
$head .= $this->mimeTag("Disposition-Notification-To", "\"" . $this->_notify . "\" <" . $this->_from . ">"); $head .= $this->mimeTag("Disposition-Notification-To", "\"" . $this->_notify . "\" <" . $this->_from . ">");
} }
$head .= $this->mimeTag("Content-Type", "multipart/mixed", ["boundary" => $this->uniqid]); $head .= $this->mimeTag("Content-Type", "multipart/mixed", array ("boundary" => $this->uniqid));
if ($this->copy) { if ($this->copy) {
$head .= $this->mimeTag("BCC", $this->copy); $head .= $this->mimeTag("BCC", $this->copy);
} }
@ -219,7 +184,7 @@ class Mail
return $head; return $head;
} }
function getSubject(): string function getSubject()
{ {
return $this->encodedWord($this->_subject); return $this->encodedWord($this->_subject);
} }
@ -227,7 +192,7 @@ class Mail
/** /**
* Вывод строки для сохранения в формате .eml * Вывод строки для сохранения в формате .eml
*/ */
function eml(): string function eml()
{ {
return "To: " . $this->_to . PHP_EOL . "Subject: {$this->getSubject()}" . PHP_EOL . $this->getHeader() . $this->getMessage(); return "To: " . $this->_to . PHP_EOL . "Subject: {$this->getSubject()}" . PHP_EOL . $this->getHeader() . $this->getMessage();
} }
@ -235,7 +200,7 @@ class Mail
/** /**
* Отправка почты * Отправка почты
*/ */
function send(): bool function send()
{ {
$result = mail($this->_to, $this->getSubject(), $this->getMessage(), $this->getHeader()); $result = mail($this->_to, $this->getSubject(), $this->getMessage(), $this->getHeader());
if(! $result) { if(! $result) {
@ -245,11 +210,10 @@ class Mail
return $result; return $result;
} }
function clear(): void function clear() {
{
foreach ($this->attachment as $key => &$value) { foreach ($this->attachment as $key => &$value) {
unset($this->attachment[$key]); unset($this->attachment[$key]);
} }
$this->attachment = []; $this->attachment = array();
} }
} }

View file

@ -1,15 +1,9 @@
<?php <?php
namespace ctiso;
use PHPMailer\PHPMailer\PHPMailer;
class MailAlt class MailAlt
{ {
/** @var PHPMailer */
public $mailer; public $mailer;
/** @var string */
public $_notify; public $_notify;
/** @var string */
public $encoding; public $encoding;
function __construct() { function __construct() {
@ -20,7 +14,7 @@ class MailAlt
/** /**
* Установка отправителя * Установка отправителя
*/ */
function from(string $name): void function from($name)
{ {
$this->mailer->setFrom($name); $this->mailer->setFrom($name);
} }
@ -28,49 +22,46 @@ class MailAlt
/** /**
* Установка получателя * Установка получателя
*/ */
function to(string $name): void // recipient function to($name) // recipient
{ {
$this->mailer->addAddress($name); $this->mailer->addAddress($name);
} }
function replyTo(string $name): void // recipient function replyTo($name) // recipient
{ {
$this->mailer->addReplyTo($name); $this->mailer->AddReplyTo($name);
} }
/** /**
* Установка получателей копии * Установка получателей копии
* @param string $name
*/ */
function copy(string $name): void // recipient cc function copy($name) // recipient cc
{ {
$this->mailer->addCC($name); $this->mailer->addCC($name);
} }
function notify(string $notify): void function notify($notify)
{ {
$this->_notify = $notify; $this->_notify = $notify;
} }
/** /**
* Тема письма * Тема письма
* @param string $subject
*/ */
function subject(string $subject): void function subject($subject/*: string*/)
{ {
$this->mailer->Subject = $subject; $this->mailer->Subject = $subject;
} }
/** /**
* Текст письма * Текст письма
* @param string $text
*/ */
function setContent(string $text): void function setContent($text)
{ {
$this->mailer->Body = $text; $this->mailer->Body = $text;
} }
function setType(string $text): void function setType($text)
{ {
$this->mailer->isHTML($text == 'text/html'); $this->mailer->isHTML($text == 'text/html');
} }
@ -78,7 +69,7 @@ class MailAlt
/** /**
* Кодировка текста в письме * Кодировка текста в письме
*/ */
function setEncoding(string $encoding): void function setEncoding($encoding)
{ {
$this->encoding = $encoding; $this->encoding = $encoding;
} }
@ -86,7 +77,7 @@ class MailAlt
/** /**
* Добавление вложения из файла * Добавление вложения из файла
*/ */
function addAttachment(string $filename, ?string $name = null): void function addAttachment($filename, $name = null)
{ {
$this->mailer->addAttachment($filename, $name); $this->mailer->addAttachment($filename, $name);
} }
@ -94,12 +85,12 @@ class MailAlt
/** /**
* Отправка почты * Отправка почты
*/ */
function send(): bool function send()
{ {
return $this->mailer->send(); return $this->mailer->send();
} }
function eml(): string { function eml() {
return $this->mailer->getSentMIMEMessage(); return $this->mailer->getSentMIMEMessage();
} }
} }

View file

@ -1,12 +0,0 @@
<?php
namespace ctiso\Model;
/**
* @property \ctiso\Database $db
*/
abstract class BaseMapper {
function getAllAsOptions(): array {
return [];
}
}

View file

@ -1,40 +1,30 @@
<?php <?php
namespace ctiso\Model; class Model_Factory
use ctiso\Registry;
use ctiso\Database;
use ctiso\Role\User;
class Factory
{ {
/** @var Database */ static $shortcut = "model";
public $db; public $db;
/** @var ?Registry */ public $_registry;
public $config; public $_shortcut;
/** @var ?User */
public $user;
public function __construct(Database $db, ?Registry $config = null, ?User $user = null) public function __construct ($db/*: Database*/, Settings $_registry = null)
{ {
$this->db = $db; $this->db = $db;
$this->config = $config; $this->_registry = $_registry;
$this->user = $user;
} }
/** /**
* Создает модель * Создает модель
* @template T * @param string $name
* @param class-string<T> $modelName * @return model
* @return T
*/ */
public function getModel($modelName) public function getModel ($name)
{ {
$modelName = "Mapper_" . $name;
$model = new $modelName(); $model = new $modelName();
$model->db = $this->db; $model->db = $this->db;
$model->factory = $this; $model->factory = $this;
$model->config = $this->config; $model->_registry = $this->_registry;
$model->user = $this->user;
$model->setUp(); $model->setUp();
// //
return $model; return $model;

View file

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

@ -6,22 +6,19 @@
* *
*/ */
namespace ctiso;
class Path class Path
{ {
const SEPARATOR = "/"; const SEPARATOR = "/";
protected array $path = []; protected $path = array();
protected array $url = []; protected $url = array();
protected bool $absolute = false; protected $absolute = false;
/** public function __construct($path)
* @param string $path Путь (Тип указан в doccomments т.к откудато приходит null)
*/
public function __construct($path = '')
{ {
$this->url = parse_url($path) ?: []; // assert(is_string($path));
$this->url = parse_url($path);
if (isset($this->url['path'])) { if (isset($this->url['path'])) {
$path = $this->url['path']; $path = $this->url['path'];
@ -38,16 +35,16 @@ class Path
} }
} }
static function factory(string $path): Path { static function factory($path) {
return new Path($path); return new Path($path);
} }
public function getParts(): array public function getParts()
{ {
return $this->path; return $this->path;
} }
public static function normalize(string $pathName): string public static function normalize($pathName)
{ {
$path = new Path($pathName); $path = new Path($pathName);
return $path->__toString(); return $path->__toString();
@ -55,12 +52,12 @@ class Path
/** /**
* Базовое имя * Базовое имя
* @param string $path * @param $path
* @return string * @return mixed
*/ */
public static function basename($path) public static function basename($path)
{ {
$list = preg_split('#\\\\|/#s', $path) ?: ['']; $list = preg_split('#\\\\|/#s', $path);
return end($list); return end($list);
} }
@ -68,19 +65,16 @@ class Path
* Возвращает расширение файла * Возвращает расширение файла
* *
* @param string $fileName Полное имя файла * @param string $fileName Полное имя файла
*
* @return string * @return string
*/ */
static function getExtension($fileName) static function getExtension($fileName)
{ {
assert(is_string($fileName) || is_null($fileName));
return pathinfo($fileName, PATHINFO_EXTENSION); return pathinfo($fileName, PATHINFO_EXTENSION);
} }
/**
* Проверяет расширение файла
* @param string $fileName Полное имя файла
* @param string|array $extension Расширение файла
* @return bool
*/
static function isType($fileName, $extension) static function isType($fileName, $extension)
{ {
if (is_array($extension)) { if (is_array($extension)) {
@ -92,11 +86,17 @@ class Path
/** /**
* Полное имя файла без расширения * Полное имя файла без расширения
*
* @param string $fileName Имя файла
*
* @return string
*/ */
static function skipExtension(string $fileName): string static function skipExtension($fileName)
{ {
assert(is_string($fileName));
$path = pathinfo($fileName); $path = pathinfo($fileName);
if (!isset($path['dirname']) || $path['dirname'] === ".") { if ($path['dirname'] == ".") {
return $path['filename']; return $path['filename'];
} else { } else {
return self::join($path['dirname'], $path['filename']); return self::join($path['dirname'], $path['filename']);
@ -107,10 +107,13 @@ class Path
* Возвращает имя файла без расширения * Возвращает имя файла без расширения
* *
* @param string $fileName Полное имя файла * @param string $fileName Полное имя файла
*
* @return string * @return string
*/ */
static function getFileName(string $fileName) static function getFileName($fileName)
{ {
assert(is_string($fileName));
return pathinfo($fileName, PATHINFO_FILENAME); return pathinfo($fileName, PATHINFO_FILENAME);
} }
@ -120,45 +123,45 @@ class Path
* Преобразует строку пути в массив * Преобразует строку пути в массив
* *
* @param string $path Путь * @param string $path Путь
* @return list<string> *
* @return array
*/ */
public static function listFromString(string $path): array public static function listFromString($path)
{ {
assert(is_string($path));
$list = preg_split('#\\\\|/#s', $path); $list = preg_split('#\\\\|/#s', $path);
return $list ?: [];
return $list;
} }
/** /**
* Преобразует относительный путь в абсолютный * Преобразует относительный путь в абсолютный
* @param array<string> $path Путь
* @return array<string>
*/ */
public static function optimize($path) // public static function optimize($path) //
{ {
$result = []; $result = array();
foreach ($path as $n) { foreach ($path as $n) {
switch ($n) { switch ($n) {
// Может быть относительным или абсолютным путем // Может быть относительным или абсолютным путем
case "": case ".": break; case "": break;
case ".": break;
case "..": case "..":
if (count($result) > 0 && $result[count($result) - 1] != '..') { if (count($result) > 0 && $result[count($result) - 1] != '..') {
array_pop($result); break; array_pop($result); break;
} }
default: default:
$result[] = $n; array_push($result, $n);
} }
} }
return $result; return $result;
} }
/** // Сравнение двух путей на равентство
* Сравнение двух путей на равентство public function equal($path/*: Path*/)
*/
public function equal(Path $path): bool
{ {
$count = count($this->path); if (count($this->path) == count($path->path)) {
if ($count == count($path->path)) { for ($i = 0; $i < count($this->path); $i++) {
for ($i = 0; $i < $count; $i++) {
if ($this->path[$i] != $path->path[$i]) { if ($this->path[$i] != $path->path[$i]) {
return false; return false;
} }
@ -168,29 +171,27 @@ class Path
return false; return false;
} }
/** public static function makeUrl($path)
* Преобразует путь в строку
* @param array{ host?: string, path?: string, query?: string, fragment?: string, scheme?: string, user?: string, pass?: string, port?: int} $path Путь
*/
public static function makeUrl($path): string
{ {
$slash = (isset($path['host']) && isset($path['path']) && (strlen($path['path']) > 0) && ($path['path'][0] != '/')) ? '/' : ''; $slash = (isset($path['host']) && (strlen($path['path']) > 0) && ($path['path'][0] != '/')) ? '/' : '';
$scheme = isset($path['scheme']) ? $path['scheme'] . ':/' : '';
$user = isset($path['user']) ? $path['user'] . (isset($path['pass']) ? ':' . $path['pass'] : '') . '@' : '';
$port = isset($path['port']) ? ':' . $path['port'] : ''; return (isset($path['scheme']) ? $path['scheme'] . ':/' : '')
$host = isset($path['host']) ? ('/' . $user . $path['host'] . $port) : ''; . (isset($path['host']) ? ('/'
. (isset($path['user']) ? $path['user'] . (isset($path['pass']) ? ':' . $path['pass'] : '') . '@' : '')
$query = isset($path['query']) ? '?' . $path['query'] : ''; . $path['host']
$fragment = isset($path['fragment']) ? '#' . $path['fragment'] : ''; . (isset($path['port']) ? ':' . $path['port'] : '')) : '')
. $slash
return $scheme . $host . $slash . ($path['path'] ?? '') . $query . $fragment; . $path['path']
. (isset($path['query']) ? '?' . $path['query'] : '')
. (isset($path['fragment']) ? '#' . $path['fragment'] : '');
} }
/** /**
* Преобразует путь в строку * Преобразует путь в строку
*
* @return string
*/ */
public function __toString(): string public function __toString()
{ {
$result = (($this->absolute) ? '/' : '') . implode(self::SEPARATOR, $this->path); $result = (($this->absolute) ? '/' : '') . implode(self::SEPARATOR, $this->path);
$this->url['path'] = $result; $this->url['path'] = $result;
@ -200,16 +201,17 @@ class Path
/** /**
* Проверяет является ли папка родительской для другой папки * Проверяет является ли папка родительской для другой папки
* *
* @param Path $path * @parma Path $path
*
* @return boolean
*/ */
public function isParent($path): bool public function isParent($path/*: Path*/)
{ {
if (isset($this->url['host']) && isset($path->url['host']) if (isset($this->url['host']) && isset($path->url['host'])
&& ($this->url['host'] != $path->url['host'])) return false; && ($this->url['host'] != $path->url['host'])) return false;
$count = count($this->path); if (count($path->path) > count($this->path)) {
if (count($path->path) > $count) { for ($i = 0; $i < count($this->path); $i++) {
for ($i = 0; $i < $count; $i++) {
if ($path->path[$i] != $this->path[$i]) { if ($path->path[$i] != $this->path[$i]) {
return false; return false;
} }
@ -219,7 +221,7 @@ class Path
return false; return false;
} }
public static function _isParent(string $path1, string $path2): bool public static function _isParent($path1, $path2)
{ {
$path = new Path($path1); $path = new Path($path1);
return $path->isParent(new Path($path2)); return $path->isParent(new Path($path2));
@ -229,6 +231,7 @@ class Path
* Находит путь относительно текущего путя * Находит путь относительно текущего путя
* *
* @param string $name Полный путь к файлу * @param string $name Полный путь к файлу
*
* @return string Относительный путь к файлу * @return string Относительный путь к файлу
*/ */
public function relPath($name) public function relPath($name)
@ -243,12 +246,7 @@ class Path
return $path->__toString(); return $path->__toString();
} }
/** // Вычисляет относительный путь в виде строки
* Вычисляет относительный путь в виде строки
* @param string $rpath Путь относительно которого вычисляется относительный путь
* @param string $lpath Путь к которому вычисляется относительный путь
* @return string Относительный путь
*/
static function relative($rpath, $lpath) { static function relative($rpath, $lpath) {
// Нужно проверять диск!! // Нужно проверять диск!!
$self = new Path($rpath); $self = new Path($rpath);
@ -256,28 +254,21 @@ class Path
$self_path = $self->getParts(); $self_path = $self->getParts();
$list_path = $list->getParts(); $list_path = $list->getParts();
$result = []; $result = array();
$count = count($list_path); for ($i = 0; $i < count($list_path); $i++) {
for ($i = 0; $i < $count; $i++) {
if (($i >= count($self_path)) || $list_path[$i] != $self_path[$i]) { if (($i >= count($self_path)) || $list_path[$i] != $self_path[$i]) {
break; break;
} }
} }
$list_count = count($list_path); for($j = $i; $j < count($list_path); $j++) {
for($j = $i; $j < $list_count; $j++) {
array_push($result, '..'); array_push($result, '..');
} }
$self_count = count($self_path); for($j = $i; $j < count($self_path); $j++) {
for($j = $i; $j < $self_count; $j++) {
array_push($result, $self_path[$j]); array_push($result, $self_path[$j]);
} }
return implode("/", $result); return implode("/", $result);
} }
/**
* @param string $path
* @return string
*/
public function append($path) public function append($path)
{ {
$base = $this->__toString(); $base = $this->__toString();
@ -287,11 +278,11 @@ class Path
/** /**
* Обьединяет строки в Path соединяя необходимым разделителем * Обьединяет строки в Path соединяя необходимым разделителем
* fixme не обрабатывает параметры урла, решение Path::join(SITE_WWW_PATH) . '?param=pampam' * fixme не обрабатывает параметры урла, решение Path::join(SITE_WWW_PATH) . '?param=pampam'
* @param string ...$args
* @return string * @return string
*/ */
static function fromJoin(...$args) { static function fromJoin($_rest) {
$result = []; $args = func_get_args();
$result = array();
$parts0 = new Path(array_shift($args)); $parts0 = new Path(array_shift($args));
$result [] = $parts0->getParts(); $result [] = $parts0->getParts();
foreach ($args as $file) { foreach ($args as $file) {
@ -308,30 +299,29 @@ class Path
/** /**
* Обьединяет строки в строку пути соединяя необходимым разделителем * Обьединяет строки в строку пути соединяя необходимым разделителем
* fixme не обрабатывает параметры урла, решение Path::join(SITE_WWW_PATH) . '?param=pampam' * fixme не обрабатывает параметры урла, решение Path::join(SITE_WWW_PATH) . '?param=pampam'
* @param string ...$args
* @return string * @return string
*/ */
static function join(...$args) static function join($_rest)
{ {
$path = call_user_func_array([self::class, "fromJoin"], $args); $args = func_get_args();
$path = call_user_func_array("self::fromJoin", $args);
return self::makeUrl($path->url); return self::makeUrl($path->url);
} }
// Проверка структуры имени файла // Проверка структуры имени файла
static function checkName(string $name, string $extension): bool static function checkName($name, $extension)
{ {
return (strlen(pathinfo($name, PATHINFO_FILENAME)) > 0) && (pathinfo($name, PATHINFO_EXTENSION) == $extension); return (strlen(pathinfo($name, PATHINFO_FILENAME)) > 0) && (pathinfo($name, PATHINFO_EXTENSION) == $extension);
} }
static function isCharName(string $char): bool static function isCharName($char)
{ {
$ch = ord($char); $ch = ord($char);
return ((($ch >= ord('a')) && ($ch <= ord('z'))) || (strpos('-._', $char) !== false) || (($ch >= ord('0')) && ($ch <= ord('9')))); return ((($ch >= ord('a')) && ($ch <= ord('z'))) || (strpos('-._', $char) !== false) || (($ch >= ord('0')) && ($ch <= ord('9'))));
} }
// Проверка имени файла // Проверка имени файла
static function isName(string $name): bool static function isName($name) {
{
if (strlen(trim($name)) == 0) { if (strlen(trim($name)) == 0) {
return false; return false;
} }
@ -343,7 +333,7 @@ class Path
return true; return true;
} }
public function isAbsolute(): bool public function isAbsolute()
{ {
return $this->absolute; return $this->absolute;
} }
@ -352,6 +342,7 @@ class Path
* Подбирает новое временное имя для файла * Подбирает новое временное имя для файла
* *
* @param string $dst Предпологаемое имя файла * @param string $dst Предпологаемое имя файла
*
* @return string Новое имя файла * @return string Новое имя файла
*/ */
static function resolveFile($dst) static function resolveFile($dst)
@ -371,46 +362,38 @@ class Path
/** /**
* Список файлов в директории * Список файлов в директории
* *
* @param ?string[] $allow массив расширений для файлов * @param array $allow массив расширений для файлов
* @param string[] $ignore массив имен пааок которые не нужно обрабатывать * @param array $ignore массив имен пааок которые не нужно обрабатывать
* *
* @return string[] * @returnarray
*/ */
public function getContent(?array $allow = null, array $ignore = []) public function getContent($allow = null, $ignore = array())
{ {
$ignore = array_merge([".", ".."], $ignore); $ignore = array_merge(array(".", ".."), $ignore);
return self::fileList($this->__toString(), $allow, $ignore); return self::fileList($this->__toString(), $allow, $ignore);
} }
/** /**
* Обьединяет строки в путь соединяя необходимым разделителем * Обьединяет строки в путь соединяя необходимым разделителем
* *
* @param ?string[] $allow массив расширений разрешеных для файлов * @param array $allow массив расширений разрешеных для файлов
* @param string[] $ignore массив имен папок которые не нужно обрабатывать * @param array $ignore массив имен пааок которые не нужно обрабатывать
* *
* @return string[] * @return array
*/ */
function getContentRec(?array $allow = null, array $ignore = []) function getContentRec($allow = null, $ignore = array())
{ {
$result = []; $result = array ();
$ignore = array_merge([".", ".."], $ignore); $ignore = array_merge(array (".", ".."), $ignore);
self::fileListAll($result, $this->__toString(), $allow, $ignore); self::fileListAll($result, $this->__toString(), $allow, $ignore);
return $result; return $result;
} }
/** // Использовать SPL ???
* Список файлов в директории protected static function fileList($base, &$allow, &$ignore)
*
* @param string $base Базовый путь
* @param ?string[] $allow массив расширений для файлов
* @param string[] $ignore массив имен папок которые не нужно обрабатывать
*
* @return string[]
*/
protected static function fileList(string $base, ?array &$allow, array &$ignore): array
{ {
if ($base == '') $base = '.'; if ($base == '') $base = '.';
$result = []; $result = array ();
$handle = opendir($base); $handle = opendir($base);
if (is_resource($handle)) { if (is_resource($handle)) {
while (true) { while (true) {
@ -432,7 +415,7 @@ class Path
return $result; return $result;
} }
protected static function fileListAll(array &$result, string $base, ?array &$allow, array &$ignore): void protected static function fileListAll(&$result, $base, &$allow, &$ignore)
{ {
$files = self::fileList($base, $allow, $ignore); $files = self::fileList($base, $allow, $ignore);
foreach ($files as $name) { foreach ($files as $name) {
@ -452,7 +435,7 @@ class Path
* *
* @return void * @return void
*/ */
static function prepare(string $dst, bool $filename = true) static function prepare($dst, $filename = true)
{ {
if ($filename) { if ($filename) {
$path_dst = pathinfo($dst, PATHINFO_DIRNAME); $path_dst = pathinfo($dst, PATHINFO_DIRNAME);
@ -467,13 +450,13 @@ class Path
/** /**
* Обновить относительную ссылку при переносе файла * Обновить относительную ссылку при переносе файла
* *
* @param string $relativePath - относительная ссылка до переноса * @param String $relativePath - относительная ссылка до переноса
* @param string $srcFile - абсолютный путь к папке содержащей файл со ссылкой до переноса * @param String $srcFile - абсолютный путь к папке содержащей файл со ссылкой до переноса
* @param string $dstFile - абсолютный путь к папке содержащей файл со ссылкой после переноса * @param String $dstFile - абсолютный путь к папке содержащей файл со ссылкой после переноса
* *
* @return string * @return String
*/ */
static function updateRelativePathOnFileMove(string $relativePath, string $srcFile, string $dstFile) { static function updateRelativePathOnFileMove($relativePath, $srcFile, $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));
} }
@ -481,14 +464,14 @@ class Path
/** /**
* Обновить относительную ссылку в файле при переносе папки * Обновить относительную ссылку в файле при переносе папки
* *
* @param string $relativePath относительная ссылка до переноса * @param String $relativePath - относительная ссылка до переноса
* @param string $fileDir абсолютный путь к директории файла содержащего ссылку до переноса * @param String $fileDir - абсолютный путь к директории файла содержащего ссылку до переноса
* @param string $srcDir абсолютный путь к переносимой директории до переноса * @param String $srcDir - абсолютный путь к переносимой директории до переноса
* @param string $dstDir абсолютный путь к переносимой директории после переноса * @param String $dstDir - абсолютный путь к переносимой директории после переноса
* *
* @return string * @return
*/ */
static function updateRelativePathOnDirectoryMove(string $relativePath, string $fileDir, string $srcDir, string $dstDir) { static function updateRelativePathOnDirectoryMove($relativePath, $fileDir, $srcDir, $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

@ -3,117 +3,80 @@
/** /**
* Преобразование типов !!! Пересмотреть использование классов!! * Преобразование типов !!! Пересмотреть использование классов!!
* Класс преобразования типа значения поля класса в тип поля таблицы * Класс преобразования типа значения поля класса в тип поля таблицы
* @package system
*/ */
namespace ctiso;
class Primitive { class Primitive {
/** // varchar
* @param mixed $value public static function to_varchar($value)
*/
public static function to_varchar($value): string
{ {
return ((string) $value); return ((string) $value);
} }
/**
* @param mixed $value
* @return mixed
*/
public static function from_varchar($value) public static function from_varchar($value)
{ {
return $value; return $value;
} }
/** // int
* @param mixed $value public static function to_bool($value)
*/
public static function to_bool($value): bool
{ {
return filter_var($value, FILTER_VALIDATE_BOOLEAN); return filter_var($value, FILTER_VALIDATE_BOOLEAN);//(int)((bool) $value);
} }
/** public static function from_bool($value)
* Преобразование значения в булевое значение
* @param string $value
* @return bool
*/
public static function from_bool($value): bool
{ {
return ((bool) $value); return ((bool) $value);
} }
/** // int
* Преобразование значения в целое число public static function to_int($value)
* @param string $value
* @return int
*/
public static function to_int($value): int
{ {
return ((int) $value); return ((int) $value);
} }
/** public static function from_int($value)
* @param mixed $value
*/
public static function from_int($value): string
{ {
return ((string) $value); return ((string) $value);
} }
/** // date
* Преобразование даты dd/mm/yy в unix timestamp public static function to_date($value)
* @param string $value
* @return int
*/
public static function to_date($value): int
{ {
$result = 0; $result = 0;
$tmp = explode("/", $value ?? '', 3); $tmp = explode("/", $value, 3);
if (!empty($tmp)) {
if (count($tmp) != 3) return $result;
if (count($tmp) != 3) { $year = intval($tmp[2]);
return $result; $month = intval($tmp[1]);
} $day = intval($tmp[0]);
$year = (int)$tmp[2];
$month = (int)$tmp[1];
$day = (int)$tmp[0];
if ($month != 0 && $day != 0 && $year != 0) { if ($month != 0 && $day != 0 && $year != 0) {
if (checkdate($month, $day, $year)) { if (checkdate($month, $day, $year)) {
return mktime(0, 0, 0, $month, $day, $year) ?: 0; return mktime(0, 0, 0, $month, $day, $year);
} else { } else {
return 0; return 0;
} }
} }
}
return $result; return $result;
} }
/** public static function to_datetime($value)
* Преобразование даты ISO 8601 в unix timestamp
* @param string $value
* @return int
*/
public static function to_datetime($value): int
{ {
$result = 0; $result = 0;
$tmp = []; $tmp = array();
if (preg_match('/(\d+)-(\d+)-(\d+)T(\d+):(\d+)Z/', $value, $tmp)) { if (preg_match('/(\d+)-(\d+)-(\d+)T(\d+):(\d+)Z/', $value, $tmp)) {
if (checkdate((int)$tmp[2], (int)$tmp[3], (int)$tmp[1])) { if (checkdate($tmp[2], $tmp[3], $tmp[1])) {
$result = mktime((int)$tmp[4], (int)$tmp[5], 0, (int)$tmp[2], (int)$tmp[3], (int)$tmp[1]) ?: 0; $result = mktime($tmp[4], $tmp[5], 0, $tmp[2], $tmp[3], $tmp[1]);
} }
} }
return $result; return $result;
} }
/** public static function from_date($value)
* Преобразование даты в формат dd/mm/yyyy
* @param int $value
* @return string
*/
public static function from_date($value): string
{ {
if ($value > 0) { if ($value > 0) {
return date("d/m/Y", $value); return date("d/m/Y", $value);
@ -121,12 +84,7 @@ class Primitive {
return ''; return '';
} }
/** public static function from_datetime($value)
* Преобразование даты в формат ISO 8601
* @param int $value
* @return string
*/
public static function from_datetime($value): string
{ {
if ($value > 0) { if ($value > 0) {
return date("Y-m-d\TH:i\Z", $value); return date("Y-m-d\TH:i\Z", $value);
@ -135,45 +93,24 @@ class Primitive {
} }
/** // secure
* @deprecated
* @template T
* @param T $value
* @return T
*/
public static function to_secure($value) public static function to_secure($value)
{ {
// Значение приабразуется во время сохранения в базе данных // Значение приабразуется во время сохранения в базе данных
return $value; return $value;
} }
/**
* @deprecated
* @template T
* @param T $value
* @return T
*/
public static function from_secure($value) public static function from_secure($value)
{ {
return $value; return $value;
} }
/** // array
* Преобразование значения в массив
* @param mixed $value
* @return array
*/
public static function to_array($value) public static function to_array($value)
{ {
return (is_array($value)) ? $value : []; return (is_array($value)) ? $value : array();
} }
/**
* @deprecated
* @template T
* @param T $value
* @return T
*/
public static function from_array($value) public static function from_array($value)
{ {
return $value; return $value;

View file

@ -1,68 +0,0 @@
<?php
namespace ctiso;
/**
* str_getcsv
* @param string $input
* @param string $delimiter
* @param string $enclosure
* @param string $escape
* @return array|false
*/
function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\")
{
$fiveMBs = 1024;
$fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');
$data = [];
if (is_resource($fp)) {
fputs($fp, $input);
rewind($fp);
$data = fgetcsv($fp, 1000, $delimiter, $enclosure);
fclose($fp);
}
return $data;
}
/**
* process_exists
* @param int $pid
* @return bool
*/
function process_exists($pid)
{
if (PHP_OS == 'WINNT') {
$content = shell_exec("tasklist.exe /NH /FO CSV");
if (!$content) {
return false;
}
$processes = explode("\n", $content);
foreach ($processes as $process) {
if ($process != "") {
$csv = str_getcsv($process);
if ($csv && $pid == $csv[1]) return true;
}
}
return false;
} else {
return file_exists("/proc/$pid");
}
}
/**
* create_single_proces
* @param string $fpid
* @param callable $fn
* @return int
*/
function create_single_process($fpid, $fn)
{
if (file_exists($fpid)) {
if (process_exists((int)file_get_contents($fpid))) {
return 1;
}
}
call_user_func($fn);
return 0;
}

View file

@ -1,62 +1,40 @@
<?php <?php
namespace ctiso; ///<reference path="Settings.php" />
use ctiso\File,
Exception;
class Registry { /**
/** @var array<string, array{path: string, data: mixed}> */ * http://www.patternsforphp.com/wiki/Registry
private array $namespace = []; * http://www.patternsforphp.com/wiki/Singleton
* http://www.phppatterns.com/docs/design/the_registry?s=registry
*/
function importFile(string $namespace, ?string $filePath = null): void { class Registry extends Settings
$data = json_decode(File::getContents($filePath), true); {
$data['_file'] = $filePath; static $instance = null;
$this->namespace[$namespace] = [
'path' => $filePath, /**
'data' => $data */
]; static public function getInstance()
{
if (self::$instance == null) {
self::$instance = new Registry();
} }
return self::$instance;
function importArray(string $namespace, array $data = []): void {
if (isset($this->namespace[$namespace])) {
$data = array_merge($this->namespace[$namespace]['data'], $data);
}
$this->namespace[$namespace] = [
'path' => null,
'data' => $data
];
} }
/** /**
* @param string $ns * Список модулей
* @param string $key
* @return mixed
* @throws Exception
*/ */
public function get(string $ns, string $key) { public function getModules()
if (isset($this->namespace[$ns]['data'][$key])) { {
return $this->namespace[$ns]['data'][$key]; return array_keys($this->data);
}
throw new Exception('Unknown key ' . $ns . '::' . $key);
} }
/** /**
* @param string $ns * Проверка наличия модуля
* @param string $key
* @return mixed|null
*/ */
public function getOpt(string $ns, string $key) { public function hasModule($name)
if (isset($this->namespace[$ns]['data'][$key])) { {
return $this->namespace[$ns]['data'][$key]; return isset($this->data[$name]);
}
return null;
}
public function has(string $ns, string $key): bool {
return isset($this->namespace[$ns]['data'][$key]);
}
function set(string $ns, string $key, mixed $value): void {
$this->namespace[$ns]['data'][$key] = $value;
} }
} }

View file

@ -1,128 +0,0 @@
<?php
namespace ctiso\Role;
use ctiso\Database;
use ctiso\Database\Statement;
use ctiso\Database\PDOStatement;
// Класс должен быть в библиотеке приложения
class User implements UserInterface
{
const LIFE_TIME = 1800; // = 30min * 60sec;
public string $fullname;
public string $name;
/** @var string */
public $access;
public string $password;
/** @var int */
public $id;
public Database $db;
public array $groups;
function __construct(Database $db, array $groups) {
$this->db = $db;
$this->groups = $groups;
}
public function setDB(Database $db): void {
$this->db = $db;
}
public function getName(): string {
return $this->name;
}
/**
* @return bool
*/
function isLogged() {
return \ctiso\Filter\Authorization::isLogged();
}
public function getUserByQuery(Statement $stmt): ?PDOStatement
{
$result = $stmt->executeQuery();
if ($result->next()) {
$this->access = $this->groups[$result->getString('access')];
$this->name = $result->getString('login');
$this->id = $result->getInt('id_user');
$this->password = $result->getString('password');
$this->fullname = implode(' ', [
$result->getString('surname'),
$result->getString('firstname'),
$result->getString('patronymic')]);
return $result;
}
return null;
}
/**
* @param PDOStatement $result
* @return string
*/
function getUserPassword($result) {
return $result->get('password');
}
public function getUserByLogin(string $login): ?PDOStatement
{
$stmt = $this->db->prepareStatement("SELECT * FROM users WHERE login = ?");
$stmt->setString(1, $login);
$result = $this->getUserByQuery($stmt);
if ($result) {
$time = time();
$id = $this->id;
$this->db->executeQuery(
"UPDATE users SET lasttime = :time WHERE id_user = :id",
['time' => $time, 'id' => $id]); // Время входа
}
return $result;
}
public function getUserById(int $id): ?PDOStatement
{
$stmt = $this->db->prepareStatement("SELECT * FROM users WHERE id_user = ?");
$stmt->setInt(1, $_SESSION ['access']);
$result = $this->getUserByQuery($stmt);
if ($result) {
$lasttime = $result->getInt('lasttime');
$time = time();
if ($time - $lasttime > self::LIFE_TIME) return null; // Вышло время сессии
$id = $this->id;
}
return $result;
}
/**
* @param string $random
* @param PDOStatement $result
* @return PDOStatement|bool
*/
function setSID(string $random, $result)
{
return $this->db->executeQuery("UPDATE users SET sid = :sid, trie_count = 0 WHERE id_user = :user", [
'user' => $result->getInt('id_user'),
'sid' => $random
]);
}
function resetTries(string $login): void {
$this->db->executeQuery(
"UPDATE users SET trie_count = :count WHERE login = :login",
['count' => 0, 'login' => $login]
);
}
function updateTries(string $login): void {
$user = $this->db->fetchOneArray("SELECT id_user, trie_count FROM users WHERE login = :login", ['login' => $login]);
if ($user === false) {
return;
}
$this->db->executeQuery(
"UPDATE users SET trie_time = :cur_time, trie_count = :count WHERE id_user = :id_user",
['cur_time' => time(), 'count' => $user['trie_count']+1, 'id_user' => $user['id_user']]
);
}
}

View file

@ -1,19 +0,0 @@
<?php
namespace ctiso\Role;
use ctiso\Database\Statement;
use ctiso\Database\PDOStatement;
interface UserInterface {
function getUserByQuery(Statement $stmt): ?PDOStatement;
function getUserByLogin(string $login): ?PDOStatement;
function getUserById(int $id): ?PDOStatement;
function getName(): string;
/**
* @param string $random
* @param PDOStatement $result
* @return PDOStatement|bool
*/
function setSID(string $random, $result);
}

View file

@ -1,9 +1,7 @@
<?php <?php
namespace ctiso;
class Security { class Security {
static function generatePassword(int $length = 9, int $strength = 0): string { static function generatePassword($length = 9, $strength = 0) {
$vowels = 'aeuy'; $vowels = 'aeuy';
$consonants = 'bdghjmnpqrstvz'; $consonants = 'bdghjmnpqrstvz';
if ($strength & 1) { if ($strength & 1) {

View file

@ -1,10 +1,8 @@
<?php <?php
namespace ctiso;
class Session class Session
{ {
function get(string $key): mixed function get($key)
{ {
if (isset($_SESSION[$key])) { if (isset($_SESSION[$key])) {
return $_SESSION[$key]; return $_SESSION[$key];
@ -12,27 +10,26 @@ class Session
return null; return null;
} }
function set(string|array $key, mixed $value): void function set($key, $value)
{ {
if (is_array($key)) { if (is_array($key)) {
$className = get_class($key[0]); $_SESSION[strtolower(get_class($key[0]))][$key[1]] = $value;
$_SESSION[strtolower($className ?: '')][$key[1]] = $value;
} else { } else {
$_SESSION[$key] = $value; $_SESSION[$key] = $value;
} }
} }
function clean(string $key): void function clean($key)
{ {
unset($_SESSION[$key]); unset($_SESSION[$key]);
} }
function start(): void function start()
{ {
@session_start(); @session_start();
} }
function stop(): void function stop()
{ {
session_destroy(); session_destroy();
} }

View file

@ -1,9 +1,5 @@
<?php <?php
namespace ctiso;
use ctiso\File,
Exception;
/** /**
* Класс реестра * Класс реестра
* Реестр организован как ассоциативный многомерный массив * Реестр организован как ассоциативный многомерный массив
@ -13,28 +9,17 @@ use ctiso\File,
* parameters1, parameters1 - Массивы с параметрами модуля * parameters1, parameters1 - Массивы с параметрами модуля
* Имя необходимо чтобы потом легко было удалить ненужные ветки дерева * Имя необходимо чтобы потом легко было удалить ненужные ветки дерева
*/ */
class Settings class Settings extends Collection
{ {
/** @var array */
public $data = [];
/** @var string */
protected $file; protected $file;
/** @var string */
protected $format = 'php'; protected $format = 'php';
/** @var bool */
protected $is_read = false;
/**
* Конструктор
* @param string $file Путь к файлу
* @param 'php'|'json'|false $format Формат файла
*/
public function __construct ($file = null, $format = false) public function __construct ($file = null, $format = false)
{ {
$fileFormat = ['theme' => 'json']; $fileFormat = ['theme' => 'json'];
$extname = pathinfo($file, PATHINFO_EXTENSION); $extname = pathinfo($file, PATHINFO_EXTENSION);
$this->format = $format ?: Arr::get($fileFormat, $extname, $extname); $this->format = $format ? $format : Arr::get($fileFormat, $extname, $extname);
$this->file = $file; $this->file = $file;
} }
@ -42,37 +27,31 @@ class Settings
* Чтение настроек из файла * Чтение настроек из файла
* @return Boolean * @return Boolean
*/ */
public function read(): bool public function read()
{ {
if (!file_exists ($this->file)) { if (!file_exists ($this->file)) {
$this->is_read = true;
return false; return false;
} }
// Не include_once т.к читать настройки можно несколько раз // Не include_once т.к читать настройки можно несколько раз
$settings = []; $settings = array();
if ($this->format == 'json') { if ($this->format == 'json') {
$settings = json_decode(File::getContents($this->file), true); $settings = json_decode(File::getContents($this->file), true);
} else { } else {
$settings = include ($this->file); include ($this->file);
} }
if (!is_array($settings)) { if (!is_array($settings)) {
throw new Exception('no data in ' . $this->file); throw new Exception($this->file);
} }
return $this->import($settings);
$this->is_read = true;
$this->data = $settings;
return true;
} }
/** /**
* Запись ключа в реестр (Реестр это многомерный массив) * Запись ключа в реестр (Реестр это многомерный массив)
* @param array $key Путь к значению ключа
* @param mixed $value Значение
* @return void
*/ */
public function writeKey(array $key, $value) public function writeKey(array $key, $value)
{ {
// assert(count($key) >= 1);
$data = &$this->data; $data = &$this->data;
while (count($key) > 1) { while (count($key) > 1) {
@ -80,10 +59,11 @@ class Settings
$data = &$data[$name]; $data = &$data[$name];
} }
// assert(count($key) == 1);
$name = array_shift($key); $name = array_shift($key);
if (is_array($value)) { if (is_array($value)) {
if (!isset($data[$name])) { if (!isset($data[$name])) {
$data[$name] = []; $data[$name] = array();
} }
$this->merge($data[$name], $value); $this->merge($data[$name], $value);
} else { } else {
@ -93,14 +73,12 @@ class Settings
/** /**
* Обновляет массив в соответствии со значением * Обновляет массив в соответствии со значением
* @param array $data Массив
* @param mixed $value Значение
*/ */
protected function merge(array &$data, $value): void protected function merge(array &$data, $value)
{ {
foreach ($value as $key => $subvalue) { foreach ($value as $key => $subvalue) {
if (is_array($subvalue)) { if (is_array($subvalue)) {
if (! isset($data[$key])) $data[$key] = []; if (! isset($data[$key])) $data[$key] = array();
$this->merge($data[$key], $subvalue); $this->merge($data[$key], $subvalue);
} else { } else {
$data[$key] = $subvalue; $data[$key] = $subvalue;
@ -110,22 +88,16 @@ class Settings
/** /**
* Чтение ключа из реестра * Чтение ключа из реестра
* @param array $key Путь к значению ключа * @param $args Путь к значению ключа
* @return mixed
*/ */
public function readKey(array $key) public function readKey(array $key)
{ {
return $this->readKeyData($key, $this->data); return $this->readKeyData($key, $this->data);
} }
/**
* Чтение ключа из реестра
* @param array $key Путь к значению ключа
* @param array $data
* @return mixed
*/
protected function readKeyData(array $key, $data) protected function readKeyData(array $key, $data)
{ {
// assert(count($key) >= 1);
while (count($key) > 1) { while (count($key) > 1) {
$name = array_shift($key); $name = array_shift($key);
if (isset($data[$name])) { if (isset($data[$name])) {
@ -135,6 +107,7 @@ class Settings
} }
} }
// assert(count($key) == 1);
$name = array_shift($key); $name = array_shift($key);
if (isset($data[$name])) { if (isset($data[$name])) {
return $data[$name]; return $data[$name];
@ -145,12 +118,12 @@ class Settings
/** /**
* Чтение ключа из реестра (Собирает все ключи с определенным значением во всех модулях) * Чтение ключа из реестра (Собирает все ключи с определенным значением во всех модулях)
* @param mixed $key Путь к значению ключа внутри модуля * @param $key Путь к значению ключа внутри модуля
* @return array
*/ */
public function readKeyList(...$key) public function readKeyList($_rest)
{ {
$result = []; $key = func_get_args();
$result = array();
foreach ($this->data as $name => $value) { foreach ($this->data as $name => $value) {
$output = $this->readKeyData($key, $value); $output = $this->readKeyData($key, $value);
if ($output) { if ($output) {
@ -160,17 +133,13 @@ class Settings
return $result; return $result;
} }
/** public function removeKey($name)
* Удаление ключа из реестра
* @param string $name Имя ключа
*/
public function removeKey($name): void
{ {
unset($this->data[$name]); unset($this->data[$name]);
} }
public function removeNode(array $key): void public function removeNode(array $key)
{ {
$data = &$this->data; $data = &$this->data;
while (count($key) > 1) { while (count($key) > 1) {
@ -181,80 +150,26 @@ class Settings
unset($data[$name]); unset($data[$name]);
} }
/** public function getOwner()
* Запись настроек в файл (Может переименовать в store)
*
* @param string $file
* @return void
*/
public function write($file = null)
{
if (!$this->is_read) {
throw new Exception('read settings before write');
}
if ($this->format == 'json') {
$result = json_encode($this->data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} else {
$result = var_export($this->data, true);
$result = "<?php\nreturn ".$result.";\n?>";
}
file_put_contents(($file) ? $file : $this->file, $result);
}
/**
* Установка значения ключа
* @param string $key Ключ
* @param mixed $value Значение
*/
public function set($key, $value): void {
$this->data[$key] = $value;
}
/**
* Получение значения ключа
* @param string $key Ключ
* @param mixed $default Значение по умолчанию
* @return mixed
*/
public function get($key, $default = null)
{
return isset($this->data[$key]) && $this->data[$key] != '' ? $this->data[$key] : $default;
}
/**
* Получение всех данных
* @return array
*/
function export() {
return $this->data;
}
/**
* Импорт данных
* @param array $data Данные
* @return void
*/
function import($data) {
$this->data = $data;
}
/**
* Список модулей/ключей
* @return array
*/
public function getKeys()
{ {
return array_keys($this->data); return array_keys($this->data);
} }
/** /**
* Проверка наличия ключа * Запись настроек в файл (Может переименовать в store)
* @param string $name Ключ *
* @return bool * @param File $file
*
* @return void
*/ */
public function hasKey($name) public function write($file = null)
{ {
return isset($this->data[$name]); if ($this->format == 'json') {
$result = json_encode($this->data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
} else {
$result = var_export($this->data, true);
$result = "<?php\n\$settings = ".$result.";\n?>";
}
file_put_contents (($file) ? $file : $this->file, $result);
} }
} }

View file

@ -7,103 +7,57 @@
* $setup->executeActions('install'); * $setup->executeActions('install');
* </code> * </code>
*/ */
namespace ctiso;
use ctiso\Tools\SQLStatementExtractor;
use ctiso\Path;
use ctiso\File;
use SimpleXMLElement;
class FakeZipArchive {
/** @var string */
public $base;
function open(string $path): void {
$this->base = $path;
}
/**
* Возвращает содержимое файла
* @param string $file
* @return string
*/
function getFromName($file) {
return File::getContents(Path::join($this->base, $file));
}
}
class Setup class Setup
{ {
/** @var array */ protected $actions = array();
protected $actions = []; public $context = array();
/** @var array */
public $context = [];
/** @var string */
protected $file; protected $file;
/** @var string */
protected $action; protected $action;
/** @var SimpleXMLElement */
protected $node; protected $node;
/** @var array */ protected $stack = array();
protected $stack = [];
/** @var FakeZipArchive */
public $zip; public $zip;
/** @var string */
public $target; public $target;
/** @var string */
public $source; public $source;
/**
* @param string $file
*/
public function __construct($file) public function __construct($file)
{ {
$this->file = $file; $this->file = $file;
$node = simplexml_load_file($file); $this->node = simplexml_load_file($file);
if ($node === false) {
throw new \RuntimeException("Can't load file $file");
}
$this->node = $node;
$this->target = ''; $this->target = '';
$this->source = ''; $this->source = '';
$this->zip = new FakeZipArchive(); $this->zip = new ZipArchive();
$this->zip->open(dirname($this->file) . '/' . $this->node->attributes()['dir']); $this->zip->open(strtr($file, array('.xml' => '.zip')));
array_push($this->stack, $this->node); array_push($this->stack, $this->node);
$this->registerAction('copy', [$this, 'copyFile']); $this->registerAction('copy', array($this, 'copyFile'));
$this->registerAction('make-directory', [$this, 'makeDirectory']); $this->registerAction('make-directory', array($this, 'makeDirectory'));
$this->registerAction('make-link', [$this, 'makeLink']); $this->registerAction('make-link', array($this, 'makeLink'));
$this->registerAction('include', [$this, 'includeFile']); $this->registerAction('include', array($this, 'includeFile'));
$this->registerAction('when', [$this, 'testWhen']); $this->registerAction('when', array($this, 'testWhen'));
} }
/** /**
* Регистрация новых действия для установки * Регистрация новых действия для установки
* @param string $name
* @param callable $action
*/ */
public function registerAction(string $name, $action): void public function registerAction($name, $action)
{ {
$this->actions[$name] = $action; $this->actions[$name] = $action;
} }
/** /**
* Установка переменных для шаблона * Установка переменных для шаблона
* @param string $name
* @param mixed $value
*/ */
public function set(string $name, $value): void public function set($name, $value)
{ {
$this->context[$name] = $value; $this->context[$name] = $value;
} }
/** function replaceFn($matches) {
* @return string
*/
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 {
@ -116,14 +70,14 @@ class Setup
return $v; return $v;
} }
public function fileContent(string $file, array $tpl): string 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*\}\}/', array($this, 'replaceFn'), $result);
return $result; return $result;
} }
function callAction(string $name, array $attributes): void function callAction($name, array $attributes)
{ {
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);
@ -132,8 +86,6 @@ class Setup
/** /**
* Заменяет переменные на их значения в строке * Заменяет переменные на их значения в строке
* @param array<string> $match массив совпадения
* @return string
*/ */
function replaceVariable(array $match) function replaceVariable(array $match)
{ {
@ -145,14 +97,12 @@ class Setup
/** /**
* Для всех аттрибутов заменяет переменные на их значения * Для всех аттрибутов заменяет переменные на их значения
* @param SimpleXMLElement $attributes аттрибуты
* @return array<string, string>
*/ */
function resolve(SimpleXMLElement $attributes): array function resolve($attributes)
{ {
$result = []; $result = array();
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+)}/", array($this, 'replaceVariable'), $value);
} }
return $result; return $result;
} }
@ -160,8 +110,7 @@ class Setup
/** /**
* Выполняет список действий если для действия не указан аттрибут when то оно выполняется всегда * Выполняет список действий если для действия не указан аттрибут when то оно выполняется всегда
* *
* @param string $action специальное действие * @param $action специальное действие
* @return void
*/ */
function executeActions($action = "install") function executeActions($action = "install")
{ {
@ -170,27 +119,23 @@ class Setup
return; return;
} }
/** @var \SimpleXMLElement */ $item/*: SimpleXMLElement*/ = $this->stack[count($this->stack) - 1];
$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(), array($this->resolve($attributes)));
array_pop($this->stack); array_pop($this->stack);
} }
} }
/** /**
* Копирования файла * Копирования файла
* preserve - Не переписывать файл если он существует * @param preserve Не переписывать файл если он существует
* template Файл является шаблоном подставить параметры до копирования * @param template Файл является шаблоном подставить параметры до копирования
* src Исходный файл * @param src Исходный файл
* dst Новый файл * @param dst Новый файл
*
* @param array{preserve?: string, template: string, src: string, dst: string} $attributes
* @return void
*/ */
public function copyFile(array $attributes) public function copyFile(array $attributes)
{ {
@ -203,9 +148,9 @@ class Setup
/** /**
* Создает символическую ссылку на папку/файл * Создает символическую ссылку на папку/файл
* @param array{target: string, link: string} $attributes * @param dst Имя папки
*/ */
public function makeLink(array $attributes): void public function makeLink(array $attributes)
{ {
if (function_exists('symlink')) { if (function_exists('symlink')) {
symlink($attributes['target'], $attributes['link']); symlink($attributes['target'], $attributes['link']);
@ -214,9 +159,9 @@ class Setup
/** /**
* Подключение файла установки * Подключение файла установки
* @param array{file: string} $attributes Имя подключаемого файла * @param file Имя подключаемого файла
*/ */
public function includeFile(array $attributes): void public function includeFile(array $attributes)
{ {
$file = basename($this->file) . "/" . $attributes['file']; $file = basename($this->file) . "/" . $attributes['file'];
@ -225,17 +170,15 @@ class Setup
$setup->executeActions(); $setup->executeActions();
} }
function targetPath(string $s): string { function targetPath($s) {
return $this->target . '/' . $s; return $this->target . '/' . $s;
} }
/** /**
* Создает новую папку * Создает новую папку
* dst Имя папки * @param dst Имя папки
*
* @param array{dst:string} $attributes
*/ */
public function makeDirectory(array $attributes): void public function makeDirectory(array $attributes)
{ {
$path = $this->targetPath($attributes['dst']); $path = $this->targetPath($attributes['dst']);
if (!file_exists($path)) { if (!file_exists($path)) {
@ -243,34 +186,27 @@ class Setup
} }
} }
function testWhen(array $attributes): void function testWhen(array $attributes)
{ {
if (!isset($attributes['test']) || $attributes['test'] == $this->action) { if (!isset($attributes['test']) || $attributes['test'] == $this->action) {
$this->executeActions($this->action); $this->executeActions($this->action);
} }
} }
/**
* Выполнение Списка SQL команд из ZIP файла
* @param Database $conn
* @param string $file
*/
function batchSQLZip($conn, $file): void
{
$stmtList = SQLStatementExtractor::extract($this->zip->getFromName($file));
foreach ($stmtList as $stmt) {
$conn->executeQuery ($stmt);
}
}
/** /**
* Выполнение Списка SQL команд * Выполнение Списка SQL команд
* @param Database $conn
* @param string $file
*/ */
static function batchSQL($conn, $file): void function batchSQLZip($conn/*: Database*/, $file)
{ {
$stmtList = SQLStatementExtractor::extractFile($file); $stmtList = Tools_SQLStatementExtractor::extract($this->zip->getFromName($file));
foreach ($stmtList as $stmt) {
$conn->executeQuery ($stmt);
}
}
static function batchSQL($conn/*: Database*/, $file)
{
$stmtList = Tools_SQLStatementExtractor::extractFile($file);
foreach ($stmtList as $stmt) { foreach ($stmtList as $stmt) {
$conn->executeQuery ($stmt); $conn->executeQuery ($stmt);
} }

66
src/Shortcut.php Normal file
View file

@ -0,0 +1,66 @@
<?php
/**
* Класс для короткого доступа к файлам / папкам
*/
class Shortcut
{
static $instance = null;
public $variables = array();
public $list = array();
// Singleton pattern
static public function getInstance()
{
if (self::$instance == null) {
self::$instance = new Shortcut();
}
return self::$instance;
}
/**
* Добавляет ярлык с именем $prefix
* Путь может содержать переменные
*/
public function addUrl($prefix, $path)
{
$this->list[$prefix] = $path;
}
/**
*
*/
public function addVar($name, $value)
{
$this->variables['$' . $name] = $value;
}
/**
* Возвращает путь по имени ярлыка
*/
static function getUrl($prefix, $name = null, $name1 = null)
{
$shortcut = self::getInstance();
$names = $shortcut->variables;
if ($name) {
$names['$name'] = $name;
}
if ($name1) {
$names['$name1'] = $name1;
}
if (isset($shortcut->list[$prefix])) {
return strtr($shortcut->list[$prefix], $names);
}
return null;
}
static function expand($path)
{
$shortcut = self::getInstance();
$names = $shortcut->variables;
return strtr($path, $names);
}
}

View file

@ -1,24 +1,19 @@
<?php <?php
namespace ctiso;
class SortRecord class SortRecord
{ {
public string $key; public $key;
public int $order; public $mode;
public $order;
function __construct(string $key, bool $order) function __construct($key, $mode, $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)
* @template T
* @param array<string, T> $a
* @param array<string, T> $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;
@ -26,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(object $a, object $b): int function compareKeys($a, $b)
{ {
if($a->{$this->key} == $b->{$this->key}) { if($a->{$this->key} == $b->{$this->key}) {
return 0; return 0;
@ -34,23 +29,23 @@ 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(array &$list): bool function sort(&$list)
{ {
return usort($list, [$this, 'compare']); return usort($list, array($this, 'compare'));
} }
function sortKeys(array &$list): bool function sortKeys(&$list)
{ {
return usort($list, [$this, 'compareKeys']); return usort($list, array($this, 'compareKeys'));
} }
function group(array &$list, string $key, array $types): void function group(&$list, $key, $types)
{ {
$groups = []; $groups = array();
foreach ($types as $name) { foreach ($types as $name) {
$groups[$name] = []; $groups[$name] = array();
} }
$groups['_any_'] = []; $groups['_any_'] = array();
foreach ($list as $item) { foreach ($list as $item) {
if (isset($groups[$item[$key]])) { if (isset($groups[$item[$key]])) {
$groups[$item[$key]][] = $item; $groups[$item[$key]][] = $item;
@ -58,7 +53,7 @@ class SortRecord
$groups['_any_'][] = $item; $groups['_any_'][] = $item;
} }
} }
$result = []; $result = array();
foreach ($groups as $value) { foreach ($groups as $value) {
$result = array_merge($result, $value); $result = array_merge($result, $value);
} }

View file

@ -1,40 +0,0 @@
<?php
/**
* Преобразование дерева из модели Plain в массив массивов (Adjacency List)
*/
namespace ctiso;
use ctiso\Functions;
class TableTree {
/**
* Обходит таблицу как дерево
* $fn ($name, $index, $rows, $cc)
* $name Ключ уровня
* $index Значение ключа уровня
* $rows Все столбцы текущго уровня
* $cc Столбцы более низкого уровня
*
* @param array $level Уровни вложенности
* @param array $table Таблица
* @param callable $fn Функция которая применяется к каждой ветке дерева
* @return array
*/
static function walk($level, $table, $fn) {
if (empty ($level)) {
return $table;
}
$name = array_shift ($level);
$keys = Functions::key_unique_values($name, $table);
$data = [];
foreach ($keys as $index) {
list($rows, $table) = Functions::partition (Functions::lcurry(['\ctiso\Functions', '__index'], $index, $name), $table);
// $rows = array_filter ($table, lcurry('__index', intval($index), $name));
//$rows = array_filter ($table, create_function ('$x', 'return __index ('.intval($index).', \''.$name.'\', $x);'));
$data[$index] = call_user_func ($fn, $name, $index, $rows, self::walk ($level, $rows, $fn));
}
return $data;
}
}

View file

@ -1,90 +0,0 @@
<?php
/**
* Расширения для PHPTAL для отображения времени и даты
*/
namespace ctiso;
use PHPTAL_Php_TalesInternal;
use ctiso\Controller\SiteInterface;
use ctiso\Controller\Component;
use ctiso\HttpRequest;
use PHPTAL_Tales;
use PHPTAL_TalesRegistry;
class Tales_DateTime implements PHPTAL_Tales
{
static public function date(string $expression, bool $nothrow = false): string
{
return "ctiso\\Tales::phptal_date(".PHPTAL_Php_TalesInternal::path($expression).")";
}
static public function time(string $expression, bool $nothrow = false): string
{
return "ctiso\\Tales::phptal_time(".PHPTAL_Php_TalesInternal::path($expression).")";
}
}
class Tales_Component implements PHPTAL_Tales
{
static public function component(string $expression, bool $nothrow = false): string
{
$s = PHPTAL_Php_TalesInternal::string($expression);
return "ctiso\\Tales::phptal_component(" . $s . ")";
}
}
class Tales_Assets implements PHPTAL_Tales
{
static public function assets(string $expression, bool $nothrow = false): string
{
$s = PHPTAL_Php_TalesInternal::string($expression);
return "ctiso\\Tales::phptal_asset(" . $s . ")";
}
}
class Tales {
/** @var ?SiteInterface */
static $site;
static function phptal_date (int $e): string {
return date("d.m.Y", $e);
}
static function phptal_time (int $e): string {
return date("H:i", $e);
}
static function phptal_asset(string $s): string {
self::$site->addStyleSheet($s);
return "";
}
/**
* Функция подключения компонента
* @param string $expression
* @return string
*/
static function phptal_component($expression): string {
$begin = floatval(microtime(true));
/** @var Component */
$component = self::$site->loadComponent($expression);
$req = new HttpRequest();
$result = $component->execute($req);
echo "<!-- ", $expression, ", ", round(floatval(microtime(true)) - $begin, 4), "sec -->";
return $result;
}
static function register(?SiteInterface $site): void {
self::$site = $site;
/* Регистрация нового префикса для подключения компонента */
$tales = PHPTAL_TalesRegistry::getInstance();
$tales->registerPrefix('component', [\ctiso\Tales_Component::class, 'component']);
$tales->registerPrefix('date', [\ctiso\Tales_DateTime::class, 'date']);
$tales->registerPrefix('time', [\ctiso\Tales_DateTime::class, 'time']);
$tales->registerPrefix('assets', [\ctiso\Tales_Assets::class, 'assets']);
}
}

View file

@ -1,10 +1,6 @@
<?php <?php
namespace ctiso\Tools; class Tools_Drawing
use GdImage;
class Drawing
{ {
const ALIGN_LEFT = "left"; const ALIGN_LEFT = "left";
const ALIGN_TOP = "top"; const ALIGN_TOP = "top";
@ -12,20 +8,9 @@ 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)
* @param GdImage $image
* @param int $left
* @param int $top
* @param int $width
* @param int $height
* @param list<int<0, 255>> $rgb
*/
static function drawRectangle(GdImage &$image, int $left, int $top, int $width, int $height, array $rgb): void
{ {
$color = imagecolorallocate($image, $rgb[0], $rgb[1], $rgb[2]); $color = imagecolorallocate($image, $rgb[0], $rgb[1], $rgb[2]);
if ($color === false) {
throw new \RuntimeException("Can't allocate color");
}
$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);
@ -36,41 +21,17 @@ class Drawing
/** /**
* http://ru2.php.net/imagettftext * http://ru2.php.net/imagettftext
*
* @param GdImage $image
* @param int $size
* @param float $angle
* @param int $left
* @param int $top
* @param int $color
* @param string $font
* @param string $text
* @param int $max_width
* @param int $max_height
* @param string $align
* @param string $valign
*/ */
static function imagettftextbox( static function imagettftextbox(&$image, $size, $angle, $left, $top, $color, $font, $text,
GdImage &$image, $max_width, $max_height, $align, $valign)
int $size, {
float $angle,
$left,
$top,
$color,
$font,
$text,
$max_width,
$max_height,
$align,
$valign
): float {
// echo $left,"\n", $top, "\n"; // echo $left,"\n", $top, "\n";
// echo $max_width,"\n", $max_height, "\n"; // echo $max_width,"\n", $max_height, "\n";
// self::drawrectnagle($image, $left, $top, $max_width, $max_height, array(0xFF,0,0)); // 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 = array();
$line_widths = []; $line_widths = array();
$largest_line_height = 0; $largest_line_height = 0;
foreach ($text_lines as $block) { foreach ($text_lines as $block) {
@ -79,14 +40,9 @@ class Drawing
$first_word = true; $first_word = true;
$last_width = 0; $last_width = 0;
$count = count($words); for ($i = 0; $i < count($words); $i++) {
$item = '';
for ($i = 0; $i < $count; $i++) {
$item = $words[$i]; $item = $words[$i];
$dimensions = imagettfbbox($size, $angle, $font, $current_line . ($first_word ? '' : ' ') . $item); $dimensions = imagettfbbox($size, $angle, $font, $current_line . ($first_word ? '' : ' ') . $item);
if ($dimensions === false) {
continue;
}
$line_width = $dimensions[2] - $dimensions[0]; $line_width = $dimensions[2] - $dimensions[0];
$line_height = $dimensions[1] - $dimensions[7]; $line_height = $dimensions[1] - $dimensions[7];
@ -95,7 +51,7 @@ class Drawing
if ($line_width > $max_width && !$first_word) { if ($line_width > $max_width && !$first_word) {
$lines[] = $current_line; $lines[] = $current_line;
$line_widths[] = $last_width ?: $line_width; $line_widths[] = $last_width ? $last_width : $line_width;
$current_line = $item; $current_line = $item;
} else { } else {
$current_line .= ($first_word ? '' : ' ') . $item; $current_line .= ($first_word ? '' : ' ') . $item;
@ -142,15 +98,20 @@ class Drawing
return $largest_line_height * count($lines); return $largest_line_height * count($lines);
} }
function imagettftextSp(GdImage $image, float $size, float $angle, int $x, int $y, int $color, string $font, string $text, int $spacing = 0): void
function imagettftextSp($image, $size, $angle, $x, $y, $color, $font, $text, $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 !== false ? ($bbox[2] - $bbox[0]) : 0); $temp_x += $spacing + ($bbox[2] - $bbox[0]);
} }
} }
} }

View file

@ -1,16 +1,8 @@
<?php <?php
namespace ctiso\Tools; class Tools_Image
use GdImage;
class Image
{ {
/** static function load($uri)
* @param string $uri
* @return GdImage|false
*/
static function load($uri): GdImage|false
{ {
$e = strtolower(pathinfo($uri, PATHINFO_EXTENSION)); $e = strtolower(pathinfo($uri, PATHINFO_EXTENSION));
switch ($e) { switch ($e) {
@ -18,32 +10,24 @@ 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(GdImage $image, int $prewidth, int $preheight, bool $force = true): GdImage|false static function fit($image, $prewidth, $preheight, $force = true)
{ {
$width = imagesx($image); $width = imagesx($image);
$height = imagesy($image); $height = imagesy($image);
$percent = min($prewidth / $width, $preheight / $height); $percent = min($prewidth / $width, $preheight / $height);
if ($percent > 1 && !$force) { if ($percent > 1 && !$force) $percent = 1;
$percent = 1; $new_width = $width * $percent;
} $new_height = $height * $percent;
$new_width = max(1, (int)($width * $percent));
$new_height = max(1, (int)($height * $percent));
$image_p = imagecreatetruecolor($new_width, $new_height); $image_p = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
return $image_p; return $image_p;
} }
/** static function save($image, $uri)
* @param GdImage $image
* @param string $uri
* @return bool
*/
static function save($image, $uri): bool
{ {
$e = strtolower(pathinfo($uri, PATHINFO_EXTENSION)); $e = strtolower(pathinfo($uri, PATHINFO_EXTENSION));
switch ($e) { switch ($e) {
@ -51,6 +35,5 @@ 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

@ -26,15 +26,8 @@
* @version $Revision: 1.5 $ * @version $Revision: 1.5 $
* @package creole.util.sql * @package creole.util.sql
*/ */
class Tools_SQLStatementExtractor {
namespace ctiso\Tools;
use Exception;
class SQLStatementExtractor
{
/** @var string */
protected static $delimiter = ';'; protected static $delimiter = ';';
/** /**
@ -43,8 +36,7 @@ class SQLStatementExtractor
* @param string $filename Path to file to read. * @param string $filename Path to file to read.
* @return array SQL statements * @return array SQL statements
*/ */
public static function extractFile($filename) public static function extractFile($filename) {
{
$buffer = file_get_contents($filename); $buffer = file_get_contents($filename);
if ($buffer !== false) { if ($buffer !== false) {
return self::extractStatements(self::getLines($buffer)); return self::extractStatements(self::getLines($buffer));
@ -55,34 +47,31 @@ class SQLStatementExtractor
/** /**
* Extract statements from string. * Extract statements from string.
* *
* @param string $buffer * @param string $txt
* @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.
* *
* @param string[] $lines Lines of the read-in file. * @param array $lines Lines of the read-in file.
* @return string[] SQL statements * @return string
*/ */
protected static function extractStatements($lines) protected static function extractStatements($lines) {
{
$statements = []; $statements = array();
$sql = ""; $sql = "";
foreach($lines as $line) { foreach($lines as $line) {
$line = trim($line); $line = trim($line);
if ( if (self::startsWith("//", $line) ||
self::startsWith("//", $line) ||
self::startsWith("--", $line) || self::startsWith("--", $line) ||
self::startsWith("#", $line) self::startsWith("#", $line)) {
) {
continue; continue;
} }
@ -118,8 +107,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 starts with $check, or they are equal, or $check is empty. * @return boolean True if $string starts with $check, or they are equal, or $check is empty.
*/ */
protected static function startsWith($check, $string) protected static function startsWith($check, $string) {
{
if ($check === "" || $check === $string) { if ($check === "" || $check === $string) {
return true; return true;
} else { } else {
@ -133,8 +121,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 $string) protected static function endsWith($check/*: string*/, $string) {
{
if ($check === "" || $check === $string) { if ($check === "" || $check === $string) {
return true; return true;
} else { } else {
@ -145,13 +132,8 @@ 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
* @param string $string The string to get the substring from.
* @param int $startpos The start position of the substring.
* @param int $endpos The end position of the substring.
* @return string The substring.
*/ */
protected static function substring(string $string, int $startpos, int $endpos = -1) protected static function substring($string, $startpos, $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) {
@ -171,12 +153,12 @@ class SQLStatementExtractor
/** /**
* Convert string buffer into array of lines. * Convert string buffer into array of lines.
* *
* @param string $buffer * @param string $filename
* @return string[] lines of file. * @return array string[] lines of file.
*/ */
protected static function getLines(string $buffer): array protected static function getLines($buffer) {
{
$lines = preg_split("/\r?\n|\r/", $buffer); $lines = preg_split("/\r?\n|\r/", $buffer);
return $lines === false ? [] : $lines; return $lines;
} }
} }

110
src/Tools/String.php Normal file
View file

@ -0,0 +1,110 @@
<?php
class Tools_String {
// from creole
static function strToArray($str) {
$str = substr($str, 1, -1); // remove { }
$res = array();
$subarr = array();
$in_subarr = 0;
$toks = explode(',', $str);
foreach($toks as $tok) {
if ($in_subarr > 0) { // already in sub-array?
$subarr[$in_subarr][] = $tok;
if ('}' === substr($tok, -1, 1)) { // check to see if we just added last component
$res[] = static::strToArray(implode(',', $subarr[$in_subarr]));
$in_subarr--;
}
} elseif ($tok[0] === '{') { // we're inside a new sub-array
if ('}' !== substr($tok, -1, 1)) {
$in_subarr++;
// if sub-array has more than one element
$subarr[$in_subarr] = array();
$subarr[$in_subarr][] = $tok;
} else {
$res[] = static::strToArray($tok);
}
} else { // not sub-array
$val = trim($tok, '"'); // remove " (surrounding strings)
// perform type castng here?
$res[] = $val;
}
}
return $res;
}
//Нормализация строк на русском
static function normalizeRussian($str) {
$result = preg_replace('/\s+/',' ', $str);
if (is_string($result)) {
$result = trim($result); //Замена длинных пробелов на одинарные, пробелы по краям
$result = mb_strtolower($result);
$result = preg_replace('/ё/','е', $str); //е на ё
}
return $result;
}
//Проверка равенства двух строк на русском языке.
static function equalRussianCheck($str1,$str2) {
return self::normalizeRussian($str1) == self::normalizeRussian($str2);
}
/**
* Попадает ли строка в список вариантов
* input: $str="foo1" $variants="foo1|foo2|foo3"
* output: true
* input: $str="foo" $variants="foo1|foo2|foo3"
* output: false
*/
static function compare_string_to_variants($str, $variants){
$variants_array = explode('|', $variants);
$founded = false;
foreach ($variants_array as $variant) {
$founded = $founded || self::equalRussianCheck($variant, $str);
}
return $founded;
}
static function mb_str_split($str) {
return preg_split('~~u', $str, null, PREG_SPLIT_NO_EMPTY);
}
static function mb_strtr($str, $from, $to) {
return str_replace(self::mb_str_split($from), self::mb_str_split($to), $str);
}
static function encodestring($st) {
$st = self::mb_strtr($st,"абвгдеёзийклмнопрстуфхъыэ !+()", "abvgdeeziyklmnoprstufh_ie_____");
$st = self::mb_strtr($st,"АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ", "ABVGDEEZIYKLMNOPRSTUFH_IE");
$st = strtr($st, array(
" " => '_',
"." => '_',
"," => '_',
"?" => '_',
"\"" => '_',
"'" => '_',
"/" => '_',
"\\" => '_',
"%" => '_',
"#" => '_',
"*" => '_',
"ж"=>"zh", "ц"=>"ts", "ч"=>"ch", "ш"=>"sh",
"щ"=>"shch","ь"=>"", "ю"=>"yu", "я"=>"ya",
"Ж"=>"ZH", "Ц"=>"TS", "Ч"=>"CH", "Ш"=>"SH",
"Щ"=>"SHCH","Ь"=>"", "Ю"=>"YU", "Я"=>"YA",
"Й"=>"i", "й"=>"ie", "ё"=>"Ye",
""=>"N"
));
return strtolower($st);
}
static function validate_encoded_string($st) {
$enc_st = self::encodestring($st);
return preg_match('/^[\w_-]+(\.[\w_-]+)?$/', $enc_st);
}
}

View file

@ -1,168 +0,0 @@
<?php
namespace ctiso\Tools;
class StringUtil
{
/**
* Преобразует строку в массив
* @param string $str
* @return array
*/
static function strToArray(string $str): array
{
$str = substr($str, 1, -1); // remove { }
$res = [];
$subarr = [];
$in_subarr = 0;
$toks = explode(',', $str);
foreach ($toks as $tok) {
if ($in_subarr > 0) { // already in sub-array?
$subarr[$in_subarr][] = $tok;
if ('}' === substr($tok, -1, 1)) { // check to see if we just added last component
$res[] = static::strToArray(implode(',', $subarr[$in_subarr]));
$in_subarr--;
}
} elseif ($tok[0] === '{') { // we're inside a new sub-array
if ('}' !== substr($tok, -1, 1)) {
$in_subarr++;
// if sub-array has more than one element
$subarr[$in_subarr] = [];
$subarr[$in_subarr][] = $tok;
} else {
$res[] = static::strToArray($tok);
}
} else { // not sub-array
$val = trim($tok, '"'); // remove " (surrounding strings)
// perform type castng here?
$res[] = $val;
}
}
return $res;
}
/**
* Нормализация строк на русском
* @param string $str
* @return string
*/
static function normalizeRussian(string $str): string
{
$result = preg_replace('/\s+/', ' ', $str);
if (is_string($result)) {
$result = trim($result); //Замена длинных пробелов на одинарные, пробелы по краям
$result = mb_strtolower($result);
$result = preg_replace('/ё/', 'е', $str); //е на ё
}
return $result;
}
/**
* Проверка равенства двух строк на русском языке.
* @param string $str1
* @param string $str2
* @return bool
*/
static function equalRussianCheck($str1, $str2): bool
{
return self::normalizeRussian($str1) == self::normalizeRussian($str2);
}
/**
* Попадает ли строка в список вариантов
* input: $str="foo1" $variants="foo1|foo2|foo3"
* output: true
* input: $str="foo" $variants="foo1|foo2|foo3"
* output: false
*
* @param string $str
* @param string $variants
* @return bool
*/
static function compare_string_to_variants($str, string $variants)
{
$variants_array = explode('|', $variants);
$founded = false;
foreach ($variants_array as $variant) {
$founded = $founded || self::equalRussianCheck($variant, $str);
}
return $founded;
}
/**
* Разбивает строку на массив символов
* @param string $str
* @return array
*/
static function mb_str_split(string $str): array
{
return preg_split('~~u', $str, -1, PREG_SPLIT_NO_EMPTY) ?: [];
}
/**
* Заменяет символы в строке на символы из другой строки
* @param string $str
* @param string $from
* @param string $to
* @return string
*/
static function mb_strtr($str, $from, $to)
{
return str_replace(self::mb_str_split($from), self::mb_str_split($to), $str);
}
static function encodestring(string $st): string
{
$st = self::mb_strtr($st, "абвгдеёзийклмнопрстуфхъыэ !+()", "abvgdeeziyklmnoprstufh_ie_____");
$st = self::mb_strtr($st, "АБВГДЕЁЗИЙКЛМНОПРСТУФХЪЫЭ", "ABVGDEEZIYKLMNOPRSTUFH_IE");
$st = strtr($st, [
" " => '_',
"." => '_',
"," => '_',
"?" => '_',
"\"" => '_',
"'" => '_',
"/" => '_',
"\\" => '_',
"%" => '_',
"#" => '_',
"*" => '_',
"ж" => "zh",
"ц" => "ts",
"ч" => "ch",
"ш" => "sh",
"щ" => "shch",
"ь" => "",
"ю" => "yu",
"я" => "ya",
"Ж" => "ZH",
"Ц" => "TS",
"Ч" => "CH",
"Ш" => "SH",
"Щ" => "SHCH",
"Ь" => "",
"Ю" => "YU",
"Я" => "YA",
"Й" => "i",
"й" => "ie",
"ё" => "Ye",
"" => "N"
]);
return strtolower($st);
}
/**
* Проверяет, является ли строка кодированной
* @param string $st
* @return int|false
*/
static function validate_encoded_string(string $st): int|false
{
$enc_st = self::encodestring($st);
return preg_match('/^[\w_-]+(\.[\w_-]+)?$/', $enc_st);
}
}

View file

@ -3,18 +3,10 @@
/** /**
* Формат для композиции изображений * Формат для композиции изображений
*/ */
class Tools_TemplateImage
namespace ctiso\Tools;
use ctiso\Tools\Drawing;
use GdImage;
class TemplateImage
{ {
/** @var array<string, string> */ 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(
/** @var array<string, string> */
static array $listfonts = array(
'georgia' => 'georgia.ttf', 'georgia' => 'georgia.ttf',
'georgiabd' => 'georgiab.ttf', 'georgiabd' => 'georgiab.ttf',
'georgiaz' => 'georgiaz.ttf', 'georgiaz' => 'georgiaz.ttf',
@ -36,21 +28,19 @@ class TemplateImage
); );
/** @var string */
protected $src; protected $src;
protected array $context = []; protected $context = array();
protected array $data = []; protected $data = array();
protected string $base = "c:\\windows\\fonts\\"; protected $base = "c:\\windows\\fonts\\";
protected GdImage $image; protected $image;
/** @var bool */ protected $prepare = true;
protected $_prepare = true;
/** @var bool */
public $debug = false; public $debug = false;
public string $resource; public $filename;
public string $filename; public $resource;
function __construct(?array $template = null) function __construct ($template = false)
{ {
// assert(is_string($src));
if($template) { if($template) {
$this->data = $template; $this->data = $template;
} }
@ -59,71 +49,66 @@ class TemplateImage
/** /**
* Путь к изображению * Путь к изображению
*/ */
function resourcePath(string $path): void function resourcePath($path)
{ {
assert(is_string($path));
$this->resource = $path; $this->resource = $path;
} }
/** /**
* Путь у шрифтам * Путь у шрифтам
*/ */
function fontPath(string $path): void function fontPath($path)
{ {
assert(is_string($path));
$this->base = $path; $this->base = $path;
} }
/** function set($name, $value)
* @param string $name
* @param mixed $value
*/
function set(string $name, $value): void
{ {
$this->context['[' . $name . ']'] = $value; assert(is_string($name));
$this->context['['.$name.']'] = $this->encode($value);
} }
function setImage(string $name): void function setImage($name)
{ {
$this->filename = $name; $this->filename = $name;
$this->image = $this->imagefromfile($name); $this->image = $this->imagefromfile($name);
} }
/** function setEmptyImage($width, $height)
* Создает пустое изображение
* @param int<1, max> $width
* @param int<1, max> $height
*/
function setEmptyImage($width, $height): void
{ {
$this->image = imagecreatetruecolor($width, $height); $this->image = imagecreatetruecolor($width, $height);
} }
/** /**
* Создает изображение из файла * Создает изображение из файла
* @param string $file
* @return GdImage|null
*/ */
function imagefromfile(string $file) function imagefromfile($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)) {
$imageFn = 'imagecreatefrom' . self::$listfiles[$suffix]; return call_user_func('imagecreatefrom' . self::$listfiles[$suffix], $file);
if (!is_callable($imageFn)) {
return null;
}
return call_user_func($imageFn, $file);
} }
return null; return null;
} }
function getFontFile(string $name): string function getFontFile($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(array $style): string function fontSuffix($style)
{ {
if($style[0] && $style[1]) return "z"; if($style[0] && $style[1]) return "z";
@ -133,79 +118,51 @@ class TemplateImage
return ""; return "";
} }
/** function imageText($text, $value/*: stdClass*/)
* @param string $text
* @param object{
* fontFamily: string,
* fontSize: int,
* fontStyle: array{string, string},
* color: string,
* align: array,
* valign: array,
* left: int,
* top: int,
* width: int,
* height: int
* } $value
*/
function imageText(string $text, object $value): void
{ {
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));
$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 = Tools_Drawing::ALIGN_LEFT;
} elseif ($value->align[2]) { } elseif ($value->align[2]) {
$align = Drawing::ALIGN_RIGHT; $align = Tools_Drawing::ALIGN_RIGHT;
} else { } else {
$align = Drawing::ALIGN_CENTER; $align = Tools_Drawing::ALIGN_CENTER;
} }
if ($value->valign[0]) { if ($value->valign[0]) {
$valign = Drawing::ALIGN_TOP; $valign = Tools_Drawing::ALIGN_TOP;
} elseif ($value->valign[1]) { } elseif ($value->valign[1]) {
$valign = Drawing::ALIGN_CENTER; $valign = Tools_Drawing::ALIGN_CENTER;
} else { } else {
$valign = Drawing::ALIGN_BOTTOM; $valign = Tools_Drawing::ALIGN_BOTTOM;
} }
Drawing::imagettftextbox( Tools_Drawing::imagettftextbox($this->image, $size, 0, $value->left, $value->top, $color, $fontfile, $text,
$this->image, $value->width, $value->height,
$size, $align, $valign);
0,
$value->left,
$value->top,
$color,
$fontfile,
$text,
$value->width,
$value->height,
$align,
$valign
);
} }
/** /**
* Перекодировка текста * Перекодировка текста
* @deprecated Можно заменить encode($x) -> $x
*/ */
function encode(string $text): string function encode($text)
{ {
return $text; assert(is_string($text));
return $text; //iconv("WINDOWS-1251", "UTF-8", $text);
} }
/** function setSize($new_width, $new_height)
* @param int<1,max> $new_width
* @param ?int<1,max> $new_height
*/
function setSize(int $new_width, ?int $new_height = null): void
{ {
$width = imagesx($this->image); $width = imagesx($this->image);
$height = imagesy($this->image); $height = imagesy($this->image);
if ($new_height == null) { if($new_height == false) {
$new_height = max(1, (int)ceil($height * $new_width / $width)); $new_height = ceil($height * $new_width / $width);
} }
// Resample // Resample
@ -215,10 +172,9 @@ class TemplateImage
$this->image = $image_p; $this->image = $image_p;
} }
function prepare(): void function prepare() {
{ if($this->prepare) {
if ($this->_prepare) { $this->prepare = false;
$this->_prepare = false;
foreach ($this->data as $value) { foreach ($this->data as $value) {
$this->imageText($value->text, $value); // break; $this->imageText($value->text, $value); // break;
} }
@ -228,8 +184,10 @@ class TemplateImage
/** /**
* Генерирует изображение из шаблона * Генерирует изображение из шаблона
*/ */
function render(?string $file = null): string|bool function render($file = null)
{ {
assert(is_string($file) || is_null($file));
$this->prepare(); $this->prepare();
if ($file == null) { if ($file == null) {

View file

@ -1,19 +1,10 @@
<?php <?php
namespace ctiso; class UTF8 {
static function str_split($str, $split_length = 1) {
class UTF8
{
/**
* @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; $split_length = (int) $split_length;
$matches = []; $matches = array();
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

@ -1,31 +0,0 @@
<?php
namespace ctiso;
class Url {
/** @var array<string, string> */
public array $parts = [];
public ?Url $parent;
/**
* @param Url|null $parent
*/
function setParent($parent): void {
$this->parent = $parent;
}
/**
* @param string[] $parts
*/
function setQuery(array $parts): void {
$this->parts = $parts;
}
function addQueryParam(string $key, ?string $value): void {
$this->parts[$key] = $value;
}
function toString(): string {
return '?' . http_build_query(array_merge($this->parts, $this->parent ? $this->parent->parts : []));
}
}

View file

@ -1,16 +1,15 @@
<?php <?php
/**
* UserMessageException.php
*
*/
/** /**
* Исключение с понятным пользователю сообщением, которое имеет смысл ему показать. * Исключение с понятным пользователю сообщением, которое имеет смысл ему показать.
* @see Controller_Front * @see Controller_Front
*/ */
namespace ctiso; class UserMessageException extends Exception {
class UserMessageException extends \Exception {
/** @var string */
public $userMessage; public $userMessage;
/**
* @param string $message
*/
public function __construct($message) { public function __construct($message) {
parent::__construct($message); parent::__construct($message);
$this->userMessage = $message; $this->userMessage = $message;

View file

@ -0,0 +1,45 @@
<?php
abstract class Validator_Rule_Abstract
{
public $field;
protected $errorMsg;
protected $ctx;
public function __construct($field, $errorMsg = null)
{
$this->field = $field;
$this->errorMsg = $errorMsg;
}
public function setName($field)
{
$this->field = $field;
return $this;
}
public function setErrorMsg($errorMsg)
{
$this->errorMsg = $errorMsg;
return $this;
}
public function getErrorMsg()
{
return $this->errorMsg;
}
public function isValid(Collection $container, $status = null)
{
return true;
}
function skipEmpty() {
return true;
}
public function setContext($ctx)
{
$this->ctx = $ctx;
}
}

View file

@ -1,58 +0,0 @@
<?php
namespace ctiso\Validator\Rule;
use ctiso\Collection;
abstract class AbstractRule
{
public string $field;
protected ?string $errorMsg;
/** @var RuleContext */
protected $ctx;
public function __construct(string $field, ?string $errorMsg = null)
{
$this->field = $field;
$this->errorMsg = $errorMsg;
}
public function setName(string $field): self
{
$this->field = $field;
return $this;
}
public function setErrorMsg(?string $errorMsg): self
{
$this->errorMsg = $errorMsg;
return $this;
}
public function getErrorMsg(): string
{
return $this->errorMsg;
}
/**
* @param Collection $container
* @param bool|null $status
* @return bool
*/
public function isValid(Collection $container, $status = null): bool
{
return true;
}
function skipEmpty(): bool {
return true;
}
/**
* @param RuleContext $ctx
*/
public function setContext($ctx): void
{
$this->ctx = $ctx;
}
}

View file

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

View file

@ -3,17 +3,14 @@
/** /**
* Проверка формата электронной почты * Проверка формата электронной почты
*/ */
namespace ctiso\Validator\Rule; class Validator_Rule_Code extends Validator_Rule_Abstract
use ctiso\Validator\Rule\AbstractRule, {
ctiso\Collection; public function getErrorMsg()
class Code extends AbstractRule
{ {
public function getErrorMsg(): string {
return "Неправильно указан персональный код"; return "Неправильно указан персональный код";
} }
function checkCode(array $code): bool { function checkCode($code) {
foreach($code as $c) { foreach($code as $c) {
if (empty($c)) { if (empty($c)) {
return false; return false;
@ -22,15 +19,14 @@ class Code extends AbstractRule
return true; return true;
} }
public function isValid(Collection $container, $status = null): bool public function isValid(Collection $container, $status = null)
{ {
if ($status == 'update') return true; if ($status == 'update') return true;
$name = $this->field; $name = $this->field;
if (is_array($_POST[$name . '_code_genre'])) { if (is_array($_POST[$name . '_code_genre'])) {
$count = count($_POST[$name . '_code_genre']); for($n = 0; $n < count($_POST[$name . '_code_genre']); $n++) {
for($n = 0; $n < $count; $n++) { $code = array(
$code = [
$_POST[$name . '_code_genre'][$n], $_POST[$name . '_code_genre'][$n],
$_POST[$name . '_code_f'][$n], $_POST[$name . '_code_f'][$n],
$_POST[$name . '_code_i'][$n], $_POST[$name . '_code_i'][$n],
@ -38,14 +34,14 @@ class Code extends AbstractRule
$_POST[$name . '_code_year'][$n], $_POST[$name . '_code_year'][$n],
$_POST[$name . '_code_month'][$n], $_POST[$name . '_code_month'][$n],
$_POST[$name . '_code_day'][$n] $_POST[$name . '_code_day'][$n]
]; );
if (!$this->checkCode($code)) { if (!$this->checkCode($code)) {
return false; return false;
} }
} }
return true; return true;
} else { } else {
$code = [ $code = array(
$_POST[$name . '_code_genre'], $_POST[$name . '_code_genre'],
$_POST[$name . '_code_f'], $_POST[$name . '_code_f'],
$_POST[$name . '_code_i'], $_POST[$name . '_code_i'],
@ -53,7 +49,7 @@ class Code extends AbstractRule
$_POST[$name . '_code_year'], $_POST[$name . '_code_year'],
$_POST[$name . '_code_month'], $_POST[$name . '_code_month'],
$_POST[$name . '_code_day'] $_POST[$name . '_code_day']
]; );
return $this->checkCode($code); return $this->checkCode($code);
} }

View file

@ -3,38 +3,30 @@
/** /**
* Проверка формата даты * Проверка формата даты
*/ */
namespace ctiso\Validator\Rule; class Validator_Rule_Count extends Validator_Rule_Abstract
use ctiso\Validator\Rule\AbstractRule,
ctiso\Collection;
class Count extends AbstractRule
{ {
public int $size = 1; public $size = 1;
public ?int $max = null; public $max = false;
public function getErrorMsg(): string public function getErrorMsg()
{ {
return "Количество записей должно быть не менне {$this->size} и не более {$this->max}"; return "Количество записей должно быть не менне {$this->size} и не более {$this->max}";
} }
/** function not_empty($s) {
* @param string $s
* @return bool
*/
function notEmpty($s): bool {
return $s != ""; return $s != "";
} }
public function isValid(Collection $container, $status = null): bool public function isValid(Collection $container, $status = null)
{ {
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, 'notEmpty'])); explode(";", $container->get($this->field))), array($this, 'not_empty')));
return $count >= $this->size && $count <= ((int)$this->max); return $count >= $this->size && $count <= $this->max;
} }
} }

View file

@ -3,23 +3,21 @@
/** /**
* Проверка формата даты * Проверка формата даты
*/ */
namespace ctiso\Validator\Rule; class Validator_Rule_Date extends Validator_Rule_Abstract
use ctiso\Validator\Rule\AbstractRule,
ctiso\Collection;
class Date extends AbstractRule
{ {
public function getErrorMsg(): string private $split = "\\/";
public function getErrorMsg()
{ {
return "Неверный формат даты"; return "Неверный формат даты";
} }
public function isValid(Collection $container, $status = null): bool public function isValid(Collection $container, $status = null)
{ {
$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($matches[2], $matches[1], $matches[3]));
} }
} }

View file

@ -3,21 +3,23 @@
/** /**
* Проверка формата электронной почты * Проверка формата электронной почты
*/ */
namespace ctiso\Validator\Rule; class Validator_Rule_Email extends Validator_Rule_Abstract
use ctiso\Validator\Rule\AbstractRule,
ctiso\Collection;
class Email extends AbstractRule
{ {
public function getErrorMsg(): string public function getErrorMsg()
{ {
return "Неверный формат электронной почты"; return "Неверный формат электронной почты";
} }
public function isValid(Collection $container, $status = null): bool public function isValid(Collection $container, $status = null)
{ {
$user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\|\{\}~\']+';
$doIsValid = '(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]\.?)+';
$ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
$ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';
$emails = explode(",", $container->get($this->field)); $emails = explode(",", $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;
} }

View file

@ -3,20 +3,22 @@
/** /**
* Проверка формата электронной почты * Проверка формата электронной почты
*/ */
namespace ctiso\Validator\Rule; class Validator_Rule_EmailList extends Validator_Rule_Abstract
use ctiso\Validator\Rule\AbstractRule,
ctiso\Collection;
class EmailList extends AbstractRule
{ {
public function getErrorMsg(): string public function getErrorMsg()
{ {
return "Неверный формат электронной почты"; return "Неверный формат электронной почты";
} }
public function isValid(Collection $container, $status = null): bool { public function isValid(Collection $container, $status = null) {
$user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\|\{\}~\']+';
$doIsValid = '(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]\.?)+';
$ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
$ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';
$emails = $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

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

View file

@ -3,28 +3,24 @@
/** /**
* Проверка формата времени * Проверка формата времени
*/ */
namespace ctiso\Validator\Rule; class Validator_Rule_IsFile extends Validator_Rule_Abstract
use ctiso\Validator\Rule\AbstractRule,
ctiso\Collection;
class IsFile extends AbstractRule
{ {
private array $type = []; private $type = array();
private int $maxsize = 1024; private $maxsize = 1024;
function skipEmpty(): bool { function skipEmpty() {
return false; return false;
} }
function setSize(int $size): void { function setSize($size) {
$this->maxsize = $size; $this->maxsize = $size;
} }
function setType(array $type): void { function setType(array $type) {
$this->type = $type; $this->type = $type;
} }
public function isValid(Collection $container, $status = null): bool public function isValid(Collection $container, $status = null)
{ {
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('Файл не загружен');

View file

@ -3,22 +3,16 @@
/** /**
* Проверка на равентство двух полей * Проверка на равентство двух полей
*/ */
namespace ctiso\Validator\Rule; class Validator_Rule_Match extends Validator_Rule_Abstract
use ctiso\Validator\Rule\AbstractRule,
ctiso\Collection;
class MatchRule extends AbstractRule
{ {
/** @var string */
public $same; public $same;
public function getErrorMsg(): string public function getErrorMsg()
{ {
return "Поля не совпадают"; return "Поля не совпадают";
} }
public function isValid(Collection $container, $status = null): bool public function isValid(Collection $container, $status = null) {
{
return (strcmp($container->get($this->field), $container->get($this->same)) == 0); return (strcmp($container->get($this->field), $container->get($this->same)) == 0);
} }
} }

Some files were not shown because too many files have changed in this diff Show more