| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- <?php
- namespace Controllers;
- use Libs\ResponseLib;
- use Models\ProductModel;
- use Psr\Http\Message\ServerRequestInterface;
- use Respect\Validation\Validator as v;
- use Respect\Validation\Exceptions\ValidationException;
- class ProductCreateController
- {
- private ProductModel $model;
- public function __construct()
- {
- $this->model = new ProductModel();
- }
- public function __invoke(ServerRequestInterface $request)
- {
- $body = json_decode((string)$request->getBody(), true) ?? [];
- try {
- v::key('company_id', v::intType()->positive())
- ->key('product_name', v::stringType()->notEmpty()->alnum(' '))
- ->key('product_price', v::number()->positive())
- ->key('category_id', v::intType()->positive())
- ->assert($body);
- } catch (ValidationException $e) {
- return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
- }
- $companyId = $body['company_id'];
- $productName = $body['product_name'];
- $productPrice = (float) $body['product_price'];
- $categoryId = $body['category_id'];
- $created = $this->model->createProduct(
- $productName,
- $productPrice,
- (int)$categoryId,
- (int)$companyId
- );
- return $created
- ? ResponseLib::sendOk(['created' => true])
- : ResponseLib::sendFail("Failed to Create Product", [], "E_DATABASE")->withStatus(402);
- }
- }
|