TypeCaster::toBool()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 2
nc 3
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 3
rs 10
c 1
b 0
f 0
1
<?php
2
/**
3
 * This file is part of NACL.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @copyright 2019 Nuglif (2018) Inc.
9
 * @license   http://www.opensource.org/licenses/mit-license.html  MIT License
10
 * @author    Pierrick Charron <[email protected]>
11
 * @author    Charle Demers <[email protected]>
12
 */
13
14
declare(strict_types=1);
15
16
namespace Nuglif\Nacl;
17
18
class TypeCaster
19
{
20 146
    public static function toNum(string $val): float|int
21
    {
22 146
        $f = (float) $val;
23 146
        $i = (int) $val;
24 146
        if ($i == $f) {
25 144
            $res = $i;
26
        } else {
27 5
            $res = $f;
28
        }
29
30 146
        if (preg_match('/[^0-9]*$/', strtolower($val), $matches)) {
31 146
            switch ($matches[0]) {
32 146
                case 'g':
33 1
                    $res *= 1000;
34
                    /* no break */
35 146
                case 'm':
36 1
                    $res *= 1000;
37
                    /* no break */
38 146
                case 'k':
39 4
                    $res *= 1000;
40 4
                    break;
41 146
                case 'gb':
42 1
                    $res *= 1024;
43
                    /* no break */
44 146
                case 'mb':
45 3
                    $res *= 1024;
46
                    /* no break */
47 146
                case 'kb':
48 3
                    $res *= 1024;
49 3
                    break;
50 146
                case 'y':
51 1
                    $res *= 60 * 60 * 24 * 365;
52 1
                    break;
53 146
                case 'w':
54 1
                    $res *= 7;
55
                    /* no break */
56 146
                case 'd':
57 1
                    $res *= 24;
58
                    /* no break */
59 146
                case 'h':
60 1
                    $res *= 60;
61
                    /* no break */
62 146
                case 'min':
63 1
                    $res *= 60;
64 1
                    break;
65 146
                case 'ms':
66 1
                    $res /= 1000;
67 1
                    break;
68
            }
69
        }
70
71 146
        return $res;
72
    }
73
74 77
    public static function toBool(string $val): bool
75
    {
76 77
        $val = strtolower($val);
77
78 77
        return 'true' === $val || 'yes' === $val || 'on' === $val;
79
    }
80
}
81