Initial commit
This commit is contained in:
49
backend/app/Controllers/BaseController.php
Normal file
49
backend/app/Controllers/BaseController.php
Normal file
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers;
|
||||
|
||||
use App\Core\Request;
|
||||
use App\Core\Response;
|
||||
|
||||
/**
|
||||
* Foundation controller offering model loading, request parsing, and validation helpers.
|
||||
*/
|
||||
class BaseController
|
||||
{
|
||||
/**
|
||||
* Validate request payload and return array of errors if any fail
|
||||
*
|
||||
* @param Request $request
|
||||
* @param array $rules List of keys and their validation constraints (e.g. ['email' => 'required|email'])
|
||||
* @return array Empty if valid, otherwise contains error messages
|
||||
*/
|
||||
protected function validate(Request $request, array $rules): array
|
||||
{
|
||||
$errors = [];
|
||||
$data = $request->getBody();
|
||||
|
||||
foreach ($rules as $field => $constraints) {
|
||||
$value = $data[$field] ?? null;
|
||||
$constraintsArray = explode('|', $constraints);
|
||||
|
||||
foreach ($constraintsArray as $constraint) {
|
||||
if ($constraint === 'required') {
|
||||
if ($value === null || $value === '') {
|
||||
$errors[$field][] = "The {$field} field is required.";
|
||||
}
|
||||
} elseif ($constraint === 'email') {
|
||||
if ($value !== null && $value !== '' && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
|
||||
$errors[$field][] = "The {$field} must be a valid email address.";
|
||||
}
|
||||
} elseif (strpos($constraint, 'min:') === 0) {
|
||||
$min = (int) substr($constraint, 4);
|
||||
if ($value !== null && strlen((string)$value) < $min) {
|
||||
$errors[$field][] = "The {$field} must be at least {$min} characters.";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $errors;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user