xref: /webtrees/app/Services/RomanNumeralsService.php (revision 9b152ff9230017d2c03aa1bf603a98b18250446d)
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 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Services;
21
22/**
23 * Convert to and from Roman Numerals
24 */
25class RomanNumeralsService
26{
27    // Convert numbers to/from roman numerals
28    private const ROMAN_NUMERALS = [
29        1000 => 'M',
30        900  => 'CM',
31        500  => 'D',
32        400  => 'CD',
33        100  => 'C',
34        90   => 'XC',
35        50   => 'L',
36        40   => 'XL',
37        10   => 'X',
38        9    => 'IX',
39        5    => 'V',
40        4    => 'IV',
41        1    => 'I',
42    ];
43
44    /**
45     * Convert a decimal number to roman numerals
46     *
47     * @param int $number
48     *
49     * @return string
50     */
51    public function numberToRomanNumerals(int $number): string
52    {
53        if ($number < 1) {
54            // Cannot convert zero/negative numbers
55            return (string) $number;
56        }
57        $roman = '';
58        foreach (self::ROMAN_NUMERALS as $key => $value) {
59            while ($number >= $key) {
60                $roman  .= $value;
61                $number -= $key;
62            }
63        }
64
65        return $roman;
66    }
67
68    /**
69     * Convert a roman numeral to decimal
70     *
71     * @param string $roman
72     *
73     * @return int
74     */
75    public function romanNumeralsToNumber(string $roman): int
76    {
77        $num = 0;
78        foreach (self::ROMAN_NUMERALS as $key => $value) {
79            while (strpos($roman, $value) === 0) {
80                $num += $key;
81                $roman = substr($roman, strlen($value));
82            }
83        }
84
85        return $num;
86    }
87}
88