| Conditions | 4 |
| Paths | 4 |
| Total Lines | 39 |
| Code Lines | 15 |
| Lines | 0 |
| Ratio | 0 % |
| Tests | 16 |
| CRAP Score | 4 |
| Changes | 0 | ||
| 1 | <?php |
||
| 15 | 15 | public function __invoke($subject, string $field): bool |
|
| 16 | { |
||
| 17 | 15 | $value = $subject->$field; |
|
| 18 | |||
| 19 | 15 | if (is_numeric($value)) { |
|
| 20 | // we double-cast here to honor scientific notation. |
||
| 21 | // (int) 1E5 == 15, but (int) (float) 1E5 == 100000 |
||
| 22 | 3 | $value = (float) $value; |
|
| 23 | 3 | $subject->$field = (int) $value; |
|
| 24 | |||
| 25 | 3 | return true; |
|
| 26 | } |
||
| 27 | |||
| 28 | 12 | if (!is_string($value)) { |
|
| 29 | // cannot sanitize a non-string |
||
| 30 | 3 | return false; |
|
| 31 | } |
||
| 32 | |||
| 33 | // it's a non-numeric string, attempt to extract an integer from it. |
||
| 34 | |||
| 35 | // remove all chars except digit and minus. this removes all + signs; any - sign takes precedence because |
||
| 36 | // 0 + -1 = -1 |
||
| 37 | // 0 - +1 = -1 |
||
| 38 | // ... at least it seems that way to me now. |
||
| 39 | 9 | $value = preg_replace('/[^0-9-]/', '', $value); |
|
| 40 | |||
| 41 | // remove all trailing minuses |
||
| 42 | 9 | $value = rtrim($value, '-'); |
|
| 43 | |||
| 44 | // remove all minuses not at the front |
||
| 45 | 9 | $isNegative = preg_match('/^-/', $value); |
|
| 46 | 9 | $value = str_replace('-', '', $value); |
|
| 47 | 9 | if ($isNegative) { |
|
| 48 | 3 | $value = '-' . $value; |
|
| 49 | } |
||
| 50 | |||
| 51 | 9 | $subject->$field = (int) $value; |
|
| 52 | |||
| 53 | 9 | return true; |
|
| 54 | } |
||
| 56 |