<?php
namespace App\Controller;
use App\Entity\Feedback;
use App\Entity\Emails;
use App\Repository\VideoRepository;
use App\Repository\ProductTypeRepository;
use App\Repository\ProductCategoryRepository;
use App\Repository\NewsCategoryRepository;
use App\Repository\NewsTagRepository;
use App\Repository\AppAreaRepository;
use App\Repository\OfficeRepository;
use App\Repository\MarkRepository;
use App\Repository\ColorRepository;
use App\Repository\CombineActionRepository;
use App\Repository\CombinePropRepository;
use App\Repository\CombineRepository;
use App\Repository\CombineProductRepository;
use App\Repository\ProductRepository;
use App\Repository\ProductColorRepository;
use App\Repository\ProductArticleRepository;
use App\Helper\ProductHelper;
use App\Helper\ArticleHelper;
use App\Helper\NewsHelper;
use App\Repository\NewsRepository;
use App\Service\CaptchaService;
use App\Service\WheretobuyService;
use App\Service\MailerService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;
use OpenApi\Annotations as OA;
/**
* @Route("/api")
*/
class ApiController extends AbstractController
{
/**
* @var String
*/
private $path = '/files';
public function paramsCtrl(array $params, array $attributes, string $thisPage)
{
$session = new Session();
$search = $session->get('search');
$sorted = $session->get('sorted');
if (isset($search)) {
$search = $search['page'] != $thisPage ? null : $search['query'];
}
if (isset($sorted) && $sorted['page'] != $thisPage) {
$session->remove('sorted');
$sorted = null;
}
if (isset($params['sort']) && array_search($params['sort'], $attributes) !== false) {
$sorted = [
'page' => $thisPage,
'field' => $thisPage.'.'.$params['sort'],
'sort' => isset($params['sort_direct']) ? $params['sort_direct'] : 'ASC',
];
}
if (isset($params['all']) && !filter_var($params['all'], FILTER_VALIDATE_BOOLEAN)) {
$params['public'] = true;
}
return [
'params' => $params,
'sorted' => $sorted,
'search' => $search
];
}
/**
* Получение списка "Категории"
* @Route("/get/news/category", methods={"get"})
* @OA\Tag (name="Публикации")
* @OA\Response (
* response=200,
* description="Получение списка категорий",
* )
* @OA\Parameter(
* name="id",
* in="query",
* description="ID: Получить запись по id категории",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="limit",
* in="query",
* description="Количество записей на одной странице",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="page",
* in="query",
* description="Номер страницы",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="short",
* in="query",
* description="Минимальный ответ",
* @OA\Schema(type="boolean")
* )
* @OA\Parameter(
* name="all",
* in="query",
* description="Указатель на видимость записей на сайте (только публичные или все)",
* @OA\Schema(type="boolean")
* )
*/
public function getNewsCategories(
Request $request,
NewsCategoryRepository $newsCategoryRepository
): Response
{
$thisPage = 'news_category';
$result = [];
$limit = $request->query->get('limit') ?? 500;
$page = $request->query->get('page') ?? 1;
$id = $request->query->get('id');
$all = $request->query->get('all');
$short = $request->query->get('short');
$short = filter_var($short, FILTER_VALIDATE_BOOLEAN);
$public = !filter_var($all, FILTER_VALIDATE_BOOLEAN);
$session = new Session();
$search = $session->get('search');
$sorted = $session->get('sorted');
if (isset($search)) {
$search = $search['page'] != $thisPage ? null : $search['query'];
}
if (isset($sorted) && $sorted['page'] != $thisPage) {
$session->remove('sorted');
$sorted = null;
}
if ($id) {
$newsCategory = $newsCategoryRepository->find($id);
$result = $newsCategory ? $newsCategory->toArray() : [];
} else {
$result['data'] = $newsCategoryRepository->findOnRequestFieldsLimit($limit, $page, $public, $search, $sorted);
$result['count'] = $newsCategoryRepository->findOnRequestFieldsCount($public, $search);
foreach ($result['data'] as &$data) {
if (!$short) {
$data = $data->toArray();
$data['preview'] = '/files/news/category/'.$data['preview'];
}
else {
$data = $data->toShortArray();
}
}
if ($sorted) {
$result['sorted'] = $sorted;
}
}
return new JsonResponse($result, Response::HTTP_OK);
}
/**
* Получение списка "Тегов"
* @Route("/get/news/tag", methods={"get"})
* @OA\Tag (name="Публикации")
* @OA\Response (
* response=200,
* description="Получение списка тегов",
* )
* @OA\Parameter(
* name="id",
* in="query",
* description="ID: Получить запись по id тэга",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="category",
* in="query",
* description="Получить метки по категории",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="video",
* in="query",
* description="Получить метки статей имеющие видеоролики",
* @OA\Schema(type="boolean")
* )
* @OA\Parameter(
* name="limit",
* in="query",
* description="Количество записей на одной странице",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="page",
* in="query",
* description="Номер страницы",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="all",
* in="query",
* description="Указатель на видимость записей на сайте (только публичные или все)",
* @OA\Schema(type="boolean")
* )
*/
public function getNewsTags(
Request $request,
NewsTagRepository $newsTagRepository
): Response
{
$thisPage = 'news_tag';
$result = [];
$limit = $request->query->get('limit') ?? 500;
$page = $request->query->get('page') ?? 1;
$id = $request->query->get('id');
$all = $request->query->get('all');
$video = $request->query->get('video');
$category = $request->query->get('category');
$video = filter_var($video, FILTER_VALIDATE_BOOLEAN);
$public = !filter_var($all, FILTER_VALIDATE_BOOLEAN);
$session = new Session();
$search = $session->get('search');
$sorted = $session->get('sorted');
if (isset($search)) {
$search = $search['page'] != $thisPage ? null : $search['query'];
}
if (isset($sorted) && $sorted['page'] != $thisPage) {
$session->remove('sorted');
$sorted = null;
}
if ($id) {
$newsTag = $newsTagRepository->find($id);
$result = $newsTag ? $newsTag->toArray() : [];
} else {
$result['data'] = $newsTagRepository->findOnRequestFieldsLimit($video, $category, $limit, $page, $public, $search, $sorted);
$result['count'] = $newsTagRepository->findOnRequestFieldsCount($video, $category, $public, $search);
foreach ($result['data'] as &$data) {
$data = $data->toShortArray();
}
if ($sorted) {
$result['sorted'] = $sorted;
}
}
return new JsonResponse($result, Response::HTTP_OK);
}
/**
* Получение списка "Публикаций"
* @Route("/get/news", methods={"get"})
* @OA\Tag (name="Публикации")
* @OA\Response (
* response=200,
* description="Получение списка публикаций",
* )
* @OA\Parameter(
* name="id",
* in="query",
* description="ID: Получить запись по id публикации",
* @OA\Schema(type="integer, string")
* )
* @OA\Parameter(
* name="category",
* in="query",
* description="Получить публикации по категории",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="tag",
* in="query",
* description="Получить публикации по метке",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="product",
* in="query",
* description="Получить публикации по продукции",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="serializer",
* in="query",
* description="Группировка для Serializer'а",
* @OA\Schema(type="string")
* )
* @OA\Parameter(
* name="limit",
* in="query",
* description="Количество записей на одной странице",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="page",
* in="query",
* description="Номер страницы",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="cards",
* in="query",
* description="Заменить тэги продукции на карточки (ProductCard.vue)",
* @OA\Schema(type="boolean")
* )
* @OA\Parameter(
* name="all",
* in="query",
* description="Указатель на видимость записей на сайте (только публичные или все)",
* @OA\Schema(type="boolean")
* )
*/
public function getNews(
Request $request,
NewsRepository $newsRepository,
NewsHelper $newsHelper
): Response
{
$thisPage = 'news';
$result = [];
$limit = $request->query->get('limit') ?? 500;
$page = $request->query->get('page') ?? 1;
$id = $request->query->get('id');
$all = $request->query->get('all');
$category = $request->query->get('category');
$serializer = $request->query->get('serializer');
$tag = $request->query->get('tag');
$product = $request->query->get('product');
$createCards = filter_var($request->query->get('cards'), FILTER_VALIDATE_BOOLEAN);
$public = !filter_var($all, FILTER_VALIDATE_BOOLEAN);
$session = new Session();
$search = $session->get('search');
$sorted = $session->get('sorted');
if (isset($search)) {
$search = $search['page'] != $thisPage ? null : $search['query'];
}
if ($this->getUser()) {
$public = false;
}
if (isset($sorted) && $sorted['page'] != $thisPage) {
$session->remove('sorted');
$sorted = null;
}
if ($id) {
$news = $newsRepository->findItem($id, $public);
$result = $news ? $newsHelper->getNews($news, $this->path, $thisPage, 'news_one', $createCards) : [];
} else {
$result['data'] = $newsRepository->findOnRequestFieldsLimit($product, $category, $tag, $limit, $page, $public, $search, $sorted);
$result['count'] = $newsRepository->findOnRequestFieldsCount($product, $category, $tag, $public, $search);
foreach ($result['data'] as &$news) {
$news = $newsHelper->getNews($news, $this->path, $thisPage, $serializer ?? 'news_show');
}
if ($sorted) {
$result['sorted'] = $sorted;
}
}
return new JsonResponse($result, Response::HTTP_OK);
}
/**
* Получение списка "Видеозаписи"
* @Route("/get/video", methods={"get"})
* @OA\Tag (name="Видеозаписи")
* @OA\Response (
* response=200,
* description="Получение списка видеозаписей",
* )
* @OA\Parameter(
* name="id",
* in="query",
* description="ID: Получить запись по id",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="product",
* in="query",
* description="Получить видеоролики по связанной продукции",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="tag",
* in="query",
* description="Получить видеоролики по метке статьи",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="limit",
* in="query",
* description="Количество записей на одной странице",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="page",
* in="query",
* description="Номер страницы",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="all",
* in="query",
* description="Указатель на видимость записей на сайте (только публичные или все)",
* @OA\Schema(type="boolean")
* )
*/
public function getVideos(
Request $request,
VideoRepository $videoRepository,
ProductHelper $productHelper
): Response
{
$thisPage = 'video';
$result = [];
$params = $request->query->all();
$id = $request->query->get('id');
$attributes = ['id', 'title', 'sort', 'public', 'link'];
$filter = $this->paramsCtrl($params, $attributes, $thisPage);
$params = $filter['params'];
$search = $filter['search'];
$sorted = $filter['sorted'];
if ($id) {
$entity = $videoRepository->find($id);
if ($entity) {
$result = $entity->toArray();
foreach ($entity->getProductsCollection() as $product) {
$result['products'][] = $productHelper->getProduct($product, $this->path, 'product', 'product_card');
}
foreach ($entity->getTag() as $tag) {
$result['tags'][] = $tag->toShortArray();
}
}
} else {
$result['data'] = $videoRepository->findOnRequestFieldsLimit($params, $search, $sorted);
$result['count'] = $videoRepository->findOnRequestFieldsCount($params, $search);
if ($sorted) {
$result['sorted'] = $sorted;
}
foreach ($result['data'] as &$data) {
$products = [];
foreach ($data->getProductsCollection() as $product) {
$products[] = $productHelper->getProduct($product, $this->path, 'product', 'product_card');
}
$tags = [];
foreach ($data->getTag() as $tag) {
$tags[] = $tag->toShortArray();
}
$data = $data->toArray();
$data['tags'] = $tags;
$data['products'] = $products;
}
}
return new JsonResponse($result, Response::HTTP_OK);
}
/**
* Получение списка "Продукции"
* @Route("/get/product", methods={"get"})
* @OA\Tag (name="Каталог")
* @OA\Response (
* response=200,
* description="Получение списка продукций",
* )
* @OA\Parameter(
* name="id",
* in="query",
* description="ID: Получить запись по id продукта",
* @OA\Schema(type="integer, string")
* )
* @OA\Parameter(
* name="limit",
* in="query",
* description="Количество записей на одной странице",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="page",
* in="query",
* description="Номер страницы",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="popular",
* in="query",
* description="Популярная продукция",
* @OA\Schema(type="boolean")
* )
* @OA\Parameter(
* name="products",
* in="query",
* description="Массив продукции",
* @OA\Schema(type="string")
* )
* @OA\Parameter(
* name="serializer",
* in="query",
* description="Группировка для Serializer'а",
* @OA\Schema(type="string")
* )
* @OA\Parameter(
* name="all",
* in="query",
* description="Указатель на видимость записей на сайте (публичные/все записи, для всех items и для ID)",
* @OA\Schema(type="boolean")
* )
* @OA\Parameter(
* name="product_category",
* in="query",
* description="ID категории продукта",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="product_type",
* in="query",
* description="ID типа продукта",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="group",
* in="query",
* description="Сгруппировать по категориям",
* @OA\Schema(type="boolean")
* )
* @OA\Parameter(
* name="search",
* in="query",
* description="Поиск по строке",
* @OA\Schema(type="string")
* )
*/
public function getProducts(
Request $request,
ProductRepository $productRepository,
ProductHelper $productHelper
): Response
{
$thisPage = 'product';
$result = [];
$limit = $request->query->get('limit') ?? 1000;
$page = $request->query->get('page') ?? 1;
$id = $request->query->get('id');
$product_category_id = $request->query->get('product_category');
$product_type_id = $request->query->get('product_type');
$products = $request->query->get('products');
$serializer = $request->query->get('serializer');
$all = $request->query->get('all');
if ($products) {
$products = explode(',', $products);
}
if (!$serializer) {
$serializer = 'product_one';
}
$popular = filter_var($request->query->get('popular'), FILTER_VALIDATE_BOOLEAN);
$group = filter_var($request->query->get('group'), FILTER_VALIDATE_BOOLEAN);
$public = !filter_var($all, FILTER_VALIDATE_BOOLEAN);
$session = new Session();
$search = $session->get('search');
$sorted = $session->get('sorted');
if (isset($search)) {
$search = $search['page'] != $thisPage ? null : $search['query'];
}
$search = $search ? $search : $request->query->get('search');
if (isset($sorted) && $sorted['page'] != $thisPage) {
$session->remove('sorted');
$sorted = null;
}
if ($id) {
$product = $productRepository->findItem($id, $public);
$group = 'product_one';
$result = $product ? $productHelper->getProduct($product, $this->path, $thisPage, $group, null, $all) : [];
} else {
$result['data'] = $productRepository->findOnRequestFieldsLimit($limit, $page, $public, $search, $sorted, $product_category_id, $product_type_id, $popular, $products);
$result['count'] = $productRepository->findOnRequestFieldsCount($public, $search, $product_category_id, $product_type_id, $popular, $products);
foreach ($result['data'] as &$product) {
$product = $productHelper->getProduct($product, $this->path, $thisPage, $serializer, $product_category_id);
}
if ($group) {
$result['data'] = $productHelper->groupBy($result['data'], $product_category_id);
}
if ($sorted) {
$result['sorted'] = $sorted;
}
}
return new JsonResponse($result, Response::HTTP_OK);
}
/**
* Получение списка "Категорий продукции"
* @Route("/get/product/category", methods={"get"})
* @OA\Tag (name="Каталог")
* @OA\Response (
* response=200,
* description="Получение списка категорий",
* )
* @OA\Parameter(
* name="id",
* in="query",
* description="ID: Получить запись по id категории",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="parent",
* in="query",
* description="Получение списка родителей и детей",
* @OA\Schema(type="boolean")
* )
* @OA\Parameter(
* name="limit",
* in="query",
* description="Количество записей на одной странице",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="page",
* in="query",
* description="Номер страницы",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="all",
* in="query",
* description="Указатель на видимость записей на сайте (только публичные или все)",
* @OA\Schema(type="boolean")
* )
* @OA\Parameter(
* name="sort",
* in="query",
* description="Поле, по которому производится сортировка",
* @OA\Schema(type="string")
* )
*/
public function getProductCategories(
Request $request,
ProductCategoryRepository $productCategoryRepository
): Response
{
$thisPage = 'product_category';
$result = [];
$limit = $request->query->get('limit') ?? 500;
$page = $request->query->get('page') ?? 1;
$id = $request->query->get('id');
$all = $request->query->get('all');
$sort = $request->query->get('sort');
$parent = filter_var($request->query->get('parent'), FILTER_VALIDATE_BOOLEAN);
$public = !filter_var($all, FILTER_VALIDATE_BOOLEAN);
$session = new Session();
$search = $session->get('search');
$sorted = $session->get('sorted');
if (isset($search)) {
$search = $search['page'] != $thisPage ? null : $search['query'];
}
if (isset($sorted) && $sorted['page'] != $thisPage) {
$session->remove('sorted');
$sorted = null;
}
$sortAccess = ['id'];
if ($sort && array_search($sort, $sortAccess) !== false) {
$sorted = [
'field' => 'c.'.$sort,
'sort' => 'ASC',
];
}
if ($id) {
$productCategory = $productCategoryRepository->find($id);
$result = $productCategory ? $productCategory->toArray() : [];
} else {
$result['data'] = $productCategoryRepository->findOnRequestFieldsLimit($limit, $page, $public, $parent, $search, $sorted);
$result['count'] = $productCategoryRepository->findOnRequestFieldsCount($public, $parent, $search);
foreach ($result['data'] as &$data) {
$data = $parent ? $data->toParentArray() : $data->toArray();
}
if ($sorted) {
$result['sorted'] = $sorted;
}
}
return new JsonResponse($result, Response::HTTP_OK);
}
/**
* Получение списка "Типы продукции"
* @Route("/get/product/type", methods={"get"})
* @OA\Tag (name="Каталог")
* @OA\Response (
* response=200,
* description="Получение списка типов",
* )
* @OA\Parameter(
* name="id",
* in="query",
* description="ID: Получить запись по id типа",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="limit",
* in="query",
* description="Количество записей на одной странице",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="category",
* in="query",
* description="Найти типы по категории",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="page",
* in="query",
* description="Номер страницы",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="all",
* in="query",
* description="Указатель на видимость записей на сайте (только публичные или все)",
* @OA\Schema(type="boolean")
* )
*/
public function getProductTypes(
Request $request,
ProductTypeRepository $productTypeRepository
): Response
{
$thisPage = 'product_type';
$result = [];
$limit = $request->query->get('limit') ?? 500;
$page = $request->query->get('page') ?? 1;
$id = $request->query->get('id');
$category = $request->query->get('category');
$all = $request->query->get('all');
$public = !filter_var($all, FILTER_VALIDATE_BOOLEAN);
$session = new Session();
$search = $session->get('search');
$sorted = $session->get('sorted');
if (isset($search)) {
$search = $search['page'] != $thisPage ? null : $search['query'];
}
if (isset($sorted) && $sorted['page'] != $thisPage) {
$session->remove('sorted');
$sorted = null;
}
if ($id) {
$productType = $productTypeRepository->find($id);
$result = $productType ? $productType->toArray() : [];
} else {
$result['data'] = $productTypeRepository->findOnRequestFieldsLimit($limit, $page, $public, $category, $search, $sorted);
$result['count'] = $productTypeRepository->findOnRequestFieldsCount($public, $category, $search);
foreach ($result['data'] as &$data) {
$data = $data->toShortArray();
}
if ($sorted) {
$result['sorted'] = $sorted;
}
}
return new JsonResponse($result, Response::HTTP_OK);
}
/**
* Получение списка "Артикулы продукции"
* @Route("/get/product/article", methods={"get"})
* @OA\Tag (name="Каталог")
* @OA\Response (
* response=200,
* description="Получение списка артикулов",
* )
* @OA\Parameter(
* name="id",
* in="query",
* description="ID: Получить запись по id артикула",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="limit",
* in="query",
* description="Количество записей на одной странице",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="page",
* in="query",
* description="Номер страницы",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="all",
* in="query",
* description="Указатель на видимость записей на сайте (только публичные или все)",
* @OA\Schema(type="boolean")
* )
* @OA\Parameter(
* name="product",
* in="query",
* description="ID продукции",
* @OA\Schema(type="integer")
* )
*/
public function getProductArticles(
Request $request,
ProductArticleRepository $productArticleRepository,
ApplicationController $appctrl
): Response
{
$thisPage = 'product_article';
$result = [];
$limit = $request->query->get('limit') ?? 500;
$page = $request->query->get('page') ?? 1;
$id = $request->query->get('id');
$all = $request->query->get('all');
$product = $request->query->get('product');
$all = filter_var($all, FILTER_VALIDATE_BOOLEAN);
$session = new Session();
$search = $session->get('search');
$sorted = $session->get('sorted');
if (isset($search)) {
$search = $search['page'] != $thisPage ? null : $search['query'];
}
if (isset($sorted) && $sorted['page'] != $thisPage) {
$session->remove('sorted');
$sorted = null;
}
if ($id) {
$productArticle = $productArticleRepository->find($id);
$result = $productArticle ? $productArticle->toArray() : [];
$result = $this->getArticleFiles($result, $appctrl);
} else {
$result['data'] = $productArticleRepository->findOnRequestFieldsLimit($limit, $page, $all, $search, $sorted, $product);
$result['count'] = $productArticleRepository->findOnRequestFieldsCount($all, $search, $product);
foreach ($result['data'] as &$data) {
$data = $data->toArray();
$data = $this->getArticleFiles($data, $appctrl);
}
if ($sorted) {
$result['sorted'] = $sorted;
}
}
return new JsonResponse($result, Response::HTTP_OK);
}
public function getArticleFiles($result, $appctrl, $selection = false) {
if ($selection) {
$result['link'] = $result['product']['articles'][0]['link'];
$result['path'] = $result['product']['path'];
if (isset($result['product']['hover'])) {
$result['hover'] = $result['product']['hover'];
}
unset($result['product']);
return $result;
}
$result['file'] = null;
$part = '-hover';
$src = '/' . $result['id'] . '/';
$result['files'] = $appctrl->getFiles('product/article', $src);
foreach ((array)$result['files'] as $file) {
if (strpos($file, $part) === false) {
$result['file'] = $result['id'] . '/' .$file;
}
}
if (!$result['file'] && $result['files']) {
$result['file'] = $result['id'] . '/' .$result['files'][0];
}
return $result;
}
/**
* Получение списка "Марки авто"
* @Route("/get/mark", methods={"get"})
* @OA\Tag (name="Подбор по цвету")
* @OA\Response (
* response=200,
* description="Получение списка марок",
* )
* @OA\Parameter(
* name="id",
* in="query",
* description="ID: Получить запись по id",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="limit",
* in="query",
* description="Количество записей на одной странице",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="page",
* in="query",
* description="Номер страницы",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="all",
* in="query",
* description="Указатель на видимость записей на сайте (только публичные или все)",
* @OA\Schema(type="boolean")
* )
*/
public function getMarks(
Request $request,
MarkRepository $markRepository
): Response
{
$thisPage = 'mark';
$result = [];
$params = $request->query->all();
$id = $request->query->get('id');
$attributes = ['id', 'title', 'public'];
$filter = $this->paramsCtrl($params, $attributes, $thisPage);
$params = $filter['params'];
$search = $filter['search'];
$sorted = $filter['sorted'];
if ($id) {
$entity = $markRepository->find($id);
$result = $entity ? $entity->toArray() : [];
} else {
$result['data'] = $markRepository->findOnRequestFieldsLimit($params, $search, $sorted);
$result['count'] = $markRepository->findOnRequestFieldsCount($params, $search);
if ($sorted) {
$result['sorted'] = $sorted;
}
foreach ($result['data'] as &$data) {
$data = $data->toArray();
}
}
return new JsonResponse($result, Response::HTTP_OK);
}
/**
* Получение списка "Цвета авто"
* @Route("/get/color", methods={"get"})
* @OA\Tag (name="Подбор по цвету")
* @OA\Response (
* response=200,
* description="Получение списка цветов",
* )
* @OA\Parameter(
* name="id",
* in="query",
* description="ID: Получить запись по id",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="limit",
* in="query",
* description="Количество записей на одной странице",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="page",
* in="query",
* description="Номер страницы",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="all",
* in="query",
* description="Указатель на видимость записей на сайте (только публичные или все)",
* @OA\Schema(type="boolean")
* )
* @OA\Parameter(
* name="mark",
* in="query",
* description="Получить по id марки авто",
* @OA\Schema(type="integer")
* )
*/
public function getColors(
Request $request,
ColorRepository $colorRepository
): Response
{
$thisPage = 'color';
$result = [];
$params = $request->query->all();
$id = $request->query->get('id');
$attributes = ['id', 'title', 'code'];
$filter = $this->paramsCtrl($params, $attributes, $thisPage);
$params = $filter['params'];
$search = $filter['search'];
$sorted = $filter['sorted'];
if ($id) {
$entity = $colorRepository->find($id);
$result = $entity ? $entity->toArray() : [];
} else {
$result['data'] = $colorRepository->findOnRequestFieldsLimit($params, $search, $sorted);
$result['count'] = $colorRepository->findOnRequestFieldsCount($params, $search);
if ($sorted) {
$result['sorted'] = $sorted;
}
foreach ($result['data'] as &$data) {
$data = $data->toArray();
}
}
return new JsonResponse($result, Response::HTTP_OK);
}
/**
* Получение списка "Подбор по цвету"
* @Route("/get/selection", methods={"get"})
* @OA\Tag (name="Подбор по цвету")
* @OA\Response (
* response=200,
* description="Получение списка подбора",
* )
* @OA\Parameter(
* name="id",
* in="query",
* description="ID: Получить запись по id",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="limit",
* in="query",
* description="Количество записей на одной странице",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="page",
* in="query",
* description="Номер страницы",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="color",
* in="query",
* description="ID цвета",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="product_article",
* in="query",
* description="ID артикля продукции",
* @OA\Schema(type="integer")
* )
*/
public function getSelections(
Request $request,
ProductColorRepository $selectionRepository,
ProductRepository $productRepository,
ColorRepository $colorRepository,
ProductHelper $productHelper,
ApplicationController $appctrl
): Response
{
$thisPage = 'selection';
$result = [];
$params = $request->query->all();
$id = $request->query->get('id');
$attributes = ['id', 'color'];
$filter = $this->paramsCtrl($params, $attributes, $thisPage);
$params = $filter['params'];
$search = $filter['search'] ?? $request->query->get('search');
$sorted = $filter['sorted'];
if ($id) {
$result = $colorRepository->find($id);
if ($result) {
$products = array();
foreach($result->getProductColors() as $productColor) {
$article = $productColor->getProductArticle();
$article = $article->toArray();
$product = $productRepository->find($article['product']['id']);
$article['product'] = $productHelper->getProduct($product, $this->path, 'product', 'product_card');
$products[] = $this->getArticleFiles($article, $appctrl, true);
}
$result = $result->toArray();
$result['products'] = $products;
}
} else {
$data = $selectionRepository->findOnRequestFieldsLimit($params, $search, $sorted);
$result['count'] = $selectionRepository->findOnRequestFieldsCount($params, $search);
$result['data'] = array();
// $articles = array();
foreach($data as &$item) {
$color = $item->getColor();
$article = $item->getProductArticle();
$article = $article->toArray();
$product = $productRepository->find($article['product']['id']);
$article['product'] = $productHelper->getProduct($product, $this->path, 'product', 'product_card');
$articles = $this->getArticleFiles($article, $appctrl, true);
$result['data'][] = [
'id' => $item->getId(),
'color' => $color->toArray(),
'product' => $articles
];
}
if ($sorted) {
$result['sorted'] = $sorted;
}
}
return new JsonResponse($result, Response::HTTP_OK);
}
/**
* Получение списка "Дейтсвия"
* @Route("/get/action", methods={"get"})
* @OA\Tag (name="Комбинирование")
* @OA\Response (
* response=200,
* description="Получение списка действий комбинирования",
* )
* @OA\Parameter(
* name="id",
* in="query",
* description="ID: Получить запись по id",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="limit",
* in="query",
* description="Количество записей на одной странице",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="page",
* in="query",
* description="Номер страницы",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="all",
* in="query",
* description="Указатель на видимость записей на сайте (только публичные или все)",
* @OA\Schema(type="boolean")
* )
*/
public function getCombineAction(
Request $request,
CombineActionRepository $combineActionRepository
): Response
{
$thisPage = 'action';
$result = [];
$params = $request->query->all();
$id = $request->query->get('id');
$attributes = ['id', 'title', 'public'];
$filter = $this->paramsCtrl($params, $attributes, $thisPage);
$params = $filter['params'];
$search = $filter['search'];
$sorted = $filter['sorted'];
if ($id) {
$entity = $combineActionRepository->find($id);
$result = $entity ? $entity->toArray() : [];
} else {
$result['data'] = $combineActionRepository->findOnRequestFieldsLimit($params, $search, $sorted);
$result['count'] = $combineActionRepository->findOnRequestFieldsCount($params, $search);
if ($sorted) {
$result['sorted'] = $sorted;
}
foreach ($result['data'] as &$data) {
$data = $data->toArray();
}
}
return new JsonResponse($result, Response::HTTP_OK);
}
/**
* Получение списка "Свойства"
* @Route("/get/prop", methods={"get"})
* @OA\Tag (name="Комбинирование")
* @OA\Response (
* response=200,
* description="Получение списка свойств комбинирования",
* )
* @OA\Parameter(
* name="id",
* in="query",
* description="ID: Получить запись по id",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="limit",
* in="query",
* description="Количество записей на одной странице",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="page",
* in="query",
* description="Номер страницы",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="all",
* in="query",
* description="Указатель на видимость записей на сайте (только публичные или все)",
* @OA\Schema(type="boolean")
* )
*/
public function getCombineProps(
Request $request,
CombinePropRepository $combinePropRepository
): Response
{
$thisPage = 'prop';
$result = [];
$params = $request->query->all();
$id = $request->query->get('id');
$attributes = ['id', 'title', 'public'];
$filter = $this->paramsCtrl($params, $attributes, $thisPage);
$params = $filter['params'];
$search = $filter['search'];
$sorted = $filter['sorted'];
if ($id) {
$entity = $combinePropRepository->find($id);
$result = $entity ? $entity->toArray() : [];
} else {
$result['data'] = $combinePropRepository->findOnRequestFieldsLimit($params, $search, $sorted);
$result['count'] = $combinePropRepository->findOnRequestFieldsCount($params, $search);
if ($sorted) {
$result['sorted'] = $sorted;
}
foreach ($result['data'] as &$data) {
$data = $data->toArray();
}
}
return new JsonResponse($result, Response::HTTP_OK);
}
/**
* Получение списка "Комбинирование"
* @Route("/get/combine", methods={"get"})
* @OA\Tag (name="Комбинирование")
* @OA\Response (
* response=200,
* description="Получение списка комбинирования",
* )
* @OA\Parameter(
* name="id",
* in="query",
* description="ID: Получить запись по id",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="limit",
* in="query",
* description="Количество записей на одной странице",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="page",
* in="query",
* description="Номер страницы",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="action",
* in="query",
* description="Получить записи по id действия",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="prop",
* in="query",
* description="Получить записи по id свойства",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="group",
* in="query",
* description="Сгруппировать результат по действия",
* @OA\Schema(type="boolean")
* )
*/
public function getCombineItems(
Request $request,
CombineRepository $combineRepository,
CombineProductRepository $combineProductRepository,
ProductHelper $productHelper
): Response
{
$thisPage = 'combine';
$result = [];
$params = $request->query->all();
$id = $request->query->get('id');
// $group = $request->query->get('group');
$group = filter_var($request->query->get('group'), FILTER_VALIDATE_BOOLEAN);
$attributes = ['id', 'title', 'description', 'period'];
$filter = $this->paramsCtrl($params, $attributes, $thisPage);
$params = $filter['params'];
$search = $filter['search'];
$sorted = $filter['sorted'];
if ($id) {
$entity = $combineRepository->find($id);
if ($entity) {
$result = $entity->toArray();
foreach($entity->getCombineProducts() as $comProd) {
$result['product_'.$comProd->getSort()] = $productHelper->getProduct($comProd->getProduct(), $this->path, 'product', 'product_card');
}
}
} else {
$data = $combineRepository->findOnRequestFieldsLimit($params, $search, $sorted);
$result['count'] = $combineRepository->findOnRequestFieldsCount($params, $search);
$result['data'] = array();
foreach($data as $entity) {
$item = $entity->toArray();
foreach($entity->getCombineProducts() as $comProd) {
$item['product_'.$comProd->getSort()] = $productHelper->getProduct($comProd->getProduct(), $this->path, 'product', 'product_card');
}
$result['data'][] = $item;
}
if ($group && $result['count'] > 0) $result['data'] = $this->groupCombine($result['data'], isset($params['prop']));
if ($sorted) {
$result['sorted'] = $sorted;
}
}
return new JsonResponse($result, Response::HTTP_OK);
}
public function groupCombine($data, $prop) {
$group = [];
$result = [];
$group_title = $prop ? $data[0]['prop']['title'] : 'Защита/Блеск/Цвет';
foreach($data as $item)
{
$group[$item['action']['title']][] = $item;
}
foreach ($group as $key => $value)
{
$result[] = [
'group' => $key.' + '.$group_title,
'combine' => $value
];
}
return $result;
}
/**
* Отправка формы
* @Route("/post-form", methods={"post"})
* @OA\Tag (name="Обратная связь")
* @OA\Response (
* response=200,
* description="Отправка формы",
* )
* @OA\Parameter(
* name="name",
* in="query",
* description="Имя отрпавителя",
* @OA\Schema(type="string")
* )
* @OA\Parameter(
* name="email",
* in="query",
* description="Почтовый ящик отправителя",
* @OA\Schema(type="string")
* )
* @OA\Parameter(
* name="message",
* in="query",
* description="Сообщение отправителя",
* @OA\Schema(type="string")
* )
* @OA\Parameter(
* name="token",
* in="query",
* description="Google reCaptcha token",
* @OA\Schema(type="string")
* )
*/
public function postFeedbackForm(
Request $request,
EntityManagerInterface $em,
CaptchaService $captchaService,
MailerService $mailerService
): JsonResponse
{
$result = ['success' => true, 'message' => null, 'inputs' => []];
$content = json_decode($request->getContent(), true);
$required = ['name', 'email', 'message', 'token'];
$subject = 'Обратная связь';
try {
foreach ($required as $field) {
if (!isset($content[$field]) || empty($content[$field])) {
/**
* throw new \Exception("Field {$field} isn't isset or empty");
* $result['inputs'][$field] = 'This field is empty';
**/
$result['inputs'][$field] = 'Это поле не может быть пустым';
}
}
if (isset($content['email']) && $content['email']) {
if (!filter_var($content['email'], FILTER_VALIDATE_EMAIL)) {
$result['inputs']['email'] = 'Указан неверный E-mail';
}
}
if ($result['inputs']) {
/**
* throw new \Exception("One or more fields are filled in incorrectly");
* $result['messages'] = "One or more fields are filled in incorrectly";
*/
$result['message'] = "Некоторые поля заполнены неверено";
$result['success'] = false;
return new JsonResponse($result);
}
if (!$captchaService->check($content['token'], $request->getClientIp())) {
/**
* throw new \Exception("Captcha is invalid");
* $result['messages'] = "Captcha is invalid";
*/
$result['message'] = "Не удается пройти проверку reCaptcha Google";
$result['success'] = false;
return new JsonResponse($result);
}
date_default_timezone_set('Asia/Vladivostok');
$date = new \DateTimeImmutable();
$feedback = (new Feedback())
->setName($content['name'])
->setEmail($content['email'])
->setMessage($content['message'])
->setSubject($subject)
->setCreatedAt($date)
->setViewed(false)
->setSent(false)
;
$message = $this->renderView('mailer.html.twig', [
'content' => $content,
'subject' => $subject,
'name_site' => $mailerService->getNameSite()
]);
$emails = $this->getEmails();
$send = $mailerService->send($subject, $message, $content, $emails);
if ($send['status']) {
$feedback->setSent(true);
$result['message'] = $send['message'];
}
$em->persist($feedback);
$em->flush();
} catch (Exception $ex) {
$result['success'] = false;
$result['message'][] = $ex->getMessage();
}
return new JsonResponse($result);
}
public function getEmails() {
$result = [];
$repository = $this->getDoctrine()->getRepository(Emails::class);
$emails = $repository->findAll();
foreach ($emails as $email) {
$result[] = $email->toArray();
}
return $result;
}
/**
* Получение списка офисов компании
* @Route("/get/offices", methods={"get"})
* @OA\Tag (name="Настройки")
* @OA\Response (
* response=200,
* description="Получение списка офисов компании"
* )
* @OA\Parameter(
* name="id",
* in="query",
* description="Получить офис по идентификатору",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="limit",
* in="query",
* description="Количество записей на одной странице",
* @OA\Schema(type="integer")
* )
* @OA\Parameter(
* name="page",
* in="query",
* description="Номер страницы",
* @OA\Schema(type="integer")
* )
*/
public function getOffices(
Request $request,
OfficeRepository $officeRepository
): JsonResponse
{
$limit = $request->query->get('limit') ?? 100;
$page = $request->query->get('page') ?? 1;
$session = new Session();
$search = $session->get('search');
$sorted = $session->get('sorted');
if ($sorted && $sorted['page'] != 'offices') {
$session->remove('sorted');
$sorted = null;
}
$id = $request->query->get('id');
if ($id) {
$office = $officeRepository->find($id);
$result = [];
if ($office) {
$result = $office->toArray();
}
} else {
$result['data'] = $officeRepository->findOnRequestFieldsLimit($limit, $page, $search, $sorted);
$result['count'] = $officeRepository->findOnRequestFieldsCount($search);
if ($sorted) {
$result['sorted'] = $sorted;
}
}
return new JsonResponse($result, Response::HTTP_OK);
}
/**
* Получение офисов Uniqom
* @Route("/get/offices/point", methods={"get"})
* @OA\Tag (name="Партнеры")
* @OA\Response (
* response=200,
* description="Получение офисов Uniqom",
* )
*/
public function getOfficesPoint(OfficeRepository $officeRepository): JsonResponse
{
// $host = $this->getParameter('host_memcached');
// $client = MemcachedAdapter::createConnection($host);
// $cache = new MemcachedAdapter($client);
// $result = $cache->get('db.offices', function (ItemInterface $itemInterface) use ($officeRepository) {
$result = [];
$offices = $officeRepository->findAll();
foreach ($offices as $office) {
$result[] = $office->toArray();
}
foreach ($result as $i => $item) {
$item['phone'] = str_replace("|", ",", $item['phone']);
$result[$i]['phone'] = array_map('trim', explode(',', $item['phone']));
$result[$i]['email'] = array_map('trim', explode(',', $item['email']));
}
$result = $this->getNormalizeRequest($result);
// return $result;
// });
return new JsonResponse($result, Response::HTTP_OK);
}
/**
* Получение списка городов, где есть офисы Uniqom
* @Route("/get/offices/cities", methods={"get"})
* @OA\Tag (name="Партнеры")
* @OA\Response (
* response=200,
* description="Получение списка городов, где есть офисы Uniqom",
* )
*/
public function getCitiesOffice(OfficeRepository $officeRepository): JsonResponse
{
// $host = $this->getParameter('host_memcached');
// $client = MemcachedAdapter::createConnection($host);
// $cache = new MemcachedAdapter($client);
// $result = $cache->get('db.office_cities', function () use ($officeRepository) {
// return $officeRepository->findCityOnly();
// });
$result = $officeRepository->findCityOnly();
return new JsonResponse($result, Response::HTTP_OK);
}
/*
* Нормализует полученные данные в красивый и адекватный вид
*/
public function getNormalizeRequest($result) {
foreach ($result as &$data) {
if (isset($data['signboard'])) {
$data['signboard'] = str_replace('"', '', $data['signboard']);
}
if (isset($data['address'])) {
if (!$data['address'] && $data['city']) $data['address'] = $data['city'];
$address = $data['address']['name'] ?? $data['address'];
$address = str_ends_with($address, '.') ? substr($address, 0, -1) : $address;
$address = !str_starts_with($address, 'г.') ? 'г. ' . $address : $address;
$address = str_replace('д.', '', $address);
$address = str_replace('ул.', 'ул. ', $address);
$address = str_replace(' корпус', ', корп.', $address);
$address = str_replace('переулок', 'пер.', $address);
if (isset($data['address']['name'])) $data['address']['name'] = $address;
else $data['address'] = $address;
}
if (isset($data['phone'])) {
foreach ($data['phone'] as $index => &$phone) {
$ph = str_starts_with($phone, '8') ? '+7' . ltrim($phone, $phone[0]) : $phone;
$ph = str_replace(" ", '', $phone);
$ph = str_replace("(", '', $ph);
$ph = str_replace(")", '', $ph);
$ph = str_replace("-", '', $ph);
if (is_numeric($ph)) {
if (str_starts_with($ph, '+') && strlen($ph) === 12) {
$ph =
substr($ph, 0, 2) . " (" . substr($ph, 2, 3) . ") " .
substr($ph, 5, 3) . '-' . substr($ph, 8, 2) . "-" .
substr($ph, 10, 2);
$phone = $ph;
}
if (str_starts_with($ph, '423') && strlen($ph) === 10) {
$ph =
"(" . substr($ph, 0, 3) . ") " . substr($ph, 3, 1) . "-" .
substr($ph, 4, 3) . "-" . substr($ph, 7, 3);
$phone = $ph;
}
if (strlen($ph) === 7) {
$ph =
substr($ph, 0, 1) . "-" . substr($ph, 1, 3) . "-" .
substr($ph, 4, 3);
$phone = $ph;
}
}
}
}
if (isset($data['email'])) {
foreach ($data['email'] as $index => $email) {
if (!$email) unset($data['email'][$index]);
}
}
if (isset($data['working_time'])) {
$workingString = $data['working_time'];
$days = ['пн', 'вт', 'ср', 'чт', 'пт', 'сб', 'вс'];
$workingDays = [];
foreach ($days as $day) {
if (($i = mb_stripos(mb_strtolower($workingString), $day)) !== false) {
$workingDays[] = [
"day" => $day,
"index" => $i
];
}
}
$workingString = str_replace("\r", ' ', $workingString);
$workingString = str_replace("\n", ' ', $workingString);
$workingTemp = explode(' ', $workingString);
$workingTime = [];
foreach ($workingTemp as &$wt) {
$wt = str_ends_with($wt, '.') ? substr($wt, 0, -1) : $wt;
$wt = str_replace(";", '', $wt);
$wt = str_replace(",", '', $wt);
$wt = str_replace(".", ':', $wt);
$ws = str_replace(":", '', $wt);
if (is_numeric($ws)) $workingTime[] = $wt;
}
$indexTime = [];
$tempString = $workingString;
foreach ($workingTime as &$wt) {
if (($i = mb_stripos($tempString, $wt)) !== false) {
$tempString = $this->str_replace_once($wt, '00:00', $tempString);
$indexTime[] = $i;
}
if (false === $i) {
$temp = str_replace(":", '.', $wt);
if (($i = mb_stripos($tempString, $temp)) !== false) {
$tempString = $this->str_replace_once($temp, '00:00', $tempString);
$indexTime[] = $i;
}
}
}
unset($tempString);
$pos1 = null;
$pos2 = null;
$day1 = '';
$workingArray = [];
foreach ($workingDays as $day) {
if (($i = mb_stripos($workingString, '-')) !== false) {
if ($i > $day['index']) {
$pos1 = $day['index'];
$day1 = $day['day'];
}
if ($i < $day['index']) $pos2 = $day['index'];
}
if ($pos1 !== null && $pos2 !== null) {
$day2 = $day['day'];
for($di = array_search($day1, $days) + 1; $di <= array_search($day2, $days); $di++) {
$time1 = null;
$time2 = null;
foreach ($indexTime as $key => $index) {
if ($day['index'] < $index && $time1 !== null) $time2 = $workingTime[$key];
if ($day['index'] < $index && $time1 == null) $time1 = $workingTime[$key];
if ($time1 && $time2) break;
}
$workingArray[] = [
"day" => $days[$di],
"start" => $time1,
"end" => $time2,
];
}
$pos1 = null;
$pos2 = null;
$day1 = '';
} else {
$time1 = null;
$time2 = null;
foreach ($indexTime as $key => $index) {
if ($day['index'] < $index && $time1 !== null) $time2 = $workingTime[$key];
if ($day['index'] < $index && $time1 == null) $time1 = $workingTime[$key];
if ($time1 && $time2) break;
}
$workingArray[] = [
"day" => $day['day'],
"start" => $time1,
"end" => $time2,
];
}
}
if ($workingArray && count($workingArray) < count($days)) {
$workingArrayTemp = [];
foreach ($days as $day) {
$index = array_search($day, array_column($workingArray, 'day'));
$workingArrayTemp[] = $index !== false ? $workingArray[$index] : [
"day" => $day,
"start" => null,
"end" => null,
];
}
$workingArray = $workingArrayTemp;
}
$data['working_time_array'] = $workingArray;
}
}
return $result;
}
public function str_replace_once($search, $replace, $text)
{
$pos = strpos($text, $search);
return $pos !== false ? substr_replace($text, $replace, $pos, strlen($search)) : $text;
}
private function makeRequest(
array $params,
WheretobuyService $wheretobuyService
): JsonResponse
{
$splice = '/';
$url = $splice . $params['action'];
$url .= $splice . $params['sitecode'];
$url .= isset($params['city']) ? $splice . $params['city'] : '';
$target = [];
if (isset($params['segment'])) {
array_push($target, 'segment='.$params['segment']);
}
if (isset($params['isAuthorised'])) {
array_push($target, 'is_authorised='.$params['isAuthorised']);
}
$target = $target ? '?' . implode('&', $target) : '';
$data = $wheretobuyService->invoke($url.$target);
if (isset($params['city'])) {
foreach ($data as $i => $item) {
$item['phone'] = str_replace(";", ",", $item['phone']);
$data[$i]['phone'] = array_map('trim', explode(',', $item['phone']));
$data[$i]['email'] = array_map('trim', explode(',', $item['email']));
$data[$i]['url'] = array_map('trim', explode(',', $item['url']));
if (empty($item['phone'])) $data[$i]['phone'] = null;
if (empty($item['email'])) $data[$i]['email'] = null;
if (empty($item['url'])) $data[$i]['url'] = null;
}
$data = $this->getNormalizeRequest($data);
}
return new JsonResponse($data);
}
/**
* Получение списка городов
* @Route("/get/cities/{sitecode}", methods={"get"})
* @OA\Tag (name="Где купить")
* @OA\Response (
* response=200,
* description="Получение списка городов",
* )
* */
public function getCities(string $sitecode, WheretobuyService $wheretobuyService)
{
$data = $this->makeRequest(array(
'action' => 'cities',
'sitecode' => $sitecode,
), $wheretobuyService);
return $data;
}
/**
* Получение списка точек
* @Route("/get/points/{sitecode}/{city}", methods={"get"})
* @OA\Tag (name="Где купить")
* @OA\Response (
* response=200,
* description="Получение списка точек",
* )
* @OA\Parameter(
* name="segment",
* in="query",
* description="Сегмент (СТО, Интернет-магазин и т.д)",
* @OA\Schema(type="string")
* )
* @OA\Parameter(
* name="is_authorised",
* in="query",
* description="Авторизованные центры",
* @OA\Schema(type="boolean")
* )
* */
public function getPoints(
string $sitecode,
int $city,
WheretobuyService $wheretobuyService,
Request $request
) {
$segment = $request->query->get('segment');
$isAuthorised = $request->query->get('is_authorised');
$data = $this->makeRequest(array(
'action' => 'points',
'sitecode' => $sitecode,
'city' => $city,
'segment' => $segment,
'isAuthorised' => $isAuthorised
), $wheretobuyService);
return $data;
}
/**
* Поиска на сайте
* @Route("/get/search", methods={"get"})
* @OA\Tag (name="Поиск")
* @OA\Response (
* response=200,
* description="Поиск продукции/публикаций на сайте",
* )
* @OA\Parameter(
* name="text",
* in="query",
* description="Поисковый запрос",
* @OA\Schema(type="string")
* )
* */
public function getSearch(
Request $request,
ProductRepository $productRepository,
ProductHelper $productHelper,
NewsRepository $newsRepository,
NewsHelper $newsHelper
) {
$result = [];
$search = $request->query->get('text');
$limit = 1000;
$page = 1;
if (!$search) {
return new JsonResponse($result, Response::HTTP_BAD_REQUEST);
}
$result['news'] = $newsRepository->findOnRequestFieldsLimit(null, null, null, $limit, $page, true, $search, null);
foreach ($result['news'] as &$news) {
$news = $newsHelper->getNews($news, $this->path, 'news', 'news_card');
}
$result['products'] = $productRepository->findOnRequestFieldsLimit($limit, $page, true, $search, null, null, null, null, null);
foreach ($result['products'] as &$product) {
$product = $productHelper->getProduct($product, $this->path, 'product', 'product_card', null, null);
$articles = array_filter($product['articles'], function($article) {
if ($article['link'] !== null) return true;
return false;
});
foreach($product['articles'] as $i => &$article) {
$excluded = !(false !== mb_stripos($article['title'], $search) || false !== mb_stripos($article['code'], $search));
if ($excluded) {
foreach($article['charact'] as &$charact) {
$color = $charact['colors'];
if (count($color) && (false !== mb_stripos($color['code'], $search) || false !== mb_stripos($color['title'], $search))) {
$excluded = false;
}
}
if ($excluded) {
unset($product['articles'][$i]);
}
}
if (!$article['link']) {
$article['link'] = $articles[0]['link'];
}
}
if (!count($product['articles'])) {
$product['articles'] = $articles;
}
$product['articles'] = array_values($product['articles']);
}
return new JsonResponse($result, Response::HTTP_OK);
}
}