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()->alnum(' ')) ->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(402); } 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]); } }