CommodityUpdateController.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 CommodityUpdateController
  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('commodities_id', val::intType()->positive())
  20. ->key('name', val::optional(val::stringType()->notEmpty()->length(1, 255)), false)
  21. ->key('flag', val::optional(val::stringType()->length(1, 10)), false)
  22. ->assert($body);
  23. } catch (ValidationException $e) {
  24. return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
  25. }
  26. $id = (int)$body['commodities_id'];
  27. $name = array_key_exists('name', $body) ? trim($body['name']) : null;
  28. $flag = array_key_exists('flag', $body) ? $body['flag'] : null;
  29. if ($name === null && $flag === null) {
  30. return ResponseLib::sendFail('Validation failed: nothing to update', [], 'E_VALIDATE')->withStatus(400);
  31. }
  32. $updated = $this->model->update($id, $name, $flag);
  33. if (!$updated) {
  34. return ResponseLib::sendFail('Commodity Not Found or Not Updated', [], 'E_DATABASE')->withStatus(204);
  35. }
  36. return ResponseLib::sendOk($updated, 'S_UPDATED');
  37. }
  38. }