CommodityUpdateController.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\CommodityModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. class CommodityUpdateController
  7. {
  8. public function __invoke(ServerRequestInterface $request)
  9. {
  10. $body = json_decode((string)$request->getBody(), true) ?? [];
  11. $id = isset($body['commodities_id']) ? (int)$body['commodities_id'] : 0;
  12. $name = array_key_exists('name', $body) ? trim((string)$body['name']) : null;
  13. $flag = array_key_exists('flag', $body) ? (string)$body['flag'] : null;
  14. if ($id <= 0) {
  15. return ResponseLib::sendFail('Validation failed: invalid commodities_id', [], 'E_VALIDATE')->withStatus(400);
  16. }
  17. if ($name === null && $flag === null) {
  18. return ResponseLib::sendFail('Validation failed: nothing to update', [], 'E_VALIDATE')->withStatus(400);
  19. }
  20. if ($name !== null && $name === '') {
  21. return ResponseLib::sendFail('Validation failed: name cannot be empty', [], 'E_VALIDATE')->withStatus(400);
  22. }
  23. $model = new CommodityModel();
  24. $updated = $model->update($id, $name, $flag);
  25. if (!$updated) {
  26. return ResponseLib::sendFail('Commodity Not Found or Not Updated', [], 'E_DATABASE')->withStatus(204);
  27. }
  28. return ResponseLib::sendOk($updated, 'S_UPDATED');
  29. }
  30. }