Created
February 25, 2022 10:19
-
-
Save vishwac09/bf7f97e5955c8d2858fa940866ad7660 to your computer and use it in GitHub Desktop.
ReftfulValdiationGoodWay
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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