| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- <?php
- namespace Controllers;
- use Libs\ResponseLib;
- use Models\CommodityModel;
- use Psr\Http\Message\ServerRequestInterface;
- use Respect\Validation\Validator as val;
- use Respect\Validation\Exceptions\ValidationException;
- class CommodityCreateController
- {
- private CommodityModel $model;
- public function __construct()
- {
- $this->model = new CommodityModel();
- }
- public function __invoke(ServerRequestInterface $request)
- {
- $body = json_decode((string)$request->getBody(), true) ?? [];
- try {
- val::key('name', val::stringType()->notEmpty()->length(1, 255))
- ->key('flag', val::optional(val::stringType()->length(1, 10)), false)
- ->assert($body);
- } catch (ValidationException $e) {
- return ResponseLib::sendFail("Validation failed: " . $e->getFullMessage(), [], "E_VALIDATE")->withStatus(400);
- }
- $name = trim($body['name']);
- $flag = $body['flag'] ?? 'a';
- $created = $this->model->create($name, $flag);
- if (!$created) {
- return ResponseLib::sendFail('Failed to create Commodity', [], 'E_DATABASE')->withStatus(500);
- }
- return ResponseLib::sendOk($created, 'S_CREATED');
- }
- }
|