|
1 | 1 | <?php |
2 | 2 |
|
3 | | -/* |
4 | | - * By adding type hints and enabling strict type checking, code can become |
5 | | - * easier to read, self-documenting and reduce the number of potential bugs. |
6 | | - * By default, type declarations are non-strict, which means they will attempt |
7 | | - * to change the original type to match the type specified by the |
8 | | - * type-declaration. |
9 | | - * |
10 | | - * In other words, if you pass a string to a function requiring a float, |
11 | | - * it will attempt to convert the string value to a float. |
12 | | - * |
13 | | - * To enable strict mode, a single declare directive must be placed at the top |
14 | | - * of the file. |
15 | | - * This means that the strictness of typing is configured on a per-file basis. |
16 | | - * This directive not only affects the type declarations of parameters, but also |
17 | | - * a function's return type. |
18 | | - * |
19 | | - * For more info review the Concept on strict type checking in the PHP track |
20 | | - * <link>. |
21 | | - * |
22 | | - * To disable strict typing, comment out the directive below. |
23 | | - */ |
24 | | - |
25 | 3 | declare(strict_types=1); |
26 | 4 |
|
27 | 5 | function calculate($question = "") |
28 | 6 | { |
29 | 7 | preg_match( |
30 | | - "/What is (-?\d+) (plus|minus|multiplied by|divided by) " |
31 | | - . "(-?\d+)(?: (plus|minus|multiplied by|divided by) (-?\d+))?\?/", |
| 8 | + "/What is (-?\d+)(?: (plus|minus|multiplied by|divided by) " |
| 9 | + . "(-?\d+)(?: (plus|minus|multiplied by|divided by) (-?\d+))?)?\?/", |
32 | 10 | $question, |
33 | 11 | $matches |
34 | 12 | ); |
35 | 13 |
|
36 | | - if (empty($matches[2])) { |
| 14 | + if (!isset($matches[1])) { |
37 | 15 | throw new InvalidArgumentException(); |
38 | 16 | } |
39 | 17 |
|
40 | | - switch ($matches[2]) { |
41 | | - case 'plus': |
42 | | - $number = $matches[1] + $matches[3]; |
43 | | - break; |
44 | | - case 'minus': |
45 | | - $number = $matches[1] - $matches[3]; |
46 | | - break; |
47 | | - case 'multiplied by': |
48 | | - $number = $matches[1] * $matches[3]; |
49 | | - break; |
50 | | - case 'divided by': |
51 | | - $number = $matches[1] / $matches[3]; |
52 | | - break; |
53 | | - default: |
54 | | - $number = 0; |
| 18 | + $number = $matches[1]; |
| 19 | + |
| 20 | + if (isset($matches[2]) && isset($matches[3])) { |
| 21 | + switch ($matches[2]) { |
| 22 | + case 'plus': |
| 23 | + $number = $matches[1] + $matches[3]; |
| 24 | + break; |
| 25 | + case 'minus': |
| 26 | + $number = $matches[1] - $matches[3]; |
| 27 | + break; |
| 28 | + case 'multiplied by': |
| 29 | + $number = $matches[1] * $matches[3]; |
| 30 | + break; |
| 31 | + case 'divided by': |
| 32 | + $number = $matches[1] / $matches[3]; |
| 33 | + break; |
| 34 | + default: |
| 35 | + throw new InvalidArgumentException(); |
| 36 | + } |
55 | 37 | } |
56 | 38 |
|
57 | 39 | if (isset($matches[4]) && isset($matches[5])) { |
|
0 commit comments