Passed
Pull Request — master (#187)
by Przemysław eRIZ
04:33
created

ContainsNameQueryBuilder::buildQuery()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 1
dl 0
loc 16
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file was created by developers working at BitBag
5
 * Do you need more information about us and what we do? Visit our https://bitbag.io website!
6
 * We are hiring developers from all over the world. Join us and start your new, exciting adventure and become part of us: https://bitbag.io/career
7
*/
8
9
declare(strict_types=1);
10
namespace BitBag\SyliusElasticsearchPlugin\QueryBuilder;
11
12
use BitBag\SyliusElasticsearchPlugin\PropertyNameResolver\ConcatedNameResolverInterface;
13
use Elastica\Query\AbstractQuery;
14
use Elastica\Query\MatchQuery;
15
use Sylius\Component\Locale\Context\LocaleContextInterface;
16
17
final class ContainsNameQueryBuilder implements QueryBuilderInterface
18
{
19
    /** @var LocaleContextInterface */
20
    private $localeContext;
21
22
    /** @var ConcatedNameResolverInterface */
23
    private $productNameNameResolver;
24
25
    /** @var string */
26
    private $namePropertyPrefix;
27
28
    public function __construct(
29
        LocaleContextInterface $localeContext,
30
        ConcatedNameResolverInterface $productNameNameResolver,
31
        string $namePropertyPrefix
32
    ) {
33
        $this->localeContext = $localeContext;
34
        $this->productNameNameResolver = $productNameNameResolver;
35
        $this->namePropertyPrefix = $namePropertyPrefix;
36
    }
37
38
    public function buildQuery(array $data): ?AbstractQuery
39
    {
40
        $localeCode = $this->localeContext->getLocaleCode();
41
        $propertyName = $this->productNameNameResolver->resolvePropertyName($localeCode);
42
43
        if (!$name = $data[$this->namePropertyPrefix]) {
44
            return null;
45
        }
46
47
        $nameQuery = new MatchQuery();
48
49
        $nameQuery->setFieldQuery($propertyName, $name);
50
        $nameQuery->setFieldFuzziness($propertyName, 2);
51
        $nameQuery->setFieldMinimumShouldMatch($propertyName, 2);
52
53
        return $nameQuery;
54
    }
55
}
56