<?php
namespace WebBundle\Helper;
use AdmBundle\Helper\StrAdm;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\EntityNotFoundException;
use Exception;
use FlexApp\Entity\PriceEntity;
use FlexApp\Interfaces\HasCodeInterface;
use FlexApp\Interfaces\LocaleInterface;
use WebBundle\Repository\FilterRepository;
use WebBundle\Service\FiltersService;
use WebBundle\WebBundle;
/**
* Class FilterHelper
* @package WebBundle\Helper
*/
class FilterHelper
{
private static $arr = [];
/**
* ЗАПАТКА
* Хелпер для сфинкса. Для получения адекватных значений фильтрации по цене. Ну и логику вынес из цикла
* @param $val
* @param null $country
* @return mixed
* @throws Exception
*/
public static function getCost($val, $country = null)
{
$arr = [
'10' => [
'en' => 10,
'pl' => 43,
'ru' => 2000,
],
'20' => [
'en' => 20,
'pl' => 85.8,
'ru' => 3000,
],
'30' => [
'en' => 30,
'pl' => 129,
'ru' => 6000,
],
];
$country = $country ? $country : App::getCurCountry();
if (!empty($arr[$val][$country])) {
$res = $arr[$val][$country];
} else {
$res = $arr[$val]['en'];
}
return $res;
}
/**
* Получение части строки запроса фильтрации , только KEY
* @param null $papam
* @param null $locale
* @return array|mixed|null
* @throws Exception
*/
public static function getWord($papam = null, $locale = null)
{
return static::get($papam, $locale, 'word');
}
/**
* Получение полного адреса фильтра
* @param null $papam
* @param null $locale
* @param null $_locale_replace указываем, если хотим, что бы URL был выдан в нужной нам локали
* @return string
* @throws Exception
*/
public static function getUrl($papam = null, $locale = null, $_locale_replace = null)
{
$url = static::get($papam, $locale);
if ($_locale_replace) {
if (preg_match("~\/{$locale}$~iu", $url)) {
$url = preg_replace("~\/{$locale}$~iu", "/{$_locale_replace}", $url, -1);
}
if (preg_match("~\/{$locale}\/~iu", $url)) {
$url = preg_replace("~\/{$locale}\/~iu", "/{$_locale_replace}/", $url, -1);
}
}
return $url;
}
/**
* @param $name
* @param null $limit
* @return mixed|string
*/
public static function normaliseAltName($name, $limit = null)
{
return StrAdm::normaliseAltName($name, $limit);
}
/**
* @param $url
* @param null $limit
* @return mixed|string
*/
public static function normaliseUrl($url, $limit = null)
{
$url = StrAdm::normaliseUrl($url, $limit);
return $url;
}
/**
* Универсальный метод формирования строки фильтров
* @param null $papam
* @param null $locale
* @param string $type
* @return array|mixed|null
* @throws Exception
*/
private static function get($papam = null, $locale = null, string $type = 'url')
{
$locale = !$locale ? App::getCurLocale() : $locale;
$papam = is_array($papam) ? array_diff($papam, ['']) : $papam;
$hash = md5(json_encode($papam));
$curFS = $papam ? false : true;
$getType = 'get' . StrHelper::ucFirst($type);
if (!static::getArr($hash . '.' . $type)) {
// первым запросом инициируем FiltersService по указанному параметру
if (!static::getArr($hash . '.FS')) {
/** @var FiltersService $oFiltersService */
$oFiltersService = static::getFS($hash, $curFS);
switch ($type) {
case 'word':
$oFiltersService->getWord($papam, $locale);
break;
default:
$oFiltersService->$getType($papam, $locale);
}
}
foreach (LocaleHelper::getListCodeAvailable() as $sLocale) {
static::$arr[$hash][$type][$sLocale] = static::getFS($hash, $curFS)->$getType(null, $sLocale);
}
}
return ArrHelper::get(static::$arr, "{$hash}.{$type}.{$locale}");
}
/**
* @param $hash
* @param bool $cur
* @return FiltersService|array
*/
private static function getFS($hash, $cur = false)
{
if (!static::getArr($hash . '.FS')) {
if ($cur) {
static::$arr[$hash]['FS'] = WebBundle::getContainer()->get('app.service.filters');
} else {
static::$arr[$hash]['FS'] = new FiltersService();
}
}
return static::getArr($hash . '.FS');
}
/**
* @param $val
* @return array
*/
private static function getArr($val)
{
return ArrHelper::get(static::$arr, $val);
}
/**
* @return object|FiltersService|null
*/
private static function filterService()
{
return WebBundle::getContainer()->get('app.service.filters');
}
/**
* @param $param
* @return mixed|string
* @throws Exception
*/
public static function checkPageUrl($param)
{
$url = static::get($param);
return explode('/', $url)[3] ?? '';
}
/**
* @param $leftMenu
* @return string|null
*/
public static function getKeyByLeftMenu(string $leftMenu)
{
/** @var FilterRepository $oRepoFilter */
try {
$oRepoFilter = App::getRepository('WebBundle:FilterEntity');
} catch (Exception $e) {
return null;
}
return $oRepoFilter->getKeyByLeftMenu($leftMenu);
}
public static function filterText (array $filters): string
{
$list = [];
$special = [];
foreach ($filters as $key => $filter) {
if ($key != 'type' && !empty($filter['list'])) {
foreach ($filter['list'] as $row) {
if (in_array($filter['id'], [422, 424])) {
$special[$filter['nameFull']][] = $row['nameMany'];
} else {
$list[] = $row['nameMany'];
}
}
}
}
foreach ($special as $key => $row) {
$list[] = $key . ' ' . join(', ', $row);
}
return join('; ', $list);
}
/**
* @param Collection<mixed, LocaleInterface> $collection
* @return Collection<string, LocaleInterface>
*/
public static function getSameCollectionWithKeysAsLocaleCode(Collection $collection): Collection
{
$newCollection = new ArrayCollection();
/** @var LocaleInterface $oneEntity */
foreach ($collection->toArray() as $oneEntity) {
try {
$newCollection->set($oneEntity->getLocale()->getCode(), $oneEntity);
} catch (EntityNotFoundException $ex) {
}
}
return $newCollection;
}
public static function clearCollectionOfKeys(Collection $collection, array $keysForRemove): void
{
foreach ($keysForRemove as $key) {
$collection->remove($key);
}
}
/**
* Передаём сюда коллекцию с сущностями реализующими HasCodeInterface, возвращаем коллекцию, где ключи - это строка кода
*
* @param array<HasCodeInterface> $collection
* @return ArrayCollection
*/
public static function getCollectionWhereKeysIsCodes(array $collection): ArrayCollection
{
return new ArrayCollection(array_combine(array_map(static fn(HasCodeInterface $item) => $item->getCode(), $collection), $collection));
}
public static function getHashForPriceEntity(PriceEntity $priceEntity): string
{
return $priceEntity->getSquare()->getCode() . $priceEntity->getCurrency()->getCode() . ($priceEntity->getCountry() ? $priceEntity->getCountry()->getCode() : '');
}
/**
* @param Collection<mixed, LocaleInterface> $collection
* @return array<string, int>
*/
public static function getKeysOfCollectionWhereKeyIsLocaleCode(Collection $collection): array
{
$returnArray = [];
foreach ($collection->toArray() as $key => $oneElementCollection) {
try {
$returnArray[$oneElementCollection->getLocale()->getCode()] = $key;
} catch (EntityNotFoundException $ex) {
}
}
return $returnArray;
}
}