[], 'code'=>[]];
/** @var string название глобального объекта JavaScript кода отвечающего за управление блоком */
protected $templateJsObject = '';
/** @var string префикс CSS класса блока */
private $cssClass = '';
public function init()
{
if (! parent::init() ) {
return false;
}
return true;
}
/**
* Устанавливаем путь к шаблонам
* @param string к директории шаблонов
*/
public function setTemplateDir($path)
{
$this->templateDir = $path;
}
/**
* Получаем путь к шаблонам
* @return string
*/
public function getTemplateDir()
{
return $this->templateDir;
}
/**
* Устанавливаем название файла шаблона блока
* @param string название файла без расширения '.php'
*/
public function setTemplateName($name)
{
$this->templateName = $name;
}
/**
* Устанавливаем контроллер и его метод
* @param \Module $controller объект контроллера
* @param string|null $action название метода контроллера
*/
public function setController($controller, $action = null)
{
$this->controller = $controller;
if ($action !== null) {
$this->controllerAction = $action;
}
}
/**
* Получаем объект контроллера
* @return \Module $controller объект контроллера
*/
public function getController()
{
return $this->controller;
}
/**
* Получаем название контроллера
* @return string
*/
public function getControllerName()
{
if ($this->controllerName) {
return $this->controllerName;
}
if (isset($this->list) && method_exists($this->list, 'getControllerName')) {
return $this->list->getControllerName();
}
if ($this->controller !== null) {
if (is_a($this->controller, '\Module')) {
return $this->controller->module_name;
}
}
return '';
}
/**
* Установим название контроллера
* @param $name
* @return static
*/
public function setControllerName($name)
{
$this->controllerName = $name;
return $this;
}
/**
* Получаем название метода контроллера
* @return string название метода
*/
public function getControllerAction()
{
return $this->controllerAction;
}
/**
* Установим название метода контроллера
* @param string $action название метода контроллера
* @return static
*/
public function setControllerAction($action)
{
$this->controllerAction = $action;
return $this;
}
/**
* Возвращаем префикс класса блока
* @param string $plus
* @return string
*/
public function cssClass($plus = '')
{
if ($this->cssClass === '') {
$this->defaultCssClass();
}
return $this->cssClass . $plus;
}
/**
* Установить префикс CSS класса блока
* @param string $class
* @return string
*/
public function defaultCssClass($class = '')
{
if ($class) {
$this->cssClass = $class;
} else {
$this->cssClass = join('-', [
'j',
$this->getControllerName(),
$this->getControllerAction(),
'block',
]);
}
return $this->cssClass;
}
/**
* Устанавливаем parent блок
* @param Block $parent
*/
protected function setParent(Block $parent)
{
$this->setController($parent->getController(), $parent->getControllerAction());
$this->setTemplateDir($parent->getTemplateDir());
$this->parent = $parent;
}
/**
* Получаем parent блок
* @return Block
*/
public function getParent()
{
return $this->parent;
}
/**
* Проверка наличия parent блока
* @return boolean
*/
public function hasParent()
{
return $this->parent !== null;
}
/**
* Отрисовываем блок
* @param array $data доп. данные шаблона
* @return string HTML
*/
public function view(array & $data = [])
{
return $this->render($data);
}
/**
* Действия выполняемые перед отрисовкой блока
*/
protected function beforeRender()
{
}
/**
* Отрисовка блока
* @param array $data дополнительные данные, передаваемые в шаблон
* @param string|null $view название шаблона или шаблон блока (по умолчанию)
* @param string|null $path название директории шаблона
* @param array $opts
* @return string HTML
*/
protected function render(array &$data = [], ?string $view = null, ?string $path = null, array $opts = [])
{
$this->beforeRender();
$data['jsObject'] = $this->templateJsObject;
# context
$data['block'] = $this;
$opts['this'] = $opts['this'] ?? $this;
# hook prefix
$opts['hookPrefix'] = 'view.tpl'; # view.tpl
return $this->view->render(
$data,
(!empty($view) ? $view : $this->templateName),
(!empty($path) ? $path : $this->templateDir),
$opts
) . ( empty($data['noJsRender']) ? $this->jsRender() : '');
}
/**
* Подключаем JavaScript файлы
* @param string|array $include название библиотеки (без расширения ".js") или полный URL
* @param bool $core подключаем версию ядра
* @param bool $version версия подключаемого файла или FALSE
*/
public function jsInclude($include, $core = true, $version = false)
{
if (empty($include)) {
return;
}
if (is_array($include)) {
foreach ($include as $v) {
$this->templateJs['includes'][] = strval($v);
}
} elseif (is_string($include)) {
$this->templateJs['includes'][] = array('file'=>$include, 'core'=>$core, 'version'=>(!$core ? $version : false));
}
}
/**
* Начало блока с JavaScript кодом
* @param string $jsObjectName название объекта отвечающего за управление блоком
*/
public function jsStart($jsObjectName = '')
{
if (! empty($jsObjectName) && is_string($jsObjectName)) {
$this->templateJsObject = $jsObjectName;
}
ob_start();
ob_implicit_flush(false);
}
/**
* Завершаем блок с JavaScript кодом
*/
public function jsStop()
{
$this->templateJs['code'][] = ltrim(ob_get_clean());
}
/**
* Рендеринг блоков JavScript кода
* @param array $attr атрибуты ';
}
$return .= $code;
unset($this->templateJs['code'][$k]);
}
return $return;
}
/**
* Словарь иконок с bootstrap2
* @param string $icon класс иконки в bootstrap2
* @return string
*/
public function iconDictionary($icon = '')
{
if (empty($icon)) return '';
$data = [
'icon' => $icon,
'noJsRender' => true,
];
$html = $this->render($data, 'icon.dictionary');
if (empty($html)) {
$html = $icon;
}
return $html;
}
# === ajax ответы ===
/**
* Формируем ответ на ajax-запрос
* Rсли data=0,1,2 - это не ключ ошибки, а просто краткий ответ
* @param mixed $data response data
* @param mixed $format response type; 0|false - raw echo, 1|true - json echo, 2 - json echo + errors
* @param bool $nativeJsonEncode использовать json_encode
* @param bool $escapeHTML енкодить html теги, при возвращении результата в iframe
* @throws ResponseException
*/
protected function ajaxResponse($data, $format = 2, $nativeJsonEncode = false, $escapeHTML = false)
{
$this->response(
parent::ajaxResponse($data, $format, $nativeJsonEncode, $escapeHTML)
);
}
/**
* Формируем ответ на ajax-запрос (для формы)
* @param array $data response data
* @param mixed $format response type; 0|false - raw echo, 1|true - json echo, 2 - json echo + errors
* @param bool $nativeJsonEncode использовать json_encode
* @param bool $escapeHTML енкодить html теги, при возвращении результата в iframe
* @throws ResponseException
*/
public function ajaxResponseForm(array $data = [], $format = 2, $nativeJsonEncode = false, $escapeHTML = false)
{
$this->response(
parent::ajaxResponseForm($data, $format, $nativeJsonEncode, $escapeHTML)
);
}
/**
* Формируем ответ на ajax-запрос (для формы отправленной через bff.iframeSubmit)
* @param array $data response data
* @throws ResponseException
*/
protected function iframeResponseForm(array $data = [])
{
$this->response(
parent::iframeResponseForm($data)
);
}
/**
* Response исключение с переадресацией
* @param string $url
* @return mixed
* @throws ResponseException
*/
public function redirect($url)
{
$response = ResponseFactory::redirect($url);
$this->response(
$response
);
return $response;
}
/**
* Response исключение с ответом
* @param \bff\http\Response|mixed $response
* @return mixed
* @throws ResponseException
*/
public function response($response = null)
{
if ($response instanceof Response) {
$response->throw();
}
return $response;
}
# === вспомогательные методы ===
/**
* Обвертка для HTML::attributeAdd
* @param array $attributes @ref атрибуты
* @param string $key ключ атрибута
* @param mixed $value значение
*/
public static function attrAdd(array & $attributes, $key, $value)
{
HTML::attributeAdd($attributes, $key, $value);
}
/**
* Обвертка для HTML::attributeRemove
* @param array $attributes
* @param string $key ключ атрибута
* @param mixed $value значение или массив значений, которые необходимо удалить
*/
public static function attrRemove(array & $attributes, $key, $value)
{
HTML::attributeRemove($attributes, $key, $value);
}
/**
* Обвертка для HTML::attributes
* @param array $attributes
* @return string
*/
public static function attributes($attributes, array $defaults = array(), array $except = array())
{
return HTML::attributes($attributes, $defaults, $except);
}
/**
* Вспомогательная обвертка для вызова callable wrapper в шаблонах
* @param string $result @ref указатель на переменную, для сохранения результат вызова
* @param array $handler @ref массив ['callable', 'ob']
* callable 'callable' - callable wrapper шаблона
* null 'ob' = null - определить необходимость использования буферизации вывода
* bool 'ob' = true - использовать буферизацию вывода
* bool 'ob' = false - не использовать буферизацию вывода
* @param callable $callback функция для вызова callable wrapper'а необходимо для возможности передачи разного количества аргументов
* @param array $opts параметры ['js', 'function']
* bool 'js' = true - вырезать тег