1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* Copyright (c) Nate Brunette. |
4
|
|
|
* Distributed under the MIT License (http://opensource.org/licenses/MIT) |
5
|
|
|
*/ |
6
|
|
|
|
7
|
|
|
namespace Tebru\Realtype; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Class Realtype |
11
|
|
|
* |
12
|
|
|
* @author Nate Brunette <[email protected]> |
13
|
|
|
*/ |
14
|
|
|
class Realtype |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* Get the real type from a string |
18
|
|
|
* |
19
|
|
|
* @param string $var |
20
|
|
|
* @return bool|float|int|string |
21
|
|
|
*/ |
22
|
|
|
public static function get($var) |
23
|
|
|
{ |
24
|
|
|
// this function is only useful for values in strings |
25
|
|
|
if (!is_string($var)) { |
26
|
|
|
return $var; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
// if the string is '0', it's an int |
30
|
|
|
if ('0' === $var) { |
31
|
|
|
return 0; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
if (self::isDouble($var)) { |
35
|
|
|
return (float) $var; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
if (self::isInt($var)) { |
39
|
|
|
return (int) $var; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
if (self::isBool($var)) { |
43
|
|
|
return 'true' === $var; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
if (self::isNull($var)) { |
47
|
|
|
return null; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
// if we've gotten this far, it's a string |
51
|
|
|
return $var; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Check if var is boolean |
56
|
|
|
* |
57
|
|
|
* 1. Do a check if the floatval() is 0, if so it's not a double |
58
|
|
|
* 2. Check if the intval() is the same as the floatval() |
59
|
|
|
* 2a. If they are the same, check if there's a decimal, if so it probably ends in .0 |
60
|
|
|
* |
61
|
|
|
* @param string $var |
62
|
|
|
* @return bool |
63
|
|
|
*/ |
64
|
|
|
private static function isDouble($var) |
65
|
|
|
{ |
66
|
|
|
return (bool) preg_match('/^\d*\.\d*$/', $var); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Check if var is an int |
71
|
|
|
* |
72
|
|
|
* Only does an extra check for 0 after cast |
73
|
|
|
* |
74
|
|
|
* @param string $var |
75
|
|
|
* @return bool |
76
|
|
|
*/ |
77
|
|
|
private static function isInt($var) |
78
|
|
|
{ |
79
|
|
|
return (bool) preg_match('/^\d+$/', $var); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
/** |
83
|
|
|
* Check if 'true' or 'false' is that value of var |
84
|
|
|
* |
85
|
|
|
* @param string $var |
86
|
|
|
* @return bool |
87
|
|
|
*/ |
88
|
|
|
private static function isBool($var) |
89
|
|
|
{ |
90
|
|
|
return 'true' === $var || 'false' === $var; |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
/** |
94
|
|
|
* Check if var is null |
95
|
|
|
* |
96
|
|
|
* @param string $var |
97
|
|
|
* @return bool |
98
|
|
|
*/ |
99
|
|
|
private static function isNull($var) |
100
|
|
|
{ |
101
|
|
|
return 'null' === $var; |
102
|
|
|
} |
103
|
|
|
} |
104
|
|
|
|