1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Copyright (C) Jan-Merijn Versteeg - All Rights Reserved |
4
|
|
|
* Unauthorized copying of this file, via any medium, is strictly prohibited |
5
|
|
|
* Proprietary and confidential |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace fieldwork\sanitizers; |
9
|
|
|
|
10
|
|
|
class NumberSanitizer extends FieldSanitizer |
11
|
|
|
{ |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* @var string[] Indicates characters that should be interpreted as radix point |
15
|
|
|
* @link http://en.wikipedia.org/wiki/Radix_point |
16
|
|
|
*/ |
17
|
|
|
private $radixes; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Indicates the precision factor |
21
|
|
|
* @var float |
22
|
|
|
*/ |
23
|
|
|
private $precision; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param string[]|null $radixes Indicates characters that should be interpreted as decimal seperators. By default, points and commas will be accepted. |
27
|
|
|
* @param float $precision Indicates the precision factor |
28
|
|
|
*/ |
29
|
|
|
function __construct ($radixes = null, $precision = 0.01) |
30
|
|
|
{ |
31
|
|
|
$this->radixes = $radixes ?: ['.', ',']; |
32
|
|
|
$this->precision = $precision; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function sanitize ($value) |
36
|
|
|
{ |
37
|
|
|
$radixEscaped = implode('', array_map(function ($radix) { |
38
|
|
|
return preg_quote($radix); |
39
|
|
|
}, $this->radixes)); |
40
|
|
|
$primaryRadix = $this->radixes[0]; |
41
|
|
|
|
42
|
|
|
// Remove all character other than 0-9 and the radixes string |
43
|
|
|
$value = preg_replace('/[^0-9' . $radixEscaped . ']+/', '', $value); |
44
|
|
|
|
45
|
|
|
// Sanity check |
46
|
|
|
if ($value === '') |
47
|
|
|
return ''; |
48
|
|
|
|
49
|
|
|
$delocalized = preg_replace('/[' . $radixEscaped . ']+/', '.', $value); |
50
|
|
|
|
51
|
|
|
// Sanity check |
52
|
|
|
if ($delocalized === '.') |
53
|
|
|
return ''; |
54
|
|
|
|
55
|
|
|
$floatval = floatval($delocalized); |
56
|
|
|
$roundedFloatVal = round($floatval / $this->precision) * $this->precision; |
57
|
|
|
|
58
|
|
|
return str_replace('.', $primaryRadix, $roundedFloatVal); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function isLive () |
62
|
|
|
{ |
63
|
|
|
return true; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Returns a short human-readable slug/string describing the object |
68
|
|
|
* @return string |
69
|
|
|
*/ |
70
|
|
|
function describeObject () |
71
|
|
|
{ |
72
|
|
|
return 'number'; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
public function getJsonData () |
76
|
|
|
{ |
77
|
|
|
return array_merge(parent::getJsonData(), array( |
78
|
|
|
'radixes' => $this->radixes, |
79
|
|
|
'precision' => $this->precision |
80
|
|
|
)); |
81
|
|
|
} |
82
|
|
|
} |