| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- <?php
- namespace Controllers;
- use Libs\ResponseLib;
- use Models\CategoryModel;
- use Models\ProductModel;
- use Models\DescriptionModel;
- use Psr\Http\Message\ServerRequestInterface;
- use Respect\Validation\Validator as v;
- use Respect\Validation\Exceptions\ValidationException;
- class ProductCreateController
- {
- private ProductModel $productModel;
- private DescriptionModel $descriptionModel;
- public function __construct()
- {
- $this->productModel = new ProductModel();
- $this->descriptionModel = new DescriptionModel();
- }
- 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()->regex('/^[\p{L}\p{N}\s\-\'\"]+$/u'))
- ->key('product_price', v::number()->positive())
- ->key('category_id', v::intType()->positive())
- ->key('product_is_kitchen', v::optional(v::boolType()))
- ->assert($body);
- if (array_key_exists('description_text', $body)) {
- v::stringType()->notEmpty()->length(1, 70)->assert($body['description_text']);
- }
- } 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'];
- $productIsKitchen = $body['product_is_kitchen'] ?? false;
- $descriptionText = $body['description_text'] ?? null;
- $productId = $this->productModel->createProduct(
- $productName,
- $productPrice,
- (int)$categoryId,
- (int)$companyId,
- $productIsKitchen
- );
- if (!$productId) {
- return ResponseLib::sendFail("Failed to Create Product", [], "E_DATABASE")->withStatus(500);
- }
- if ($descriptionText !== null) {
- $descriptionCreated = $this->descriptionModel->addDescription(
- (int)$productId,
- (int)$companyId,
- $descriptionText
- );
- if (!$descriptionCreated) {
- return ResponseLib::sendFail("Product Created, but Failed to Create Description.", [], "E_DATABASE")->withStatus(500);
- }
- }
- return ResponseLib::sendOk(['created' => true, 'product_id' => $productId]);
- }
- }
|