Passed
Pull Request — master (#69)
by Manuele
04:16
created

SearchProductsQueryBuilder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 6
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace BitBag\SyliusElasticsearchPlugin\QueryBuilder;
5
6
use BitBag\SyliusElasticsearchPlugin\PropertyNameResolver\SearchPropertyNameResolverRegistryInterface;
7
use Elastica\Query\AbstractQuery;
8
use Elastica\Query\MultiMatch;
9
use Sylius\Component\Locale\Context\LocaleContextInterface;
10
11
final class SearchProductsQueryBuilder implements QueryBuilderInterface
12
{
13
    public const QUERY_KEY = 'query';
14
15
    /**
16
     * @var SearchPropertyNameResolverRegistryInterface
17
     */
18
    private $searchProperyNameResolverRegistry;
19
    /**
20
     * @var LocaleContextInterface
21
     */
22
    private $localeContext;
23
24
    public function __construct(
25
        SearchPropertyNameResolverRegistryInterface $searchProperyNameResolverRegistry,
26
        LocaleContextInterface $localeContext
27
    ) {
28
        $this->searchProperyNameResolverRegistry = $searchProperyNameResolverRegistry;
29
        $this->localeContext = $localeContext;
30
    }
31
32
    public function buildQuery(array $data): ?AbstractQuery
33
    {
34
        if (!array_key_exists(self::QUERY_KEY, $data)) {
35
            throw new \RuntimeException(
36
                sprintf(
37
                    'Could not build search products query because there\'s no "query" key in provided data. ' .
38
                    'Got the following keys: %s',
39
                    implode(', ', array_keys($data))
40
                )
41
            );
42
        }
43
        if (!is_string($data[self::QUERY_KEY])) {
44
            throw new \RuntimeException(
45
                sprintf(
46
                    'Could not build search products query because the provided "query" is expected to be a string ' .
47
                    'but "%s" is given.',
48
                    is_object($data[self::QUERY_KEY]) ? get_class($data[self::QUERY_KEY]) : gettype($data[self::QUERY_KEY])
49
                )
50
            );
51
        }
52
53
        $multiMatch = new MultiMatch();
54
        $multiMatch->setQuery($data['query']);
55
        $multiMatch->setFuzziness('AUTO');
56
        $fields = [];
57
        foreach ($this->searchProperyNameResolverRegistry->getPropertyNameResolvers() as $propertyNameResolver) {
58
            $fields[] = $propertyNameResolver->resolvePropertyName($this->localeContext->getLocaleCode());
59
        }
60
        $multiMatch->setFields($fields);
61
        return $multiMatch;
62
    }
63
}
64