. */ namespace SP\Modules\Web\Controllers\Traits; use Exception; use Klein\Klein; use SP\Core\Context\Session; use SP\Domain\Core\Exceptions\SPException; use SP\Http\JsonMessage; use SP\Http\JsonResponse; /** * Trait JsonTrait * * @property Session $session * @property Klein $router */ trait JsonTrait { /** * Returns JSON response * * @param int $status Status code * @param string $description Untranslated description string * @param array|null $messages Untranslated massages array of strings * * @return bool * @throws SPException */ protected function returnJsonResponse(int $status, string $description, ?array $messages = null): bool { $jsonResponse = new JsonMessage(); $jsonResponse->setStatus($status); $jsonResponse->setDescription($description); if (null !== $messages) { $jsonResponse->setMessages($messages); } return JsonResponse::factory($this->router->response())->send($jsonResponse); } /** * Returns JSON response * * @param mixed $data * @param int $status Status code * @param string|null $description Untranslated description string * @param array|null $messages * * @return bool * @throws SPException */ protected function returnJsonResponseData( $data, int $status = JsonMessage::JSON_SUCCESS, ?string $description = null, ?array $messages = null ): bool { $jsonResponse = new JsonMessage(); $jsonResponse->setStatus($status); $jsonResponse->setData($data); if (null !== $description) { $jsonResponse->setDescription($description); } if (null !== $messages) { $jsonResponse->setMessages($messages); } return JsonResponse::factory($this->router->response())->send($jsonResponse); } /** * Returns JSON response * * @param Exception $exception * @param int $status * * @return bool * @throws SPException */ protected function returnJsonResponseException(Exception $exception, int $status = JsonMessage::JSON_ERROR): bool { $jsonResponse = new JsonMessage(); $jsonResponse->setStatus($status); $jsonResponse->setDescription($exception->getMessage()); if ($exception instanceof SPException && $exception->getHint() !== null) { $jsonResponse->setMessages([$exception->getHint()]); } return JsonResponse::factory($this->router->response())->send($jsonResponse); } }