tfettig01 /
InputGuard
| 1 | <?php |
||
| 2 | declare(strict_types=1); |
||
| 3 | |||
| 4 | namespace InputGuard\Guards; |
||
| 5 | |||
| 6 | use InputGuard\Guards\Bases\SingleInput; |
||
| 7 | use InputGuard\Guards\Bases\StringBase; |
||
| 8 | |||
| 9 | /** |
||
| 10 | * Base valid inputs: |
||
| 11 | * 1) An empty string. |
||
| 12 | * 2) A scalar (can be cast back and forth by PHP), and a class with a __toString() method. |
||
| 13 | * |
||
| 14 | * Modifiable validations: |
||
| 15 | * 1) Character length for the string. |
||
| 16 | * 2) Regex on the string. |
||
| 17 | */ |
||
| 18 | class StringableGuard implements Guard |
||
| 19 | { |
||
| 20 | use ErrorMessagesBase; |
||
| 21 | use StringBase; |
||
| 22 | use SingleInput; |
||
| 23 | |||
| 24 | 12 | public function __construct($input, ?int $default = null) |
|
| 25 | { |
||
| 26 | 12 | $this->input = $input; |
|
| 27 | 12 | $this->value = $default; |
|
| 28 | 12 | } |
|
| 29 | |||
| 30 | 11 | protected function validationShortCircuit($input): bool |
|
| 31 | { |
||
| 32 | // The is_scalar is a short circuit for anything not a integer, float, string, boolean. |
||
| 33 | 11 | if ($this->strict ? \is_string($input) : \is_scalar($input)) { |
|
|
0 ignored issues
–
show
Coding Style
introduced
by
Loading history...
|
|||
| 34 | 6 | return true; |
|
| 35 | } |
||
| 36 | |||
| 37 | 5 | return (\is_object($input) && method_exists($input, '__toString')); |
|
| 38 | } |
||
| 39 | |||
| 40 | /** |
||
| 41 | * @return null|string|object |
||
| 42 | */ |
||
| 43 | 10 | public function value() |
|
| 44 | { |
||
| 45 | 10 | $this->success(); |
|
| 46 | |||
| 47 | 10 | return $this->value; |
|
| 48 | } |
||
| 49 | } |
||
| 50 |