<?php
namespace WebBundle\Service;
/*
* class: BaseService
* -----------------------------------------------------
* базовый класс для сервисов, исключительно для наследования.
*/
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use WebBundle\Helper\App;
abstract class ExtendService
{
protected array $errors = [];
/**
* Получаем объект сервиса
* @param $id
* @return object
*/
public function get($id)
{
return App::getContainer()->get($id);
}
/**
* translator
* @param $val
* @param array $parameters
* @param null $domain
* @param null $locale
* @return string
*/
public function translate($val, $locale = null, array $parameters = [], $domain = null): string
{
return App::getTranslator()->trans($val, $parameters, $domain, $locale);
}
/**
* Renders a view.
*
* @param string $view The view name
* @param array $parameters An array of parameters to pass to the view
* @return string
*/
public function render(string $view, array $parameters = []): string
{
$content = App::getContainer()->get('twig')->render($view, $parameters);
// фикс лишних табов и переносов строк от твига
$content = preg_replace(['#\\t{2,}#umi'], [' '], $content);
$content = preg_replace(['# {2,}#umi'], [' '], $content);
return preg_replace(['#\\n{2,}#umi'], [''], $content);
}
/**
* Generates a URL from the given parameters.
* @param string $route The name of the route
* @param mixed $parameters An array of parameters
* @param bool|int|string $referenceType
* @return string The generated URL
* @see UrlGeneratorInterface
*/
public function generateUrl(string $route, $parameters = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string
{
return urldecode(App::getRouter()->generate($route, $parameters, $referenceType));
}
protected function setError(string $error): void
{
$this->errors[] = $error;
}
/**
* Получение ошибок в сервисе
* @return string
*/
public function getErrors(): string
{
$error = count($this->errors) == 1 ? $this->errors[0] : implode('; ', $this->errors);
return is_array($error) ? json_encode($error) : $error;
}
/**
* Проверка наличия ошибок в сервисе
* @return bool
*/
public function hasErrors(): bool
{
return 0 < count($this->errors);
}
}