|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Odiseo\SyliusReportPlugin\Controller\Action; |
|
6
|
|
|
|
|
7
|
|
|
use FOS\RestBundle\View\ConfigurableViewHandlerInterface; |
|
8
|
|
|
use FOS\RestBundle\View\View; |
|
9
|
|
|
use Sylius\Component\Core\Model\ProductInterface; |
|
10
|
|
|
use Sylius\Component\Core\Repository\ProductRepositoryInterface; |
|
11
|
|
|
use Sylius\Component\Locale\Context\LocaleContextInterface; |
|
12
|
|
|
use Symfony\Component\HttpFoundation\Request; |
|
13
|
|
|
use Symfony\Component\HttpFoundation\Response; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* @author Odiseo Team <[email protected]> |
|
17
|
|
|
*/ |
|
18
|
|
|
final class ProductSearchAction |
|
19
|
|
|
{ |
|
20
|
|
|
private ProductRepositoryInterface$productRepository; |
|
21
|
|
|
|
|
22
|
|
|
private LocaleContextInterface $localeContext; |
|
23
|
|
|
|
|
24
|
|
|
private ConfigurableViewHandlerInterface $viewHandler; |
|
25
|
|
|
|
|
26
|
|
|
public function __construct( |
|
27
|
|
|
ProductRepositoryInterface $productRepository, |
|
28
|
|
|
LocaleContextInterface $localeContext, |
|
29
|
|
|
ConfigurableViewHandlerInterface $viewHandler |
|
30
|
|
|
) { |
|
31
|
|
|
$this->productRepository = $productRepository; |
|
32
|
|
|
$this->localeContext = $localeContext; |
|
33
|
|
|
$this->viewHandler = $viewHandler; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
public function __invoke(Request $request): Response |
|
37
|
|
|
{ |
|
38
|
|
|
$locale = $this->localeContext->getLocaleCode(); |
|
39
|
|
|
|
|
40
|
|
|
$products = $this->getProducts($request->get('name', ''), $locale); |
|
41
|
|
|
$view = View::create($products); |
|
42
|
|
|
|
|
43
|
|
|
$this->viewHandler->setExclusionStrategyGroups(['Autocomplete']); |
|
44
|
|
|
$view->getContext()->enableMaxDepth(); |
|
45
|
|
|
|
|
46
|
|
|
return $this->viewHandler->handle($view); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
private function getProducts(string $query, string $locale): array |
|
50
|
|
|
{ |
|
51
|
|
|
$products = []; |
|
52
|
|
|
$searchProducts = $this->productRepository->findByNamePart($query, $locale); |
|
53
|
|
|
|
|
54
|
|
|
/** @var ProductInterface $product */ |
|
55
|
|
|
foreach ($searchProducts as $product) { |
|
56
|
|
|
$productLabel = ucfirst(strtolower($product->getName() ?? '')); |
|
57
|
|
|
$isNew = count(array_filter($products, function ($product) use ($productLabel): bool { |
|
58
|
|
|
return $product['name'] === $productLabel; |
|
59
|
|
|
})) === 0; |
|
60
|
|
|
|
|
61
|
|
|
if ($isNew) { |
|
62
|
|
|
$products[] = [ |
|
63
|
|
|
'name' => $productLabel, |
|
64
|
|
|
'id' => $product->getId(), |
|
65
|
|
|
]; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
return $products; |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|