Completed
Push — pagerfanta-fix ( 187c46...923c07 )
by Kamil
25:06 queued 03:45
created

MoneyFilter::apply()   C

Complexity

Conditions 7
Paths 33

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 14
nc 33
nop 4
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sylius\Component\Grid\Filter;
13
14
use Sylius\Component\Grid\Data\DataSourceInterface;
15
use Sylius\Component\Grid\Filtering\FilterInterface;
16
17
/**
18
 * @author Jan Góralski <[email protected]>
19
 */
20
final class MoneyFilter implements FilterInterface
21
{
22
    const DEFAULT_SCALE = 2;
23
24
    /**
25
     * {@inheritdoc}
26
     */
27
    public function apply(DataSourceInterface $dataSource, $name, $data, array $options)
28
    {
29
        if (empty($data)) {
30
            return;
31
        }
32
33
        $field = isset($options['field']) ? $options['field'] : $name;
34
        $scale = isset($options['scale']) ? (int) $options['scale'] : self::DEFAULT_SCALE;
35
36
        $greaterThan = $this->getDataValue($data, 'greaterThan');
37
        $lessThan = $this->getDataValue($data, 'lessThan');
38
39
        $expressionBuilder = $dataSource->getExpressionBuilder();
40
41
        if (!empty($data['currency'])) {
42
            $dataSource->restrict($expressionBuilder->equals($options['currency_field'], $data['currency']));
43
        }
44
        if ('' !== $greaterThan) {
45
            $expressionBuilder->greaterThan($field, $this->normalizeAmount($greaterThan, $scale));
46
        }
47
        if ('' !== $lessThan) {
48
            $expressionBuilder->lessThan($field, $this->normalizeAmount($lessThan, $scale));
49
        }
50
    }
51
52
    /**
53
     * @param string|float $amount
54
     * @param int $scale
55
     *
56
     * @return int
57
     */
58
    private function normalizeAmount($amount, $scale)
59
    {
60
        return (int) round($amount * (10 ** $scale));
61
    }
62
63
    /**
64
     * @param string[] $data
65
     * @param string $key
66
     *
67
     * @return string
68
     */
69
    private function getDataValue(array $data, $key)
70
    {
71
        return isset($data[$key]) ? $data[$key] : '';
72
    }
73
}
74