Created
February 25, 2022 10:12
-
-
Save vishwac09/9f8cc72bbba66f2db34eb6b2c534572e to your computer and use it in GitHub Desktop.
RestfulValdiationBadWay
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 | |
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