Completed
Push — master ( 803d3c...9ccb75 )
by Josh
12:51
created

NumericFilter::filterUint()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
/**
4
* @package   s9e\TextFormatter
5
* @copyright Copyright (c) 2010-2017 The s9e Authors
6
* @license   http://www.opensource.org/licenses/mit-license.php The MIT License
7
*/
8
namespace s9e\TextFormatter\Parser\AttributeFilters;
9
10
use s9e\TextFormatter\Parser\Logger;
11
12
class NumericFilter
13
{
14
	/**
15
	* Filter a float value
16
	*
17
	* @param  string $attrValue Original value
18
	* @return mixed             Filtered value, or FALSE if invalid
19
	*/
20 14
	public static function filterFloat($attrValue)
21
	{
22 14
		return filter_var($attrValue, FILTER_VALIDATE_FLOAT);
23
	}
24
25
	/**
26
	* Filter an int value
27
	*
28
	* @param  string $attrValue Original value
29
	* @return mixed             Filtered value, or FALSE if invalid
30
	*/
31 15
	public static function filterInt($attrValue)
32
	{
33 15
		return filter_var($attrValue, FILTER_VALIDATE_INT);
34
	}
35
36
	/**
37
	* Filter a range value
38
	*
39
	* @param  string  $attrValue Original value
40
	* @param  integer $min       Minimum value
41
	* @param  integer $max       Maximum value
42
	* @param  Logger  $logger    Parser's Logger instance
43
	* @return mixed              Filtered value, or FALSE if invalid
44
	*/
45
	public static function filterRange($attrValue, $min, $max, Logger $logger = null)
46
	{
47
		$attrValue = filter_var($attrValue, FILTER_VALIDATE_INT);
48
49
		if ($attrValue === false)
50
		{
51
			return false;
52
		}
53
54
		if ($attrValue < $min)
55
		{
56
			if (isset($logger))
57
			{
58
				$logger->warn(
59
					'Value outside of range, adjusted up to min value',
60
					[
61
						'attrValue' => $attrValue,
62
						'min'       => $min,
63
						'max'       => $max
64
					]
65
				);
66
			}
67
68
			return $min;
69
		}
70
71
		if ($attrValue > $max)
72
		{
73
			if (isset($logger))
74
			{
75
				$logger->warn(
76
					'Value outside of range, adjusted down to max value',
77
					[
78
						'attrValue' => $attrValue,
79
						'min'       => $min,
80
						'max'       => $max
81
					]
82
				);
83
			}
84
85
			return $max;
86
		}
87
88
		return $attrValue;
89
	}
90
91
	/**
92
	* Filter a uint value
93
	*
94
	* @param  string $attrValue Original value
95
	* @return mixed             Filtered value, or FALSE if invalid
96
	*/
97 15
	public static function filterUint($attrValue)
98
	{
99 15
		return filter_var($attrValue, FILTER_VALIDATE_INT, [
100 15
			'options' => ['min_range' => 0]
101
		]);
102
	}
103
}