@@ -24,513 +24,513 @@ |
||
| 24 | 24 | */ |
| 25 | 25 | class ResponseBuilder |
| 26 | 26 | { |
| 27 | - /** |
|
| 28 | - * Default HTTP code to be used with success responses |
|
| 29 | - * |
|
| 30 | - * @var int |
|
| 31 | - */ |
|
| 32 | - public const DEFAULT_HTTP_CODE_OK = HttpResponse::HTTP_OK; |
|
| 33 | - |
|
| 34 | - /** |
|
| 35 | - * Default HTTP code to be used with error responses |
|
| 36 | - * |
|
| 37 | - * @var int |
|
| 38 | - */ |
|
| 39 | - public const DEFAULT_HTTP_CODE_ERROR = HttpResponse::HTTP_BAD_REQUEST; |
|
| 40 | - |
|
| 41 | - /** |
|
| 42 | - * Min allowed HTTP code for errorXXX() |
|
| 43 | - * |
|
| 44 | - * @var int |
|
| 45 | - */ |
|
| 46 | - public const ERROR_HTTP_CODE_MIN = 400; |
|
| 47 | - |
|
| 48 | - /** |
|
| 49 | - * Max allowed HTTP code for errorXXX() |
|
| 50 | - * |
|
| 51 | - * @var int |
|
| 52 | - */ |
|
| 53 | - public const ERROR_HTTP_CODE_MAX = 599; |
|
| 54 | - |
|
| 55 | - /** |
|
| 56 | - * Configuration keys |
|
| 57 | - */ |
|
| 58 | - public const CONF_KEY_DEBUG_DEBUG_KEY = 'response_builder.debug.debug_key'; |
|
| 59 | - public const CONF_KEY_DEBUG_EX_TRACE_ENABLED = 'response_builder.debug.exception_handler.trace_enabled'; |
|
| 60 | - public const CONF_KEY_DEBUG_EX_TRACE_KEY = 'response_builder.debug.exception_handler.trace_key'; |
|
| 61 | - public const CONF_KEY_MAP = 'response_builder.map'; |
|
| 62 | - public const CONF_KEY_ENCODING_OPTIONS = 'response_builder.encoding_options'; |
|
| 63 | - public const CONF_KEY_CLASSES = 'response_builder.classes'; |
|
| 64 | - public const CONF_KEY_MIN_CODE = 'response_builder.min_code'; |
|
| 65 | - public const CONF_KEY_MAX_CODE = 'response_builder.max_code'; |
|
| 66 | - public const CONF_KEY_RESPONSE_KEY_MAP = 'response_builder.map'; |
|
| 67 | - public const CONF_EXCEPTION_HANDLER_KEY = 'response_builder.exception_handler'; |
|
| 68 | - |
|
| 69 | - /** |
|
| 70 | - * Default keys to be used by exception handler while adding debug information |
|
| 71 | - */ |
|
| 72 | - public const KEY_DEBUG = 'debug'; |
|
| 73 | - public const KEY_TRACE = 'trace'; |
|
| 74 | - public const KEY_CLASS = 'class'; |
|
| 75 | - public const KEY_FILE = 'file'; |
|
| 76 | - public const KEY_LINE = 'line'; |
|
| 77 | - public const KEY_KEY = 'key'; |
|
| 78 | - public const KEY_METHOD = 'method'; |
|
| 79 | - public const KEY_SUCCESS = 'success'; |
|
| 80 | - public const KEY_CODE = 'code'; |
|
| 81 | - public const KEY_LOCALE = 'locale'; |
|
| 82 | - public const KEY_MESSAGE = 'message'; |
|
| 83 | - public const KEY_DATA = 'data'; |
|
| 84 | - |
|
| 85 | - /** |
|
| 86 | - * Default key to be used by exception handler while processing ValidationException |
|
| 87 | - * to return all the error messages |
|
| 88 | - * |
|
| 89 | - * @var string |
|
| 90 | - */ |
|
| 91 | - public const KEY_MESSAGES = 'messages'; |
|
| 92 | - |
|
| 93 | - /** |
|
| 94 | - * Default JSON encoding options. Must be specified as final value (i.e. 271) and NOT |
|
| 95 | - * PHP expression i.e. `JSON_HEX_TAG|JSON_HEX_APOS|...` as such syntax is not yet supported |
|
| 96 | - * by PHP. |
|
| 97 | - * |
|
| 98 | - * 271 = JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE |
|
| 99 | - * |
|
| 100 | - * @var int |
|
| 101 | - */ |
|
| 102 | - public const DEFAULT_ENCODING_OPTIONS = 271; |
|
| 103 | - |
|
| 104 | - /** |
|
| 105 | - * Reads and validates "classes" config mapping |
|
| 106 | - * |
|
| 107 | - * @return array Classes mapping as specified in configuration or empty array if configuration found |
|
| 108 | - * |
|
| 109 | - * @throws \RuntimeException if "classes" mapping is technically invalid (i.e. not array etc). |
|
| 110 | - */ |
|
| 111 | - protected static function getClassesMapping(): ?array |
|
| 112 | - { |
|
| 113 | - $classes = Config::get(self::CONF_KEY_CLASSES); |
|
| 114 | - |
|
| 115 | - if ($classes !== null) { |
|
| 116 | - if (!is_array($classes)) { |
|
| 117 | - throw new \RuntimeException( |
|
| 118 | - sprintf('CONFIG: "classes" mapping must be an array (%s given)', gettype($classes))); |
|
| 119 | - } |
|
| 120 | - |
|
| 121 | - $mandatory_keys = [ |
|
| 122 | - static::KEY_KEY, |
|
| 123 | - static::KEY_METHOD, |
|
| 124 | - ]; |
|
| 125 | - foreach ($classes as $class_name => $class_config) { |
|
| 126 | - foreach ($mandatory_keys as $key_name) { |
|
| 127 | - if (!array_key_exists($key_name, $class_config)) { |
|
| 128 | - throw new \RuntimeException("CONFIG: Missing '{$key_name}' for '{$class_name}' class mapping"); |
|
| 129 | - } |
|
| 130 | - } |
|
| 131 | - } |
|
| 132 | - } else { |
|
| 133 | - $classes = []; |
|
| 134 | - } |
|
| 135 | - |
|
| 136 | - return $classes; |
|
| 137 | - } |
|
| 138 | - |
|
| 139 | - /** |
|
| 140 | - * Returns success |
|
| 141 | - * |
|
| 142 | - * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node |
|
| 143 | - * of the JSON response, single supported object or @null if there's no |
|
| 144 | - * to be returned. |
|
| 145 | - * @param integer|null $api_code API code to be returned or @null to use value of BaseApiCodes::OK(). |
|
| 146 | - * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 147 | - * substitution or @null if none. |
|
| 148 | - * @param integer|null $http_code HTTP code to be used for HttpResponse sent or @null |
|
| 149 | - * for default DEFAULT_HTTP_CODE_OK. |
|
| 150 | - * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 151 | - * options or pass @null to use value from your config (or defaults). |
|
| 152 | - * |
|
| 153 | - * @return HttpResponse |
|
| 154 | - */ |
|
| 155 | - public static function success($data = null, $api_code = null, array $placeholders = null, |
|
| 156 | - int $http_code = null, int $json_opts = null): HttpResponse |
|
| 157 | - { |
|
| 158 | - return static::buildSuccessResponse($data, $api_code, $placeholders, $http_code, $json_opts); |
|
| 159 | - } |
|
| 160 | - |
|
| 161 | - /** |
|
| 162 | - * Returns success |
|
| 163 | - * |
|
| 164 | - * @param integer|null $api_code API code to be returned or @null to use value of BaseApiCodes::OK(). |
|
| 165 | - * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 166 | - * substitution or @null if none. |
|
| 167 | - * @param integer|null $http_code HTTP code to be used for HttpResponse sent or @null |
|
| 168 | - * for default DEFAULT_HTTP_CODE_OK. |
|
| 169 | - * |
|
| 170 | - * @return HttpResponse |
|
| 171 | - */ |
|
| 172 | - public static function successWithCode(int $api_code = null, array $placeholders = null, |
|
| 173 | - int $http_code = null): HttpResponse |
|
| 174 | - { |
|
| 175 | - return static::success(null, $api_code, $placeholders, $http_code); |
|
| 176 | - } |
|
| 177 | - |
|
| 178 | - /** |
|
| 179 | - * Returns success with custom HTTP code |
|
| 180 | - * |
|
| 181 | - * @param integer|null $http_code HTTP return code to be set for this response. If @null is passed, falls back |
|
| 182 | - * to DEFAULT_HTTP_CODE_OK. |
|
| 183 | - * |
|
| 184 | - * @return HttpResponse |
|
| 185 | - */ |
|
| 186 | - public static function successWithHttpCode(int $http_code = null): HttpResponse |
|
| 187 | - { |
|
| 188 | - return static::buildSuccessResponse(null, BaseApiCodes::OK(), [], $http_code); |
|
| 189 | - } |
|
| 190 | - |
|
| 191 | - /** |
|
| 192 | - * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node. |
|
| 193 | - * of the JSON response, single supported object or @null if there's no |
|
| 194 | - * to be returned. |
|
| 195 | - * @param integer|null $api_code API code to be returned or @null to use value of BaseApiCodes::OK(). |
|
| 196 | - * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 197 | - * substitution or @null if none. |
|
| 198 | - * @param integer|null $http_code HTTP code to be used for HttpResponse sent or @null |
|
| 199 | - * for default DEFAULT_HTTP_CODE_OK. |
|
| 200 | - * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 201 | - * options or pass @null to use value from your config (or defaults). |
|
| 202 | - * |
|
| 203 | - * @return HttpResponse |
|
| 204 | - * |
|
| 205 | - * @throws \InvalidArgumentException Thrown when provided arguments are invalid. |
|
| 206 | - */ |
|
| 207 | - protected static function buildSuccessResponse($data = null, int $api_code = null, array $placeholders = null, |
|
| 208 | - int $http_code = null, int $json_opts = null): HttpResponse |
|
| 209 | - { |
|
| 210 | - $http_code = $http_code ?? static::DEFAULT_HTTP_CODE_OK; |
|
| 211 | - $api_code = $api_code ?? BaseApiCodes::OK(); |
|
| 212 | - |
|
| 213 | - Validator::assertInt('api_code', $api_code); |
|
| 214 | - Validator::assertInt('http_code', $http_code); |
|
| 215 | - Validator::assertIntRange('http_code', $http_code, 200, 299); |
|
| 216 | - |
|
| 217 | - return static::make(true, $api_code, $api_code, $data, $http_code, $placeholders, null, $json_opts); |
|
| 218 | - } |
|
| 219 | - |
|
| 220 | - /** |
|
| 221 | - * Builds error Response object. Supports optional arguments passed to Lang::get() if associated error |
|
| 222 | - * message uses placeholders as well as return data payload |
|
| 223 | - * |
|
| 224 | - * @param integer $api_code Your API code to be returned with the response object. |
|
| 225 | - * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 226 | - * substitution or @null if none. |
|
| 227 | - * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node |
|
| 228 | - * of the JSON response, single supported object or @null if there's no |
|
| 229 | - * to be returned. |
|
| 230 | - * @param integer|null $http_code HTTP code to be used for HttpResponse sent or @null |
|
| 231 | - * for default DEFAULT_HTTP_CODE_ERROR. |
|
| 232 | - * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 233 | - * options or pass @null to use value from your config (or defaults). |
|
| 234 | - * |
|
| 235 | - * @return HttpResponse |
|
| 236 | - */ |
|
| 237 | - public static function error(int $api_code, array $placeholders = null, $data = null, int $http_code = null, |
|
| 238 | - int $encoding_options = null): HttpResponse |
|
| 239 | - { |
|
| 240 | - return static::buildErrorResponse($data, $api_code, $http_code, $placeholders, $encoding_options); |
|
| 241 | - } |
|
| 242 | - |
|
| 243 | - /** |
|
| 244 | - * @param integer $api_code Your API code to be returned with the response object. |
|
| 245 | - * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node |
|
| 246 | - * of the JSON response, single supported object or @null if there's no |
|
| 247 | - * to be returned. |
|
| 248 | - * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 249 | - * substitution or @null if none. |
|
| 250 | - * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 251 | - * options or pass @null to use value from your config (or defaults). |
|
| 252 | - * |
|
| 253 | - * @return HttpResponse |
|
| 254 | - */ |
|
| 255 | - public static function errorWithData(int $api_code, $data, array $placeholders = null, |
|
| 256 | - int $json_opts = null): HttpResponse |
|
| 257 | - { |
|
| 258 | - return static::buildErrorResponse($data, $api_code, null, $placeholders, $json_opts); |
|
| 259 | - } |
|
| 260 | - |
|
| 261 | - /** |
|
| 262 | - * @param integer $api_code Your API code to be returned with the response object. |
|
| 263 | - * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node |
|
| 264 | - * of the JSON response, single supported object or @null if there's no |
|
| 265 | - * to be returned. |
|
| 266 | - * @param integer $http_code HTTP code to be used for HttpResponse sent. |
|
| 267 | - * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 268 | - * substitution or @null if none. |
|
| 269 | - * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 270 | - * options or pass @null to use value from your config (or defaults). |
|
| 271 | - * |
|
| 272 | - * @return HttpResponse |
|
| 273 | - * |
|
| 274 | - * @throws \InvalidArgumentException if http_code is @null |
|
| 275 | - */ |
|
| 276 | - public static function errorWithDataAndHttpCode(int $api_code, $data, int $http_code, array $placeholders = null, |
|
| 277 | - int $json_opts = null): HttpResponse |
|
| 278 | - { |
|
| 279 | - return static::buildErrorResponse($data, $api_code, $http_code, $placeholders, $json_opts); |
|
| 280 | - } |
|
| 281 | - |
|
| 282 | - /** |
|
| 283 | - * @param integer $api_code Your API code to be returned with the response object. |
|
| 284 | - * @param integer $http_code HTTP code to be used for HttpResponse sent or @null |
|
| 285 | - * for default DEFAULT_HTTP_CODE_ERROR. |
|
| 286 | - * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 287 | - * substitution or @null if none. |
|
| 288 | - * |
|
| 289 | - * @return HttpResponse |
|
| 290 | - * |
|
| 291 | - * @throws \InvalidArgumentException if http_code is @null |
|
| 292 | - */ |
|
| 293 | - public static function errorWithHttpCode(int $api_code, int $http_code, array $placeholders = null): HttpResponse |
|
| 294 | - { |
|
| 295 | - return static::buildErrorResponse(null, $api_code, $http_code, $placeholders); |
|
| 296 | - } |
|
| 297 | - |
|
| 298 | - /** |
|
| 299 | - * @param integer $api_code Your API code to be returned with the response object. |
|
| 300 | - * @param string $message Custom message to be returned as part of error response |
|
| 301 | - * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node |
|
| 302 | - * of the JSON response, single supported object or @null if there's no |
|
| 303 | - * to be returned. |
|
| 304 | - * @param integer|null $http_code Optional HTTP status code to be used for HttpResponse sent |
|
| 305 | - * or @null for DEFAULT_HTTP_CODE_ERROR |
|
| 306 | - * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 307 | - * options or pass @null to use value from your config (or defaults). |
|
| 308 | - * |
|
| 309 | - * @return HttpResponse |
|
| 310 | - */ |
|
| 311 | - public static function errorWithMessageAndData(int $api_code, string $message, $data, |
|
| 312 | - int $http_code = null, int $json_opts = null): HttpResponse |
|
| 313 | - { |
|
| 314 | - return static::buildErrorResponse($data, $api_code, $http_code, null, |
|
| 315 | - $message, null, $json_opts); |
|
| 316 | - } |
|
| 317 | - |
|
| 318 | - /** |
|
| 319 | - * @param integer $api_code Your API code to be returned with the response object. |
|
| 320 | - * @param string $message custom message to be returned as part of error response |
|
| 321 | - * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node |
|
| 322 | - * of the JSON response, single supported object or @null if there's no |
|
| 323 | - * to be returned. |
|
| 324 | - * @param integer|null $http_code HTTP code to be used for HttpResponse sent or @null |
|
| 325 | - * for default DEFAULT_HTTP_CODE_ERROR. |
|
| 326 | - * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 327 | - * options or pass @null to use value from your config (or defaults). |
|
| 328 | - * @param array|null $debug_data optional debug data array to be added to returned JSON. |
|
| 329 | - * |
|
| 330 | - * @return HttpResponse |
|
| 331 | - */ |
|
| 332 | - public static function errorWithMessageAndDataAndDebug(int $api_code, string $message, $data, |
|
| 333 | - int $http_code = null, int $json_opts = null, |
|
| 334 | - array $debug_data = null): HttpResponse |
|
| 335 | - { |
|
| 336 | - return static::buildErrorResponse($data, $api_code, $http_code, null, |
|
| 337 | - $message, null, $json_opts, $debug_data); |
|
| 338 | - } |
|
| 339 | - |
|
| 340 | - /** |
|
| 341 | - * @param integer $api_code Your API code to be returned with the response object. |
|
| 342 | - * @param string $message Custom message to be returned as part of error response |
|
| 343 | - * @param integer|null $http_code HTTP code to be used with final response sent or @null |
|
| 344 | - * for default DEFAULT_HTTP_CODE_ERROR. |
|
| 345 | - * |
|
| 346 | - * @return HttpResponse |
|
| 347 | - */ |
|
| 348 | - public static function errorWithMessage(int $api_code, string $message, int $http_code = null): HttpResponse |
|
| 349 | - { |
|
| 350 | - return static::buildErrorResponse(null, $api_code, $http_code, null, $message); |
|
| 351 | - } |
|
| 352 | - |
|
| 353 | - /** |
|
| 354 | - * Builds error Response object. Supports optional arguments passed to Lang::get() if associated error message |
|
| 355 | - * uses placeholders as well as return data payload |
|
| 356 | - * |
|
| 357 | - * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node |
|
| 358 | - * of the JSON response, single supported object or @null if there's no |
|
| 359 | - * to be returned. |
|
| 360 | - * @param integer $api_code Your API code to be returned with the response object. |
|
| 361 | - * @param integer|null $http_code HTTP code to be used for HttpResponse sent or @null |
|
| 362 | - * for default DEFAULT_HTTP_CODE_ERROR. |
|
| 363 | - * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 364 | - * substitution or @null if none. |
|
| 365 | - * @param string|null $message custom message to be returned as part of error response |
|
| 366 | - * @param array|null $headers optional HTTP headers to be returned in error response |
|
| 367 | - * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 368 | - * options or pass @null to use value from your config (or defaults). |
|
| 369 | - * @param array|null $debug_data optional debug data array to be added to returned JSON. |
|
| 370 | - * |
|
| 371 | - * @return HttpResponse |
|
| 372 | - * |
|
| 373 | - * @throws \InvalidArgumentException Thrown if $code is not correct, outside the range, equals OK code etc. |
|
| 374 | - * |
|
| 375 | - * @noinspection MoreThanThreeArgumentsInspection |
|
| 376 | - */ |
|
| 377 | - protected static function buildErrorResponse($data, int $api_code, int $http_code = null, |
|
| 378 | - array $placeholders = null, |
|
| 379 | - string $message = null, array $headers = null, |
|
| 380 | - int $json_opts = null, |
|
| 381 | - array $debug_data = null): HttpResponse |
|
| 382 | - { |
|
| 383 | - $http_code = $http_code ?? static::DEFAULT_HTTP_CODE_ERROR; |
|
| 384 | - $headers = $headers ?? []; |
|
| 385 | - |
|
| 386 | - Validator::assertInt('api_code', $api_code); |
|
| 387 | - |
|
| 388 | - $code_ok = BaseApiCodes::OK(); |
|
| 389 | - if ($api_code !== $code_ok) { |
|
| 390 | - Validator::assertIntRange('api_code', $api_code, BaseApiCodes::getMinCode(), BaseApiCodes::getMaxCode()); |
|
| 391 | - } |
|
| 392 | - if ($api_code === $code_ok) { |
|
| 393 | - throw new \InvalidArgumentException( |
|
| 394 | - "Error response cannot use api_code of value {$code_ok} which is reserved for OK"); |
|
| 395 | - } |
|
| 396 | - |
|
| 397 | - Validator::assertInt('http_code', $http_code); |
|
| 398 | - Validator::assertIntRange('http_code', $http_code, static::ERROR_HTTP_CODE_MIN, static::ERROR_HTTP_CODE_MAX); |
|
| 399 | - |
|
| 400 | - $msg_or_api_code = $message ?? $api_code; |
|
| 401 | - |
|
| 402 | - return static::make(false, $api_code, $msg_or_api_code, $data, $http_code, |
|
| 403 | - $placeholders, $headers, $json_opts, $debug_data); |
|
| 404 | - } |
|
| 405 | - |
|
| 406 | - /** |
|
| 407 | - * @param boolean $success @true if response reports successful operation, @false otherwise. |
|
| 408 | - * @param integer $api_code Your API code to be returned with the response object. |
|
| 409 | - * @param string|integer $msg_or_api_code message string or valid API code to get message for |
|
| 410 | - * @param object|array|null $data optional additional data to be included in response object |
|
| 411 | - * @param integer|null $http_code HTTP code for the HttpResponse or @null for either DEFAULT_HTTP_CODE_OK |
|
| 412 | - * or DEFAULT_HTTP_CODE_ERROR depending on the $success. |
|
| 413 | - * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 414 | - * substitution or @null if none. |
|
| 415 | - * @param array|null $headers Optional HTTP headers to be returned in the response. |
|
| 416 | - * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 417 | - * options or pass @null to use value from your config (or defaults). |
|
| 418 | - * @param array|null $debug_data Optional debug data array to be added to returned JSON. |
|
| 419 | - * |
|
| 420 | - * @return HttpResponse |
|
| 421 | - * |
|
| 422 | - * @throws \InvalidArgumentException If $api_code is neither a string nor valid integer code. |
|
| 423 | - * @throws \InvalidArgumentException if $data is an object of class that is not configured in "classes" mapping. |
|
| 424 | - * |
|
| 425 | - * @noinspection MoreThanThreeArgumentsInspection |
|
| 426 | - */ |
|
| 427 | - protected static function make(bool $success, int $api_code, $msg_or_api_code, $data = null, |
|
| 428 | - int $http_code = null, array $placeholders = null, array $headers = null, |
|
| 429 | - int $json_opts = null, array $debug_data = null): HttpResponse |
|
| 430 | - { |
|
| 431 | - $headers = $headers ?? []; |
|
| 432 | - $http_code = $http_code ?? ($success ? static::DEFAULT_HTTP_CODE_OK : static::DEFAULT_HTTP_CODE_ERROR); |
|
| 433 | - $json_opts = $json_opts ?? Config::get(self::CONF_KEY_ENCODING_OPTIONS, static::DEFAULT_ENCODING_OPTIONS); |
|
| 434 | - |
|
| 435 | - Validator::assertInt('encoding_options', $json_opts); |
|
| 436 | - |
|
| 437 | - Validator::assertInt('api_code', $api_code); |
|
| 438 | - if (!BaseApiCodes::isCodeValid($api_code)) { |
|
| 439 | - $min = BaseApiCodes::getMinCode(); |
|
| 440 | - $max = BaseApiCodes::getMaxCode(); |
|
| 441 | - throw new \InvalidArgumentException("API code value ({$api_code}) is out of allowed range {$min}-{$max}"); |
|
| 442 | - } |
|
| 443 | - |
|
| 444 | - return Response::json( |
|
| 445 | - static::buildResponse($success, $api_code, $msg_or_api_code, $placeholders, $data, $debug_data), |
|
| 446 | - $http_code, $headers, $json_opts); |
|
| 447 | - } |
|
| 448 | - |
|
| 449 | - /** |
|
| 450 | - * If $msg_or_api_code is integer value, returns human readable message associated with that code (with |
|
| 451 | - * fallback to built-in default string if no api code mapping is set. If $msg_or_api_code is a string, |
|
| 452 | - * returns it unaltered. |
|
| 453 | - * |
|
| 454 | - * @param boolean $success @true if response reports successful operation, @false otherwise. |
|
| 455 | - * @param integer $api_code Your API code to be returned with the response object. |
|
| 456 | - * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 457 | - * substitution or @null if none. |
|
| 458 | - * |
|
| 459 | - * @return string |
|
| 460 | - */ |
|
| 461 | - protected static function getMessageForApiCode(bool $success, int $api_code, array $placeholders = null): string |
|
| 462 | - { |
|
| 463 | - // We got integer value here not a message string, so we need to check if we have the mapping for |
|
| 464 | - // this string already configured. |
|
| 465 | - $key = BaseApiCodes::getCodeMessageKey($api_code); |
|
| 466 | - if ($key === null) { |
|
| 467 | - // nope, let's get the default one instead, based of |
|
| 468 | - $fallback_code = $success ? BaseApiCodes::OK() : BaseApiCodes::NO_ERROR_MESSAGE(); |
|
| 469 | - $key = BaseApiCodes::getCodeMessageKey($fallback_code); |
|
| 470 | - } |
|
| 471 | - |
|
| 472 | - $placeholders = $placeholders ?? []; |
|
| 473 | - if (!array_key_exists('api_code', $placeholders)) { |
|
| 474 | - $placeholders['api_code'] = $api_code; |
|
| 475 | - } |
|
| 476 | - |
|
| 477 | - return \Lang::get($key, $placeholders); |
|
| 478 | - } |
|
| 479 | - |
|
| 480 | - /** |
|
| 481 | - * Creates standardised API response array. This is final method called in the whole pipeline before we |
|
| 482 | - * return final JSON back to client. If you want to manipulate your response, this is the place to do that. |
|
| 483 | - * If you set APP_DEBUG to true, 'code_hex' field will be additionally added to reported JSON for easier |
|
| 484 | - * manual debugging. |
|
| 485 | - * |
|
| 486 | - * @param boolean $success @true if response reports successful operation, @false otherwise. |
|
| 487 | - * @param integer $api_code Your API code to be returned with the response object. |
|
| 488 | - * @param string|integer $msg_or_api_code Message string or valid API code to get message for. |
|
| 489 | - * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 490 | - * substitution or @null if none. |
|
| 491 | - * @param object|array|null $data API response data if any |
|
| 492 | - * @param array|null $debug_data optional debug data array to be added to returned JSON. |
|
| 493 | - * |
|
| 494 | - * @return array response ready to be encoded as json and sent back to client |
|
| 495 | - * |
|
| 496 | - * @throws \RuntimeException in case of missing or invalid "classes" mapping configuration |
|
| 497 | - */ |
|
| 498 | - protected static function buildResponse(bool $success, int $api_code, |
|
| 499 | - $msg_or_api_code, array $placeholders = null, |
|
| 500 | - $data = null, array $debug_data = null): array |
|
| 501 | - { |
|
| 502 | - // ensure $data is either @null, array or object of class with configured mapping. |
|
| 503 | - $converter = new Converter(); |
|
| 504 | - |
|
| 505 | - $data = $converter->convert($data); |
|
| 506 | - if ($data !== null && !is_object($data)) { |
|
| 507 | - // ensure we get object in final JSON structure in data node |
|
| 508 | - $data = (object)$data; |
|
| 509 | - } |
|
| 510 | - |
|
| 511 | - // get human readable message for API code or use message string (if given instead of API code) |
|
| 512 | - if (is_int($msg_or_api_code)) { |
|
| 513 | - $message = self::getMessageForApiCode($success, $msg_or_api_code, $placeholders); |
|
| 514 | - } else { |
|
| 515 | - Validator::assertString('message', $msg_or_api_code); |
|
| 516 | - $message = $msg_or_api_code; |
|
| 517 | - } |
|
| 518 | - |
|
| 519 | - /** @noinspection PhpUndefinedClassInspection */ |
|
| 520 | - $response = [ |
|
| 521 | - static::KEY_SUCCESS => $success, |
|
| 522 | - static::KEY_CODE => $api_code, |
|
| 523 | - static::KEY_LOCALE => \App::getLocale(), |
|
| 524 | - static::KEY_MESSAGE => $message, |
|
| 525 | - static::KEY_DATA => $data, |
|
| 526 | - ]; |
|
| 527 | - |
|
| 528 | - if ($debug_data !== null) { |
|
| 529 | - $debug_key = Config::get(static::CONF_KEY_DEBUG_DEBUG_KEY, self::KEY_DEBUG); |
|
| 530 | - $response[ $debug_key ] = $debug_data; |
|
| 531 | - } |
|
| 532 | - |
|
| 533 | - return $response; |
|
| 534 | - } |
|
| 27 | + /** |
|
| 28 | + * Default HTTP code to be used with success responses |
|
| 29 | + * |
|
| 30 | + * @var int |
|
| 31 | + */ |
|
| 32 | + public const DEFAULT_HTTP_CODE_OK = HttpResponse::HTTP_OK; |
|
| 33 | + |
|
| 34 | + /** |
|
| 35 | + * Default HTTP code to be used with error responses |
|
| 36 | + * |
|
| 37 | + * @var int |
|
| 38 | + */ |
|
| 39 | + public const DEFAULT_HTTP_CODE_ERROR = HttpResponse::HTTP_BAD_REQUEST; |
|
| 40 | + |
|
| 41 | + /** |
|
| 42 | + * Min allowed HTTP code for errorXXX() |
|
| 43 | + * |
|
| 44 | + * @var int |
|
| 45 | + */ |
|
| 46 | + public const ERROR_HTTP_CODE_MIN = 400; |
|
| 47 | + |
|
| 48 | + /** |
|
| 49 | + * Max allowed HTTP code for errorXXX() |
|
| 50 | + * |
|
| 51 | + * @var int |
|
| 52 | + */ |
|
| 53 | + public const ERROR_HTTP_CODE_MAX = 599; |
|
| 54 | + |
|
| 55 | + /** |
|
| 56 | + * Configuration keys |
|
| 57 | + */ |
|
| 58 | + public const CONF_KEY_DEBUG_DEBUG_KEY = 'response_builder.debug.debug_key'; |
|
| 59 | + public const CONF_KEY_DEBUG_EX_TRACE_ENABLED = 'response_builder.debug.exception_handler.trace_enabled'; |
|
| 60 | + public const CONF_KEY_DEBUG_EX_TRACE_KEY = 'response_builder.debug.exception_handler.trace_key'; |
|
| 61 | + public const CONF_KEY_MAP = 'response_builder.map'; |
|
| 62 | + public const CONF_KEY_ENCODING_OPTIONS = 'response_builder.encoding_options'; |
|
| 63 | + public const CONF_KEY_CLASSES = 'response_builder.classes'; |
|
| 64 | + public const CONF_KEY_MIN_CODE = 'response_builder.min_code'; |
|
| 65 | + public const CONF_KEY_MAX_CODE = 'response_builder.max_code'; |
|
| 66 | + public const CONF_KEY_RESPONSE_KEY_MAP = 'response_builder.map'; |
|
| 67 | + public const CONF_EXCEPTION_HANDLER_KEY = 'response_builder.exception_handler'; |
|
| 68 | + |
|
| 69 | + /** |
|
| 70 | + * Default keys to be used by exception handler while adding debug information |
|
| 71 | + */ |
|
| 72 | + public const KEY_DEBUG = 'debug'; |
|
| 73 | + public const KEY_TRACE = 'trace'; |
|
| 74 | + public const KEY_CLASS = 'class'; |
|
| 75 | + public const KEY_FILE = 'file'; |
|
| 76 | + public const KEY_LINE = 'line'; |
|
| 77 | + public const KEY_KEY = 'key'; |
|
| 78 | + public const KEY_METHOD = 'method'; |
|
| 79 | + public const KEY_SUCCESS = 'success'; |
|
| 80 | + public const KEY_CODE = 'code'; |
|
| 81 | + public const KEY_LOCALE = 'locale'; |
|
| 82 | + public const KEY_MESSAGE = 'message'; |
|
| 83 | + public const KEY_DATA = 'data'; |
|
| 84 | + |
|
| 85 | + /** |
|
| 86 | + * Default key to be used by exception handler while processing ValidationException |
|
| 87 | + * to return all the error messages |
|
| 88 | + * |
|
| 89 | + * @var string |
|
| 90 | + */ |
|
| 91 | + public const KEY_MESSAGES = 'messages'; |
|
| 92 | + |
|
| 93 | + /** |
|
| 94 | + * Default JSON encoding options. Must be specified as final value (i.e. 271) and NOT |
|
| 95 | + * PHP expression i.e. `JSON_HEX_TAG|JSON_HEX_APOS|...` as such syntax is not yet supported |
|
| 96 | + * by PHP. |
|
| 97 | + * |
|
| 98 | + * 271 = JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE |
|
| 99 | + * |
|
| 100 | + * @var int |
|
| 101 | + */ |
|
| 102 | + public const DEFAULT_ENCODING_OPTIONS = 271; |
|
| 103 | + |
|
| 104 | + /** |
|
| 105 | + * Reads and validates "classes" config mapping |
|
| 106 | + * |
|
| 107 | + * @return array Classes mapping as specified in configuration or empty array if configuration found |
|
| 108 | + * |
|
| 109 | + * @throws \RuntimeException if "classes" mapping is technically invalid (i.e. not array etc). |
|
| 110 | + */ |
|
| 111 | + protected static function getClassesMapping(): ?array |
|
| 112 | + { |
|
| 113 | + $classes = Config::get(self::CONF_KEY_CLASSES); |
|
| 114 | + |
|
| 115 | + if ($classes !== null) { |
|
| 116 | + if (!is_array($classes)) { |
|
| 117 | + throw new \RuntimeException( |
|
| 118 | + sprintf('CONFIG: "classes" mapping must be an array (%s given)', gettype($classes))); |
|
| 119 | + } |
|
| 120 | + |
|
| 121 | + $mandatory_keys = [ |
|
| 122 | + static::KEY_KEY, |
|
| 123 | + static::KEY_METHOD, |
|
| 124 | + ]; |
|
| 125 | + foreach ($classes as $class_name => $class_config) { |
|
| 126 | + foreach ($mandatory_keys as $key_name) { |
|
| 127 | + if (!array_key_exists($key_name, $class_config)) { |
|
| 128 | + throw new \RuntimeException("CONFIG: Missing '{$key_name}' for '{$class_name}' class mapping"); |
|
| 129 | + } |
|
| 130 | + } |
|
| 131 | + } |
|
| 132 | + } else { |
|
| 133 | + $classes = []; |
|
| 134 | + } |
|
| 135 | + |
|
| 136 | + return $classes; |
|
| 137 | + } |
|
| 138 | + |
|
| 139 | + /** |
|
| 140 | + * Returns success |
|
| 141 | + * |
|
| 142 | + * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node |
|
| 143 | + * of the JSON response, single supported object or @null if there's no |
|
| 144 | + * to be returned. |
|
| 145 | + * @param integer|null $api_code API code to be returned or @null to use value of BaseApiCodes::OK(). |
|
| 146 | + * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 147 | + * substitution or @null if none. |
|
| 148 | + * @param integer|null $http_code HTTP code to be used for HttpResponse sent or @null |
|
| 149 | + * for default DEFAULT_HTTP_CODE_OK. |
|
| 150 | + * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 151 | + * options or pass @null to use value from your config (or defaults). |
|
| 152 | + * |
|
| 153 | + * @return HttpResponse |
|
| 154 | + */ |
|
| 155 | + public static function success($data = null, $api_code = null, array $placeholders = null, |
|
| 156 | + int $http_code = null, int $json_opts = null): HttpResponse |
|
| 157 | + { |
|
| 158 | + return static::buildSuccessResponse($data, $api_code, $placeholders, $http_code, $json_opts); |
|
| 159 | + } |
|
| 160 | + |
|
| 161 | + /** |
|
| 162 | + * Returns success |
|
| 163 | + * |
|
| 164 | + * @param integer|null $api_code API code to be returned or @null to use value of BaseApiCodes::OK(). |
|
| 165 | + * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 166 | + * substitution or @null if none. |
|
| 167 | + * @param integer|null $http_code HTTP code to be used for HttpResponse sent or @null |
|
| 168 | + * for default DEFAULT_HTTP_CODE_OK. |
|
| 169 | + * |
|
| 170 | + * @return HttpResponse |
|
| 171 | + */ |
|
| 172 | + public static function successWithCode(int $api_code = null, array $placeholders = null, |
|
| 173 | + int $http_code = null): HttpResponse |
|
| 174 | + { |
|
| 175 | + return static::success(null, $api_code, $placeholders, $http_code); |
|
| 176 | + } |
|
| 177 | + |
|
| 178 | + /** |
|
| 179 | + * Returns success with custom HTTP code |
|
| 180 | + * |
|
| 181 | + * @param integer|null $http_code HTTP return code to be set for this response. If @null is passed, falls back |
|
| 182 | + * to DEFAULT_HTTP_CODE_OK. |
|
| 183 | + * |
|
| 184 | + * @return HttpResponse |
|
| 185 | + */ |
|
| 186 | + public static function successWithHttpCode(int $http_code = null): HttpResponse |
|
| 187 | + { |
|
| 188 | + return static::buildSuccessResponse(null, BaseApiCodes::OK(), [], $http_code); |
|
| 189 | + } |
|
| 190 | + |
|
| 191 | + /** |
|
| 192 | + * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node. |
|
| 193 | + * of the JSON response, single supported object or @null if there's no |
|
| 194 | + * to be returned. |
|
| 195 | + * @param integer|null $api_code API code to be returned or @null to use value of BaseApiCodes::OK(). |
|
| 196 | + * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 197 | + * substitution or @null if none. |
|
| 198 | + * @param integer|null $http_code HTTP code to be used for HttpResponse sent or @null |
|
| 199 | + * for default DEFAULT_HTTP_CODE_OK. |
|
| 200 | + * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 201 | + * options or pass @null to use value from your config (or defaults). |
|
| 202 | + * |
|
| 203 | + * @return HttpResponse |
|
| 204 | + * |
|
| 205 | + * @throws \InvalidArgumentException Thrown when provided arguments are invalid. |
|
| 206 | + */ |
|
| 207 | + protected static function buildSuccessResponse($data = null, int $api_code = null, array $placeholders = null, |
|
| 208 | + int $http_code = null, int $json_opts = null): HttpResponse |
|
| 209 | + { |
|
| 210 | + $http_code = $http_code ?? static::DEFAULT_HTTP_CODE_OK; |
|
| 211 | + $api_code = $api_code ?? BaseApiCodes::OK(); |
|
| 212 | + |
|
| 213 | + Validator::assertInt('api_code', $api_code); |
|
| 214 | + Validator::assertInt('http_code', $http_code); |
|
| 215 | + Validator::assertIntRange('http_code', $http_code, 200, 299); |
|
| 216 | + |
|
| 217 | + return static::make(true, $api_code, $api_code, $data, $http_code, $placeholders, null, $json_opts); |
|
| 218 | + } |
|
| 219 | + |
|
| 220 | + /** |
|
| 221 | + * Builds error Response object. Supports optional arguments passed to Lang::get() if associated error |
|
| 222 | + * message uses placeholders as well as return data payload |
|
| 223 | + * |
|
| 224 | + * @param integer $api_code Your API code to be returned with the response object. |
|
| 225 | + * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 226 | + * substitution or @null if none. |
|
| 227 | + * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node |
|
| 228 | + * of the JSON response, single supported object or @null if there's no |
|
| 229 | + * to be returned. |
|
| 230 | + * @param integer|null $http_code HTTP code to be used for HttpResponse sent or @null |
|
| 231 | + * for default DEFAULT_HTTP_CODE_ERROR. |
|
| 232 | + * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 233 | + * options or pass @null to use value from your config (or defaults). |
|
| 234 | + * |
|
| 235 | + * @return HttpResponse |
|
| 236 | + */ |
|
| 237 | + public static function error(int $api_code, array $placeholders = null, $data = null, int $http_code = null, |
|
| 238 | + int $encoding_options = null): HttpResponse |
|
| 239 | + { |
|
| 240 | + return static::buildErrorResponse($data, $api_code, $http_code, $placeholders, $encoding_options); |
|
| 241 | + } |
|
| 242 | + |
|
| 243 | + /** |
|
| 244 | + * @param integer $api_code Your API code to be returned with the response object. |
|
| 245 | + * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node |
|
| 246 | + * of the JSON response, single supported object or @null if there's no |
|
| 247 | + * to be returned. |
|
| 248 | + * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 249 | + * substitution or @null if none. |
|
| 250 | + * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 251 | + * options or pass @null to use value from your config (or defaults). |
|
| 252 | + * |
|
| 253 | + * @return HttpResponse |
|
| 254 | + */ |
|
| 255 | + public static function errorWithData(int $api_code, $data, array $placeholders = null, |
|
| 256 | + int $json_opts = null): HttpResponse |
|
| 257 | + { |
|
| 258 | + return static::buildErrorResponse($data, $api_code, null, $placeholders, $json_opts); |
|
| 259 | + } |
|
| 260 | + |
|
| 261 | + /** |
|
| 262 | + * @param integer $api_code Your API code to be returned with the response object. |
|
| 263 | + * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node |
|
| 264 | + * of the JSON response, single supported object or @null if there's no |
|
| 265 | + * to be returned. |
|
| 266 | + * @param integer $http_code HTTP code to be used for HttpResponse sent. |
|
| 267 | + * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 268 | + * substitution or @null if none. |
|
| 269 | + * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 270 | + * options or pass @null to use value from your config (or defaults). |
|
| 271 | + * |
|
| 272 | + * @return HttpResponse |
|
| 273 | + * |
|
| 274 | + * @throws \InvalidArgumentException if http_code is @null |
|
| 275 | + */ |
|
| 276 | + public static function errorWithDataAndHttpCode(int $api_code, $data, int $http_code, array $placeholders = null, |
|
| 277 | + int $json_opts = null): HttpResponse |
|
| 278 | + { |
|
| 279 | + return static::buildErrorResponse($data, $api_code, $http_code, $placeholders, $json_opts); |
|
| 280 | + } |
|
| 281 | + |
|
| 282 | + /** |
|
| 283 | + * @param integer $api_code Your API code to be returned with the response object. |
|
| 284 | + * @param integer $http_code HTTP code to be used for HttpResponse sent or @null |
|
| 285 | + * for default DEFAULT_HTTP_CODE_ERROR. |
|
| 286 | + * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 287 | + * substitution or @null if none. |
|
| 288 | + * |
|
| 289 | + * @return HttpResponse |
|
| 290 | + * |
|
| 291 | + * @throws \InvalidArgumentException if http_code is @null |
|
| 292 | + */ |
|
| 293 | + public static function errorWithHttpCode(int $api_code, int $http_code, array $placeholders = null): HttpResponse |
|
| 294 | + { |
|
| 295 | + return static::buildErrorResponse(null, $api_code, $http_code, $placeholders); |
|
| 296 | + } |
|
| 297 | + |
|
| 298 | + /** |
|
| 299 | + * @param integer $api_code Your API code to be returned with the response object. |
|
| 300 | + * @param string $message Custom message to be returned as part of error response |
|
| 301 | + * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node |
|
| 302 | + * of the JSON response, single supported object or @null if there's no |
|
| 303 | + * to be returned. |
|
| 304 | + * @param integer|null $http_code Optional HTTP status code to be used for HttpResponse sent |
|
| 305 | + * or @null for DEFAULT_HTTP_CODE_ERROR |
|
| 306 | + * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 307 | + * options or pass @null to use value from your config (or defaults). |
|
| 308 | + * |
|
| 309 | + * @return HttpResponse |
|
| 310 | + */ |
|
| 311 | + public static function errorWithMessageAndData(int $api_code, string $message, $data, |
|
| 312 | + int $http_code = null, int $json_opts = null): HttpResponse |
|
| 313 | + { |
|
| 314 | + return static::buildErrorResponse($data, $api_code, $http_code, null, |
|
| 315 | + $message, null, $json_opts); |
|
| 316 | + } |
|
| 317 | + |
|
| 318 | + /** |
|
| 319 | + * @param integer $api_code Your API code to be returned with the response object. |
|
| 320 | + * @param string $message custom message to be returned as part of error response |
|
| 321 | + * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node |
|
| 322 | + * of the JSON response, single supported object or @null if there's no |
|
| 323 | + * to be returned. |
|
| 324 | + * @param integer|null $http_code HTTP code to be used for HttpResponse sent or @null |
|
| 325 | + * for default DEFAULT_HTTP_CODE_ERROR. |
|
| 326 | + * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 327 | + * options or pass @null to use value from your config (or defaults). |
|
| 328 | + * @param array|null $debug_data optional debug data array to be added to returned JSON. |
|
| 329 | + * |
|
| 330 | + * @return HttpResponse |
|
| 331 | + */ |
|
| 332 | + public static function errorWithMessageAndDataAndDebug(int $api_code, string $message, $data, |
|
| 333 | + int $http_code = null, int $json_opts = null, |
|
| 334 | + array $debug_data = null): HttpResponse |
|
| 335 | + { |
|
| 336 | + return static::buildErrorResponse($data, $api_code, $http_code, null, |
|
| 337 | + $message, null, $json_opts, $debug_data); |
|
| 338 | + } |
|
| 339 | + |
|
| 340 | + /** |
|
| 341 | + * @param integer $api_code Your API code to be returned with the response object. |
|
| 342 | + * @param string $message Custom message to be returned as part of error response |
|
| 343 | + * @param integer|null $http_code HTTP code to be used with final response sent or @null |
|
| 344 | + * for default DEFAULT_HTTP_CODE_ERROR. |
|
| 345 | + * |
|
| 346 | + * @return HttpResponse |
|
| 347 | + */ |
|
| 348 | + public static function errorWithMessage(int $api_code, string $message, int $http_code = null): HttpResponse |
|
| 349 | + { |
|
| 350 | + return static::buildErrorResponse(null, $api_code, $http_code, null, $message); |
|
| 351 | + } |
|
| 352 | + |
|
| 353 | + /** |
|
| 354 | + * Builds error Response object. Supports optional arguments passed to Lang::get() if associated error message |
|
| 355 | + * uses placeholders as well as return data payload |
|
| 356 | + * |
|
| 357 | + * @param object|array|null $data Array of primitives and supported objects to be returned in 'data' node |
|
| 358 | + * of the JSON response, single supported object or @null if there's no |
|
| 359 | + * to be returned. |
|
| 360 | + * @param integer $api_code Your API code to be returned with the response object. |
|
| 361 | + * @param integer|null $http_code HTTP code to be used for HttpResponse sent or @null |
|
| 362 | + * for default DEFAULT_HTTP_CODE_ERROR. |
|
| 363 | + * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 364 | + * substitution or @null if none. |
|
| 365 | + * @param string|null $message custom message to be returned as part of error response |
|
| 366 | + * @param array|null $headers optional HTTP headers to be returned in error response |
|
| 367 | + * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 368 | + * options or pass @null to use value from your config (or defaults). |
|
| 369 | + * @param array|null $debug_data optional debug data array to be added to returned JSON. |
|
| 370 | + * |
|
| 371 | + * @return HttpResponse |
|
| 372 | + * |
|
| 373 | + * @throws \InvalidArgumentException Thrown if $code is not correct, outside the range, equals OK code etc. |
|
| 374 | + * |
|
| 375 | + * @noinspection MoreThanThreeArgumentsInspection |
|
| 376 | + */ |
|
| 377 | + protected static function buildErrorResponse($data, int $api_code, int $http_code = null, |
|
| 378 | + array $placeholders = null, |
|
| 379 | + string $message = null, array $headers = null, |
|
| 380 | + int $json_opts = null, |
|
| 381 | + array $debug_data = null): HttpResponse |
|
| 382 | + { |
|
| 383 | + $http_code = $http_code ?? static::DEFAULT_HTTP_CODE_ERROR; |
|
| 384 | + $headers = $headers ?? []; |
|
| 385 | + |
|
| 386 | + Validator::assertInt('api_code', $api_code); |
|
| 387 | + |
|
| 388 | + $code_ok = BaseApiCodes::OK(); |
|
| 389 | + if ($api_code !== $code_ok) { |
|
| 390 | + Validator::assertIntRange('api_code', $api_code, BaseApiCodes::getMinCode(), BaseApiCodes::getMaxCode()); |
|
| 391 | + } |
|
| 392 | + if ($api_code === $code_ok) { |
|
| 393 | + throw new \InvalidArgumentException( |
|
| 394 | + "Error response cannot use api_code of value {$code_ok} which is reserved for OK"); |
|
| 395 | + } |
|
| 396 | + |
|
| 397 | + Validator::assertInt('http_code', $http_code); |
|
| 398 | + Validator::assertIntRange('http_code', $http_code, static::ERROR_HTTP_CODE_MIN, static::ERROR_HTTP_CODE_MAX); |
|
| 399 | + |
|
| 400 | + $msg_or_api_code = $message ?? $api_code; |
|
| 401 | + |
|
| 402 | + return static::make(false, $api_code, $msg_or_api_code, $data, $http_code, |
|
| 403 | + $placeholders, $headers, $json_opts, $debug_data); |
|
| 404 | + } |
|
| 405 | + |
|
| 406 | + /** |
|
| 407 | + * @param boolean $success @true if response reports successful operation, @false otherwise. |
|
| 408 | + * @param integer $api_code Your API code to be returned with the response object. |
|
| 409 | + * @param string|integer $msg_or_api_code message string or valid API code to get message for |
|
| 410 | + * @param object|array|null $data optional additional data to be included in response object |
|
| 411 | + * @param integer|null $http_code HTTP code for the HttpResponse or @null for either DEFAULT_HTTP_CODE_OK |
|
| 412 | + * or DEFAULT_HTTP_CODE_ERROR depending on the $success. |
|
| 413 | + * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 414 | + * substitution or @null if none. |
|
| 415 | + * @param array|null $headers Optional HTTP headers to be returned in the response. |
|
| 416 | + * @param integer|null $json_opts See http://php.net/manual/en/function.json-encode.php for supported |
|
| 417 | + * options or pass @null to use value from your config (or defaults). |
|
| 418 | + * @param array|null $debug_data Optional debug data array to be added to returned JSON. |
|
| 419 | + * |
|
| 420 | + * @return HttpResponse |
|
| 421 | + * |
|
| 422 | + * @throws \InvalidArgumentException If $api_code is neither a string nor valid integer code. |
|
| 423 | + * @throws \InvalidArgumentException if $data is an object of class that is not configured in "classes" mapping. |
|
| 424 | + * |
|
| 425 | + * @noinspection MoreThanThreeArgumentsInspection |
|
| 426 | + */ |
|
| 427 | + protected static function make(bool $success, int $api_code, $msg_or_api_code, $data = null, |
|
| 428 | + int $http_code = null, array $placeholders = null, array $headers = null, |
|
| 429 | + int $json_opts = null, array $debug_data = null): HttpResponse |
|
| 430 | + { |
|
| 431 | + $headers = $headers ?? []; |
|
| 432 | + $http_code = $http_code ?? ($success ? static::DEFAULT_HTTP_CODE_OK : static::DEFAULT_HTTP_CODE_ERROR); |
|
| 433 | + $json_opts = $json_opts ?? Config::get(self::CONF_KEY_ENCODING_OPTIONS, static::DEFAULT_ENCODING_OPTIONS); |
|
| 434 | + |
|
| 435 | + Validator::assertInt('encoding_options', $json_opts); |
|
| 436 | + |
|
| 437 | + Validator::assertInt('api_code', $api_code); |
|
| 438 | + if (!BaseApiCodes::isCodeValid($api_code)) { |
|
| 439 | + $min = BaseApiCodes::getMinCode(); |
|
| 440 | + $max = BaseApiCodes::getMaxCode(); |
|
| 441 | + throw new \InvalidArgumentException("API code value ({$api_code}) is out of allowed range {$min}-{$max}"); |
|
| 442 | + } |
|
| 443 | + |
|
| 444 | + return Response::json( |
|
| 445 | + static::buildResponse($success, $api_code, $msg_or_api_code, $placeholders, $data, $debug_data), |
|
| 446 | + $http_code, $headers, $json_opts); |
|
| 447 | + } |
|
| 448 | + |
|
| 449 | + /** |
|
| 450 | + * If $msg_or_api_code is integer value, returns human readable message associated with that code (with |
|
| 451 | + * fallback to built-in default string if no api code mapping is set. If $msg_or_api_code is a string, |
|
| 452 | + * returns it unaltered. |
|
| 453 | + * |
|
| 454 | + * @param boolean $success @true if response reports successful operation, @false otherwise. |
|
| 455 | + * @param integer $api_code Your API code to be returned with the response object. |
|
| 456 | + * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 457 | + * substitution or @null if none. |
|
| 458 | + * |
|
| 459 | + * @return string |
|
| 460 | + */ |
|
| 461 | + protected static function getMessageForApiCode(bool $success, int $api_code, array $placeholders = null): string |
|
| 462 | + { |
|
| 463 | + // We got integer value here not a message string, so we need to check if we have the mapping for |
|
| 464 | + // this string already configured. |
|
| 465 | + $key = BaseApiCodes::getCodeMessageKey($api_code); |
|
| 466 | + if ($key === null) { |
|
| 467 | + // nope, let's get the default one instead, based of |
|
| 468 | + $fallback_code = $success ? BaseApiCodes::OK() : BaseApiCodes::NO_ERROR_MESSAGE(); |
|
| 469 | + $key = BaseApiCodes::getCodeMessageKey($fallback_code); |
|
| 470 | + } |
|
| 471 | + |
|
| 472 | + $placeholders = $placeholders ?? []; |
|
| 473 | + if (!array_key_exists('api_code', $placeholders)) { |
|
| 474 | + $placeholders['api_code'] = $api_code; |
|
| 475 | + } |
|
| 476 | + |
|
| 477 | + return \Lang::get($key, $placeholders); |
|
| 478 | + } |
|
| 479 | + |
|
| 480 | + /** |
|
| 481 | + * Creates standardised API response array. This is final method called in the whole pipeline before we |
|
| 482 | + * return final JSON back to client. If you want to manipulate your response, this is the place to do that. |
|
| 483 | + * If you set APP_DEBUG to true, 'code_hex' field will be additionally added to reported JSON for easier |
|
| 484 | + * manual debugging. |
|
| 485 | + * |
|
| 486 | + * @param boolean $success @true if response reports successful operation, @false otherwise. |
|
| 487 | + * @param integer $api_code Your API code to be returned with the response object. |
|
| 488 | + * @param string|integer $msg_or_api_code Message string or valid API code to get message for. |
|
| 489 | + * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders |
|
| 490 | + * substitution or @null if none. |
|
| 491 | + * @param object|array|null $data API response data if any |
|
| 492 | + * @param array|null $debug_data optional debug data array to be added to returned JSON. |
|
| 493 | + * |
|
| 494 | + * @return array response ready to be encoded as json and sent back to client |
|
| 495 | + * |
|
| 496 | + * @throws \RuntimeException in case of missing or invalid "classes" mapping configuration |
|
| 497 | + */ |
|
| 498 | + protected static function buildResponse(bool $success, int $api_code, |
|
| 499 | + $msg_or_api_code, array $placeholders = null, |
|
| 500 | + $data = null, array $debug_data = null): array |
|
| 501 | + { |
|
| 502 | + // ensure $data is either @null, array or object of class with configured mapping. |
|
| 503 | + $converter = new Converter(); |
|
| 504 | + |
|
| 505 | + $data = $converter->convert($data); |
|
| 506 | + if ($data !== null && !is_object($data)) { |
|
| 507 | + // ensure we get object in final JSON structure in data node |
|
| 508 | + $data = (object)$data; |
|
| 509 | + } |
|
| 510 | + |
|
| 511 | + // get human readable message for API code or use message string (if given instead of API code) |
|
| 512 | + if (is_int($msg_or_api_code)) { |
|
| 513 | + $message = self::getMessageForApiCode($success, $msg_or_api_code, $placeholders); |
|
| 514 | + } else { |
|
| 515 | + Validator::assertString('message', $msg_or_api_code); |
|
| 516 | + $message = $msg_or_api_code; |
|
| 517 | + } |
|
| 518 | + |
|
| 519 | + /** @noinspection PhpUndefinedClassInspection */ |
|
| 520 | + $response = [ |
|
| 521 | + static::KEY_SUCCESS => $success, |
|
| 522 | + static::KEY_CODE => $api_code, |
|
| 523 | + static::KEY_LOCALE => \App::getLocale(), |
|
| 524 | + static::KEY_MESSAGE => $message, |
|
| 525 | + static::KEY_DATA => $data, |
|
| 526 | + ]; |
|
| 527 | + |
|
| 528 | + if ($debug_data !== null) { |
|
| 529 | + $debug_key = Config::get(static::CONF_KEY_DEBUG_DEBUG_KEY, self::KEY_DEBUG); |
|
| 530 | + $response[ $debug_key ] = $debug_data; |
|
| 531 | + } |
|
| 532 | + |
|
| 533 | + return $response; |
|
| 534 | + } |
|
| 535 | 535 | |
| 536 | 536 | } |
@@ -22,144 +22,144 @@ |
||
| 22 | 22 | */ |
| 23 | 23 | class Converter |
| 24 | 24 | { |
| 25 | - /** |
|
| 26 | - * @var array |
|
| 27 | - */ |
|
| 28 | - protected $classes = []; |
|
| 29 | - |
|
| 30 | - /** |
|
| 31 | - * Converter constructor. |
|
| 32 | - * |
|
| 33 | - * @throws \RuntimeException |
|
| 34 | - */ |
|
| 35 | - public function __construct() |
|
| 36 | - { |
|
| 37 | - $classes = Config::get(ResponseBuilder::CONF_KEY_CLASSES) ?? []; |
|
| 38 | - if (!is_array($classes)) { |
|
| 39 | - throw new \RuntimeException( |
|
| 40 | - sprintf('CONFIG: "classes" mapping must be an array (%s given)', gettype($classes))); |
|
| 41 | - } |
|
| 42 | - |
|
| 43 | - $this->classes = $classes; |
|
| 44 | - } |
|
| 45 | - |
|
| 46 | - /** |
|
| 47 | - * Returns local copy of configuration mapping for the classes. |
|
| 48 | - * |
|
| 49 | - * @return array |
|
| 50 | - */ |
|
| 51 | - public function getClasses(): array |
|
| 52 | - { |
|
| 53 | - return $this->classes; |
|
| 54 | - } |
|
| 55 | - |
|
| 56 | - /** |
|
| 57 | - * Checks if we have "classes" mapping configured for $data object class. |
|
| 58 | - * Returns @true if there's valid config for this class. |
|
| 59 | - * Throws \RuntimeException if there's no config "classes" mapping entry for this object configured. |
|
| 60 | - * Throws \InvalidArgumentException if No data conversion mapping configured for given class. |
|
| 61 | - * |
|
| 62 | - * @param object $data Object to check mapping for. |
|
| 63 | - * |
|
| 64 | - * @return array |
|
| 65 | - * |
|
| 66 | - * @throws \InvalidArgumentException |
|
| 67 | - */ |
|
| 68 | - protected function getClassMappingConfigOrThrow(object $data): array |
|
| 69 | - { |
|
| 70 | - $result = null; |
|
| 71 | - |
|
| 72 | - // check for exact class name match... |
|
| 73 | - $cls = get_class($data); |
|
| 74 | - if (array_key_exists($cls, $this->classes)) { |
|
| 75 | - $result = $this->classes[ $cls ]; |
|
| 76 | - } else { |
|
| 77 | - // no exact match, then lets try with `instanceof` |
|
| 78 | - foreach (array_keys($this->classes) as $class_name) { |
|
| 79 | - if ($data instanceof $class_name) { |
|
| 80 | - $result = $this->classes[ $class_name ]; |
|
| 81 | - break; |
|
| 82 | - } |
|
| 83 | - } |
|
| 84 | - } |
|
| 85 | - |
|
| 86 | - if ($result === null) { |
|
| 87 | - throw new \InvalidArgumentException(sprintf('No data conversion mapping configured for "%s" class.', $cls)); |
|
| 88 | - } |
|
| 89 | - |
|
| 90 | - return $result; |
|
| 91 | - } |
|
| 92 | - |
|
| 93 | - /** |
|
| 94 | - * We need to prepare source data |
|
| 95 | - * |
|
| 96 | - * @param object|array|null $data |
|
| 97 | - * |
|
| 98 | - * @return array|null |
|
| 99 | - * |
|
| 100 | - * @throws \InvalidArgumentException |
|
| 101 | - */ |
|
| 102 | - public function convert($data = null): ?array |
|
| 103 | - { |
|
| 104 | - if ($data === null) { |
|
| 105 | - return null; |
|
| 106 | - } |
|
| 107 | - |
|
| 108 | - if (is_object($data)) { |
|
| 109 | - $cfg = $this->getClassMappingConfigOrThrow($data); |
|
| 110 | - $data = [$cfg[ ResponseBuilder::KEY_KEY ] => $data->{$cfg[ ResponseBuilder::KEY_METHOD ]}()]; |
|
| 111 | - } elseif (!is_array($data)) { |
|
| 112 | - throw new \InvalidArgumentException( |
|
| 113 | - sprintf('Payload must be null, array or object with mapping ("%s" given).', gettype($data))); |
|
| 114 | - } |
|
| 115 | - |
|
| 116 | - return $this->convertArray($data); |
|
| 117 | - } |
|
| 118 | - |
|
| 119 | - /** |
|
| 120 | - * Recursively walks $data array and converts all known objects if found. Note |
|
| 121 | - * $data array is passed by reference so source $data array may be modified. |
|
| 122 | - * |
|
| 123 | - * @param array $data array to recursively convert known elements of |
|
| 124 | - * |
|
| 125 | - * @return array |
|
| 126 | - * |
|
| 127 | - * @throws \RuntimeException |
|
| 128 | - */ |
|
| 129 | - protected function convertArray(array $data): array |
|
| 130 | - { |
|
| 131 | - // This is to ensure that we either have array with user provided keys i.e. ['foo'=>'bar'], which will then |
|
| 132 | - // be turned into JSON object or array without user specified keys (['bar']) which we would return as JSON |
|
| 133 | - // array. But you can't mix these two as the final JSON would not produce predictable results. |
|
| 134 | - $string_keys_cnt = 0; |
|
| 135 | - $int_keys_cnt = 0; |
|
| 136 | - foreach ($data as $key => $val) { |
|
| 137 | - if (is_int($key)) { |
|
| 138 | - $int_keys_cnt++; |
|
| 139 | - } else { |
|
| 140 | - $string_keys_cnt++; |
|
| 141 | - } |
|
| 142 | - |
|
| 143 | - if (($string_keys_cnt > 0) && ($int_keys_cnt > 0)) { |
|
| 144 | - throw new \RuntimeException( |
|
| 145 | - 'Invalid data array. Either set own keys for all the items or do not specify any keys at all. ' . |
|
| 146 | - 'Arrays with mixed keys are not supported by design.'); |
|
| 147 | - } |
|
| 148 | - } |
|
| 149 | - |
|
| 150 | - foreach ($data as $key => $val) { |
|
| 151 | - if (is_array($val)) { |
|
| 152 | - $data[ $key ] = $this->convertArray($val); |
|
| 153 | - } elseif (is_object($val)) { |
|
| 154 | - $cls = get_class($val); |
|
| 155 | - if (array_key_exists($cls, $this->classes)) { |
|
| 156 | - $conversion_method = $this->classes[ $cls ][ ResponseBuilder::KEY_METHOD ]; |
|
| 157 | - $converted_data = $val->$conversion_method(); |
|
| 158 | - $data[ $key ] = $converted_data; |
|
| 159 | - } |
|
| 160 | - } |
|
| 161 | - } |
|
| 162 | - |
|
| 163 | - return $data; |
|
| 164 | - } |
|
| 25 | + /** |
|
| 26 | + * @var array |
|
| 27 | + */ |
|
| 28 | + protected $classes = []; |
|
| 29 | + |
|
| 30 | + /** |
|
| 31 | + * Converter constructor. |
|
| 32 | + * |
|
| 33 | + * @throws \RuntimeException |
|
| 34 | + */ |
|
| 35 | + public function __construct() |
|
| 36 | + { |
|
| 37 | + $classes = Config::get(ResponseBuilder::CONF_KEY_CLASSES) ?? []; |
|
| 38 | + if (!is_array($classes)) { |
|
| 39 | + throw new \RuntimeException( |
|
| 40 | + sprintf('CONFIG: "classes" mapping must be an array (%s given)', gettype($classes))); |
|
| 41 | + } |
|
| 42 | + |
|
| 43 | + $this->classes = $classes; |
|
| 44 | + } |
|
| 45 | + |
|
| 46 | + /** |
|
| 47 | + * Returns local copy of configuration mapping for the classes. |
|
| 48 | + * |
|
| 49 | + * @return array |
|
| 50 | + */ |
|
| 51 | + public function getClasses(): array |
|
| 52 | + { |
|
| 53 | + return $this->classes; |
|
| 54 | + } |
|
| 55 | + |
|
| 56 | + /** |
|
| 57 | + * Checks if we have "classes" mapping configured for $data object class. |
|
| 58 | + * Returns @true if there's valid config for this class. |
|
| 59 | + * Throws \RuntimeException if there's no config "classes" mapping entry for this object configured. |
|
| 60 | + * Throws \InvalidArgumentException if No data conversion mapping configured for given class. |
|
| 61 | + * |
|
| 62 | + * @param object $data Object to check mapping for. |
|
| 63 | + * |
|
| 64 | + * @return array |
|
| 65 | + * |
|
| 66 | + * @throws \InvalidArgumentException |
|
| 67 | + */ |
|
| 68 | + protected function getClassMappingConfigOrThrow(object $data): array |
|
| 69 | + { |
|
| 70 | + $result = null; |
|
| 71 | + |
|
| 72 | + // check for exact class name match... |
|
| 73 | + $cls = get_class($data); |
|
| 74 | + if (array_key_exists($cls, $this->classes)) { |
|
| 75 | + $result = $this->classes[ $cls ]; |
|
| 76 | + } else { |
|
| 77 | + // no exact match, then lets try with `instanceof` |
|
| 78 | + foreach (array_keys($this->classes) as $class_name) { |
|
| 79 | + if ($data instanceof $class_name) { |
|
| 80 | + $result = $this->classes[ $class_name ]; |
|
| 81 | + break; |
|
| 82 | + } |
|
| 83 | + } |
|
| 84 | + } |
|
| 85 | + |
|
| 86 | + if ($result === null) { |
|
| 87 | + throw new \InvalidArgumentException(sprintf('No data conversion mapping configured for "%s" class.', $cls)); |
|
| 88 | + } |
|
| 89 | + |
|
| 90 | + return $result; |
|
| 91 | + } |
|
| 92 | + |
|
| 93 | + /** |
|
| 94 | + * We need to prepare source data |
|
| 95 | + * |
|
| 96 | + * @param object|array|null $data |
|
| 97 | + * |
|
| 98 | + * @return array|null |
|
| 99 | + * |
|
| 100 | + * @throws \InvalidArgumentException |
|
| 101 | + */ |
|
| 102 | + public function convert($data = null): ?array |
|
| 103 | + { |
|
| 104 | + if ($data === null) { |
|
| 105 | + return null; |
|
| 106 | + } |
|
| 107 | + |
|
| 108 | + if (is_object($data)) { |
|
| 109 | + $cfg = $this->getClassMappingConfigOrThrow($data); |
|
| 110 | + $data = [$cfg[ ResponseBuilder::KEY_KEY ] => $data->{$cfg[ ResponseBuilder::KEY_METHOD ]}()]; |
|
| 111 | + } elseif (!is_array($data)) { |
|
| 112 | + throw new \InvalidArgumentException( |
|
| 113 | + sprintf('Payload must be null, array or object with mapping ("%s" given).', gettype($data))); |
|
| 114 | + } |
|
| 115 | + |
|
| 116 | + return $this->convertArray($data); |
|
| 117 | + } |
|
| 118 | + |
|
| 119 | + /** |
|
| 120 | + * Recursively walks $data array and converts all known objects if found. Note |
|
| 121 | + * $data array is passed by reference so source $data array may be modified. |
|
| 122 | + * |
|
| 123 | + * @param array $data array to recursively convert known elements of |
|
| 124 | + * |
|
| 125 | + * @return array |
|
| 126 | + * |
|
| 127 | + * @throws \RuntimeException |
|
| 128 | + */ |
|
| 129 | + protected function convertArray(array $data): array |
|
| 130 | + { |
|
| 131 | + // This is to ensure that we either have array with user provided keys i.e. ['foo'=>'bar'], which will then |
|
| 132 | + // be turned into JSON object or array without user specified keys (['bar']) which we would return as JSON |
|
| 133 | + // array. But you can't mix these two as the final JSON would not produce predictable results. |
|
| 134 | + $string_keys_cnt = 0; |
|
| 135 | + $int_keys_cnt = 0; |
|
| 136 | + foreach ($data as $key => $val) { |
|
| 137 | + if (is_int($key)) { |
|
| 138 | + $int_keys_cnt++; |
|
| 139 | + } else { |
|
| 140 | + $string_keys_cnt++; |
|
| 141 | + } |
|
| 142 | + |
|
| 143 | + if (($string_keys_cnt > 0) && ($int_keys_cnt > 0)) { |
|
| 144 | + throw new \RuntimeException( |
|
| 145 | + 'Invalid data array. Either set own keys for all the items or do not specify any keys at all. ' . |
|
| 146 | + 'Arrays with mixed keys are not supported by design.'); |
|
| 147 | + } |
|
| 148 | + } |
|
| 149 | + |
|
| 150 | + foreach ($data as $key => $val) { |
|
| 151 | + if (is_array($val)) { |
|
| 152 | + $data[ $key ] = $this->convertArray($val); |
|
| 153 | + } elseif (is_object($val)) { |
|
| 154 | + $cls = get_class($val); |
|
| 155 | + if (array_key_exists($cls, $this->classes)) { |
|
| 156 | + $conversion_method = $this->classes[ $cls ][ ResponseBuilder::KEY_METHOD ]; |
|
| 157 | + $converted_data = $val->$conversion_method(); |
|
| 158 | + $data[ $key ] = $converted_data; |
|
| 159 | + } |
|
| 160 | + } |
|
| 161 | + } |
|
| 162 | + |
|
| 163 | + return $data; |
|
| 164 | + } |
|
| 165 | 165 | } |
@@ -15,88 +15,88 @@ |
||
| 15 | 15 | */ |
| 16 | 16 | class Validator |
| 17 | 17 | { |
| 18 | - /** @var string */ |
|
| 19 | - public const TYPE_STRING = 'string'; |
|
| 18 | + /** @var string */ |
|
| 19 | + public const TYPE_STRING = 'string'; |
|
| 20 | 20 | |
| 21 | - /** @var string */ |
|
| 22 | - public const TYPE_INTEGER = 'integer'; |
|
| 21 | + /** @var string */ |
|
| 22 | + public const TYPE_INTEGER = 'integer'; |
|
| 23 | 23 | |
| 24 | - /** @var string */ |
|
| 25 | - public const TYPE_BOOL = 'boolean'; |
|
| 24 | + /** @var string */ |
|
| 25 | + public const TYPE_BOOL = 'boolean'; |
|
| 26 | 26 | |
| 27 | - /** |
|
| 28 | - * Checks if given $val is of type integer |
|
| 29 | - * |
|
| 30 | - * @param string $key Name of the key to be used if exception is thrown. |
|
| 31 | - * @param mixed $var Variable to be asserted. |
|
| 32 | - * |
|
| 33 | - * @return void |
|
| 34 | - * |
|
| 35 | - * @throws \InvalidArgumentException |
|
| 36 | - */ |
|
| 37 | - public static function assertInt(string $key, $var): void |
|
| 38 | - { |
|
| 39 | - self::assertType($key, $var, [self::TYPE_INTEGER]); |
|
| 40 | - } |
|
| 27 | + /** |
|
| 28 | + * Checks if given $val is of type integer |
|
| 29 | + * |
|
| 30 | + * @param string $key Name of the key to be used if exception is thrown. |
|
| 31 | + * @param mixed $var Variable to be asserted. |
|
| 32 | + * |
|
| 33 | + * @return void |
|
| 34 | + * |
|
| 35 | + * @throws \InvalidArgumentException |
|
| 36 | + */ |
|
| 37 | + public static function assertInt(string $key, $var): void |
|
| 38 | + { |
|
| 39 | + self::assertType($key, $var, [self::TYPE_INTEGER]); |
|
| 40 | + } |
|
| 41 | 41 | |
| 42 | - /** |
|
| 43 | - * Checks if given $val is of type string |
|
| 44 | - * |
|
| 45 | - * @param string $name Label or name of the variable to be used in exception message (if thrown). |
|
| 46 | - * @param mixed $var Variable to be asserted. |
|
| 47 | - * |
|
| 48 | - * @return void |
|
| 49 | - * |
|
| 50 | - * @throws \InvalidArgumentException |
|
| 51 | - */ |
|
| 52 | - public static function assertString(string $name, $var): void |
|
| 53 | - { |
|
| 54 | - self::assertType($name, $var, [self::TYPE_STRING]); |
|
| 55 | - } |
|
| 42 | + /** |
|
| 43 | + * Checks if given $val is of type string |
|
| 44 | + * |
|
| 45 | + * @param string $name Label or name of the variable to be used in exception message (if thrown). |
|
| 46 | + * @param mixed $var Variable to be asserted. |
|
| 47 | + * |
|
| 48 | + * @return void |
|
| 49 | + * |
|
| 50 | + * @throws \InvalidArgumentException |
|
| 51 | + */ |
|
| 52 | + public static function assertString(string $name, $var): void |
|
| 53 | + { |
|
| 54 | + self::assertType($name, $var, [self::TYPE_STRING]); |
|
| 55 | + } |
|
| 56 | 56 | |
| 57 | - /** |
|
| 58 | - * @param string $name Label or name of the variable to be used in exception message (if thrown). |
|
| 59 | - * @param mixed $var Variable to be asserted. |
|
| 60 | - * @param int $min Min allowed value (inclusive) |
|
| 61 | - * @param int $max Max allowed value (inclusive) |
|
| 62 | - * |
|
| 63 | - * @return void |
|
| 64 | - * |
|
| 65 | - * @throws \InvalidArgumentException |
|
| 66 | - * @throws \RuntimeException |
|
| 67 | - */ |
|
| 68 | - public static function assertIntRange(string $name, $var, int $min, int $max): void |
|
| 69 | - { |
|
| 70 | - self::assertInt($name, $var); |
|
| 57 | + /** |
|
| 58 | + * @param string $name Label or name of the variable to be used in exception message (if thrown). |
|
| 59 | + * @param mixed $var Variable to be asserted. |
|
| 60 | + * @param int $min Min allowed value (inclusive) |
|
| 61 | + * @param int $max Max allowed value (inclusive) |
|
| 62 | + * |
|
| 63 | + * @return void |
|
| 64 | + * |
|
| 65 | + * @throws \InvalidArgumentException |
|
| 66 | + * @throws \RuntimeException |
|
| 67 | + */ |
|
| 68 | + public static function assertIntRange(string $name, $var, int $min, int $max): void |
|
| 69 | + { |
|
| 70 | + self::assertInt($name, $var); |
|
| 71 | 71 | |
| 72 | - if ($min > $max) { |
|
| 73 | - throw new \RuntimeException( |
|
| 74 | - sprintf('%s: Invalid range for "%s". Ensure bound values are not swapped.', __FUNCTION__, $name)); |
|
| 75 | - } |
|
| 72 | + if ($min > $max) { |
|
| 73 | + throw new \RuntimeException( |
|
| 74 | + sprintf('%s: Invalid range for "%s". Ensure bound values are not swapped.', __FUNCTION__, $name)); |
|
| 75 | + } |
|
| 76 | 76 | |
| 77 | - if (($min > $var) || ($var > $max)) { |
|
| 78 | - throw new \InvalidArgumentException( |
|
| 79 | - sprintf('Invalid value of "%s" (%d). Must be between %d-%d inclusive.', $name, $var, $min, $max)); |
|
| 80 | - } |
|
| 81 | - } |
|
| 77 | + if (($min > $var) || ($var > $max)) { |
|
| 78 | + throw new \InvalidArgumentException( |
|
| 79 | + sprintf('Invalid value of "%s" (%d). Must be between %d-%d inclusive.', $name, $var, $min, $max)); |
|
| 80 | + } |
|
| 81 | + } |
|
| 82 | 82 | |
| 83 | - /** |
|
| 84 | - * Checks if $item (of name $key) is of type that is include in $allowed_types. |
|
| 85 | - * |
|
| 86 | - * @param string $name Label or name of the variable to be used in exception message (if thrown). |
|
| 87 | - * @param mixed $var Variable to be asserted. |
|
| 88 | - * @param array $allowed_types Array of allowed types for $var, i.e. [Validator::TYPE_INTEGER] |
|
| 89 | - * |
|
| 90 | - * @return void |
|
| 91 | - * |
|
| 92 | - * @throws \InvalidArgumentException |
|
| 93 | - */ |
|
| 94 | - public static function assertType(string $name, $var, array $allowed_types): void |
|
| 95 | - { |
|
| 96 | - $type = gettype($var); |
|
| 97 | - if (!in_array($type, $allowed_types)) { |
|
| 98 | - $msg = sprintf('"%s" must be one of allowed types: %s (%s given)', $name, implode(', ', $allowed_types), gettype($var)); |
|
| 99 | - throw new \InvalidArgumentException($msg); |
|
| 100 | - } |
|
| 101 | - } |
|
| 83 | + /** |
|
| 84 | + * Checks if $item (of name $key) is of type that is include in $allowed_types. |
|
| 85 | + * |
|
| 86 | + * @param string $name Label or name of the variable to be used in exception message (if thrown). |
|
| 87 | + * @param mixed $var Variable to be asserted. |
|
| 88 | + * @param array $allowed_types Array of allowed types for $var, i.e. [Validator::TYPE_INTEGER] |
|
| 89 | + * |
|
| 90 | + * @return void |
|
| 91 | + * |
|
| 92 | + * @throws \InvalidArgumentException |
|
| 93 | + */ |
|
| 94 | + public static function assertType(string $name, $var, array $allowed_types): void |
|
| 95 | + { |
|
| 96 | + $type = gettype($var); |
|
| 97 | + if (!in_array($type, $allowed_types)) { |
|
| 98 | + $msg = sprintf('"%s" must be one of allowed types: %s (%s given)', $name, implode(', ', $allowed_types), gettype($var)); |
|
| 99 | + throw new \InvalidArgumentException($msg); |
|
| 100 | + } |
|
| 101 | + } |
|
| 102 | 102 | } |
@@ -27,180 +27,180 @@ |
||
| 27 | 27 | */ |
| 28 | 28 | class ExceptionHandlerHelper |
| 29 | 29 | { |
| 30 | - /** |
|
| 31 | - * Render an exception into valid API response. |
|
| 32 | - * |
|
| 33 | - * @param \Illuminate\Http\Request $request Request object |
|
| 34 | - * @param \Exception $ex Exception |
|
| 35 | - * |
|
| 36 | - * @return HttpResponse |
|
| 37 | - */ |
|
| 38 | - public static function render(/** @scrutinizer ignore-unused */ $request, Exception $ex): HttpResponse |
|
| 39 | - { |
|
| 40 | - $result = null; |
|
| 41 | - $cfg = self::getExceptionHandlerConfig(); |
|
| 42 | - |
|
| 43 | - if ($ex instanceof HttpException) { |
|
| 44 | - // Check if we have any exception configuration for this particular Http status code. |
|
| 45 | - $ex_cfg = $cfg[ HttpException::class ][ $ex->getStatusCode() ] ?? null; |
|
| 46 | - if ($ex_cfg === null) { |
|
| 47 | - $ex_cfg = $cfg[ HttpException::class ]['default']; |
|
| 48 | - } |
|
| 49 | - |
|
| 50 | - $api_code = $ex_cfg['api_code'] ?? BaseApiCodes::EX_UNCAUGHT_EXCEPTION(); |
|
| 51 | - $http_code = $ex_cfg['http_code'] ?? ResponseBuilder::DEFAULT_HTTP_CODE_ERROR; |
|
| 52 | - $msg_key = $ex_cfg['msg_key'] ?? null; |
|
| 53 | - $result = static::error($ex, $api_code, $http_code, $msg_key); |
|
| 54 | - } elseif ($ex instanceof ValidationException) { |
|
| 55 | - $http_code = HttpResponse::HTTP_UNPROCESSABLE_ENTITY; |
|
| 56 | - $ex_cfg = $cfg[ HttpException::class ][ $http_code ]; |
|
| 57 | - $api_code = $ex_cfg['api_code'] ?? BaseApiCodes::EX_UNCAUGHT_EXCEPTION(); |
|
| 58 | - $http_code = $ex_cfg['http_code'] ?? $http_code; |
|
| 59 | - $result = static::error($ex, $api_code, $http_code); |
|
| 60 | - } |
|
| 61 | - |
|
| 62 | - if ($result === null) { |
|
| 63 | - $ex_cfg = $cfg['default']; |
|
| 64 | - $result = static::error($ex, $ex_cfg['api_code'], $ex_cfg['http_code']); |
|
| 65 | - } |
|
| 66 | - |
|
| 67 | - return $result; |
|
| 68 | - } |
|
| 69 | - |
|
| 70 | - /** |
|
| 71 | - * Convert an authentication exception into an unauthenticated response. |
|
| 72 | - * |
|
| 73 | - * @param \Illuminate\Http\Request $request |
|
| 74 | - * @param \Illuminate\Auth\AuthenticationException $exception |
|
| 75 | - * |
|
| 76 | - * @return HttpResponse |
|
| 77 | - */ |
|
| 78 | - protected function unauthenticated(/** @scrutinizer ignore-unused */ $request, |
|
| 79 | - AuthException $exception): HttpResponse |
|
| 80 | - { |
|
| 81 | - $cfg = static::getExceptionHandlerConfig(HttpException::class); |
|
| 82 | - $api_code = $cfg[ HttpResponse::HTTP_UNAUTHORIZED ]['api_code']; |
|
| 83 | - $http_code = $cfg[ HttpResponse::HTTP_UNAUTHORIZED ]['http_code']; |
|
| 84 | - |
|
| 85 | - return static::error($exception, $api_code, $http_code); |
|
| 86 | - } |
|
| 87 | - |
|
| 88 | - /** |
|
| 89 | - * Process single error and produce valid API response. |
|
| 90 | - * |
|
| 91 | - * @param Exception $ex Exception to be handled. |
|
| 92 | - * @param integer $api_code |
|
| 93 | - * @param integer $http_code |
|
| 94 | - * |
|
| 95 | - * @return HttpResponse |
|
| 96 | - */ |
|
| 97 | - protected static function error(Exception $ex, |
|
| 98 | - int $api_code, int $http_code = null, string $msg_key = null): HttpResponse |
|
| 99 | - { |
|
| 100 | - $ex_http_code = ($ex instanceof HttpException) ? $ex->getStatusCode() : $ex->getCode(); |
|
| 101 | - $http_code = $http_code ?? $ex_http_code; |
|
| 102 | - |
|
| 103 | - // Check if we now have valid HTTP error code for this case or need to make one up. |
|
| 104 | - // We cannot throw any exception if codes are invalid because we are in Exception Handler already. |
|
| 105 | - if ($http_code < ResponseBuilder::ERROR_HTTP_CODE_MIN) { |
|
| 106 | - // Not a valid code, let's try to get the exception status. |
|
| 107 | - $http_code = $ex_http_code; |
|
| 108 | - } |
|
| 109 | - // Can it be considered a valid HTTP error code? |
|
| 110 | - if ($http_code < ResponseBuilder::ERROR_HTTP_CODE_MIN) { |
|
| 111 | - $http_code = ResponseBuilder::DEFAULT_HTTP_CODE_ERROR; |
|
| 112 | - } |
|
| 113 | - |
|
| 114 | - // Let's build the error message. |
|
| 115 | - $error_message = $ex->getMessage(); |
|
| 116 | - |
|
| 117 | - $placeholders = [ |
|
| 118 | - 'api_code' => $api_code, |
|
| 119 | - 'message' => ($error_message !== '') ? $error_message : '???', |
|
| 120 | - ]; |
|
| 121 | - |
|
| 122 | - // Check if we have dedicated HTTP Code message for this type of HttpException and its status code. |
|
| 123 | - if (($error_message === '') && ($ex instanceof HttpException)) { |
|
| 124 | - $error_message = Lang::get("response-builder::builder.http_{$ex_http_code}", $placeholders); |
|
| 125 | - } |
|
| 126 | - |
|
| 127 | - // Still got nothing? Fall back to built-in generic message for this type of exception. |
|
| 128 | - if ($error_message === '') { |
|
| 129 | - $key = BaseApiCodes::getCodeMessageKey(($ex instanceof HttpException) |
|
| 130 | - ? BaseApiCodes::EX_HTTP_EXCEPTION() : BaseApiCodes::NO_ERROR_MESSAGE()); |
|
| 131 | - $error_message = Lang::get($key, $placeholders); |
|
| 132 | - } |
|
| 133 | - |
|
| 134 | - // If we have trace data debugging enabled, let's gather some debug info and add to the response. |
|
| 135 | - $trace_data = null; |
|
| 136 | - if (Config::get(ResponseBuilder::CONF_KEY_DEBUG_EX_TRACE_ENABLED, false)) { |
|
| 137 | - $trace_data = [ |
|
| 138 | - Config::get(ResponseBuilder::CONF_KEY_DEBUG_EX_TRACE_KEY, ResponseBuilder::KEY_TRACE) => [ |
|
| 139 | - ResponseBuilder::KEY_CLASS => get_class($ex), |
|
| 140 | - ResponseBuilder::KEY_FILE => $ex->getFile(), |
|
| 141 | - ResponseBuilder::KEY_LINE => $ex->getLine(), |
|
| 142 | - ], |
|
| 143 | - ]; |
|
| 144 | - } |
|
| 145 | - |
|
| 146 | - // If this is ValidationException, add all the messages from MessageBag to the data node. |
|
| 147 | - $data = null; |
|
| 148 | - if ($ex instanceof ValidationException) { |
|
| 149 | - /** @var ValidationException $ex */ |
|
| 150 | - $data = [ResponseBuilder::KEY_MESSAGES => $ex->validator->errors()->messages()]; |
|
| 151 | - } |
|
| 152 | - |
|
| 153 | - return ResponseBuilder::errorWithMessageAndDataAndDebug($api_code, $error_message, $data, |
|
| 154 | - $http_code, null, $trace_data); |
|
| 155 | - } |
|
| 156 | - |
|
| 157 | - /** |
|
| 158 | - * Returns built-in configration array for ExceptionHandlerHelper |
|
| 159 | - * |
|
| 160 | - * @return array |
|
| 161 | - */ |
|
| 162 | - protected static function getExceptionHandlerBaseConfig(): array |
|
| 163 | - { |
|
| 164 | - return [ |
|
| 165 | - HttpException::class => [ |
|
| 166 | - // used by unauthenticated() to obtain api and http code for the exception |
|
| 167 | - HttpResponse::HTTP_UNAUTHORIZED => [ |
|
| 168 | - 'api_code' => BaseApiCodes::EX_AUTHENTICATION_EXCEPTION(), |
|
| 169 | - 'http_code' => HttpResponse::HTTP_UNAUTHORIZED, |
|
| 170 | - ], |
|
| 171 | - |
|
| 172 | - // Required by ValidationException handler |
|
| 173 | - HttpResponse::HTTP_UNPROCESSABLE_ENTITY => [ |
|
| 174 | - 'api_code' => BaseApiCodes::EX_VALIDATION_EXCEPTION(), |
|
| 175 | - 'http_code' => HttpResponse::HTTP_UNPROCESSABLE_ENTITY, |
|
| 176 | - ], |
|
| 177 | - // default handler is mandatory |
|
| 178 | - 'default' => [ |
|
| 179 | - 'api_code' => BaseApiCodes::EX_HTTP_EXCEPTION(), |
|
| 180 | - 'http_code' => HttpResponse::HTTP_BAD_REQUEST, |
|
| 181 | - ], |
|
| 182 | - ], |
|
| 183 | - // default handler is mandatory |
|
| 184 | - 'default' => [ |
|
| 185 | - 'api_code' => BaseApiCodes::EX_UNCAUGHT_EXCEPTION(), |
|
| 186 | - 'http_code' => HttpResponse::HTTP_INTERNAL_SERVER_ERROR, |
|
| 187 | - ], |
|
| 188 | - ]; |
|
| 189 | - } |
|
| 190 | - |
|
| 191 | - /** |
|
| 192 | - * Returns configration array for ExceptionHandlerHelper with user config merged with built-in config. |
|
| 193 | - * |
|
| 194 | - * @param string|null $key optional configuration node key to have only this portion of the |
|
| 195 | - * config returned (i.e. `http_exception`). |
|
| 196 | - * |
|
| 197 | - * @return array |
|
| 198 | - */ |
|
| 199 | - protected static function getExceptionHandlerConfig(string $key = null): array |
|
| 200 | - { |
|
| 201 | - $result = array_merge(Config::get(ResponseBuilder::CONF_EXCEPTION_HANDLER_KEY, []), |
|
| 202 | - self::getExceptionHandlerBaseConfig()); |
|
| 203 | - |
|
| 204 | - return ($key === null) ? $result : $result[ $key ]; |
|
| 205 | - } |
|
| 30 | + /** |
|
| 31 | + * Render an exception into valid API response. |
|
| 32 | + * |
|
| 33 | + * @param \Illuminate\Http\Request $request Request object |
|
| 34 | + * @param \Exception $ex Exception |
|
| 35 | + * |
|
| 36 | + * @return HttpResponse |
|
| 37 | + */ |
|
| 38 | + public static function render(/** @scrutinizer ignore-unused */ $request, Exception $ex): HttpResponse |
|
| 39 | + { |
|
| 40 | + $result = null; |
|
| 41 | + $cfg = self::getExceptionHandlerConfig(); |
|
| 42 | + |
|
| 43 | + if ($ex instanceof HttpException) { |
|
| 44 | + // Check if we have any exception configuration for this particular Http status code. |
|
| 45 | + $ex_cfg = $cfg[ HttpException::class ][ $ex->getStatusCode() ] ?? null; |
|
| 46 | + if ($ex_cfg === null) { |
|
| 47 | + $ex_cfg = $cfg[ HttpException::class ]['default']; |
|
| 48 | + } |
|
| 49 | + |
|
| 50 | + $api_code = $ex_cfg['api_code'] ?? BaseApiCodes::EX_UNCAUGHT_EXCEPTION(); |
|
| 51 | + $http_code = $ex_cfg['http_code'] ?? ResponseBuilder::DEFAULT_HTTP_CODE_ERROR; |
|
| 52 | + $msg_key = $ex_cfg['msg_key'] ?? null; |
|
| 53 | + $result = static::error($ex, $api_code, $http_code, $msg_key); |
|
| 54 | + } elseif ($ex instanceof ValidationException) { |
|
| 55 | + $http_code = HttpResponse::HTTP_UNPROCESSABLE_ENTITY; |
|
| 56 | + $ex_cfg = $cfg[ HttpException::class ][ $http_code ]; |
|
| 57 | + $api_code = $ex_cfg['api_code'] ?? BaseApiCodes::EX_UNCAUGHT_EXCEPTION(); |
|
| 58 | + $http_code = $ex_cfg['http_code'] ?? $http_code; |
|
| 59 | + $result = static::error($ex, $api_code, $http_code); |
|
| 60 | + } |
|
| 61 | + |
|
| 62 | + if ($result === null) { |
|
| 63 | + $ex_cfg = $cfg['default']; |
|
| 64 | + $result = static::error($ex, $ex_cfg['api_code'], $ex_cfg['http_code']); |
|
| 65 | + } |
|
| 66 | + |
|
| 67 | + return $result; |
|
| 68 | + } |
|
| 69 | + |
|
| 70 | + /** |
|
| 71 | + * Convert an authentication exception into an unauthenticated response. |
|
| 72 | + * |
|
| 73 | + * @param \Illuminate\Http\Request $request |
|
| 74 | + * @param \Illuminate\Auth\AuthenticationException $exception |
|
| 75 | + * |
|
| 76 | + * @return HttpResponse |
|
| 77 | + */ |
|
| 78 | + protected function unauthenticated(/** @scrutinizer ignore-unused */ $request, |
|
| 79 | + AuthException $exception): HttpResponse |
|
| 80 | + { |
|
| 81 | + $cfg = static::getExceptionHandlerConfig(HttpException::class); |
|
| 82 | + $api_code = $cfg[ HttpResponse::HTTP_UNAUTHORIZED ]['api_code']; |
|
| 83 | + $http_code = $cfg[ HttpResponse::HTTP_UNAUTHORIZED ]['http_code']; |
|
| 84 | + |
|
| 85 | + return static::error($exception, $api_code, $http_code); |
|
| 86 | + } |
|
| 87 | + |
|
| 88 | + /** |
|
| 89 | + * Process single error and produce valid API response. |
|
| 90 | + * |
|
| 91 | + * @param Exception $ex Exception to be handled. |
|
| 92 | + * @param integer $api_code |
|
| 93 | + * @param integer $http_code |
|
| 94 | + * |
|
| 95 | + * @return HttpResponse |
|
| 96 | + */ |
|
| 97 | + protected static function error(Exception $ex, |
|
| 98 | + int $api_code, int $http_code = null, string $msg_key = null): HttpResponse |
|
| 99 | + { |
|
| 100 | + $ex_http_code = ($ex instanceof HttpException) ? $ex->getStatusCode() : $ex->getCode(); |
|
| 101 | + $http_code = $http_code ?? $ex_http_code; |
|
| 102 | + |
|
| 103 | + // Check if we now have valid HTTP error code for this case or need to make one up. |
|
| 104 | + // We cannot throw any exception if codes are invalid because we are in Exception Handler already. |
|
| 105 | + if ($http_code < ResponseBuilder::ERROR_HTTP_CODE_MIN) { |
|
| 106 | + // Not a valid code, let's try to get the exception status. |
|
| 107 | + $http_code = $ex_http_code; |
|
| 108 | + } |
|
| 109 | + // Can it be considered a valid HTTP error code? |
|
| 110 | + if ($http_code < ResponseBuilder::ERROR_HTTP_CODE_MIN) { |
|
| 111 | + $http_code = ResponseBuilder::DEFAULT_HTTP_CODE_ERROR; |
|
| 112 | + } |
|
| 113 | + |
|
| 114 | + // Let's build the error message. |
|
| 115 | + $error_message = $ex->getMessage(); |
|
| 116 | + |
|
| 117 | + $placeholders = [ |
|
| 118 | + 'api_code' => $api_code, |
|
| 119 | + 'message' => ($error_message !== '') ? $error_message : '???', |
|
| 120 | + ]; |
|
| 121 | + |
|
| 122 | + // Check if we have dedicated HTTP Code message for this type of HttpException and its status code. |
|
| 123 | + if (($error_message === '') && ($ex instanceof HttpException)) { |
|
| 124 | + $error_message = Lang::get("response-builder::builder.http_{$ex_http_code}", $placeholders); |
|
| 125 | + } |
|
| 126 | + |
|
| 127 | + // Still got nothing? Fall back to built-in generic message for this type of exception. |
|
| 128 | + if ($error_message === '') { |
|
| 129 | + $key = BaseApiCodes::getCodeMessageKey(($ex instanceof HttpException) |
|
| 130 | + ? BaseApiCodes::EX_HTTP_EXCEPTION() : BaseApiCodes::NO_ERROR_MESSAGE()); |
|
| 131 | + $error_message = Lang::get($key, $placeholders); |
|
| 132 | + } |
|
| 133 | + |
|
| 134 | + // If we have trace data debugging enabled, let's gather some debug info and add to the response. |
|
| 135 | + $trace_data = null; |
|
| 136 | + if (Config::get(ResponseBuilder::CONF_KEY_DEBUG_EX_TRACE_ENABLED, false)) { |
|
| 137 | + $trace_data = [ |
|
| 138 | + Config::get(ResponseBuilder::CONF_KEY_DEBUG_EX_TRACE_KEY, ResponseBuilder::KEY_TRACE) => [ |
|
| 139 | + ResponseBuilder::KEY_CLASS => get_class($ex), |
|
| 140 | + ResponseBuilder::KEY_FILE => $ex->getFile(), |
|
| 141 | + ResponseBuilder::KEY_LINE => $ex->getLine(), |
|
| 142 | + ], |
|
| 143 | + ]; |
|
| 144 | + } |
|
| 145 | + |
|
| 146 | + // If this is ValidationException, add all the messages from MessageBag to the data node. |
|
| 147 | + $data = null; |
|
| 148 | + if ($ex instanceof ValidationException) { |
|
| 149 | + /** @var ValidationException $ex */ |
|
| 150 | + $data = [ResponseBuilder::KEY_MESSAGES => $ex->validator->errors()->messages()]; |
|
| 151 | + } |
|
| 152 | + |
|
| 153 | + return ResponseBuilder::errorWithMessageAndDataAndDebug($api_code, $error_message, $data, |
|
| 154 | + $http_code, null, $trace_data); |
|
| 155 | + } |
|
| 156 | + |
|
| 157 | + /** |
|
| 158 | + * Returns built-in configration array for ExceptionHandlerHelper |
|
| 159 | + * |
|
| 160 | + * @return array |
|
| 161 | + */ |
|
| 162 | + protected static function getExceptionHandlerBaseConfig(): array |
|
| 163 | + { |
|
| 164 | + return [ |
|
| 165 | + HttpException::class => [ |
|
| 166 | + // used by unauthenticated() to obtain api and http code for the exception |
|
| 167 | + HttpResponse::HTTP_UNAUTHORIZED => [ |
|
| 168 | + 'api_code' => BaseApiCodes::EX_AUTHENTICATION_EXCEPTION(), |
|
| 169 | + 'http_code' => HttpResponse::HTTP_UNAUTHORIZED, |
|
| 170 | + ], |
|
| 171 | + |
|
| 172 | + // Required by ValidationException handler |
|
| 173 | + HttpResponse::HTTP_UNPROCESSABLE_ENTITY => [ |
|
| 174 | + 'api_code' => BaseApiCodes::EX_VALIDATION_EXCEPTION(), |
|
| 175 | + 'http_code' => HttpResponse::HTTP_UNPROCESSABLE_ENTITY, |
|
| 176 | + ], |
|
| 177 | + // default handler is mandatory |
|
| 178 | + 'default' => [ |
|
| 179 | + 'api_code' => BaseApiCodes::EX_HTTP_EXCEPTION(), |
|
| 180 | + 'http_code' => HttpResponse::HTTP_BAD_REQUEST, |
|
| 181 | + ], |
|
| 182 | + ], |
|
| 183 | + // default handler is mandatory |
|
| 184 | + 'default' => [ |
|
| 185 | + 'api_code' => BaseApiCodes::EX_UNCAUGHT_EXCEPTION(), |
|
| 186 | + 'http_code' => HttpResponse::HTTP_INTERNAL_SERVER_ERROR, |
|
| 187 | + ], |
|
| 188 | + ]; |
|
| 189 | + } |
|
| 190 | + |
|
| 191 | + /** |
|
| 192 | + * Returns configration array for ExceptionHandlerHelper with user config merged with built-in config. |
|
| 193 | + * |
|
| 194 | + * @param string|null $key optional configuration node key to have only this portion of the |
|
| 195 | + * config returned (i.e. `http_exception`). |
|
| 196 | + * |
|
| 197 | + * @return array |
|
| 198 | + */ |
|
| 199 | + protected static function getExceptionHandlerConfig(string $key = null): array |
|
| 200 | + { |
|
| 201 | + $result = array_merge(Config::get(ResponseBuilder::CONF_EXCEPTION_HANDLER_KEY, []), |
|
| 202 | + self::getExceptionHandlerBaseConfig()); |
|
| 203 | + |
|
| 204 | + return ($key === null) ? $result : $result[ $key ]; |
|
| 205 | + } |
|
| 206 | 206 | } |
@@ -10,54 +10,54 @@ |
||
| 10 | 10 | */ |
| 11 | 11 | return [ |
| 12 | 12 | |
| 13 | - 'ok' => 'OK', |
|
| 14 | - 'no_error_message' => 'Błąd #:api_code', |
|
| 13 | + 'ok' => 'OK', |
|
| 14 | + 'no_error_message' => 'Błąd #:api_code', |
|
| 15 | 15 | |
| 16 | - // Used by Exception Handler Helper (when used) |
|
| 17 | - 'uncaught_exception' => 'Nieprzechwycony wyjątek: :message', |
|
| 18 | - 'http_exception' => 'Wyjątek HTTP: :message', |
|
| 16 | + // Used by Exception Handler Helper (when used) |
|
| 17 | + 'uncaught_exception' => 'Nieprzechwycony wyjątek: :message', |
|
| 18 | + 'http_exception' => 'Wyjątek HTTP: :message', |
|
| 19 | 19 | |
| 20 | - // HttpException handler (added in 6.4.0) |
|
| 21 | - // Error messages for HttpException caught w/o custom messages |
|
| 22 | - // https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml |
|
| 23 | - 'http_400' => 'Bad Request', |
|
| 24 | - 'http_401' => 'Unauthorized', |
|
| 25 | - 'http_402' => 'Payment Required', |
|
| 26 | - 'http_403' => 'Forbidden', |
|
| 27 | - 'http_404' => 'Not Found', |
|
| 28 | - 'http_405' => 'Method Not Allowed', |
|
| 29 | - 'http_406' => 'Not Acceptable', |
|
| 30 | - 'http_407' => 'Proxy Authentication Required', |
|
| 31 | - 'http_408' => 'Request Timeout', |
|
| 32 | - 'http_409' => 'Conflict', |
|
| 33 | - 'http_410' => 'Gone', |
|
| 34 | - 'http_411' => 'Length Required', |
|
| 35 | - 'http_412' => 'Precondition Failed', |
|
| 36 | - 'http_413' => 'Payload Too Large', |
|
| 37 | - 'http_414' => 'URI Too Long', |
|
| 38 | - 'http_415' => 'Unsupported Media Type', |
|
| 39 | - 'http_416' => 'Range Not Satisfiable', |
|
| 40 | - 'http_417' => 'Expectation Failed', |
|
| 41 | - 'http_421' => 'Misdirected Request', |
|
| 42 | - 'http_422' => 'Unprocessable Entity', |
|
| 43 | - 'http_423' => 'Locked', |
|
| 44 | - 'http_424' => 'Failed Dependency', |
|
| 45 | - 'http_425' => 'Too Early', |
|
| 46 | - 'http_426' => 'Upgrade Required', |
|
| 47 | - 'http_428' => 'Precondition Required', |
|
| 48 | - 'http_429' => 'Too Many Requests', |
|
| 49 | - 'http_431' => 'Request Header Fields Too Large', |
|
| 50 | - 'http_451' => 'Unavailable For Legal Reasons', |
|
| 51 | - 'http_500' => 'Internal Server Error', |
|
| 52 | - 'http_501' => 'Not Implemented', |
|
| 53 | - 'http_502' => 'Bad Gateway', |
|
| 54 | - 'http_503' => 'Service Unavailable', |
|
| 55 | - 'http_504' => 'Gateway Timeout', |
|
| 56 | - 'http_505' => 'HTTP Version Not Supported', |
|
| 57 | - 'http_506' => 'Variant Also Negotiates', |
|
| 58 | - 'http_507' => 'Insufficient Storage', |
|
| 59 | - 'http_508' => 'Loop Detected', |
|
| 60 | - 'http_509' => 'Unassigned', |
|
| 61 | - 'http_510' => 'Not Extended', |
|
| 62 | - 'http_511' => 'Network Authentication Required', |
|
| 20 | + // HttpException handler (added in 6.4.0) |
|
| 21 | + // Error messages for HttpException caught w/o custom messages |
|
| 22 | + // https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml |
|
| 23 | + 'http_400' => 'Bad Request', |
|
| 24 | + 'http_401' => 'Unauthorized', |
|
| 25 | + 'http_402' => 'Payment Required', |
|
| 26 | + 'http_403' => 'Forbidden', |
|
| 27 | + 'http_404' => 'Not Found', |
|
| 28 | + 'http_405' => 'Method Not Allowed', |
|
| 29 | + 'http_406' => 'Not Acceptable', |
|
| 30 | + 'http_407' => 'Proxy Authentication Required', |
|
| 31 | + 'http_408' => 'Request Timeout', |
|
| 32 | + 'http_409' => 'Conflict', |
|
| 33 | + 'http_410' => 'Gone', |
|
| 34 | + 'http_411' => 'Length Required', |
|
| 35 | + 'http_412' => 'Precondition Failed', |
|
| 36 | + 'http_413' => 'Payload Too Large', |
|
| 37 | + 'http_414' => 'URI Too Long', |
|
| 38 | + 'http_415' => 'Unsupported Media Type', |
|
| 39 | + 'http_416' => 'Range Not Satisfiable', |
|
| 40 | + 'http_417' => 'Expectation Failed', |
|
| 41 | + 'http_421' => 'Misdirected Request', |
|
| 42 | + 'http_422' => 'Unprocessable Entity', |
|
| 43 | + 'http_423' => 'Locked', |
|
| 44 | + 'http_424' => 'Failed Dependency', |
|
| 45 | + 'http_425' => 'Too Early', |
|
| 46 | + 'http_426' => 'Upgrade Required', |
|
| 47 | + 'http_428' => 'Precondition Required', |
|
| 48 | + 'http_429' => 'Too Many Requests', |
|
| 49 | + 'http_431' => 'Request Header Fields Too Large', |
|
| 50 | + 'http_451' => 'Unavailable For Legal Reasons', |
|
| 51 | + 'http_500' => 'Internal Server Error', |
|
| 52 | + 'http_501' => 'Not Implemented', |
|
| 53 | + 'http_502' => 'Bad Gateway', |
|
| 54 | + 'http_503' => 'Service Unavailable', |
|
| 55 | + 'http_504' => 'Gateway Timeout', |
|
| 56 | + 'http_505' => 'HTTP Version Not Supported', |
|
| 57 | + 'http_506' => 'Variant Also Negotiates', |
|
| 58 | + 'http_507' => 'Insufficient Storage', |
|
| 59 | + 'http_508' => 'Loop Detected', |
|
| 60 | + 'http_509' => 'Unassigned', |
|
| 61 | + 'http_510' => 'Not Extended', |
|
| 62 | + 'http_511' => 'Network Authentication Required', |
|
| 63 | 63 | ]; |
@@ -10,55 +10,55 @@ |
||
| 10 | 10 | */ |
| 11 | 11 | return [ |
| 12 | 12 | |
| 13 | - 'ok' => 'OK', |
|
| 14 | - 'no_error_message' => 'Error #:api_code', |
|
| 13 | + 'ok' => 'OK', |
|
| 14 | + 'no_error_message' => 'Error #:api_code', |
|
| 15 | 15 | |
| 16 | - // Used by Exception Handler Helper (when used) |
|
| 17 | - 'uncaught_exception' => 'Uncaught exception: :message', |
|
| 18 | - 'http_exception' => 'HTTP exception: :message', |
|
| 16 | + // Used by Exception Handler Helper (when used) |
|
| 17 | + 'uncaught_exception' => 'Uncaught exception: :message', |
|
| 18 | + 'http_exception' => 'HTTP exception: :message', |
|
| 19 | 19 | |
| 20 | - // HttpException handler (added in 6.4.0) |
|
| 21 | - // Error messages for HttpException caught w/o custom messages |
|
| 22 | - // https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml |
|
| 23 | - 'http_400' => 'Bad Request', |
|
| 24 | - 'http_401' => 'Unauthorized', |
|
| 25 | - 'http_402' => 'Payment Required', |
|
| 26 | - 'http_403' => 'Forbidden', |
|
| 27 | - 'http_404' => 'Not Found', |
|
| 28 | - 'http_405' => 'Method Not Allowed', |
|
| 29 | - 'http_406' => 'Not Acceptable', |
|
| 30 | - 'http_407' => 'Proxy Authentication Required', |
|
| 31 | - 'http_408' => 'Request Timeout', |
|
| 32 | - 'http_409' => 'Conflict', |
|
| 33 | - 'http_410' => 'Gone', |
|
| 34 | - 'http_411' => 'Length Required', |
|
| 35 | - 'http_412' => 'Precondition Failed', |
|
| 36 | - 'http_413' => 'Payload Too Large', |
|
| 37 | - 'http_414' => 'URI Too Long', |
|
| 38 | - 'http_415' => 'Unsupported Media Type', |
|
| 39 | - 'http_416' => 'Range Not Satisfiable', |
|
| 40 | - 'http_417' => 'Expectation Failed', |
|
| 41 | - 'http_421' => 'Misdirected Request', |
|
| 42 | - 'http_422' => 'Unprocessable Entity', |
|
| 43 | - 'http_423' => 'Locked', |
|
| 44 | - 'http_424' => 'Failed Dependency', |
|
| 45 | - 'http_425' => 'Too Early', |
|
| 46 | - 'http_426' => 'Upgrade Required', |
|
| 47 | - 'http_428' => 'Precondition Required', |
|
| 48 | - 'http_429' => 'Too Many Requests', |
|
| 49 | - 'http_431' => 'Request Header Fields Too Large', |
|
| 50 | - 'http_451' => 'Unavailable For Legal Reasons', |
|
| 51 | - 'http_500' => 'Internal Server Error', |
|
| 52 | - 'http_501' => 'Not Implemented', |
|
| 53 | - 'http_502' => 'Bad Gateway', |
|
| 54 | - 'http_503' => 'Service Unavailable', |
|
| 55 | - 'http_504' => 'Gateway Timeout', |
|
| 56 | - 'http_505' => 'HTTP Version Not Supported', |
|
| 57 | - 'http_506' => 'Variant Also Negotiates', |
|
| 58 | - 'http_507' => 'Insufficient Storage', |
|
| 59 | - 'http_508' => 'Loop Detected', |
|
| 60 | - 'http_509' => 'Unassigned', |
|
| 61 | - 'http_510' => 'Not Extended', |
|
| 62 | - 'http_511' => 'Network Authentication Required', |
|
| 20 | + // HttpException handler (added in 6.4.0) |
|
| 21 | + // Error messages for HttpException caught w/o custom messages |
|
| 22 | + // https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml |
|
| 23 | + 'http_400' => 'Bad Request', |
|
| 24 | + 'http_401' => 'Unauthorized', |
|
| 25 | + 'http_402' => 'Payment Required', |
|
| 26 | + 'http_403' => 'Forbidden', |
|
| 27 | + 'http_404' => 'Not Found', |
|
| 28 | + 'http_405' => 'Method Not Allowed', |
|
| 29 | + 'http_406' => 'Not Acceptable', |
|
| 30 | + 'http_407' => 'Proxy Authentication Required', |
|
| 31 | + 'http_408' => 'Request Timeout', |
|
| 32 | + 'http_409' => 'Conflict', |
|
| 33 | + 'http_410' => 'Gone', |
|
| 34 | + 'http_411' => 'Length Required', |
|
| 35 | + 'http_412' => 'Precondition Failed', |
|
| 36 | + 'http_413' => 'Payload Too Large', |
|
| 37 | + 'http_414' => 'URI Too Long', |
|
| 38 | + 'http_415' => 'Unsupported Media Type', |
|
| 39 | + 'http_416' => 'Range Not Satisfiable', |
|
| 40 | + 'http_417' => 'Expectation Failed', |
|
| 41 | + 'http_421' => 'Misdirected Request', |
|
| 42 | + 'http_422' => 'Unprocessable Entity', |
|
| 43 | + 'http_423' => 'Locked', |
|
| 44 | + 'http_424' => 'Failed Dependency', |
|
| 45 | + 'http_425' => 'Too Early', |
|
| 46 | + 'http_426' => 'Upgrade Required', |
|
| 47 | + 'http_428' => 'Precondition Required', |
|
| 48 | + 'http_429' => 'Too Many Requests', |
|
| 49 | + 'http_431' => 'Request Header Fields Too Large', |
|
| 50 | + 'http_451' => 'Unavailable For Legal Reasons', |
|
| 51 | + 'http_500' => 'Internal Server Error', |
|
| 52 | + 'http_501' => 'Not Implemented', |
|
| 53 | + 'http_502' => 'Bad Gateway', |
|
| 54 | + 'http_503' => 'Service Unavailable', |
|
| 55 | + 'http_504' => 'Gateway Timeout', |
|
| 56 | + 'http_505' => 'HTTP Version Not Supported', |
|
| 57 | + 'http_506' => 'Variant Also Negotiates', |
|
| 58 | + 'http_507' => 'Insufficient Storage', |
|
| 59 | + 'http_508' => 'Loop Detected', |
|
| 60 | + 'http_509' => 'Unassigned', |
|
| 61 | + 'http_510' => 'Not Extended', |
|
| 62 | + 'http_511' => 'Network Authentication Required', |
|
| 63 | 63 | ]; |
| 64 | 64 | |
@@ -21,180 +21,180 @@ |
||
| 21 | 21 | */ |
| 22 | 22 | class BaseApiCodes |
| 23 | 23 | { |
| 24 | - use ApiCodesHelpers; |
|
| 25 | - |
|
| 26 | - /** |
|
| 27 | - * protected code range - lowest code for reserved range. |
|
| 28 | - * |
|
| 29 | - * @var int |
|
| 30 | - */ |
|
| 31 | - public const RESERVED_MIN_API_CODE_OFFSET = 0; |
|
| 32 | - |
|
| 33 | - /** |
|
| 34 | - * protected code range - highest code for reserved range |
|
| 35 | - * |
|
| 36 | - * @var int |
|
| 37 | - */ |
|
| 38 | - public const RESERVED_MAX_API_CODE_OFFSET = 19; |
|
| 39 | - |
|
| 40 | - /** |
|
| 41 | - * built-in codes: OK |
|
| 42 | - * |
|
| 43 | - * @var int |
|
| 44 | - */ |
|
| 45 | - protected const OK_OFFSET = 0; |
|
| 46 | - /** |
|
| 47 | - * built-in code for fallback message mapping |
|
| 48 | - * |
|
| 49 | - * @var int |
|
| 50 | - */ |
|
| 51 | - protected const NO_ERROR_MESSAGE_OFFSET = 1; |
|
| 52 | - /** |
|
| 53 | - * built-in error code for HTTP_NOT_FOUND exception |
|
| 54 | - * |
|
| 55 | - * @var int |
|
| 56 | - */ |
|
| 57 | - protected const EX_HTTP_NOT_FOUND_OFFSET = 10; |
|
| 58 | - /** |
|
| 59 | - * built-in error code for HTTP_SERVICE_UNAVAILABLE exception |
|
| 60 | - * |
|
| 61 | - * @var int |
|
| 62 | - */ |
|
| 63 | - protected const EX_HTTP_SERVICE_UNAVAILABLE_OFFSET = 11; |
|
| 64 | - /** |
|
| 65 | - * built-in error code for HTTP_EXCEPTION |
|
| 66 | - * |
|
| 67 | - * @var int |
|
| 68 | - */ |
|
| 69 | - protected const EX_HTTP_EXCEPTION_OFFSET = 12; |
|
| 70 | - /** |
|
| 71 | - * built-in error code for UNCAUGHT_EXCEPTION |
|
| 72 | - * |
|
| 73 | - * @var int |
|
| 74 | - */ |
|
| 75 | - protected const EX_UNCAUGHT_EXCEPTION_OFFSET = 13; |
|
| 76 | - |
|
| 77 | - /** |
|
| 78 | - * built-in error code for \Illuminate\Auth\AuthenticationException |
|
| 79 | - * |
|
| 80 | - * @var int |
|
| 81 | - */ |
|
| 82 | - protected const EX_AUTHENTICATION_EXCEPTION_OFFSET = 14; |
|
| 83 | - |
|
| 84 | - /** |
|
| 85 | - * built-in error code for \Illuminate\Auth\AuthenticationException |
|
| 86 | - * |
|
| 87 | - * @var int |
|
| 88 | - */ |
|
| 89 | - protected const EX_VALIDATION_EXCEPTION_OFFSET = 15; |
|
| 90 | - |
|
| 91 | - /** |
|
| 92 | - * Returns base code mapping array |
|
| 93 | - * |
|
| 94 | - * @return array |
|
| 95 | - */ |
|
| 96 | - protected static function getBaseMap(): array |
|
| 97 | - { |
|
| 98 | - $tpl = 'response-builder::builder.http_%d'; |
|
| 99 | - |
|
| 100 | - return [ |
|
| 101 | - self::OK() => 'response-builder::builder.ok', |
|
| 102 | - self::NO_ERROR_MESSAGE() => 'response-builder::builder.no_error_message', |
|
| 103 | - self::EX_HTTP_EXCEPTION() => 'response-builder::builder.http_exception', |
|
| 104 | - self::EX_UNCAUGHT_EXCEPTION() => 'response-builder::builder.uncaught_exception', |
|
| 105 | - self::EX_HTTP_NOT_FOUND() => sprintf($tpl, HttpResponse::HTTP_NOT_FOUND), |
|
| 106 | - self::EX_HTTP_SERVICE_UNAVAILABLE() => sprintf($tpl, HttpResponse::HTTP_SERVICE_UNAVAILABLE), |
|
| 107 | - self::EX_AUTHENTICATION_EXCEPTION() => sprintf($tpl, HttpResponse::HTTP_UNAUTHORIZED), |
|
| 108 | - self::EX_VALIDATION_EXCEPTION() => sprintf($tpl, HttpResponse::HTTP_UNPROCESSABLE_ENTITY), |
|
| 109 | - ]; |
|
| 110 | - } |
|
| 111 | - |
|
| 112 | - /** |
|
| 113 | - * Returns API code for internal code OK |
|
| 114 | - * |
|
| 115 | - * @return int valid API code in current range |
|
| 116 | - */ |
|
| 117 | - public static function OK(): int |
|
| 118 | - { |
|
| 119 | - return static::getCodeForInternalOffset(static::OK_OFFSET); |
|
| 120 | - } |
|
| 121 | - |
|
| 122 | - /** |
|
| 123 | - * Returns API code for internal code NO_ERROR_MESSAGE |
|
| 124 | - * |
|
| 125 | - * @return int valid API code in current range |
|
| 126 | - */ |
|
| 127 | - public static function NO_ERROR_MESSAGE(): int |
|
| 128 | - { |
|
| 129 | - return static::getCodeForInternalOffset(static::NO_ERROR_MESSAGE_OFFSET); |
|
| 130 | - } |
|
| 131 | - |
|
| 132 | - /** |
|
| 133 | - * Returns API code for internal code EX_HTTP_NOT_FOUND |
|
| 134 | - * |
|
| 135 | - * @return int valid API code in current range |
|
| 136 | - * |
|
| 137 | - * @deprecated Configure Exception Handler to use your own API code. |
|
| 138 | - */ |
|
| 139 | - public static function EX_HTTP_NOT_FOUND(): int |
|
| 140 | - { |
|
| 141 | - return static::getCodeForInternalOffset(static::EX_HTTP_NOT_FOUND_OFFSET); |
|
| 142 | - } |
|
| 143 | - |
|
| 144 | - /** |
|
| 145 | - * Returns API code for internal code EX_HTTP_EXCEPTION |
|
| 146 | - * |
|
| 147 | - * @return int valid API code in current range |
|
| 148 | - */ |
|
| 149 | - public static function EX_HTTP_EXCEPTION(): int |
|
| 150 | - { |
|
| 151 | - return static::getCodeForInternalOffset(static::EX_HTTP_EXCEPTION_OFFSET); |
|
| 152 | - } |
|
| 153 | - |
|
| 154 | - /** |
|
| 155 | - * Returns API code for internal code EX_UNCAUGHT_EXCEPTION |
|
| 156 | - * |
|
| 157 | - * @return int valid API code in current range |
|
| 158 | - */ |
|
| 159 | - public static function EX_UNCAUGHT_EXCEPTION(): int |
|
| 160 | - { |
|
| 161 | - return static::getCodeForInternalOffset(static::EX_UNCAUGHT_EXCEPTION_OFFSET); |
|
| 162 | - } |
|
| 163 | - |
|
| 164 | - /** |
|
| 165 | - * Returns API code for internal code EX_AUTHENTICATION_EXCEPTION |
|
| 166 | - * |
|
| 167 | - * @return int valid API code in current range |
|
| 168 | - * |
|
| 169 | - * @deprecated Configure Exception Handler to use your own API code. |
|
| 170 | - */ |
|
| 171 | - public static function EX_AUTHENTICATION_EXCEPTION(): int |
|
| 172 | - { |
|
| 173 | - return static::getCodeForInternalOffset(static::EX_AUTHENTICATION_EXCEPTION_OFFSET); |
|
| 174 | - } |
|
| 175 | - |
|
| 176 | - /** |
|
| 177 | - * Returns API code for internal code EX_VALIDATION_EXCEPTION |
|
| 178 | - * |
|
| 179 | - * @return int valid API code in current range |
|
| 180 | - * |
|
| 181 | - * @deprecated Configure Exception Handler to use your own API code. |
|
| 182 | - */ |
|
| 183 | - public static function EX_VALIDATION_EXCEPTION(): int |
|
| 184 | - { |
|
| 185 | - return static::getCodeForInternalOffset(static::EX_VALIDATION_EXCEPTION_OFFSET); |
|
| 186 | - } |
|
| 187 | - |
|
| 188 | - /** |
|
| 189 | - * Returns API code for internal code EX_HTTP_SERVICE_UNAVAILABLE |
|
| 190 | - * |
|
| 191 | - * @return int valid API code in current range |
|
| 192 | - * |
|
| 193 | - * @deprecated Configure Exception Handler to use your own API code. |
|
| 194 | - */ |
|
| 195 | - public static function EX_HTTP_SERVICE_UNAVAILABLE(): int |
|
| 196 | - { |
|
| 197 | - return static::getCodeForInternalOffset(static::EX_HTTP_SERVICE_UNAVAILABLE_OFFSET); |
|
| 198 | - } |
|
| 24 | + use ApiCodesHelpers; |
|
| 25 | + |
|
| 26 | + /** |
|
| 27 | + * protected code range - lowest code for reserved range. |
|
| 28 | + * |
|
| 29 | + * @var int |
|
| 30 | + */ |
|
| 31 | + public const RESERVED_MIN_API_CODE_OFFSET = 0; |
|
| 32 | + |
|
| 33 | + /** |
|
| 34 | + * protected code range - highest code for reserved range |
|
| 35 | + * |
|
| 36 | + * @var int |
|
| 37 | + */ |
|
| 38 | + public const RESERVED_MAX_API_CODE_OFFSET = 19; |
|
| 39 | + |
|
| 40 | + /** |
|
| 41 | + * built-in codes: OK |
|
| 42 | + * |
|
| 43 | + * @var int |
|
| 44 | + */ |
|
| 45 | + protected const OK_OFFSET = 0; |
|
| 46 | + /** |
|
| 47 | + * built-in code for fallback message mapping |
|
| 48 | + * |
|
| 49 | + * @var int |
|
| 50 | + */ |
|
| 51 | + protected const NO_ERROR_MESSAGE_OFFSET = 1; |
|
| 52 | + /** |
|
| 53 | + * built-in error code for HTTP_NOT_FOUND exception |
|
| 54 | + * |
|
| 55 | + * @var int |
|
| 56 | + */ |
|
| 57 | + protected const EX_HTTP_NOT_FOUND_OFFSET = 10; |
|
| 58 | + /** |
|
| 59 | + * built-in error code for HTTP_SERVICE_UNAVAILABLE exception |
|
| 60 | + * |
|
| 61 | + * @var int |
|
| 62 | + */ |
|
| 63 | + protected const EX_HTTP_SERVICE_UNAVAILABLE_OFFSET = 11; |
|
| 64 | + /** |
|
| 65 | + * built-in error code for HTTP_EXCEPTION |
|
| 66 | + * |
|
| 67 | + * @var int |
|
| 68 | + */ |
|
| 69 | + protected const EX_HTTP_EXCEPTION_OFFSET = 12; |
|
| 70 | + /** |
|
| 71 | + * built-in error code for UNCAUGHT_EXCEPTION |
|
| 72 | + * |
|
| 73 | + * @var int |
|
| 74 | + */ |
|
| 75 | + protected const EX_UNCAUGHT_EXCEPTION_OFFSET = 13; |
|
| 76 | + |
|
| 77 | + /** |
|
| 78 | + * built-in error code for \Illuminate\Auth\AuthenticationException |
|
| 79 | + * |
|
| 80 | + * @var int |
|
| 81 | + */ |
|
| 82 | + protected const EX_AUTHENTICATION_EXCEPTION_OFFSET = 14; |
|
| 83 | + |
|
| 84 | + /** |
|
| 85 | + * built-in error code for \Illuminate\Auth\AuthenticationException |
|
| 86 | + * |
|
| 87 | + * @var int |
|
| 88 | + */ |
|
| 89 | + protected const EX_VALIDATION_EXCEPTION_OFFSET = 15; |
|
| 90 | + |
|
| 91 | + /** |
|
| 92 | + * Returns base code mapping array |
|
| 93 | + * |
|
| 94 | + * @return array |
|
| 95 | + */ |
|
| 96 | + protected static function getBaseMap(): array |
|
| 97 | + { |
|
| 98 | + $tpl = 'response-builder::builder.http_%d'; |
|
| 99 | + |
|
| 100 | + return [ |
|
| 101 | + self::OK() => 'response-builder::builder.ok', |
|
| 102 | + self::NO_ERROR_MESSAGE() => 'response-builder::builder.no_error_message', |
|
| 103 | + self::EX_HTTP_EXCEPTION() => 'response-builder::builder.http_exception', |
|
| 104 | + self::EX_UNCAUGHT_EXCEPTION() => 'response-builder::builder.uncaught_exception', |
|
| 105 | + self::EX_HTTP_NOT_FOUND() => sprintf($tpl, HttpResponse::HTTP_NOT_FOUND), |
|
| 106 | + self::EX_HTTP_SERVICE_UNAVAILABLE() => sprintf($tpl, HttpResponse::HTTP_SERVICE_UNAVAILABLE), |
|
| 107 | + self::EX_AUTHENTICATION_EXCEPTION() => sprintf($tpl, HttpResponse::HTTP_UNAUTHORIZED), |
|
| 108 | + self::EX_VALIDATION_EXCEPTION() => sprintf($tpl, HttpResponse::HTTP_UNPROCESSABLE_ENTITY), |
|
| 109 | + ]; |
|
| 110 | + } |
|
| 111 | + |
|
| 112 | + /** |
|
| 113 | + * Returns API code for internal code OK |
|
| 114 | + * |
|
| 115 | + * @return int valid API code in current range |
|
| 116 | + */ |
|
| 117 | + public static function OK(): int |
|
| 118 | + { |
|
| 119 | + return static::getCodeForInternalOffset(static::OK_OFFSET); |
|
| 120 | + } |
|
| 121 | + |
|
| 122 | + /** |
|
| 123 | + * Returns API code for internal code NO_ERROR_MESSAGE |
|
| 124 | + * |
|
| 125 | + * @return int valid API code in current range |
|
| 126 | + */ |
|
| 127 | + public static function NO_ERROR_MESSAGE(): int |
|
| 128 | + { |
|
| 129 | + return static::getCodeForInternalOffset(static::NO_ERROR_MESSAGE_OFFSET); |
|
| 130 | + } |
|
| 131 | + |
|
| 132 | + /** |
|
| 133 | + * Returns API code for internal code EX_HTTP_NOT_FOUND |
|
| 134 | + * |
|
| 135 | + * @return int valid API code in current range |
|
| 136 | + * |
|
| 137 | + * @deprecated Configure Exception Handler to use your own API code. |
|
| 138 | + */ |
|
| 139 | + public static function EX_HTTP_NOT_FOUND(): int |
|
| 140 | + { |
|
| 141 | + return static::getCodeForInternalOffset(static::EX_HTTP_NOT_FOUND_OFFSET); |
|
| 142 | + } |
|
| 143 | + |
|
| 144 | + /** |
|
| 145 | + * Returns API code for internal code EX_HTTP_EXCEPTION |
|
| 146 | + * |
|
| 147 | + * @return int valid API code in current range |
|
| 148 | + */ |
|
| 149 | + public static function EX_HTTP_EXCEPTION(): int |
|
| 150 | + { |
|
| 151 | + return static::getCodeForInternalOffset(static::EX_HTTP_EXCEPTION_OFFSET); |
|
| 152 | + } |
|
| 153 | + |
|
| 154 | + /** |
|
| 155 | + * Returns API code for internal code EX_UNCAUGHT_EXCEPTION |
|
| 156 | + * |
|
| 157 | + * @return int valid API code in current range |
|
| 158 | + */ |
|
| 159 | + public static function EX_UNCAUGHT_EXCEPTION(): int |
|
| 160 | + { |
|
| 161 | + return static::getCodeForInternalOffset(static::EX_UNCAUGHT_EXCEPTION_OFFSET); |
|
| 162 | + } |
|
| 163 | + |
|
| 164 | + /** |
|
| 165 | + * Returns API code for internal code EX_AUTHENTICATION_EXCEPTION |
|
| 166 | + * |
|
| 167 | + * @return int valid API code in current range |
|
| 168 | + * |
|
| 169 | + * @deprecated Configure Exception Handler to use your own API code. |
|
| 170 | + */ |
|
| 171 | + public static function EX_AUTHENTICATION_EXCEPTION(): int |
|
| 172 | + { |
|
| 173 | + return static::getCodeForInternalOffset(static::EX_AUTHENTICATION_EXCEPTION_OFFSET); |
|
| 174 | + } |
|
| 175 | + |
|
| 176 | + /** |
|
| 177 | + * Returns API code for internal code EX_VALIDATION_EXCEPTION |
|
| 178 | + * |
|
| 179 | + * @return int valid API code in current range |
|
| 180 | + * |
|
| 181 | + * @deprecated Configure Exception Handler to use your own API code. |
|
| 182 | + */ |
|
| 183 | + public static function EX_VALIDATION_EXCEPTION(): int |
|
| 184 | + { |
|
| 185 | + return static::getCodeForInternalOffset(static::EX_VALIDATION_EXCEPTION_OFFSET); |
|
| 186 | + } |
|
| 187 | + |
|
| 188 | + /** |
|
| 189 | + * Returns API code for internal code EX_HTTP_SERVICE_UNAVAILABLE |
|
| 190 | + * |
|
| 191 | + * @return int valid API code in current range |
|
| 192 | + * |
|
| 193 | + * @deprecated Configure Exception Handler to use your own API code. |
|
| 194 | + */ |
|
| 195 | + public static function EX_HTTP_SERVICE_UNAVAILABLE(): int |
|
| 196 | + { |
|
| 197 | + return static::getCodeForInternalOffset(static::EX_HTTP_SERVICE_UNAVAILABLE_OFFSET); |
|
| 198 | + } |
|
| 199 | 199 | |
| 200 | 200 | } |
@@ -15,65 +15,65 @@ discard block |
||
| 15 | 15 | use \Symfony\Component\HttpFoundation\Response as HttpResponse; |
| 16 | 16 | |
| 17 | 17 | return [ |
| 18 | - /* |
|
| 18 | + /* |
|
| 19 | 19 | |----------------------------------------------------------------------------------------------------------- |
| 20 | 20 | | Code range settings |
| 21 | 21 | |----------------------------------------------------------------------------------------------------------- |
| 22 | 22 | */ |
| 23 | - 'min_code' => 100, |
|
| 24 | - 'max_code' => 1024, |
|
| 23 | + 'min_code' => 100, |
|
| 24 | + 'max_code' => 1024, |
|
| 25 | 25 | |
| 26 | - /* |
|
| 26 | + /* |
|
| 27 | 27 | |----------------------------------------------------------------------------------------------------------- |
| 28 | 28 | | Error code to message mapping |
| 29 | 29 | |----------------------------------------------------------------------------------------------------------- |
| 30 | 30 | | |
| 31 | 31 | */ |
| 32 | - 'map' => [ |
|
| 33 | - // YOUR_API_CODE => '<MESSAGE_KEY>', |
|
| 34 | - ], |
|
| 32 | + 'map' => [ |
|
| 33 | + // YOUR_API_CODE => '<MESSAGE_KEY>', |
|
| 34 | + ], |
|
| 35 | 35 | |
| 36 | - /* |
|
| 36 | + /* |
|
| 37 | 37 | |----------------------------------------------------------------------------------------------------------- |
| 38 | 38 | | Response Builder classes |
| 39 | 39 | |----------------------------------------------------------------------------------------------------------- |
| 40 | 40 | | |
| 41 | 41 | */ |
| 42 | - 'classes' => [ |
|
| 43 | - \Illuminate\Database\Eloquent\Model::class => [ |
|
| 44 | - 'key' => 'item', |
|
| 45 | - 'method' => 'toArray', |
|
| 46 | - ], |
|
| 47 | - \Illuminate\Support\Collection::class => [ |
|
| 48 | - 'key' => 'items', |
|
| 49 | - 'method' => 'toArray', |
|
| 50 | - ], |
|
| 51 | - \Illuminate\Database\Eloquent\Collection::class => [ |
|
| 52 | - 'key' => 'items', |
|
| 53 | - 'method' => 'toArray', |
|
| 54 | - ], |
|
| 55 | - \Illuminate\Http\Resources\Json\JsonResource::class => [ |
|
| 56 | - 'key' => 'item', |
|
| 57 | - 'method' => 'toArray', |
|
| 58 | - ], |
|
| 59 | - ], |
|
| 42 | + 'classes' => [ |
|
| 43 | + \Illuminate\Database\Eloquent\Model::class => [ |
|
| 44 | + 'key' => 'item', |
|
| 45 | + 'method' => 'toArray', |
|
| 46 | + ], |
|
| 47 | + \Illuminate\Support\Collection::class => [ |
|
| 48 | + 'key' => 'items', |
|
| 49 | + 'method' => 'toArray', |
|
| 50 | + ], |
|
| 51 | + \Illuminate\Database\Eloquent\Collection::class => [ |
|
| 52 | + 'key' => 'items', |
|
| 53 | + 'method' => 'toArray', |
|
| 54 | + ], |
|
| 55 | + \Illuminate\Http\Resources\Json\JsonResource::class => [ |
|
| 56 | + 'key' => 'item', |
|
| 57 | + 'method' => 'toArray', |
|
| 58 | + ], |
|
| 59 | + ], |
|
| 60 | 60 | |
| 61 | - /* |
|
| 61 | + /* |
|
| 62 | 62 | |----------------------------------------------------------------------------------------------------------- |
| 63 | 63 | | data-to-json encoding options |
| 64 | 64 | |----------------------------------------------------------------------------------------------------------- |
| 65 | 65 | | |
| 66 | 66 | */ |
| 67 | - 'encoding_options' => JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE, |
|
| 67 | + 'encoding_options' => JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE, |
|
| 68 | 68 | |
| 69 | - /* |
|
| 69 | + /* |
|
| 70 | 70 | |----------------------------------------------------------------------------------------------------------- |
| 71 | 71 | | Exception handler error codes |
| 72 | 72 | |----------------------------------------------------------------------------------------------------------- |
| 73 | 73 | | |
| 74 | 74 | */ |
| 75 | - 'exception_handler' => [ |
|
| 76 | - /* |
|
| 75 | + 'exception_handler' => [ |
|
| 76 | + /* |
|
| 77 | 77 | * HTTP Exceptions |
| 78 | 78 | * Use this section to define how you want any Http Exception to be handled. |
| 79 | 79 | * This means that you can define any Http code (i.e. 404 => HttpResponse::HTTP_NOT_FOUND) |
@@ -104,20 +104,20 @@ discard block |
||
| 104 | 104 | // 'api_code' => BaseApiCodes::EX_UNCAUGHT_EXCEPTION(), |
| 105 | 105 | // 'http_code' => HttpResponse::HTTP_INTERNAL_SERVER_ERROR, |
| 106 | 106 | // ], |
| 107 | - ], |
|
| 107 | + ], |
|
| 108 | 108 | |
| 109 | - /* |
|
| 109 | + /* |
|
| 110 | 110 | |----------------------------------------------------------------------------------------------------------- |
| 111 | 111 | | Debug config |
| 112 | 112 | |----------------------------------------------------------------------------------------------------------- |
| 113 | 113 | | |
| 114 | 114 | */ |
| 115 | - 'debug' => [ |
|
| 116 | - 'debug_key' => 'debug', |
|
| 117 | - 'exception_handler' => [ |
|
| 118 | - 'trace_key' => 'trace', |
|
| 119 | - 'trace_enabled' => env('APP_DEBUG', false), |
|
| 120 | - ], |
|
| 121 | - ], |
|
| 115 | + 'debug' => [ |
|
| 116 | + 'debug_key' => 'debug', |
|
| 117 | + 'exception_handler' => [ |
|
| 118 | + 'trace_key' => 'trace', |
|
| 119 | + 'trace_enabled' => env('APP_DEBUG', false), |
|
| 120 | + ], |
|
| 121 | + ], |
|
| 122 | 122 | |
| 123 | 123 | ]; |
@@ -21,128 +21,128 @@ |
||
| 21 | 21 | */ |
| 22 | 22 | trait ApiCodesHelpers |
| 23 | 23 | { |
| 24 | - /** |
|
| 25 | - * Returns lowest allowed error code for this module |
|
| 26 | - * |
|
| 27 | - * @return integer |
|
| 28 | - * |
|
| 29 | - * @throws \RuntimeException Throws exception if no min_code set up |
|
| 30 | - */ |
|
| 31 | - public static function getMinCode(): int |
|
| 32 | - { |
|
| 33 | - $key = ResponseBuilder::CONF_KEY_MIN_CODE; |
|
| 34 | - $min_code = Config::get($key, null); |
|
| 35 | - |
|
| 36 | - if ($min_code === null) { |
|
| 37 | - throw new \RuntimeException(sprintf('CONFIG: Missing "%s" key', $key)); |
|
| 38 | - } |
|
| 39 | - |
|
| 40 | - return $min_code; |
|
| 41 | - } |
|
| 42 | - |
|
| 43 | - /** |
|
| 44 | - * Returns highest allowed error code for this module |
|
| 45 | - * |
|
| 46 | - * @return integer |
|
| 47 | - * |
|
| 48 | - * @throws \RuntimeException Throws exception if no max_code set up |
|
| 49 | - */ |
|
| 50 | - public static function getMaxCode(): int |
|
| 51 | - { |
|
| 52 | - $key = ResponseBuilder::CONF_KEY_MAX_CODE; |
|
| 53 | - $max_code = Config::get($key, null); |
|
| 54 | - |
|
| 55 | - if ($max_code === null) { |
|
| 56 | - throw new \RuntimeException(sprintf('CONFIG: Missing "%s" key', $key)); |
|
| 57 | - } |
|
| 58 | - |
|
| 59 | - return $max_code; |
|
| 60 | - } |
|
| 61 | - |
|
| 62 | - /** |
|
| 63 | - * Returns array of error code constants defined in this class. Used mainly for debugging/tests |
|
| 64 | - * |
|
| 65 | - * @return array |
|
| 66 | - * @throws \ReflectionException |
|
| 67 | - */ |
|
| 68 | - public static function getApiCodeConstants(): array |
|
| 69 | - { |
|
| 70 | - /** @noinspection PhpUnhandledExceptionInspection */ |
|
| 71 | - return (new \ReflectionClass(static::class))->getConstants(); |
|
| 72 | - } |
|
| 73 | - |
|
| 74 | - /** |
|
| 75 | - * Returns complete error code to locale string mapping array |
|
| 76 | - * |
|
| 77 | - * @return array |
|
| 78 | - * |
|
| 79 | - * @throws \RuntimeException Thrown when builder map is not configured. |
|
| 80 | - */ |
|
| 81 | - public static function getMap(): array |
|
| 82 | - { |
|
| 83 | - $user_map = Config::get(ResponseBuilder::CONF_KEY_MAP, null); |
|
| 84 | - if ($user_map === null) { |
|
| 85 | - throw new \RuntimeException(sprintf('CONFIG: Missing "%s" key', ResponseBuilder::CONF_KEY_MAP)); |
|
| 86 | - } |
|
| 87 | - if (!is_array($user_map)) { |
|
| 88 | - throw new \RuntimeException(sprintf('CONFIG: "%s" must be an array', ResponseBuilder::CONF_KEY_MAP)); |
|
| 89 | - } |
|
| 90 | - return Util::mergeConfig(BaseApiCodes::getBaseMap(), $user_map); |
|
| 91 | - } |
|
| 92 | - |
|
| 93 | - /** |
|
| 94 | - * Returns locale mappings key for given api code or @null if there's no mapping |
|
| 95 | - * |
|
| 96 | - * @param integer $api_code Api code to look for mapped message for. |
|
| 97 | - * |
|
| 98 | - * @return string|null |
|
| 99 | - * |
|
| 100 | - * @throws \InvalidArgumentException If $code is not in allowed range. |
|
| 101 | - */ |
|
| 102 | - public static function getCodeMessageKey(int $api_code): ?string |
|
| 103 | - { |
|
| 104 | - if (!static::isCodeValid($api_code)) { |
|
| 105 | - $min = static::getMinCode(); |
|
| 106 | - $max = static::getMaxCode(); |
|
| 107 | - throw new \InvalidArgumentException("API code value ({$api_code}) is out of allowed range {$min}-{$max}"); |
|
| 108 | - } |
|
| 109 | - |
|
| 110 | - $map = static::getMap(); |
|
| 111 | - |
|
| 112 | - return $map[ $api_code ] ?? null; |
|
| 113 | - } |
|
| 114 | - |
|
| 115 | - /** |
|
| 116 | - * Checks if given API $code can be used in current configuration. |
|
| 117 | - * |
|
| 118 | - * @param int $code API code to validate |
|
| 119 | - * |
|
| 120 | - * @return bool |
|
| 121 | - */ |
|
| 122 | - public static function isCodeValid(int $code): bool |
|
| 123 | - { |
|
| 124 | - return ($code === 0) || (($code >= static::getMinCode()) && ($code <= static::getMaxCode())); |
|
| 125 | - } |
|
| 126 | - |
|
| 127 | - /** |
|
| 128 | - * Returns final API code for internal code, remapped to configured code range |
|
| 129 | - * |
|
| 130 | - * @param int $internal_code |
|
| 131 | - * |
|
| 132 | - * @return int |
|
| 133 | - * |
|
| 134 | - * @throws \InvalidArgumentException |
|
| 135 | - */ |
|
| 136 | - protected static function getCodeForInternalOffset(int $internal_code): int |
|
| 137 | - { |
|
| 138 | - $min = static::RESERVED_MIN_API_CODE_OFFSET; |
|
| 139 | - $max = static::RESERVED_MAX_API_CODE_OFFSET; |
|
| 140 | - if (($internal_code < $min) || ($internal_code > $max)) { |
|
| 141 | - throw new \InvalidArgumentException( |
|
| 142 | - "Invalid internal code ({$internal_code}). Must be between {$min}-{$max} inclusive."); |
|
| 143 | - } |
|
| 144 | - |
|
| 145 | - return ($internal_code === 0) ? 0 : $internal_code + static::getMinCode(); |
|
| 146 | - } |
|
| 24 | + /** |
|
| 25 | + * Returns lowest allowed error code for this module |
|
| 26 | + * |
|
| 27 | + * @return integer |
|
| 28 | + * |
|
| 29 | + * @throws \RuntimeException Throws exception if no min_code set up |
|
| 30 | + */ |
|
| 31 | + public static function getMinCode(): int |
|
| 32 | + { |
|
| 33 | + $key = ResponseBuilder::CONF_KEY_MIN_CODE; |
|
| 34 | + $min_code = Config::get($key, null); |
|
| 35 | + |
|
| 36 | + if ($min_code === null) { |
|
| 37 | + throw new \RuntimeException(sprintf('CONFIG: Missing "%s" key', $key)); |
|
| 38 | + } |
|
| 39 | + |
|
| 40 | + return $min_code; |
|
| 41 | + } |
|
| 42 | + |
|
| 43 | + /** |
|
| 44 | + * Returns highest allowed error code for this module |
|
| 45 | + * |
|
| 46 | + * @return integer |
|
| 47 | + * |
|
| 48 | + * @throws \RuntimeException Throws exception if no max_code set up |
|
| 49 | + */ |
|
| 50 | + public static function getMaxCode(): int |
|
| 51 | + { |
|
| 52 | + $key = ResponseBuilder::CONF_KEY_MAX_CODE; |
|
| 53 | + $max_code = Config::get($key, null); |
|
| 54 | + |
|
| 55 | + if ($max_code === null) { |
|
| 56 | + throw new \RuntimeException(sprintf('CONFIG: Missing "%s" key', $key)); |
|
| 57 | + } |
|
| 58 | + |
|
| 59 | + return $max_code; |
|
| 60 | + } |
|
| 61 | + |
|
| 62 | + /** |
|
| 63 | + * Returns array of error code constants defined in this class. Used mainly for debugging/tests |
|
| 64 | + * |
|
| 65 | + * @return array |
|
| 66 | + * @throws \ReflectionException |
|
| 67 | + */ |
|
| 68 | + public static function getApiCodeConstants(): array |
|
| 69 | + { |
|
| 70 | + /** @noinspection PhpUnhandledExceptionInspection */ |
|
| 71 | + return (new \ReflectionClass(static::class))->getConstants(); |
|
| 72 | + } |
|
| 73 | + |
|
| 74 | + /** |
|
| 75 | + * Returns complete error code to locale string mapping array |
|
| 76 | + * |
|
| 77 | + * @return array |
|
| 78 | + * |
|
| 79 | + * @throws \RuntimeException Thrown when builder map is not configured. |
|
| 80 | + */ |
|
| 81 | + public static function getMap(): array |
|
| 82 | + { |
|
| 83 | + $user_map = Config::get(ResponseBuilder::CONF_KEY_MAP, null); |
|
| 84 | + if ($user_map === null) { |
|
| 85 | + throw new \RuntimeException(sprintf('CONFIG: Missing "%s" key', ResponseBuilder::CONF_KEY_MAP)); |
|
| 86 | + } |
|
| 87 | + if (!is_array($user_map)) { |
|
| 88 | + throw new \RuntimeException(sprintf('CONFIG: "%s" must be an array', ResponseBuilder::CONF_KEY_MAP)); |
|
| 89 | + } |
|
| 90 | + return Util::mergeConfig(BaseApiCodes::getBaseMap(), $user_map); |
|
| 91 | + } |
|
| 92 | + |
|
| 93 | + /** |
|
| 94 | + * Returns locale mappings key for given api code or @null if there's no mapping |
|
| 95 | + * |
|
| 96 | + * @param integer $api_code Api code to look for mapped message for. |
|
| 97 | + * |
|
| 98 | + * @return string|null |
|
| 99 | + * |
|
| 100 | + * @throws \InvalidArgumentException If $code is not in allowed range. |
|
| 101 | + */ |
|
| 102 | + public static function getCodeMessageKey(int $api_code): ?string |
|
| 103 | + { |
|
| 104 | + if (!static::isCodeValid($api_code)) { |
|
| 105 | + $min = static::getMinCode(); |
|
| 106 | + $max = static::getMaxCode(); |
|
| 107 | + throw new \InvalidArgumentException("API code value ({$api_code}) is out of allowed range {$min}-{$max}"); |
|
| 108 | + } |
|
| 109 | + |
|
| 110 | + $map = static::getMap(); |
|
| 111 | + |
|
| 112 | + return $map[ $api_code ] ?? null; |
|
| 113 | + } |
|
| 114 | + |
|
| 115 | + /** |
|
| 116 | + * Checks if given API $code can be used in current configuration. |
|
| 117 | + * |
|
| 118 | + * @param int $code API code to validate |
|
| 119 | + * |
|
| 120 | + * @return bool |
|
| 121 | + */ |
|
| 122 | + public static function isCodeValid(int $code): bool |
|
| 123 | + { |
|
| 124 | + return ($code === 0) || (($code >= static::getMinCode()) && ($code <= static::getMaxCode())); |
|
| 125 | + } |
|
| 126 | + |
|
| 127 | + /** |
|
| 128 | + * Returns final API code for internal code, remapped to configured code range |
|
| 129 | + * |
|
| 130 | + * @param int $internal_code |
|
| 131 | + * |
|
| 132 | + * @return int |
|
| 133 | + * |
|
| 134 | + * @throws \InvalidArgumentException |
|
| 135 | + */ |
|
| 136 | + protected static function getCodeForInternalOffset(int $internal_code): int |
|
| 137 | + { |
|
| 138 | + $min = static::RESERVED_MIN_API_CODE_OFFSET; |
|
| 139 | + $max = static::RESERVED_MAX_API_CODE_OFFSET; |
|
| 140 | + if (($internal_code < $min) || ($internal_code > $max)) { |
|
| 141 | + throw new \InvalidArgumentException( |
|
| 142 | + "Invalid internal code ({$internal_code}). Must be between {$min}-{$max} inclusive."); |
|
| 143 | + } |
|
| 144 | + |
|
| 145 | + return ($internal_code === 0) ? 0 : $internal_code + static::getMinCode(); |
|
| 146 | + } |
|
| 147 | 147 | |
| 148 | 148 | } |