diff --git a/docs/divide.md b/docs/divide.md new file mode 100644 index 0000000..e533230 --- /dev/null +++ b/docs/divide.md @@ -0,0 +1,35 @@ +# divide + +Divide two numbers. + +## Parameters + +* a (`integer`, `float`, `double`, `instruction`) - The number to divide. +* b (`integer`, `float`, `double`, `instruction`) - The number to divide by. + +## Return + +(`integer`, `float`, `double`) - The result of the division. + +## Exceptions + +* `EvaluationException` - If there was an error while evaluating one or more parameters. +* `TypeException` - If one or more parameters are not of the expected type. +* `ZeroDivisionException` - If the divisor is zero. + +## Instruction Example + +```json +{ + "type": "divide", + "_": { + "a": 10, + "b": 2 + } +} +``` + +### Last Updated + +Monday, December 26th, 2022. +Written by [Netkas](https://git.n64.cc/netkas) \ No newline at end of file diff --git a/src/RTEX/Objects/Program/Instructions/Divide.php b/src/RTEX/Objects/Program/Instructions/Divide.php index 8a33426..cc430ce 100644 --- a/src/RTEX/Objects/Program/Instructions/Divide.php +++ b/src/RTEX/Objects/Program/Instructions/Divide.php @@ -10,6 +10,7 @@ use RTEX\Engine; use RTEX\Exceptions\EvaluationException; use RTEX\Exceptions\InstructionException; + use RTEX\Exceptions\Runtime\TypeException; use RTEX\Exceptions\Runtime\ZeroDivisionException; use RTEX\Interfaces\InstructionInterface; @@ -66,15 +67,23 @@ /** * @param Engine $engine * @return int - * @throws ZeroDivisionException * @throws EvaluationException + * @throws TypeException + * @throws ZeroDivisionException */ public function eval(Engine $engine): int { - if ($this->B === 0) + $a = $engine->eval($this->A); + $b = $engine->eval($this->B); + + if(!(is_int($a) || is_float($a) || is_double($a))) + throw new TypeException('Cannot divide a non-numeric value'); + if(!(is_int($b) || is_float($b) || is_double($b))) + throw new TypeException('Cannot divide by a non-numeric value'); + if ($b === 0) throw new ZeroDivisionException(sprintf('Division by zero in %s', $this)); - return (intval($engine->eval($this->A)) / intval($engine->eval($this->B))); + return (intval($a) / intval($b)); } /**