jalendport /
craft-roman
| 1 | <?php |
||
| 2 | /** |
||
| 3 | * Roman plugin for Craft CMS 3.x |
||
| 4 | * |
||
| 5 | * Convert an integer into roman numerals and vice versa. |
||
| 6 | * |
||
| 7 | * @link dominion-designs.com |
||
| 8 | * @copyright Copyright (c) 2019 Jalen Davenport |
||
| 9 | */ |
||
| 10 | |||
| 11 | namespace jalendport\roman\services; |
||
| 12 | |||
| 13 | use craft\base\Component; |
||
| 14 | |||
| 15 | /** |
||
| 16 | * RomanService Service |
||
| 17 | * |
||
| 18 | * @author Jalen Davenport |
||
| 19 | * @package Roman |
||
| 20 | * @since 1.0.0 |
||
| 21 | */ |
||
| 22 | class RomanService extends Component |
||
| 23 | { |
||
| 24 | |||
| 25 | /** |
||
| 26 | * @var string |
||
| 27 | */ |
||
| 28 | private $result = ''; |
||
| 29 | |||
| 30 | /** |
||
| 31 | * @var array |
||
| 32 | */ |
||
| 33 | public $romanNumerals = [ |
||
| 34 | 'M' => 1000, |
||
| 35 | 'CM' => 900, |
||
| 36 | 'D' => 500, |
||
| 37 | 'CD' => 400, |
||
| 38 | 'C' => 100, |
||
| 39 | 'XC' => 90, |
||
| 40 | 'L' => 50, |
||
| 41 | 'XL' => 40, |
||
| 42 | 'X' => 10, |
||
| 43 | 'IX' => 9, |
||
| 44 | 'V' => 5, |
||
| 45 | 'IV' => 4, |
||
| 46 | 'I' => 1 |
||
| 47 | ]; |
||
| 48 | |||
| 49 | /** |
||
| 50 | * @param null $number |
||
|
0 ignored issues
–
show
Documentation
Bug
introduced
by
Loading history...
|
|||
| 51 | * @return string|null |
||
| 52 | */ |
||
| 53 | public function getRoman($number = null) |
||
| 54 | { |
||
| 55 | $this->result = null; |
||
| 56 | foreach($this->romanNumerals as $key => $value) |
||
| 57 | { |
||
| 58 | $matches = (int)($number / $value); |
||
| 59 | $this->result .= str_repeat($key, $matches); |
||
| 60 | $number %= $value; |
||
| 61 | } |
||
| 62 | return $this->result; |
||
| 63 | } |
||
| 64 | |||
| 65 | /** |
||
| 66 | * @param null $roman |
||
|
0 ignored issues
–
show
|
|||
| 67 | * @return string|null |
||
| 68 | */ |
||
| 69 | public function getNumber($roman = null) |
||
| 70 | { |
||
| 71 | $this->result = null; |
||
| 72 | foreach($this->romanNumerals as $key => $value) |
||
| 73 | { |
||
| 74 | while (strpos($roman, $key) === 0) |
||
| 75 | { |
||
| 76 | $this->result += $value; |
||
| 77 | $roman = substr($roman, strlen($key)); |
||
| 78 | } |
||
| 79 | } |
||
| 80 | return $this->result; |
||
| 81 | } |
||
| 82 | |||
| 83 | } |
||
| 84 |