Passed
Push — master ( c5feea...1cc810 )
by Mikołaj
11:24
created

HasPriceBetweenQueryBuilder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 3
1
<?php
2
3
/*
4
 * This file has been created by developers from BitBag.
5
 * Feel free to contact us once you face any issues or want to start
6
 * another great project.
7
 * You can find more information about us on https://bitbag.shop and write us
8
 * an email on [email protected].
9
 */
10
11
declare(strict_types=1);
12
13
namespace BitBag\SyliusElasticsearchPlugin\QueryBuilder;
14
15
use BitBag\SyliusElasticsearchPlugin\PropertyNameResolver\ConcatedNameResolverInterface;
16
use BitBag\SyliusElasticsearchPlugin\PropertyNameResolver\PriceNameResolverInterface;
17
use Elastica\Query\AbstractQuery;
18
use Elastica\Query\Range;
19
use Sylius\Component\Channel\Context\ChannelContextInterface;
20
21
final class HasPriceBetweenQueryBuilder implements QueryBuilderInterface
22
{
23
    /**
24
     * @var ConcatedNameResolverInterface
25
     */
26
    private $channelPricingNameResolver;
27
28
    /**
29
     * @var PriceNameResolverInterface
30
     */
31
    private $priceNameResolver;
32
33
    /**
34
     * @var ChannelContextInterface
35
     */
36
    private $channelContext;
37
38
    /**
39
     * @param PriceNameResolverInterface $priceNameResolver
40
     * @param ConcatedNameResolverInterface $channelPricingNameResolver
41
     * @param ChannelContextInterface $channelContext
42
     */
43
    public function __construct(
44
        PriceNameResolverInterface $priceNameResolver,
45
        ConcatedNameResolverInterface $channelPricingNameResolver,
46
        ChannelContextInterface $channelContext
47
    ) {
48
        $this->channelPricingNameResolver = $channelPricingNameResolver;
49
        $this->priceNameResolver = $priceNameResolver;
50
        $this->channelContext = $channelContext;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function buildQuery(array $data): ?AbstractQuery
57
    {
58
        $minPrice = $data[$this->priceNameResolver->resolveMinPriceName()];
59
        $maxPrice = $data[$this->priceNameResolver->resolveMaxPriceName()];
60
61
        if (!$minPrice || !$maxPrice) {
62
            return null;
63
        }
64
65
        $channelCode = $this->channelContext->getChannel()->getCode();
66
        $propertyName = $this->channelPricingNameResolver->resolvePropertyName($channelCode);
67
        $rangeQuery = new Range();
68
69
        $rangeQuery->setParam($propertyName, [
70
            'gte' => $this->getPriceFromString($minPrice),
71
            'lt' => $this->getPriceFromString($maxPrice),
72
        ]);
73
74
        return $rangeQuery;
75
    }
76
77
    private function getPriceFromString(string $price): int
78
    {
79
        return (int) round($price * 100, 2);
80
    }
81
}
82