ProductGetController.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\ProductModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. use Respect\Validation\Validator as v;
  7. use Respect\Validation\Exceptions\ValidationException;
  8. class ProductGetController
  9. {
  10. private ProductModel $model;
  11. public function __construct()
  12. {
  13. $this->model = new ProductModel();
  14. }
  15. public function __invoke(ServerRequestInterface $request)
  16. {
  17. $body = json_decode((string)$request->getBody(), true) ?? [];
  18. try {
  19. v::key('company_id', v::intType()->positive())
  20. ->assert($body);
  21. } catch (ValidationException $e) {
  22. return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(401);
  23. }
  24. $companyId = (int) $body['company_id'];
  25. $products = $this->model->getProducts($companyId);
  26. if ($products) {
  27. return ResponseLib::sendOk($products);
  28. }
  29. return ResponseLib::sendFail("Failed to retrieve products", [], "E_DATABASE")->withStatus(500);
  30. }
  31. }