/
MoneyValidator.php
78 lines (67 loc) · 2.27 KB
/
MoneyValidator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\validators;
use Craft;
use Money\Currencies\ISOCurrencies;
use Money\Currency;
use Money\Formatter\IntlMoneyFormatter;
use Money\Money;
use NumberFormatter;
use yii\validators\Validator;
/**
* Class MoneyValidator.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 4.0.0
*/
class MoneyValidator extends Validator
{
/**
* @var int|float|null
*/
public int|null|float $max = null;
/**
* @var int|float|null
*/
public int|null|float $min = null;
/**
* @inheritdoc
*/
public function validateAttribute($model, $attribute): void
{
$currencies = new ISOCurrencies();
$numberFormatter = new NumberFormatter(Craft::$app->getFormattingLocale()->id, NumberFormatter::CURRENCY);
$moneyFormatter = new IntlMoneyFormatter($numberFormatter, $currencies);
$value = $model->$attribute;
if ($normalized = (!$value instanceof Money)) {
$currency = !$value['currency'] instanceof Currency ? new Currency($value['currency']) : $value['currency'];
$value = new Money($value['value'], $currency);
}
if ($this->max !== null) {
$max = new Money($this->max, $value->getCurrency());
if ($value->greaterThan($max)) {
$this->addError($model, $attribute, Craft::t('app', '{attribute} must be no greater than {max}.', [
'attribute' => $model->getAttributeLabel($attribute),
'max' => $moneyFormatter->format($max),
]));
}
}
if ($this->min !== null) {
$min = new Money($this->min, $value->getCurrency());
if ($value->lessThan($min)) {
$this->addError($model, $attribute, Craft::t('app', '{attribute} must be no less than {min}.', [
'attribute' => $model->getAttributeLabel($attribute),
'min' => $moneyFormatter->format($min),
]));
}
}
if ($normalized) {
// Update the value on the model to the Money object
$model->$attribute = $value;
}
}
}