CommodityCreateController.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\CommodityModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. use Respect\Validation\Validator as val;
  7. use Respect\Validation\Exceptions\ValidationException;
  8. class CommodityCreateController
  9. {
  10. private CommodityModel $model;
  11. public function __construct()
  12. {
  13. $this->model = new CommodityModel();
  14. }
  15. public function __invoke(ServerRequestInterface $request)
  16. {
  17. $body = json_decode((string)$request->getBody(), true) ?? [];
  18. try {
  19. val::key('name', val::stringType()->notEmpty()->length(1, 255))
  20. ->key('flag', val::optional(val::stringType()->length(1, 10)), false)
  21. ->assert($body);
  22. } catch (ValidationException $e) {
  23. return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
  24. }
  25. $name = trim($body['name']);
  26. $flag = $body['flag'] ?? 'a';
  27. $created = $this->model->create($name, $flag);
  28. if (!$created) {
  29. return ResponseLib::sendFail('Failed to create Commodity', [], 'E_DATABASE')->withStatus(500);
  30. }
  31. return ResponseLib::sendOk($created, 'S_CREATED');
  32. }
  33. }