| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Yatra\Http\Requests; |
| 6 |
|
| 7 |
/** |
| 8 |
* Base Request Class |
| 9 |
* Handles validation and sanitization |
| 10 |
*/ |
| 11 |
abstract class BaseRequest |
| 12 |
{ |
| 13 |
/** |
| 14 |
* @var array |
| 15 |
*/ |
| 16 |
protected array $data; |
| 17 |
|
| 18 |
/** |
| 19 |
* @var array |
| 20 |
*/ |
| 21 |
protected array $errors = []; |
| 22 |
|
| 23 |
/** |
| 24 |
* Constructor |
| 25 |
*/ |
| 26 |
public function __construct(array $data) |
| 27 |
{ |
| 28 |
$this->data = $this->sanitize($data); |
| 29 |
} |
| 30 |
|
| 31 |
/** |
| 32 |
* Validate the request |
| 33 |
*/ |
| 34 |
abstract public function validate(): bool; |
| 35 |
|
| 36 |
/** |
| 37 |
* Get validation rules |
| 38 |
*/ |
| 39 |
abstract protected function rules(): array; |
| 40 |
|
| 41 |
/** |
| 42 |
* Sanitize input data |
| 43 |
*/ |
| 44 |
protected function sanitize(array $data): array |
| 45 |
{ |
| 46 |
$sanitized = []; |
| 47 |
|
| 48 |
foreach ($data as $key => $value) { |
| 49 |
if (is_string($value)) { |
| 50 |
$sanitized[$key] = sanitize_text_field($value); |
| 51 |
} elseif (is_array($value)) { |
| 52 |
$sanitized[$key] = $this->sanitize($value); |
| 53 |
} else { |
| 54 |
$sanitized[$key] = $value; |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
return $sanitized; |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Get validated data |
| 63 |
*/ |
| 64 |
public function validated(): array |
| 65 |
{ |
| 66 |
return $this->data; |
| 67 |
} |
| 68 |
|
| 69 |
/** |
| 70 |
* Get errors |
| 71 |
*/ |
| 72 |
public function errors(): array |
| 73 |
{ |
| 74 |
return $this->errors; |
| 75 |
} |
| 76 |
|
| 77 |
/** |
| 78 |
* Check if request is valid |
| 79 |
*/ |
| 80 |
public function isValid(): bool |
| 81 |
{ |
| 82 |
return empty($this->errors); |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
|