Completed
Push — master ( e0c8cf...938a71 )
by Pierre
07:16
created

Roman::to()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 5
nop 1
dl 0
loc 20
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace Popy\Calendar\Formatter\NumberConverter;
4
5
use Popy\Calendar\Formatter\NumberConverterInterface;
6
7
/**
8
 * Roman units converter.
9
 */
10
class Roman implements NumberConverterInterface
11
{
12
    protected static $table = [
13
        'M'  => 1000,
14
        'CM' => 900,
15
        'D'  => 500,
16
        'CD' => 400,
17
        'C'  => 100,
18
        'XC' => 90,
19
        'L'  => 50,
20
        'XL' => 40,
21
        'X'  => 10,
22
        'IX' => 9,
23
        'V'  => 5,
24
        'IV' => 4,
25
        'I'  => 1,
26
    ];
27
28
    /**
29
     * @inheritDoc
30
     */
31
    public function to($input)
32
    {
33
        if ($input === 0) {
34
            return '0';
35
        }
36
37
        if ($input < 0) {
38
            return '-' . $this->to(-$input);
39
        }
40
        
41
        $res = '';
42
43
        foreach (self::$table as $symbol => $value) {
44
            while ($input >= $value) {
45
                $res .= $symbol;
46
                $input -= $value;
47
            }
48
        }
49
50
        return $res;
51
    }
52
53
    /**
54
     * @inheritDoc
55
     */
56
    public function from($input)
57
    {
58
        if ($input === '0') {
59
            return 0;
60
        }
61
62
        $res = $i = 0;
63
        $len = strlen($input);
64
        $sign = 1;
65
66
        if (substr($input, 0, 1) === '-') {
67
            $sign = -1;
68
            $i = 1;
69
        }
70
71
        while ($i < $len) {
72
            foreach (static::$table as $symbol => $value) {
73
                $sl = strlen($symbol);
74
75
                if ($symbol === substr($input, $i, $sl)) {
76
                    $res += $value;
77
                    $i += $sl;
78
79
                    continue 2;
80
                }
81
            }
82
83
            // If nothing matched, exit.
84
            return null;
85
        }
86
87
        return $sign * $res;
88
    }
89
}
90