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 Odiseo\SyliusReportPlugin\Repository\AddressRepositoryInterface; |
10
|
|
|
use Sylius\Component\Addressing\Model\CountryInterface; |
11
|
|
|
use Sylius\Component\Core\Model\AddressInterface; |
12
|
|
|
use Sylius\Component\Resource\Repository\RepositoryInterface; |
13
|
|
|
use Symfony\Component\HttpFoundation\Request; |
14
|
|
|
use Symfony\Component\HttpFoundation\Response; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @author Odiseo Team <[email protected]> |
18
|
|
|
*/ |
19
|
|
|
final class PostcodeSearchAction |
20
|
|
|
{ |
21
|
|
|
private AddressRepositoryInterface $addressRepository; |
22
|
|
|
|
23
|
|
|
private RepositoryInterface $countryRepository; |
24
|
|
|
|
25
|
|
|
private ConfigurableViewHandlerInterface $viewHandler; |
26
|
|
|
|
27
|
|
|
public function __construct( |
28
|
|
|
AddressRepositoryInterface $addressRepository, |
29
|
|
|
RepositoryInterface $countryRepository, |
30
|
|
|
ConfigurableViewHandlerInterface $viewHandler |
31
|
|
|
) { |
32
|
|
|
$this->addressRepository = $addressRepository; |
33
|
|
|
$this->countryRepository = $countryRepository; |
34
|
|
|
$this->viewHandler = $viewHandler; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function __invoke(Request $request): Response |
38
|
|
|
{ |
39
|
|
|
$addresses = $this->getAddresses($request->get('postcode', '')); |
40
|
|
|
$view = View::create($addresses); |
41
|
|
|
|
42
|
|
|
$this->viewHandler->setExclusionStrategyGroups(['Autocomplete']); |
43
|
|
|
$view->getContext()->enableMaxDepth(); |
44
|
|
|
|
45
|
|
|
return $this->viewHandler->handle($view); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
private function getAddresses(string $query): array |
49
|
|
|
{ |
50
|
|
|
$addresses = []; |
51
|
|
|
$searchAddresses = $this->addressRepository->findByPostcode($query); |
52
|
|
|
|
53
|
|
|
/** @var AddressInterface $address */ |
54
|
|
|
foreach ($searchAddresses as $address) { |
55
|
|
|
/** @var CountryInterface|null $country */ |
56
|
|
|
$country = $this->countryRepository->findOneBy([ |
57
|
|
|
'code' => $address->getCountryCode() |
58
|
|
|
]); |
59
|
|
|
|
60
|
|
|
$countryName = $country !== null ? $country->getName() : $address->getCountryCode(); |
61
|
|
|
|
62
|
|
|
$postcodeLabel = $address->getPostcode().', '.$countryName; |
63
|
|
|
$isNew = count(array_filter($addresses, function ($address) use ($postcodeLabel): bool { |
64
|
|
|
return $address['postcode'] === $postcodeLabel; |
65
|
|
|
})) === 0; |
66
|
|
|
|
67
|
|
|
if ($isNew) { |
68
|
|
|
$addresses[] = [ |
69
|
|
|
'postcode' => $postcodeLabel, |
70
|
|
|
'id' => $address->getId(), |
71
|
|
|
]; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
return $addresses; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|