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
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Sylius\Component\Grid\Filter; |
15
|
|
|
|
16
|
|
|
use Sylius\Component\Grid\Data\DataSourceInterface; |
17
|
|
|
use Sylius\Component\Grid\Filtering\FilterInterface; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @author Jan Góralski <[email protected]> |
21
|
|
|
*/ |
22
|
|
|
final class MoneyFilter implements FilterInterface |
23
|
|
|
{ |
24
|
|
|
public const DEFAULT_SCALE = 2; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* {@inheritdoc} |
28
|
|
|
*/ |
29
|
|
|
public function apply(DataSourceInterface $dataSource, string $name, $data, array $options): void |
30
|
|
|
{ |
31
|
|
|
if (empty($data)) { |
32
|
|
|
return; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
$field = $options['field'] ?? $name; |
36
|
|
|
$scale = isset($options['scale']) ? (int) $options['scale'] : self::DEFAULT_SCALE; |
37
|
|
|
|
38
|
|
|
$greaterThan = $this->getDataValue($data, 'greaterThan'); |
39
|
|
|
$lessThan = $this->getDataValue($data, 'lessThan'); |
40
|
|
|
|
41
|
|
|
$expressionBuilder = $dataSource->getExpressionBuilder(); |
42
|
|
|
|
43
|
|
|
if (!empty($data['currency'])) { |
44
|
|
|
$dataSource->restrict($expressionBuilder->equals($options['currency_field'], $data['currency'])); |
45
|
|
|
} |
46
|
|
|
if ('' !== $greaterThan) { |
47
|
|
|
$expressionBuilder->greaterThan($field, $this->normalizeAmount((float) $greaterThan, $scale)); |
48
|
|
|
} |
49
|
|
|
if ('' !== $lessThan) { |
50
|
|
|
$expressionBuilder->lessThan($field, $this->normalizeAmount((float) $lessThan, $scale)); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @param float $amount |
56
|
|
|
* @param int $scale |
57
|
|
|
* |
58
|
|
|
* @return int |
59
|
|
|
*/ |
60
|
|
|
private function normalizeAmount(float $amount, int $scale): int |
61
|
|
|
{ |
62
|
|
|
return (int) round($amount * (10 ** $scale)); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param string[] $data |
67
|
|
|
* @param string $key |
68
|
|
|
* |
69
|
|
|
* @return string |
70
|
|
|
*/ |
71
|
|
|
private function getDataValue(array $data, string $key): string |
72
|
|
|
{ |
73
|
|
|
return $data[$key] ?? ''; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|