xref: /webtrees/app/Services/RomanNumeralsService.php (revision 83615acfc72bfb50678c6481f2a00bab04041a87)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17declare(strict_types=1);
18
19namespace Fisharebest\Webtrees\Services;
20
21/**
22 * Convert to and from Roman Numerals
23 */
24class RomanNumeralsService
25{
26    // Convert numbers to/from roman numerals
27    private const ROMAN_NUMERALS = [
28        1000 => 'M',
29        900  => 'CM',
30        500  => 'D',
31        400  => 'CD',
32        100  => 'C',
33        90   => 'XC',
34        50   => 'L',
35        40   => 'XL',
36        10   => 'X',
37        9    => 'IX',
38        5    => 'V',
39        4    => 'IV',
40        1    => 'I',
41    ];
42
43    /**
44     * Convert a decimal number to roman numerals
45     *
46     * @param int $number
47     *
48     * @return string
49     */
50    public function numberToRomanNumerals(int $number): string
51    {
52        if ($number < 1) {
53            // Cannot convert zero/negative numbers
54            return (string) $number;
55        }
56        $roman = '';
57        foreach (self::ROMAN_NUMERALS as $key => $value) {
58            while ($number >= $key) {
59                $roman  .= $value;
60                $number -= $key;
61            }
62        }
63
64        return $roman;
65    }
66
67    /**
68     * Convert a roman numeral to decimal
69     *
70     * @param string $roman
71     *
72     * @return int
73     */
74    public function romanNumeralsToNumber(string $roman): int
75    {
76        $num = 0;
77        foreach (self::ROMAN_NUMERALS as $key => $value) {
78            while (strpos($roman, $value) === 0) {
79                $num += $key;
80                $roman = substr($roman, strlen($value));
81            }
82        }
83
84        return $num;
85    }
86}
87