<?php
namespace JoshDiFabio;
interface RomanNumeralGeneratorInterface
{
/**
* @param int $number
* @return string
* @throws \InvalidArgumentException Argument not an integer or out of range
* @author Josh Di Fabio <joshdifabio@hotmail.com>
*/
public function generate($number);
}
class RomanNumeral
{
const ONE = 'I';
const FOUR = 'IV';
const FIVE = 'V';
const NINE = 'IX';
const TEN = 'X';
const FOURTY = 'XL';
const FIFTY = 'L';
const NINETY = 'XC';
const ONE_HUNDRED = 'C';
const FOUR_HUNDRED = 'CD';
const FIVE_HUNDRED = 'D';
const NINE_HUNDRED = 'CM';
const ONE_THOUSAND = 'M';
/**
* @return array
* @author Josh Di Fabio <joshdifabio@hotmail.com>
*/
public static function getIntegerToNumeralMap()
{
return array(
1 => RomanNumeral::ONE,
4 => RomanNumeral::FOUR,
5 => RomanNumeral::FIVE,
9 => RomanNumeral::NINE,
10 => RomanNumeral::TEN,
40 => RomanNumeral::FOURTY,
50 => RomanNumeral::FIFTY,
90 => RomanNumeral::NINETY,
100 => RomanNumeral::ONE_HUNDRED,
400 => RomanNumeral::FOUR_HUNDRED,
500 => RomanNumeral::FIVE_HUNDRED,
900 => RomanNumeral::NINE_HUNDRED,
1000 => RomanNumeral::ONE_THOUSAND,
);
}
}
class RomanNumeralGenerator implements RomanNumeralGeneratorInterface
{
/**
* @param int $number
* @return string
* @throws \InvalidArgumentException Argument not an integer or out of range
* @author Josh Di Fabio <joshdifabio@hotmail.com>
*/
public function generate($number)
{
if (!is_integer($number)) {
throw new \InvalidArgumentException('Provided argument is not an integer.');
}
if (1 > $number || 3999 < $number) {
throw new \InvalidArgumentException(
'The provided number is not within the allowed range of 1 to 3999.');
}
$numeralString = '';
$integerToNumeralMap = RomanNumeral::getIntegerToNumeralMap();
krsort($integerToNumeralMap);
while (0 < $number) {
foreach ($integerToNumeralMap as $_integer => $_numeral) {
/*
* if the input number less any already selected numerals is larger than the current
* numeral, select the current numeral and deduct its integer value from the input
* number
*/
if ($number >= $_integer) {
$numeralString .= $_numeral;
$number -= $_integer;
break;
}
}
}
return $numeralString;
}
}
$generator = new RomanNumeralGenerator;
echo $generator->generate('adsad');
Output for git.master, git.master_jit, rfc.property-hooks
Fatal error: Uncaught InvalidArgumentException: Provided argument is not an integer. in /in/98HUP:66
Stack trace:
#0 /in/98HUP(97): JoshDiFabio\RomanNumeralGenerator->generate('adsad')
#1 {main}
thrown in /in/98HUP on line 66
Process exited with code 255.
This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.