|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Service\Calculator; |
|
4
|
|
|
|
|
5
|
|
|
use Exception; |
|
6
|
|
|
|
|
7
|
|
|
class CalculatorService |
|
8
|
|
|
{ |
|
9
|
|
|
/** |
|
10
|
|
|
* @var array |
|
11
|
|
|
*/ |
|
12
|
|
|
private array $operators = ['addition', 'subtraction', 'multiplication', 'division']; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @param string $operator |
|
16
|
|
|
* @param string $operandA |
|
17
|
|
|
* @param string $operandB |
|
18
|
|
|
* |
|
19
|
|
|
* @return mixed |
|
20
|
|
|
*/ |
|
21
|
|
|
public function calculate(string $operator, string $operandA, string $operandB): mixed |
|
22
|
|
|
{ |
|
23
|
|
|
if(!in_array($operator, $this->operators)) |
|
24
|
|
|
{ |
|
25
|
|
|
throw new Exception("$operator is not a valid operator."); |
|
26
|
|
|
} |
|
27
|
|
|
if($operandA === '' || $operandB === '') |
|
28
|
|
|
{ |
|
29
|
|
|
throw new Exception("The operands must not be empty."); |
|
30
|
|
|
} |
|
31
|
|
|
if(!is_numeric($operandA)) |
|
32
|
|
|
{ |
|
33
|
|
|
throw new Exception("$operandA is not a valid operand."); |
|
34
|
|
|
} |
|
35
|
|
|
if(!is_numeric($operandB)) |
|
36
|
|
|
{ |
|
37
|
|
|
throw new Exception("$operandB is not a valid operand."); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
$operandA = intval($operandA); |
|
41
|
|
|
$operandB = intval($operandB); |
|
42
|
|
|
if($operator === 'division' && $operandB === 0) |
|
43
|
|
|
{ |
|
44
|
|
|
throw new Exception("Division by 0 is not allowed."); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
return match($operator) { |
|
48
|
|
|
'addition' => $operandA + $operandB, |
|
49
|
|
|
'subtraction' => $operandA - $operandB, |
|
50
|
|
|
'multiplication' => $operandA * $operandB, |
|
51
|
|
|
'division' => $operandA / $operandB, |
|
52
|
|
|
}; |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|