src/WebBundle/Helper/App.php line 678

Open in your IDE?
  1. <?php
  2. namespace WebBundle\Helper;
  3. use Doctrine\Bundle\DoctrineBundle\Registry;
  4. use Doctrine\ORM\EntityManager;
  5. use Doctrine\ORM\NonUniqueResultException;
  6. use Doctrine\ORM\ORMException;
  7. use Doctrine\Persistence\ObjectRepository;
  8. use Exception;
  9. use FlexApp\Constant\TimeConstant;
  10. use FlexApp\Service\BBCodeManager;
  11. use FlexApp\ValueObject\LocaleVo;
  12. use LogicException;
  13. use Memcache;
  14. use Monolog\Logger;
  15. use Pheanstalk\Pheanstalk;
  16. use RuntimeException;
  17. use Symfony\Component\DependencyInjection\Container;
  18. use Symfony\Component\DependencyInjection\ContainerInterface;
  19. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\HttpFoundation\Session\Session;
  22. use Symfony\Component\HttpKernel\HttpKernelInterface;
  23. use Symfony\Component\HttpKernel\Kernel;
  24. use Symfony\Component\HttpKernel\KernelInterface;
  25. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  26. use Symfony\Component\Process\Process;
  27. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  28. use Symfony\Component\Routing\RouterInterface;
  29. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  30. use Symfony\Component\Security\Csrf\CsrfToken;
  31. use Symfony\Component\Translation\IdentityTranslator;
  32. use Symfony\Component\VarDumper\VarDumper;
  33. use Twig_Environment;
  34. use WebBundle\Constant\CookieKeysConstant;
  35. use WebBundle\Entity\ListCountry;
  36. use WebBundle\Entity\User;
  37. use WebBundle\Repository\ListCountryRepository;
  38. use WebBundle\Service\LocationService;
  39. use WebBundle\Service\SphinxSearcherService;
  40. use WebBundle\WebBundle;
  41. /*
  42.  * class: Help
  43.  * -----------------------------------------------------
  44.  * Класс хелпера, для упрошенного обращения в методам и функциям.
  45.  * @package WebBundle\Helper
  46.  */
  47. class App
  48. {
  49.     private static $isGeneral;
  50.     private static $oContainer;
  51.     private static $sCountryList;
  52.     private static $sCurCountryData;
  53.     private static $oRouter;
  54.     private static $oPortal;
  55.     private static $oSphinxSearcher;
  56.     private static $oRequest;
  57.     private static $oLogger;
  58.     private static $oKernel;
  59.     private static $oSession;
  60.     private static $oTwig;
  61.     private static $oTranslator;
  62.     private static $oDoctrine;
  63.     private static $oEntityManager;
  64.     private static $microtime;
  65.     private static array $langsAvailable = [];
  66.     /**
  67.      * Хелпер Дамепра от Symfony, передавать можно любое количество парметров
  68.      * @param $params
  69.      * @return mixed
  70.      */
  71.     public static function dump(...$params)
  72.     {
  73.         if ($params) {
  74.             $params = (count($params) <= 1) ? $params[0] : $params;
  75.         } else {
  76.             $params '';
  77.         }
  78.         return VarDumper::dump($params);
  79.     }
  80.     /**
  81.      * Хелпер Дамепра от Symfony, передавать можно любое количество парметров
  82.      * Обернут в exit , для остановки дальнейшего вывода кода
  83.      * @param $params
  84.      */
  85.     public static function dumpExit(...$params)
  86.     {
  87.         if ($params) {
  88.             $params = (count($params) <= 1) ? $params[0] : $params;
  89.         } else {
  90.             $params '';
  91.         }
  92.         exit(VarDumper::dump($params));
  93.     }
  94.     /**
  95.      * Иногда удобнее вывести не через дамепр symfony
  96.      * @param $params
  97.      */
  98.     public static function debug(...$params)
  99.     {
  100.         if ($params) {
  101.             $params = (count($params) <= 1) ? $params[0] : $params;
  102.         } else {
  103.             $params '';
  104.         }
  105.         echo '<pre>';
  106.         print_r($params);
  107.         echo '</pre>';
  108.     }
  109.     /**
  110.      * Иногда удобнее вывести не через дамепр symfony
  111.      * Обернут в exit , для остановки дальнейшего вывода кода
  112.      * @param $params
  113.      */
  114.     public static function debugExit(...$params)
  115.     {
  116.         if ($params) {
  117.             $params = (count($params) <= 1) ? $params[0] : $params;
  118.         } else {
  119.             $params '';
  120.         }
  121.         echo '<pre>';
  122.         print_r($params);
  123.         exit('</pre>');
  124.     }
  125.     /**
  126.      * @return ContainerInterface|Container
  127.      */
  128.     public static function getContainer()
  129.     {
  130.         if (!static::$oContainer) {
  131.             static::$oContainer WebBundle::getContainer();
  132.         }
  133.         return static::$oContainer;
  134.     }
  135.     /**
  136.      * @return string
  137.      * @throws Exception
  138.      */
  139.     public static function csrfToken()
  140.     {
  141.         /** @var CsrfToken $securityCsrf */
  142.         $securityCsrf self::getContainer()->get('security.csrf.token_manager')->getToken('authenticate');
  143.         return $securityCsrf->getValue();
  144.     }
  145.     /**
  146.      * @param string $id
  147.      * @param ?string $locale
  148.      * @param ?array $parameters
  149.      * @param ?string $domain
  150.      * @return string
  151.      */
  152.     public static function trans(string $id, ?string $locale null, ?array $parameters = [], ?string $domain null): string
  153.     {
  154.         try {
  155.             return static::getTranslator()->trans($id$parameters$domain$locale);
  156.         } catch (Exception $e) {
  157.             return $id;
  158.         }
  159.     }
  160.     /**
  161.      * @param       $id
  162.      * @param null $locale
  163.      * @param array $parameters
  164.      * @param null $domain
  165.      * @return string
  166.      * @throws Exception
  167.      */
  168.     public static function transReact($id$locale null, array $parameters = [], $domain null)
  169.     {
  170.         $localeValue = new LocaleVo($localeApp::getRequest()->request->get('countryCode'null));
  171.         $bbCodeManager = static::getContainer()->get(BBCodeManager::class)->init($localeValue);
  172.         return $bbCodeManager->parse(static::getTranslator()->trans($id$parameters$domain$locale));
  173.     }
  174.     /**
  175.      * Текущая локаль юзера
  176.      * @param bool $full
  177.      * @return string
  178.      */
  179.     public static function getCurLocale($full false)
  180.     {
  181.         return LocaleHelper::getCurLocale($full);
  182.     }
  183.     /**
  184.      * Текущая страна пользователя
  185.      * @return string
  186.      * @throws Exception
  187.      */
  188.     public static function getCurCountry(): string
  189.     {
  190.         return LocaleHelper::getCurCountry();
  191.     }
  192.     public static function getCurCountryEntity(): ?ListCountry
  193.     {
  194.         $countryRepository = static::getRepository(ListCountry::class);
  195.         return $countryRepository->find(static::getCurCountryId());
  196.     }
  197.     /**
  198.      * Текущая страна пользователя
  199.      * @return int
  200.      * @throws Exception
  201.      */
  202.     public static function getCurCountryId()
  203.     {
  204.         $id self::getCountryList()[LocaleHelper::getCurCountry()]['id'] ?? null;
  205.         return empty($id) ? 380 $id;
  206.     }
  207.     /**
  208.      * Получение кода страны.
  209.      *
  210.      * @param bool $forIp
  211.      * @return null|string
  212.      * @throws NonUniqueResultException
  213.      * @throws ORMException
  214.      * @throws Exception
  215.      */
  216.     public static function getCountryCode($forIp false): ?string
  217.     {
  218.         $locationCode CookieHelper::get(CookieKeysConstant::COUNTRY);
  219.         // проверяем правильность кода страны
  220.         if (!empty($locationCode) && empty(static::getCountryList()[$locationCode])) {
  221.             unset($locationCode);
  222.         }
  223.         if (empty($locationCode)) {
  224.             $locationCode LocaleHelper::getCurCountry();
  225.             if ($forIp || $locationCode == 'en') {
  226.                 $locationCode = static::getCountryByIp();
  227.             }
  228.             // проверяем правильность кука
  229.             if (empty($locationCode) || empty(static::getCountryList()[$locationCode])) {
  230.                 $locationCode 'us';
  231.             }
  232.             CookieHelper::set(CookieKeysConstant::COUNTRY$locationCode, ['httponly' => false]);
  233.         }
  234.         return $locationCode;
  235.     }
  236.     /**
  237.      * @param string|null $ip
  238.      * @return string
  239.      * @throws Exception
  240.      */
  241.     public static function getCountryByIp($ip null)
  242.     {
  243.         /** @var LocationService $locationService */
  244.         $locationService = static::getContainer()->get('app.service.location');
  245.         $location $locationService->getCountryRecord($ip != null $ip : static::getRequest()->getClientIp());
  246.         return strtolower($location $location->country->isoCode 'us');
  247.     }
  248.     public static function getLangsAvailable(): array
  249.     {
  250.         if (empty(static::$langsAvailable)) {
  251.             static::$langsAvailable explode('|'App::getParameter('langs_available'));
  252.         }
  253.         return static::$langsAvailable;
  254.     }
  255.     /**
  256.      * Список стран, с которыми работаем
  257.      * @param bool $full
  258.      * @return array
  259.      * @throws Exception
  260.      */
  261.     public static function getCountryList(bool $full false): array
  262.     {
  263.         $translator self::getTranslator();
  264.         $memcache = static::getMemcache();
  265.         $memcacheKey 'APP_GET_COUNTRY_LIST_CACHE' $translator->getLocale() . $full;
  266.         $sCountryList $memcache->get($memcacheKey);
  267.         if (!empty($sCountryList)) {
  268.             return $sCountryList;
  269.         }
  270.         /** @var ListCountryRepository $countryRepo */
  271.         $countryRepo self::getDoctrine()->getRepository(ListCountry::class);
  272.         $countries $countryRepo->getListForLocalize();
  273.         $countryList = [];
  274.         /** @var ListCountry $country */
  275.         foreach ($countries as $country) {
  276.             $locales explode('|'$country['locale']);
  277.             $name $translator->trans($country['alias']);
  278.             $code strtolower($country['code']);
  279.             $countryList[$code] = [
  280.                 'id' => $country['id'],
  281.                 'code' => $code,
  282.                 'name' => $name,
  283.                 'alias' => $country['alias'],
  284.                 'locale' => $locales[0],
  285.                 'locales' => $country['locale'],
  286.                 'localesArr' => $locales,
  287.                 'pvType' => $country['pvType'],
  288.                 'phoneCode' => $country['phoneCode'],
  289.             ];
  290.         }
  291.         // Сортировка стран по алфавиту
  292.         // Если сортировать просто asort($countryList) то он отсортирует по id
  293.         $cSort array_column($countryList'name''code');
  294.         asort($cSort);
  295.         $sortedCountryList = [];
  296.         foreach ($cSort as $key => $value) {
  297.             $sortedCountryList[$key] = $countryList[$key];
  298.         }
  299.         // принято решение убрать локализацию "весь мир"
  300.         // убираем фиктивные страны
  301.         if (!$full) {
  302.             unset($sortedCountryList['es-cn']);
  303.         }
  304.         // ставим кеш на месяц
  305.         $memcache->add($memcacheKey$sortedCountryListMEMCACHE_COMPRESSED, (int) TimeConstant::MONTH);
  306.         return $sortedCountryList;
  307.     }
  308.     /**
  309.      * Текущая страна пользователя
  310.      * @return array
  311.      * @throws Exception
  312.      */
  313.     public static function getCurCountryData()
  314.     {
  315.         if (!static::$sCurCountryData) {
  316.             $list self::getCountryList();
  317.             if (self::getCurCountry() == 'en') {
  318.                 $list[self::getCurCountry()]['pvType'] = 2;
  319.             }
  320.             static::$sCurCountryData $list[self::getCurCountry()];
  321.         }
  322.         return static::$sCurCountryData;
  323.     }
  324.     /**
  325.      * @param $objectName
  326.      * @param null $managerName
  327.      * @return ObjectRepository
  328.      * @throws Exception
  329.      */
  330.     public static function getRepository($objectName$managerName null)
  331.     {
  332.         return self::getDoctrine()->getRepository($objectName$managerName);
  333.     }
  334.     /**
  335.      * @return mixed
  336.      * @throws Exception
  337.      */
  338.     public static function getCountryListId()
  339.     {
  340.         $memcache = static::getMemcache();
  341.         $memcacheKey 'APP_GET_COUNTRY_LIST_ID_CACHE';
  342.         $sCountryListId $memcache->get($memcacheKey);
  343.         if (!empty($sCountryListId)) {
  344.             return $sCountryListId;
  345.         }
  346.         /** @var ListCountryRepository $countryRepo */
  347.         $countryRepo = static::getRepository('WebBundle:ListCountry');
  348.         $countries $countryRepo->getListForLocalize();
  349.         $countryList = [];
  350.         /** @var ListCountry $country */
  351.         foreach ($countries as $country) {
  352.             $countryList[] = $country['id'];
  353.         }
  354.         // ставим кеш на месяц
  355.         $memcache->add($memcacheKey$countryListMEMCACHE_COMPRESSED, (int) TimeConstant::MONTH);
  356.         return $countryList;
  357.     }
  358.     /**
  359.      * @return RouterInterface
  360.      */
  361.     public static function getRouter()
  362.     {
  363.         if (!static::$oRouter) {
  364.             try {
  365.                 static::$oRouter = static::getContainer()->get('router');
  366.             } catch (Exception $e) {
  367.             }
  368.         }
  369.         return static::$oRouter;
  370.     }
  371.     /**
  372.      * @return PortalHelper
  373.      * @throws Exception
  374.      */
  375.     public static function getPortal()
  376.     {
  377.         if (!static::$oPortal) {
  378.             static::$oPortal = static::getContainer()->get('portal');
  379.         }
  380.         return static::$oPortal;
  381.     }
  382.     /**
  383.      * Получение значений из параметров
  384.      * @param string $name
  385.      * @return mixed
  386.      * @throws InvalidArgumentException
  387.      */
  388.     public static function getParameter($name)
  389.     {
  390.         return self::getContainer()->getParameter($name);
  391.     }
  392.     /**
  393.      * Получение имени своего домена без лишних данных из конфига.
  394.      * @return mixed|string
  395.      */
  396.     public static function getDomain()
  397.     {
  398.         $domain = static::getParameter('domain');
  399.         $domain trim($domain'.');
  400.         $domain trim($domain);
  401.         return $domain;
  402.     }
  403.     /**
  404.      * @return Memcache
  405.      * @throws Exception
  406.      */
  407.     public static function getMemcache(): Memcache
  408.     {
  409.         return static::getContainer()->get('app.service.cache')->getMemcache();
  410.     }
  411.     /**
  412.      * Получаем чистое имя класса без неймспейсов
  413.      * @param $obj
  414.      * @return null|string
  415.      */
  416.     public static function getClassName($obj)
  417.     {
  418.         $name is_object($obj) ? get_class($obj) : $obj;
  419.         $name str_replace('\\''/'$name);
  420.         $name explode('/'$name);
  421.         $name array_pop($name);
  422.         return $name;
  423.     }
  424.     /**
  425.      * @return object|SphinxSearcherService
  426.      * @throws Exception
  427.      */
  428.     public static function getSphinxSearcher()
  429.     {
  430.         if (!static::$oSphinxSearcher) {
  431.             static::$oSphinxSearcher = static::getContainer()->get('sphinx_searcher');
  432.         }
  433.         return static::$oSphinxSearcher;
  434.     }
  435.     /**
  436.      * @param array $data
  437.      * @param int $limit
  438.      * @param bool $withSchema
  439.      * @param bool $full
  440.      * @param bool $getCount
  441.      * @return array
  442.      * @throws Exception
  443.      */
  444.     public static function searchSphinx($data = [], $limit 0$withSchema false$full false$getCount false)
  445.     {
  446.         return static::getSphinxSearcher()->searchSphinx($data$limit$withSchema$full$getCount);
  447.     }
  448.     /**
  449.      * @return bool
  450.      */
  451.     public static function getHash()
  452.     {
  453.         return md5(static::getContainer()->getParameter('salt') . date("Y.m.d"));
  454.     }
  455.     /**
  456.      * генератор MetaDescription из тектовой стороки
  457.      * @param $text
  458.      * @return string
  459.      */
  460.     public static function genMetaDescription($text)
  461.     {
  462.         $limitChar 150;
  463.         $desc '';
  464.         $text strip_tags($text);
  465.         $text html_entity_decode($text);
  466.         $arr explode("."$text);
  467.         foreach ($arr as $str) {
  468.             $descTmp '';
  469.             if (mb_strlen($str'UTF-8') > 3) {
  470.                 $descTmp $desc $str '. ';
  471.             }
  472.             if (mb_strlen($descTmp'UTF-8') > $limitChar && mb_strlen($desc'UTF-8') > 80) {
  473.                 break;
  474.             }
  475.             if (mb_strlen($descTmp'UTF-8') > $limitChar) {
  476.                 $descTmp StrHelper::cutText($descTmp$limitChar);
  477.             }
  478.             $desc $descTmp;
  479.         }
  480.         $desc trim($desc);
  481.         return $desc;
  482.     }
  483.     /**
  484.      * @param          $route
  485.      * @param array $parameters
  486.      * @param bool|int $referenceType
  487.      * @return string
  488.      * @throws Exception
  489.      */
  490.     public static function generateUrl($route$parameters = [], $referenceType UrlGeneratorInterface::ABSOLUTE_PATH)
  491.     {
  492.         $url = static::getRouter()->generate($route$parameters$referenceType);
  493.         return urldecode($url);
  494.     }
  495.     /**
  496.      * Перевод строки ТП в массив. Только строки коротые под plural
  497.      * @param string $str
  498.      * @return string[]
  499.      */
  500.     public static function transPluralStrToArray(string $str): array
  501.     {
  502.         $rows explode('|'$str);
  503.         $pattern '~\{(\d)}(.*)~';
  504.         foreach ($rows as $i => $r) {
  505.             preg_match($pattern$r$out);
  506.             $rows[$i] = [
  507.                 'key' => intval($out[1]),
  508.                 'val' => trim($out[2]),
  509.             ];
  510.         }
  511.         return $rows;
  512.     }
  513.     /**
  514.      * Получаем склонение, в виде числа, что соответвует
  515.      * 0 = 0 комментариев
  516.      * 1 = 1 комментарий
  517.      * 2 = 2 комментария
  518.      * 3 = 5 комментариев
  519.      * @param $number
  520.      * @param null $lc
  521.      * @param null $allowLang
  522.      * @param int $allowKey включает доп ключь для варианта перевода
  523.      * @return int
  524.      */
  525.     public static function plural($number$lc null$allowLang null$allowKey 0)
  526.     {
  527.         $lc $lc $lc App::getCurLocale();
  528.         $number intval($number);
  529.         $cases = [201112];
  530.         if ($number 0) {
  531.             $res = ($number 100 && $number 100 20) ? $cases[min($number 105)];
  532.             $res $res 1;
  533.         } else {
  534.             $res $number;
  535.         }
  536.         // сделал что бы можно было включать желаемый вариант сколнения по по языку и добовлять нужный ключь склонения
  537.         if ($allowKey && $allowLang && $lc == $allowLang) {
  538.             if ($number && $res == $allowKey) {
  539.                 $res $allowKey;
  540.             } else {
  541.                 $res 3;
  542.             }
  543.         } else {
  544.             // фикс склонения для всех языков кроме RU , если число больше одного и имеет в окончании единицу, то ставим множественное склонение
  545.             if ($lc != 'ru') {
  546.                 if ($number 1) {
  547.                     $res 3;
  548.                 }
  549.             }
  550.         }
  551.         // фикс склонения для всех языков кроме RU , если число больше одного и имеет в окончании единицу, то ставим множественное склонение
  552.         return $res;
  553.     }
  554.     /**
  555.      * @param string $controller
  556.      * @param array $path
  557.      * @param array $query
  558.      * @return mixed
  559.      * @throws Exception
  560.      */
  561.     public static function forward($controller, array $path = [], array $query = [])
  562.     {
  563.         $request self::getRequest();
  564.         $path['_forwarded'] = $request->attributes;
  565.         $path['_controller'] = $controller;
  566.         $subRequest $request->duplicate($querynull$path);
  567.         return self::getContainer()->get('http_kernel')->handle($subRequestHttpKernelInterface::SUB_REQUEST);
  568.     }
  569.     /**
  570.      * Проверяем значение на число
  571.      * @param $val
  572.      * @return bool
  573.      */
  574.     public static function isInt($val)
  575.     {
  576.         preg_match_all('/[0-9]+/'$val$matchId);
  577.         $matchId ArrHelper::get($matchId'0.0');
  578.         if ($matchId) {
  579.             if ($matchId != $val) {
  580.                 $res false// строка c числом
  581.             } else {
  582.                 $res true// число
  583.             }
  584.         } else {
  585.             $res false// строка
  586.         }
  587.         return $res;
  588.     }
  589.     /**
  590.      * Получить юзера из его токена
  591.      * @return User|null
  592.      * @throws Exception
  593.      */
  594.     public static function getCurUser(): ?User
  595.     {
  596.         if (!App::getContainer()->has('security.token_storage')) {
  597.             throw new LogicException('The SecurityBundle is not registered in your application.');
  598.         }
  599.         /** @var TokenInterface $securiToken */
  600.         if ($securiToken App::getContainer()->get('security.token_storage')->getToken()) {
  601.             $user $securiToken->getUser();
  602.             if ($user instanceof User) {
  603.                 return $user;
  604.             }
  605.         }
  606.         return null;
  607.     }
  608.     /**
  609.      * Проверка на расположения кода: локально или на боевом сервере
  610.      *
  611.      * @return bool
  612.      */
  613.     public static function isGeneral(): bool
  614.     {
  615.         if (self::$isGeneral == null) {
  616.             $isGeneral false;
  617.             if (self::getContainer()->hasParameter('general')) {
  618.                 $isGeneral self::getContainer()->getParameter('general');
  619.             }
  620.             self::$isGeneral boolval($isGeneral);
  621.         }
  622.         return self::$isGeneral;
  623.     }
  624.     /**
  625.      * Проверяем на наличие DEV окружения, не зависимо TE это или TR
  626.      * @return bool
  627.      * @throws Exception
  628.      */
  629.     public static function isDev()
  630.     {
  631.         $env = static::getKernel()->getEnvironment();
  632.         return StrHelper::isInStr($env'dev');
  633.     }
  634.     /**
  635.      * Проверяем на наличие DEV окружения и подставляет немецкий ip в этом случае
  636.      * @param Request|null $request
  637.      * @return null|string
  638.      * @throws Exception
  639.      */
  640.     public static function getIp(?Request $request null): ?string
  641.     {
  642.         $request $request ?: App::getRequest();
  643.         return App::isDev() ? '213.136.79.122' $request->getClientIp();
  644.     }
  645.     /**
  646.      * Проверка на локальную копию сайта по хосту
  647.      * @return bool
  648.      */
  649.     public static function isLocEnv()
  650.     {
  651.         $host RequestHelper::getRequest()->getHost();
  652.         if ($host == '') {
  653.             return false;
  654.         }
  655.         if ($host == 'adm.tile.expert') {
  656.             return false;
  657.         }
  658.         if ($host == 'tile.expert') {
  659.             return false;
  660.         }
  661.         return true;
  662.     }
  663.     /**
  664.      * проверка окружения для вакансий - учетом локали ру
  665.      * @param bool $isDev
  666.      * @return bool
  667.      * @throws Exception
  668.      */
  669.     public static function isVacancyTE($isDev false)
  670.     {
  671.         $env = static::getKernel()->getEnvironment();
  672.         if ($isDev) {
  673.             return $env == 'te_dev';
  674.         } else {
  675.             return StrHelper::isInStr($env'te');
  676.         }
  677.     }
  678.     /**
  679.      * Запуск EXEC из PHP
  680.      * @param $command
  681.      * @return array|false|string|string[]
  682.      */
  683.     public static function runConsole($command)
  684.     {
  685.         if (!is_array($command)) {
  686.             $command explode(' '$command);
  687.         }
  688.         $process = new Process($command);
  689.         $process->setTimeout((int) TimeConstant::MINUTE 30);
  690.         try {
  691.             $process->run();
  692.             if (!$process->isSuccessful()) {
  693.                 return ['error' => $process->getErrorOutput()];
  694.             }
  695.             $out $process->getOutput();
  696.             $process->stop();
  697.         } catch (ProcessTimedOutException $e) {
  698.             return ['error' => 'TimedOut Error'];
  699.         }
  700.         return $out;
  701.     }
  702.     /**
  703.      * @return bool
  704.      * @throws Exception
  705.      * @todo убрать после отладки
  706.      * Проверка окружения TEST
  707.      */
  708.     public static function isTest()
  709.     {
  710.         $env = static::getKernel()->getEnvironment();
  711.         return StrHelper::isInStr($env'test');
  712.     }
  713.     /**
  714.      * получить сервис очередей
  715.      * @return Pheanstalk
  716.      */
  717.     public static function getPheanstalk()
  718.     {
  719.         if (static::getContainer()->hasParameter('pheanstalk_server')) {
  720.             $pheanstalkHost = static::getParameter('pheanstalk_server');
  721.         } else {
  722.             throw new RuntimeException('parameter not found: pheanstalk_server');
  723.         }
  724.         $pheanstalk = new Pheanstalk($pheanstalkHost);
  725.         if (null === $pheanstalk) {
  726.             throw new RuntimeException('Pheanstalk not found: ');
  727.         }
  728.         if (!$pheanstalk->getConnection()->isServiceListening()) {
  729.             throw new RuntimeException('Pheanstalk not connected');
  730.         }
  731.         return $pheanstalk;
  732.     }
  733.     /**
  734.      * @return object|Request
  735.      * @throws LogicException
  736.      */
  737.     public static function getRequest()
  738.     {
  739.         if (!self::$oRequest) {
  740.             self::$oRequest RequestHelper::getRequest();
  741.         }
  742.         return self::$oRequest;
  743.     }
  744.     /**
  745.      * @return Logger
  746.      * @throws Exception
  747.      */
  748.     public static function getLogger()
  749.     {
  750.         if (!self::$oLogger) {
  751.             if (!self::getContainer()->has('logger')) {
  752.                 throw new LogicException('The Monolog/Logger is not found');
  753.             }
  754.             /** @var Logger $oLogger */
  755.             $oLogger self::getContainer()->get('logger');
  756.             self::$oLogger $oLogger;
  757.         }
  758.         return self::$oLogger;
  759.     }
  760.     /**
  761.      * @return KernelInterface|Kernel
  762.      * @throws Exception
  763.      */
  764.     public static function getKernel()
  765.     {
  766.         if (!self::$oKernel) {
  767.             if (!self::getContainer()->has('kernel')) {
  768.                 throw new LogicException('The KernelInterface is not found');
  769.             }
  770.             self::$oKernel self::getContainer()->get('kernel');
  771.         }
  772.         return self::$oKernel;
  773.     }
  774.     /**
  775.      * @return Session
  776.      * @throws Exception
  777.      */
  778.     public static function getSession()
  779.     {
  780.         if (!self::$oSession) {
  781.             if (!self::getContainer()->has('session')) {
  782.                 throw new LogicException('The Session is not found');
  783.             }
  784.             /** @var Session $oSession */
  785.             $oSession self::getContainer()->get('session');
  786.             self::$oSession $oSession;
  787.         }
  788.         return self::$oSession;
  789.     }
  790.     /**
  791.      * @return Twig_Environment
  792.      * @throws Exception
  793.      */
  794.     public static function getTwig()
  795.     {
  796.         if (!self::getContainer()->has('twig')) {
  797.             throw new LogicException('The twig is not found');
  798.         }
  799.         if (!self::$oTwig) {
  800.             /** @var Twig_Environment $oTwig */
  801.             $oTwig self::getContainer()->get('twig');
  802.             self::$oTwig $oTwig;
  803.         }
  804.         return self::$oTwig;
  805.     }
  806.     /**
  807.      * @return IdentityTranslator
  808.      * @throws LogicException
  809.      * @throws Exception
  810.      */
  811.     public static function getTranslator()
  812.     {
  813.         if (!self::$oTranslator) {
  814.             if (!self::getContainer()->has('translator')) {
  815.                 throw new LogicException('The translator is not found');
  816.             }
  817.             self::$oTranslator self::getContainer()->get('translator');
  818.         }
  819.         return self::$oTranslator;
  820.     }
  821.     /**
  822.      * @return Registry
  823.      * @throws LogicException
  824.      * @throws Exception
  825.      */
  826.     public static function getDoctrine()
  827.     {
  828.         if (!self::$oDoctrine) {
  829.             if (!self::getContainer()->has('doctrine')) {
  830.                 throw new LogicException('The DoctrineBundle is not registered');
  831.             }
  832.             self::$oDoctrine self::getContainer()->get('doctrine');
  833.         }
  834.         return self::$oDoctrine;
  835.     }
  836.     /**
  837.      * @param null $name
  838.      * @return EntityManager
  839.      * @throws Exception
  840.      */
  841.     public static function em($name null)
  842.     {
  843.         $key $name $name 'default';
  844.         if (empty(self::$oEntityManager[$key])) {
  845.             self::$oEntityManager[$key] = self::getDoctrine()->getManager($name);
  846.         }
  847.         return self::$oEntityManager[$key];
  848.     }
  849.     /**
  850.      * @return EntityManager
  851.      * @throws Exception
  852.      */
  853.     public static function emAdm()
  854.     {
  855.         return self::em('logs');
  856.     }
  857.     public static function microTime($text ''$stop false)
  858.     {
  859.         if (empty(self::$microtime)) {
  860.             self::$microtime microtime(true);
  861.         } else {
  862.             $t microtime(true);
  863.             $res round((float) $t3) - round((float) self::$microtime3);
  864.             self::$microtime $t;
  865.             if (!empty($text)) {
  866.                 $res $text ': ' $res;
  867.             }
  868.             if ($stop) {
  869.                 App::dumpExit($res);
  870.             } else {
  871.                 App::dump($res);
  872.             }
  873.         }
  874.     }
  875.     /**
  876.      * @param $name
  877.      * @return bool
  878.      * @throws Exception
  879.      */
  880.     public static function isRole($name)
  881.     {
  882.         if (App::getContainer()->get('security.token_storage')->getToken() === null) {
  883.             return false;
  884.         } else {
  885.             return self::getContainer()->get('security.authorization_checker')->isGranted($name);
  886.         }
  887.     }
  888.     /**
  889.      * sizer - функция для красивого отображения размерности файлов("1024" ->  "1 kb")
  890.      *
  891.      * @param $size integer bytes
  892.      * @return string
  893.      */
  894.     public static function sizer($size)
  895.     {
  896.         $unit = ['b''kb''mb''gb''tb''pb'];
  897.         return @round($size pow(1024, ($i floor(log($size1024)))), 2) . ' ' $unit[$i];
  898.     }
  899.     /**
  900.      * @param string $functionName
  901.      * @return bool
  902.      */
  903.     public static function checkCallFunction(string $functionName)
  904.     {
  905.         $traces debug_backtrace();
  906.         if ($traces) {
  907.             foreach ($traces as $trace) {
  908.                 if ($trace['function'] == $functionName) {
  909.                     return true;
  910.                 }
  911.             }
  912.         }
  913.         return false;
  914.     }
  915. }