src/Controller/API/ApiSelectionController.php line 36

Open in your IDE?
  1. <?php
  2. namespace App\Controller\API;
  3. use App\Repository\ProductArticleRepository;
  4. use App\Controller\API\ApiBuildController;
  5. use App\Helper\RepositoryHelper;
  6. use App\Service\StaticService;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\JsonResponse;
  10. use Symfony\Component\Routing\Annotation\Route;
  11. use OpenApi\Annotations as OA;
  12. use Doctrine\Persistence\ManagerRegistry;
  13. /**
  14.  * Class ApiSelectionController
  15.  * @package App\Controller\API
  16.  * 
  17.  */
  18. class ApiSelectionController extends ApiBuildController
  19. {
  20.     private $registry;
  21.     public function __construct(ManagerRegistry $registry
  22.     {
  23.         $this->registry $registry;
  24.         parent::__construct($registry);
  25.     }
  26.     /**
  27.      * @OA\Tag (name="Получение параметров подбора")
  28.      * @Route("/api/select/{selection<wipers|parts>}/{entity<mark|model|category>}", methods={"GET"})
  29.      */
  30.     public function select(Request $requeststring $entitystring $selection
  31.     {
  32.         $result = [];
  33.         $params $request->query->all();
  34.         $entityClassName 'App\Entity\\' ucfirst($entity);
  35.         $routes = [
  36.             'wipers' => \App\Entity\SelectionWiper::class,
  37.             'parts' => \App\Entity\SelectionPart::class
  38.         ];
  39.         if (isset($routes[$selection]) && class_exists($entityClassName)) {
  40.             $repository $this->registry->getRepository($entityClassName);
  41.             $sortedDefault = ['sorted' => ['field' => $entity.'.title']];
  42.             $params =$this->normilize(
  43.                 array_merge($sortedDefault$params), 
  44.                 $entity
  45.             );
  46.             $params $this->normalize_years($params);
  47.             $repHelper = new RepositoryHelper($this->registry$entityClassName);
  48.             $result $repHelper->serialize(
  49.                 $repository->findOnRequest($params$routes[$selection]), 
  50.                 'selection/param'
  51.             );
  52.         }
  53.         return new JsonResponse($result);
  54.     }
  55.     /**
  56.      * @OA\Tag (name="Получение параметров подбора (модификация)")
  57.      * @Route("/api/select/{selection<wipers|parts>}/{entity<modification|body|years|engine>}", methods={"GET"})
  58.      */
  59.     public function selectModification(Request $requeststring $entitystring $selection
  60.     {
  61.         $result $array = [];
  62.         $params $request->query->all();
  63.         $entityClassName \App\Entity\Modification::class;
  64.         $entityAlias 'modification';
  65.         $routes = [
  66.             'wipers' => \App\Entity\SelectionWiper::class,
  67.             'parts' => \App\Entity\SelectionPart::class
  68.         ];
  69.         $groupBy = [
  70.             'body' => "{$entityAlias}.body",
  71.             'engine' => "{$entityAlias}.engine",
  72.             'years' => "{$entityAlias}.yearFrom, {$entityAlias}.yearTo"
  73.         ];
  74.         $sortBy = [
  75.             'years' => [
  76.                 'sort' => 'ASC',
  77.                 'field' => "{$entityAlias}.yearFrom"
  78.             ],
  79.             'default' => [
  80.                 'field' => "{$entityAlias}.body"
  81.             ]
  82.         ];
  83.         if (isset($routes[$selection]) && class_exists($entityClassName)) {
  84.             $repository $this->registry->getRepository($entityClassName);
  85.             $sortedDefault = isset($sortBy[$entity]) ? ['sorted' => $sortBy[$entity]] : ['sorted' => $sortBy['default']];
  86.             $groupByDefault = isset($groupBy[$entity]) ? ['groupBy' => $groupBy[$entity]] : [];
  87.    
  88.             $params =$this->normilize(
  89.                 array_merge($sortedDefault$groupByDefault$params), 
  90.                 $entity
  91.             );
  92.             $params $this->normalize_years($params);
  93.             $result $repository->findOnRequest($params$routes[$selection]);
  94.             $repHelper = new RepositoryHelper($this->registry$entityClassName);
  95.    
  96.             foreach($result as &$item) {
  97.                 $method 'get'.ucfirst($entity);
  98.                 $item method_exists(__CLASS__$method) ? $this->$method($repHelper->serialize($item'selection/param'), $selection) : $repHelper->serialize($item'selection/param');
  99.                 if ($item) {
  100.                     $array[] = $item;
  101.                 }
  102.             }
  103.         }
  104.         return new JsonResponse($array);
  105.     }
  106.     /**
  107.      * @OA\Tag (name="Получение данных подбора")
  108.      * @Route("/api/select/{selection<wipers|parts|all>}/data", methods={"GET"})
  109.      */
  110.     public function selectData(Request $requestStaticService $staticServicestring $selection
  111.     {
  112.         $result = [];
  113.         $params $request->query->all();
  114.         if (count($params) == 0) {
  115.             return new JsonResponse($resultResponse::HTTP_BAD_REQUEST);
  116.         }
  117.     
  118.         $routes = [
  119.             'wipers' => \App\Entity\SelectionWiper::class,
  120.             'parts' => \App\Entity\SelectionPart::class
  121.         ];
  122.         if (isset($routes[$selection])) {
  123.             $params =$this->normalize_years($params);  
  124.             $class $routes[$selection];
  125.             $repository $this->registry->getRepository($class);
  126.             $repHelper = new RepositoryHelper($this->registry,  $class);
  127.             $result $repHelper->serialize(
  128.                 $repository->getResponseAPI($repository->findOnRequest($params)), 
  129.                 'selection/data'
  130.             );
  131.         }
  132.         if ($selection === 'all' && $params['search'] && strlen($params['search']) > 2) {
  133.             $params['search'] = $this->clearTerm($params['search']);
  134.             $class \App\Entity\ProductOem::class;
  135.             $repository $this->registry->getRepository($class);
  136.             // $oemND = $repository->findOnSearchRequest(array_merge($params, ['productArticle' => null]));
  137.             $joinProductData = [];
  138.             // foreach($oemND as $oem) {
  139.             //     $joinProductData[$oem->getProduct()->getId()][] = $oem;
  140.             // }
  141.             $class \App\Entity\ProductArticle::class;
  142.             $repository $this->registry->getRepository($class);
  143.             $repHelper = new RepositoryHelper($this->registry$class);
  144.             $result $repHelper->serialize(
  145.                 $repository->getResponseAPI($repository->findOnSearchRequest($params), $joinProductData), 
  146.                 'selection/data'
  147.             );
  148.         }
  149.         $mapArticles = [];
  150.         foreach($result as &$item) {
  151.             foreach($item['products'] as &$product) {
  152.                 foreach($product['articles'] as &$article) {
  153.                     if ($article['title'] !== 'Н/Д') {
  154.                         $mapArticles[mb_strtolower($article['title'])] = &$article;
  155.                     }
  156.                 }
  157.             }
  158.         }
  159.         if (!empty($mapArticles)) {
  160.             $articles array_keys($mapArticles);
  161.             $static $staticService->getImageByArticles($articlestrue) ?? [];
  162.             foreach($static as $key => $images) {
  163.                 $article = &$mapArticles[$key];
  164.                 $article['image'] = array_shift($images);
  165.             }
  166.         }
  167.         return new JsonResponse($result);
  168.     }
  169.      /**
  170.      * @OA\Tag (name="Получение данных подбора по ID артикула")
  171.      * @Route("/api/select/{selection<wipers|parts>}/data/{id}", methods={"GET"})
  172.      */
  173.     public function selectDataByID(Request $requestStaticService $staticServicestring $selectionstring $id
  174.     {
  175.         $result = [];
  176.         $params $request->query->all();
  177.         $routes = [
  178.             'wipers' => \App\Entity\SelectionWiper::class,
  179.             'parts' => \App\Entity\SelectionPart::class
  180.         ];
  181.         if (isset($routes[$selection]) && $id != null) {
  182.             $class \App\Entity\ProductArticle::class;
  183.             $repository $this->registry->getRepository($class);
  184.             $repHelper = new RepositoryHelper($this->registry$class);
  185.             $article $repository->find($id);
  186.             if ($article !== null) {
  187.                 $product $article->getProduct();
  188.                 $product->clearArticlesAndOems();
  189.                 $product->addProductArticle($article);
  190.                 
  191.                 $repository $this->registry->getRepository($routes[$selection]);
  192.                 $selections $repository->findByProductArticleId($id);
  193.                 $applicable $repHelper->serialize($selections'selection/applicable');
  194.                 $result $repHelper->serialize($product'selection/id');
  195.                 $result['applicable'] = $applicable;
  196.                 $result['article'] = [
  197.                     ...$result['article'],
  198.                     'images' => $staticService->getImageByArticle($result['article']['title'])
  199.                 ];
  200.             }
  201.         }
  202.         return new JsonResponse($result);
  203.     }
  204.     public function normalize_years(&$params) {
  205.         if (isset($params['years']) && $params['years'] !== null) {
  206.             $years = ['yearFrom''yearTo'];
  207.             foreach(explode('|'$params['years']) as $i => $year) {
  208.                 $params[$years[$i]] = $year ? (int)$year NULL;
  209.             }
  210.             unset($params['years']);
  211.         }
  212.         return $params;
  213.     }
  214.     public function getYears($item$selection):array
  215.     {
  216.         if ($selection === 'parts') {
  217.             return [
  218.                 'id' => $item['yearFrom'].'|'.$item['yearTo'],
  219.                 'title' => ($item['yearFrom'] ?? 'н/д') .' - '. ($item['yearTo'] ?? 'наст. время')
  220.             ];
  221.         }
  222.         return [
  223.             'id' => $item['yearFrom'].'|'.$item['yearTo'],
  224.             'title' => $item['yearFrom']
  225.         ];
  226.     }
  227.     public function getBody($item$selection): ?array
  228.     {
  229.         if ($item['body'] === null) return null;
  230.         return [
  231.             'id' => $item['body'],
  232.             'title' => $item['body'],
  233.             'modelId' => $item['modelId']
  234.         ];
  235.     }
  236.     public function getEngine($item$selection): ?array
  237.     {
  238.         if ($item['engine'] === null) return null;
  239.     
  240.         return [
  241.             'id' => $item['engine'],
  242.             'title' => $item['engine'],
  243.         ];
  244.     }
  245.     /**
  246.      * remove bad characters
  247.      * @param  string $term input string
  248.      * @return string
  249.      */
  250.     public function escapeTerm($term): string
  251.     {
  252.         return trim(str_replace(array("'""*"'_''#''%23'), ''$term));
  253.     }
  254.     /**
  255.      * clear search term
  256.      * @param  string $term input string
  257.      * @return string
  258.      */
  259.     public function clearTerm($term): string
  260.     {
  261.         $term $this->escapeTerm($term);
  262.         $pattern "/[^\w,\x2D,А-Я,а-я,ёЁ,_]/u";
  263.         $replacement '';
  264.         return preg_replace($pattern$replacement$term);
  265.     }
  266. }