Completed
Push — master ( 804d85...2fedac )
by Nate
02:09
created

Realtype::isDouble()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/*
3
 * Copyright (c) 2015 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 floatval($var);
36
        }
37
38
        if (self::isInt($var)) {
39
            return intval($var);
40
        }
41
42
        if (self::isBool($var)) {
43
            return ('true' === $var) ? true : false;
44
        }
45
46
        // if we've gotten this far, it's a string
47
        return $var;
48
    }
49
50
    /**
51
     * Check if var is boolean
52
     *
53
     * 1. Do a check if the floatval() is 0, if so it's not a double
54
     * 2. Check if the intval() is the same as the floatval()
55
     * 2a. If they are the same, check if there's a decimal, if so it probably ends in .0
56
     *
57
     * @param string $var
58
     * @return bool
59
     */
60
    private static function isDouble($var)
61
    {
62
        return (bool)preg_match('/^\d*\.\d*$/', $var);
63
    }
64
65
    /**
66
     * Check if var is an int
67
     *
68
     * Only does an extra check for 0 after cast
69
     *
70
     * @param string $var
71
     * @return bool
72
     */
73
    private static function isInt($var)
74
    {
75
        return (bool)preg_match('/^\d+$/', $var);
76
    }
77
78
    /**
79
     * Check if 'true' or 'false' is that value of var
80
     *
81
     * @param string $var
82
     * @return bool
83
     */
84
    private static function isBool($var)
85
    {
86
        if ('true' === $var || 'false' === $var) {
87
            return true;
88
        }
89
90
        return false;
91
    }
92
}
93