DiscountCreateController.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\DiscountModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. use Respect\Validation\Exceptions\ValidationException;
  7. use Respect\Validation\Validator as val;
  8. class DiscountCreateController
  9. {
  10. private DiscountModel $model;
  11. public function __construct()
  12. {
  13. $this->model = new DiscountModel();
  14. }
  15. public function __invoke(ServerRequestInterface $request)
  16. {
  17. $body = json_decode((string)$request->getBody(), true) ?? [];
  18. try {
  19. val::key('discount_value', val::intType()->positive())
  20. ->key('discount_code', val::stringType()->notEmpty()->length(1, 255))
  21. ->assert($body);
  22. } catch (ValidationException $e) {
  23. return ResponseLib::sendFail('Validation failed: ' . $e->getFullMessage(), [], 'E_VALIDATE')->withStatus(400);
  24. }
  25. $discountValue = (int)$body['discount_value'];
  26. $discountCode = trim((string)$body['discount_code']);
  27. if ($discountCode === '') {
  28. return ResponseLib::sendFail('Validation failed: discount_code must not be empty', [], 'E_VALIDATE')->withStatus(400);
  29. }
  30. $discountValue = $discountValue * 100;
  31. if ($discountValue <= 0) {
  32. return ResponseLib::sendFail('Validation failed: discount_value must be greater than zero', [], 'E_VALIDATE')->withStatus(400);
  33. }
  34. try {
  35. $created = $this->model->create($discountValue, $discountCode);
  36. } catch (\PDOException $e) {
  37. if (($e->getCode() ?? '') === '23505') {
  38. return ResponseLib::sendFail('Discount code already exists', [], 'E_DUPLICATE')->withStatus(409);
  39. }
  40. return ResponseLib::sendFail('Failed to create discount: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
  41. } catch (\Throwable $e) {
  42. return ResponseLib::sendFail('Failed to create discount: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
  43. }
  44. return ResponseLib::sendOk($created, 'S_CREATED');
  45. }
  46. }