Skip to content

Instantly share code, notes, and snippets.

@vishwac09
Created February 25, 2022 10:12
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/9f8cc72bbba66f2db34eb6b2c534572e to your computer and use it in GitHub Desktop.
Save vishwac09/9f8cc72bbba66f2db34eb6b2c534572e to your computer and use it in GitHub Desktop.
RestfulValdiationBadWay
<?php
class VehicleCreateRestResource {
// POST handler
public function post() {
try {
$payload = []json_decode(\Drupal::request()->getContent());
// Check if vehicle name is not empty.
if (empty($payload['name'])) {
throw new \Exception("Vehicle name cannot be empty", 400);
}
else {
// id the value is present
if (strlen($payload['name']) <= 4) {
throw new \Exception("Vehicle name too short", 400);
}
if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $payload['name'])) {
throw new \Exception("Vehicle name cannot contain special characters", 400);
}
}
// Repeat similar for other fields.
// Proceed to Entity creation if all validation pass.
Vehicle::create($payload);
return new Response($payload, 200);
} catch (\Exception $e) {}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment