Skip to content

Instantly share code, notes, and snippets.

@vishwac09
Created February 25, 2022 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vishwac09/bf7f97e5955c8d2858fa940866ad7660 to your computer and use it in GitHub Desktop.
Save vishwac09/bf7f97e5955c8d2858fa940866ad7660 to your computer and use it in GitHub Desktop.
ReftfulValdiationGoodWay
<?php
use JsonSchema\Validator;
use VehicleCreateSchema;
class VehicleCreateRestResource {
// POST handler
public function post() {
try {
$payload = (array)json_decode($this->request->getContent());
$query = $this->request->query->all();
$validator = new Validator();
$validator->check($payload, new VehicleCreateSchema()->getCreateSchema());
if (!$validator->isValid()) {
$msg = '';
foreach ($validator->getErrors() as $error) {
$msg .= 'Field: ' . $error['property'] .' Error: '. $error['message'] . '.';
}
throw new \Exception($msg, 400);
}
// Proceed to Entity creation if all validation pass.
Vehicle::create($payload);
return new ModifiedResourceResponse([
"message" => 'Create a new Vehicle entity',
"code" => 200
], 200);
} catch (\Exception $e) {
$error = [
'error' => $e->getMessage(),
'code' => $e->getCode()
];
return new ModifiedResourceResponse($error, $e->getCode());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment