forked from NIT-Administrative-Systems/dynamic-forms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumber.php
More file actions
68 lines (55 loc) · 2.16 KB
/
Copy pathNumber.php
File metadata and controls
68 lines (55 loc) · 2.16 KB
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
<?php
namespace Northwestern\SysDev\DynamicForms\Components\Inputs;
use Illuminate\Contracts\Support\MessageBag;
use Illuminate\Support\Arr;
use Illuminate\Validation\Factory;
use Northwestern\SysDev\DynamicForms\Components\BaseComponent;
use Northwestern\SysDev\DynamicForms\RuleBag;
class Number extends BaseComponent
{
const TYPE = 'number';
protected function processValidations(string $fieldKey, string $fieldLabel, mixed $submissionValue, Factory $validator): MessageBag
{
$rules = new RuleBag($fieldKey, ['numeric']);
$this->validation('required')
? $rules->add('required')
: $rules->add('nullable');
$rules->addIfNotNull(sprintf('min:%s', $this->validation('min')), $this->validation('min'));
$rules->addIfNotNull(sprintf('max:%s', $this->validation('max')), $this->validation('max'));
return $validator->make(
[$fieldKey => $submissionValue],
$rules->rules(),
[],
[$fieldKey => $fieldLabel]
)->messages();
}
/**
* Ensure we return numerics instead of strings.
*/
public function submissionValue(): mixed
{
$requireFloat = Arr::get($this->additional, 'requireDecimal');
$significantDigits = Arr::get($this->additional, 'decimalLimit');
$caster = function ($number) use ($requireFloat, $significantDigits) {
if ($number === null || $number === '') {
return null;
}
if ($requireFloat) {
// Explicitly configured to be a float
$number = (float) $number;
} else {
// Not configured to be a float, so go with whatever they entered.
$number = is_float($number)
? (float) $number
: (int) $number;
}
if ($significantDigits) {
$number = (float) sprintf("%.{$significantDigits}f", $number);
}
return $number;
};
return $this->hasMultipleValues()
? collect($this->submissionValue)->map($caster)->all()
: $caster($this->submissionValue);
}
}