Passed
Pull Request — dev (#124)
by Marcin
06:09
created
src/lang/pl/builder.php 1 patch
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -10,54 +10,54 @@
 block discarded – undo
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
 ];
Please login to merge, or discard this patch.
src/lang/en/builder.php 1 patch
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -10,55 +10,55 @@
 block discarded – undo
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
 
Please login to merge, or discard this patch.
src/BaseApiCodes.php 1 patch
Indentation   +175 added lines, -175 removed lines patch added patch discarded remove patch
@@ -21,180 +21,180 @@
 block discarded – undo
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
 }
Please login to merge, or discard this patch.
src/ApiCodesHelpers.php 1 patch
Indentation   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -21,125 +21,125 @@
 block discarded – undo
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
-    public 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
-        Validator::assertIsIntRange('internal_code', $internal_code, $min, $max);
141
-
142
-        return ($internal_code === 0) ? 0 : $internal_code + static::getMinCode();
143
-    }
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
+	public 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
+		Validator::assertIsIntRange('internal_code', $internal_code, $min, $max);
141
+
142
+		return ($internal_code === 0) ? 0 : $internal_code + static::getMinCode();
143
+	}
144 144
 
145 145
 }
Please login to merge, or discard this patch.
src/ExceptionHandlerHelper.php 2 patches
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -27,224 +27,224 @@
 block discarded – undo
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 = static::getExceptionHandlerConfig()['map'];
42
-
43
-        if ($ex instanceof HttpException) {
44
-            // Check if we have any exception configuration for this particular Http status code.
45
-            // This confing entry is guaranted to exist (at least 'default'). Enforced by tests.
46
-            $http_code = $ex->getStatusCode();
47
-            $ex_cfg = $cfg[ HttpException::class ][ $http_code ] ?? null;
48
-            $ex_cfg = $ex_cfg ?? $cfg[ HttpException::class ]['default'];
49
-            $result = self::processException($ex, $ex_cfg, $http_code);
50
-        } elseif ($ex instanceof ValidationException) {
51
-            // This entry is guaranted to exist. Enforced by tests.
52
-            $http_code = HttpResponse::HTTP_UNPROCESSABLE_ENTITY;
53
-            $ex_cfg = $cfg[ HttpException::class ][ $http_code ];
54
-            $result = self::processException($ex, $ex_cfg, $http_code);
55
-        }
56
-
57
-        if ($result === null) {
58
-            // This entry is guaranted to exist. Enforced by tests.
59
-            $http_code = HttpResponse::HTTP_INTERNAL_SERVER_ERROR;
60
-            $ex_cfg = $cfg['default'];
61
-            $result = self::processException($ex, $ex_cfg, $http_code);
62
-        }
63
-
64
-        return $result;
65
-    }
66
-
67
-    protected static function processException(\Exception $ex, array $ex_cfg, int $http_code)
68
-    {
69
-        $api_code = $ex_cfg['api_code'];
70
-        $http_code = $ex_cfg['http_code'] ?? $http_code;
71
-        $msg_key = $ex_cfg['msg_key'] ?? null;
72
-        $msg_enforce = $ex_cfg['msg_enforce'] ?? false;
73
-
74
-        // No message key, let's get exception message and if there's nothing useful, fallback to built-in one.
75
-        $error_message = $ex->getMessage();
76
-        $placeholders = [
77
-            'api_code' => $api_code,
78
-            'message'  => ($error_message !== '') ? $error_message : '???',
79
-        ];
80
-
81
-        // shall we enforce error message?
82
-        if ($msg_enforce) {
83
-            // yes, please.
84
-            if ($msg_key === null) {
85
-                // there's no msg_key configured for this exact code, so let's obtain our default message
86
-                $error_message = ($msg_key === null) ? static::getErrorMessageForException($ex, $http_code, $placeholders) : Lang::get($msg_key, $placeholders);
87
-            }
88
-        } else {
89
-            // nothing enforced, handling pipeline: ex_message -> user_defined msg -> http_ex -> default
90
-            if ($error_message === '') {
91
-                $error_message = ($msg_key === null) ? static::getErrorMessageForException($ex, $http_code, $placeholders) : Lang::get($msg_key, $placeholders);
92
-            }
93
-        }
94
-
95
-        // Lets' try to build the error response with what we have now
96
-        $result = static::error($ex, $api_code, $http_code, $error_message);
97
-
98
-        if ($result === null) {
99
-            $ex_cfg = $cfg[ HttpException::class ][ $http_code ];
100
-            $api_code = $ex_cfg['api_code'] ?? BaseApiCodes::EX_VALIDATION_EXCEPTION();
101
-            $http_code = $ex_cfg['http_code'] ?? $http_code;
102
-            $result = static::error($ex, $api_code, $http_code, $error_message);
103
-        }
104
-
105
-        return $result;
106
-    }
107
-
108
-    /**
109
-     * Returns error message for given exception. If exception message is empty, then falls back to
110
-     * `default` handler either for HttpException (if $ex is instance of it), or generic `default`
111
-     * config.
112
-     *
113
-     * @param \Exception $ex
114
-     * @param int        $http_code
115
-     * @param array      $placeholders
116
-     *
117
-     * @return string
118
-     */
119
-    protected static function getErrorMessageForException(\Exception $ex, int $http_code, array $placeholders): string
120
-    {
121
-        // exception message is uselss, lets go deeper
122
-        if ($ex instanceof HttpException) {
123
-            $error_message = Lang::get("response-builder::builder.http_{$http_code}", $placeholders);
124
-        } else {
125
-            // Still got nothing? Fall back to built-in generic message for this type of exception.
126
-            $key = BaseApiCodes::getCodeMessageKey(($ex instanceof HttpException)
127
-                ? BaseApiCodes::EX_HTTP_EXCEPTION() : BaseApiCodes::NO_ERROR_MESSAGE());
128
-            $error_message = Lang::get($key, $placeholders);
129
-        }
130
-
131
-        return $error_message;
132
-    }
133
-
134
-    /**
135
-     * Convert an authentication exception into an unauthenticated response.
136
-     *
137
-     * @param \Illuminate\Http\Request                 $request
138
-     * @param \Illuminate\Auth\AuthenticationException $exception
139
-     *
140
-     * @return HttpResponse
141
-     */
142
-    protected function unauthenticated(/** @scrutinizer ignore-unused */ $request,
143
-                                                                         AuthException $exception): HttpResponse
144
-    {
145
-        // This entry is guaranted to exist. Enforced by tests.
146
-        $http_code = HttpResponse::HTTP_UNAUTHORIZED;
147
-        $cfg = static::getExceptionHandlerConfig()['map'][ HttpException::class ][ $http_code ];
148
-
149
-        return static::processException($exception, $cfg, $http_code);
150
-    }
151
-
152
-    /**
153
-     * Process single error and produce valid API response.
154
-     *
155
-     * @param Exception $ex Exception to be handled.
156
-     * @param integer   $api_code
157
-     * @param integer   $http_code
158
-     *
159
-     * @return HttpResponse
160
-     */
161
-    protected static function error(Exception $ex,
162
-                                    int $api_code, int $http_code = null, string $error_message): HttpResponse
163
-    {
164
-        $ex_http_code = ($ex instanceof HttpException) ? $ex->getStatusCode() : $ex->getCode();
165
-        $http_code = $http_code ?? $ex_http_code;
166
-
167
-        // Check if we now have valid HTTP error code for this case or need to make one up.
168
-        // We cannot throw any exception if codes are invalid because we are in Exception Handler already.
169
-        if ($http_code < ResponseBuilder::ERROR_HTTP_CODE_MIN) {
170
-            // Not a valid code, let's try to get the exception status.
171
-            $http_code = $ex_http_code;
172
-        }
173
-        // Can it be considered a valid HTTP error code?
174
-        if ($http_code < ResponseBuilder::ERROR_HTTP_CODE_MIN) {
175
-            // We now handle uncaught exception, so we cannot throw another one if there's
176
-            // something wrong with the configuration, so we try to recover and use built-in
177
-            // codes instead.
178
-            // FIXME: We should log this event as (warning or error?)
179
-            $http_code = ResponseBuilder::DEFAULT_HTTP_CODE_ERROR;
180
-        }
181
-
182
-        // If we have trace data debugging enabled, let's gather some debug info and add to the response.
183
-        $debug_data = null;
184
-        if (Config::get(ResponseBuilder::CONF_KEY_DEBUG_EX_TRACE_ENABLED, false)) {
185
-            $debug_data = [
186
-                Config::get(ResponseBuilder::CONF_KEY_DEBUG_EX_TRACE_KEY, ResponseBuilder::KEY_TRACE) => [
187
-                    ResponseBuilder::KEY_CLASS => get_class($ex),
188
-                    ResponseBuilder::KEY_FILE  => $ex->getFile(),
189
-                    ResponseBuilder::KEY_LINE  => $ex->getLine(),
190
-                ],
191
-            ];
192
-        }
193
-
194
-        // If this is ValidationException, add all the messages from MessageBag to the data node.
195
-        $data = null;
196
-        if ($ex instanceof ValidationException) {
197
-            /** @var ValidationException $ex */
198
-            $data = [ResponseBuilder::KEY_MESSAGES => $ex->validator->errors()->messages()];
199
-        }
200
-
201
-        return Builder::error($api_code)
202
-            ->withMessage($error_message)
203
-            ->withHttpCode($http_code)
204
-            ->withData($data)
205
-            ->withDebugData($debug_data)
206
-            ->build();
207
-    }
208
-
209
-    protected
210
-    static function getExceptionHandlerDefaultConfig(): array
211
-    {
212
-        return [
213
-            'map' => [
214
-                HttpException::class => [
215
-                    // used by unauthenticated() to obtain api and http code for the exception
216
-                    HttpResponse::HTTP_UNAUTHORIZED         => [
217
-                        'api_code' => BaseApiCodes::EX_AUTHENTICATION_EXCEPTION(),
218
-                    ],
219
-                    // Required by ValidationException handler
220
-                    HttpResponse::HTTP_UNPROCESSABLE_ENTITY => [
221
-                        'api_code' => BaseApiCodes::EX_VALIDATION_EXCEPTION(),
222
-                    ],
223
-                    // default handler is mandatory. `default` entry MUST have both `api_code` and `http_code` set.
224
-                    'default'                               => [
225
-                        'api_code'  => BaseApiCodes::EX_HTTP_EXCEPTION(),
226
-                        'http_code' => HttpResponse::HTTP_BAD_REQUEST,
227
-                    ],
228
-                ],
229
-                // default handler is mandatory. `default` entry MUST have both `api_code` and `http_code` set.
230
-                'default'            => [
231
-                    'api_code'  => BaseApiCodes::EX_UNCAUGHT_EXCEPTION(),
232
-                    'http_code' => HttpResponse::HTTP_INTERNAL_SERVER_ERROR,
233
-                ],
234
-            ],
235
-        ];
236
-    }
237
-
238
-    /**
239
-     * Returns ExceptionHandlerHelper configration array with user configuration merged into built-in defaults.
240
-     *
241
-     * @return array
242
-     */
243
-    protected
244
-    static function getExceptionHandlerConfig(): array
245
-    {
246
-        return Util::mergeConfig(static::getExceptionHandlerDefaultConfig(),
247
-            \Config::get(ResponseBuilder::CONF_KEY_EXCEPTION_HANDLER, []));
248
-    }
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 = static::getExceptionHandlerConfig()['map'];
42
+
43
+		if ($ex instanceof HttpException) {
44
+			// Check if we have any exception configuration for this particular Http status code.
45
+			// This confing entry is guaranted to exist (at least 'default'). Enforced by tests.
46
+			$http_code = $ex->getStatusCode();
47
+			$ex_cfg = $cfg[ HttpException::class ][ $http_code ] ?? null;
48
+			$ex_cfg = $ex_cfg ?? $cfg[ HttpException::class ]['default'];
49
+			$result = self::processException($ex, $ex_cfg, $http_code);
50
+		} elseif ($ex instanceof ValidationException) {
51
+			// This entry is guaranted to exist. Enforced by tests.
52
+			$http_code = HttpResponse::HTTP_UNPROCESSABLE_ENTITY;
53
+			$ex_cfg = $cfg[ HttpException::class ][ $http_code ];
54
+			$result = self::processException($ex, $ex_cfg, $http_code);
55
+		}
56
+
57
+		if ($result === null) {
58
+			// This entry is guaranted to exist. Enforced by tests.
59
+			$http_code = HttpResponse::HTTP_INTERNAL_SERVER_ERROR;
60
+			$ex_cfg = $cfg['default'];
61
+			$result = self::processException($ex, $ex_cfg, $http_code);
62
+		}
63
+
64
+		return $result;
65
+	}
66
+
67
+	protected static function processException(\Exception $ex, array $ex_cfg, int $http_code)
68
+	{
69
+		$api_code = $ex_cfg['api_code'];
70
+		$http_code = $ex_cfg['http_code'] ?? $http_code;
71
+		$msg_key = $ex_cfg['msg_key'] ?? null;
72
+		$msg_enforce = $ex_cfg['msg_enforce'] ?? false;
73
+
74
+		// No message key, let's get exception message and if there's nothing useful, fallback to built-in one.
75
+		$error_message = $ex->getMessage();
76
+		$placeholders = [
77
+			'api_code' => $api_code,
78
+			'message'  => ($error_message !== '') ? $error_message : '???',
79
+		];
80
+
81
+		// shall we enforce error message?
82
+		if ($msg_enforce) {
83
+			// yes, please.
84
+			if ($msg_key === null) {
85
+				// there's no msg_key configured for this exact code, so let's obtain our default message
86
+				$error_message = ($msg_key === null) ? static::getErrorMessageForException($ex, $http_code, $placeholders) : Lang::get($msg_key, $placeholders);
87
+			}
88
+		} else {
89
+			// nothing enforced, handling pipeline: ex_message -> user_defined msg -> http_ex -> default
90
+			if ($error_message === '') {
91
+				$error_message = ($msg_key === null) ? static::getErrorMessageForException($ex, $http_code, $placeholders) : Lang::get($msg_key, $placeholders);
92
+			}
93
+		}
94
+
95
+		// Lets' try to build the error response with what we have now
96
+		$result = static::error($ex, $api_code, $http_code, $error_message);
97
+
98
+		if ($result === null) {
99
+			$ex_cfg = $cfg[ HttpException::class ][ $http_code ];
100
+			$api_code = $ex_cfg['api_code'] ?? BaseApiCodes::EX_VALIDATION_EXCEPTION();
101
+			$http_code = $ex_cfg['http_code'] ?? $http_code;
102
+			$result = static::error($ex, $api_code, $http_code, $error_message);
103
+		}
104
+
105
+		return $result;
106
+	}
107
+
108
+	/**
109
+	 * Returns error message for given exception. If exception message is empty, then falls back to
110
+	 * `default` handler either for HttpException (if $ex is instance of it), or generic `default`
111
+	 * config.
112
+	 *
113
+	 * @param \Exception $ex
114
+	 * @param int        $http_code
115
+	 * @param array      $placeholders
116
+	 *
117
+	 * @return string
118
+	 */
119
+	protected static function getErrorMessageForException(\Exception $ex, int $http_code, array $placeholders): string
120
+	{
121
+		// exception message is uselss, lets go deeper
122
+		if ($ex instanceof HttpException) {
123
+			$error_message = Lang::get("response-builder::builder.http_{$http_code}", $placeholders);
124
+		} else {
125
+			// Still got nothing? Fall back to built-in generic message for this type of exception.
126
+			$key = BaseApiCodes::getCodeMessageKey(($ex instanceof HttpException)
127
+				? BaseApiCodes::EX_HTTP_EXCEPTION() : BaseApiCodes::NO_ERROR_MESSAGE());
128
+			$error_message = Lang::get($key, $placeholders);
129
+		}
130
+
131
+		return $error_message;
132
+	}
133
+
134
+	/**
135
+	 * Convert an authentication exception into an unauthenticated response.
136
+	 *
137
+	 * @param \Illuminate\Http\Request                 $request
138
+	 * @param \Illuminate\Auth\AuthenticationException $exception
139
+	 *
140
+	 * @return HttpResponse
141
+	 */
142
+	protected function unauthenticated(/** @scrutinizer ignore-unused */ $request,
143
+																		 AuthException $exception): HttpResponse
144
+	{
145
+		// This entry is guaranted to exist. Enforced by tests.
146
+		$http_code = HttpResponse::HTTP_UNAUTHORIZED;
147
+		$cfg = static::getExceptionHandlerConfig()['map'][ HttpException::class ][ $http_code ];
148
+
149
+		return static::processException($exception, $cfg, $http_code);
150
+	}
151
+
152
+	/**
153
+	 * Process single error and produce valid API response.
154
+	 *
155
+	 * @param Exception $ex Exception to be handled.
156
+	 * @param integer   $api_code
157
+	 * @param integer   $http_code
158
+	 *
159
+	 * @return HttpResponse
160
+	 */
161
+	protected static function error(Exception $ex,
162
+									int $api_code, int $http_code = null, string $error_message): HttpResponse
163
+	{
164
+		$ex_http_code = ($ex instanceof HttpException) ? $ex->getStatusCode() : $ex->getCode();
165
+		$http_code = $http_code ?? $ex_http_code;
166
+
167
+		// Check if we now have valid HTTP error code for this case or need to make one up.
168
+		// We cannot throw any exception if codes are invalid because we are in Exception Handler already.
169
+		if ($http_code < ResponseBuilder::ERROR_HTTP_CODE_MIN) {
170
+			// Not a valid code, let's try to get the exception status.
171
+			$http_code = $ex_http_code;
172
+		}
173
+		// Can it be considered a valid HTTP error code?
174
+		if ($http_code < ResponseBuilder::ERROR_HTTP_CODE_MIN) {
175
+			// We now handle uncaught exception, so we cannot throw another one if there's
176
+			// something wrong with the configuration, so we try to recover and use built-in
177
+			// codes instead.
178
+			// FIXME: We should log this event as (warning or error?)
179
+			$http_code = ResponseBuilder::DEFAULT_HTTP_CODE_ERROR;
180
+		}
181
+
182
+		// If we have trace data debugging enabled, let's gather some debug info and add to the response.
183
+		$debug_data = null;
184
+		if (Config::get(ResponseBuilder::CONF_KEY_DEBUG_EX_TRACE_ENABLED, false)) {
185
+			$debug_data = [
186
+				Config::get(ResponseBuilder::CONF_KEY_DEBUG_EX_TRACE_KEY, ResponseBuilder::KEY_TRACE) => [
187
+					ResponseBuilder::KEY_CLASS => get_class($ex),
188
+					ResponseBuilder::KEY_FILE  => $ex->getFile(),
189
+					ResponseBuilder::KEY_LINE  => $ex->getLine(),
190
+				],
191
+			];
192
+		}
193
+
194
+		// If this is ValidationException, add all the messages from MessageBag to the data node.
195
+		$data = null;
196
+		if ($ex instanceof ValidationException) {
197
+			/** @var ValidationException $ex */
198
+			$data = [ResponseBuilder::KEY_MESSAGES => $ex->validator->errors()->messages()];
199
+		}
200
+
201
+		return Builder::error($api_code)
202
+			->withMessage($error_message)
203
+			->withHttpCode($http_code)
204
+			->withData($data)
205
+			->withDebugData($debug_data)
206
+			->build();
207
+	}
208
+
209
+	protected
210
+	static function getExceptionHandlerDefaultConfig(): array
211
+	{
212
+		return [
213
+			'map' => [
214
+				HttpException::class => [
215
+					// used by unauthenticated() to obtain api and http code for the exception
216
+					HttpResponse::HTTP_UNAUTHORIZED         => [
217
+						'api_code' => BaseApiCodes::EX_AUTHENTICATION_EXCEPTION(),
218
+					],
219
+					// Required by ValidationException handler
220
+					HttpResponse::HTTP_UNPROCESSABLE_ENTITY => [
221
+						'api_code' => BaseApiCodes::EX_VALIDATION_EXCEPTION(),
222
+					],
223
+					// default handler is mandatory. `default` entry MUST have both `api_code` and `http_code` set.
224
+					'default'                               => [
225
+						'api_code'  => BaseApiCodes::EX_HTTP_EXCEPTION(),
226
+						'http_code' => HttpResponse::HTTP_BAD_REQUEST,
227
+					],
228
+				],
229
+				// default handler is mandatory. `default` entry MUST have both `api_code` and `http_code` set.
230
+				'default'            => [
231
+					'api_code'  => BaseApiCodes::EX_UNCAUGHT_EXCEPTION(),
232
+					'http_code' => HttpResponse::HTTP_INTERNAL_SERVER_ERROR,
233
+				],
234
+			],
235
+		];
236
+	}
237
+
238
+	/**
239
+	 * Returns ExceptionHandlerHelper configration array with user configuration merged into built-in defaults.
240
+	 *
241
+	 * @return array
242
+	 */
243
+	protected
244
+	static function getExceptionHandlerConfig(): array
245
+	{
246
+		return Util::mergeConfig(static::getExceptionHandlerDefaultConfig(),
247
+			\Config::get(ResponseBuilder::CONF_KEY_EXCEPTION_HANDLER, []));
248
+	}
249 249
 
250 250
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -44,13 +44,13 @@  discard block
 block discarded – undo
44 44
             // Check if we have any exception configuration for this particular Http status code.
45 45
             // This confing entry is guaranted to exist (at least 'default'). Enforced by tests.
46 46
             $http_code = $ex->getStatusCode();
47
-            $ex_cfg = $cfg[ HttpException::class ][ $http_code ] ?? null;
48
-            $ex_cfg = $ex_cfg ?? $cfg[ HttpException::class ]['default'];
47
+            $ex_cfg = $cfg[HttpException::class][$http_code] ?? null;
48
+            $ex_cfg = $ex_cfg ?? $cfg[HttpException::class]['default'];
49 49
             $result = self::processException($ex, $ex_cfg, $http_code);
50 50
         } elseif ($ex instanceof ValidationException) {
51 51
             // This entry is guaranted to exist. Enforced by tests.
52 52
             $http_code = HttpResponse::HTTP_UNPROCESSABLE_ENTITY;
53
-            $ex_cfg = $cfg[ HttpException::class ][ $http_code ];
53
+            $ex_cfg = $cfg[HttpException::class][$http_code];
54 54
             $result = self::processException($ex, $ex_cfg, $http_code);
55 55
         }
56 56
 
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
         $result = static::error($ex, $api_code, $http_code, $error_message);
97 97
 
98 98
         if ($result === null) {
99
-            $ex_cfg = $cfg[ HttpException::class ][ $http_code ];
99
+            $ex_cfg = $cfg[HttpException::class][$http_code];
100 100
             $api_code = $ex_cfg['api_code'] ?? BaseApiCodes::EX_VALIDATION_EXCEPTION();
101 101
             $http_code = $ex_cfg['http_code'] ?? $http_code;
102 102
             $result = static::error($ex, $api_code, $http_code, $error_message);
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
     {
145 145
         // This entry is guaranted to exist. Enforced by tests.
146 146
         $http_code = HttpResponse::HTTP_UNAUTHORIZED;
147
-        $cfg = static::getExceptionHandlerConfig()['map'][ HttpException::class ][ $http_code ];
147
+        $cfg = static::getExceptionHandlerConfig()['map'][HttpException::class][$http_code];
148 148
 
149 149
         return static::processException($exception, $cfg, $http_code);
150 150
     }
Please login to merge, or discard this patch.
src/lang/fa/builder.php 1 patch
Indentation   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -10,56 +10,56 @@
 block discarded – undo
10 10
  */
11 11
 return [
12 12
 
13
-    'ok'                       => 'موفق',
14
-    'no_error_message'         => 'خطای شماره :api_code',
13
+	'ok'                       => 'موفق',
14
+	'no_error_message'         => 'خطای شماره :api_code',
15 15
 
16
-    // can be used by Exception Handler (if enabled)
17
-    'uncaught_exception'       => 'استثناء مدیریت نشده :message',
18
-    // we talking API call here, hence we have http_not_found
19
-    'http_exception'           => 'استثناء HTTP :message',
16
+	// can be used by Exception Handler (if enabled)
17
+	'uncaught_exception'       => 'استثناء مدیریت نشده :message',
18
+	// we talking API call here, hence we have http_not_found
19
+	'http_exception'           => 'استثناء HTTP :message',
20 20
 
21
-    // HttpException handler (added in 6.4.0)
22
-    // Error messages for HttpException caught w/o custom messages
23
-    // https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
24
-    'http_400'                 => 'Bad Request',
25
-    'http_401'                 => 'اجازه دسترسی ندارید',
26
-    'http_402'                 => 'Payment Required',
27
-    'http_403'                 => 'Forbidden',
28
-    'http_404'                 => 'Not Found',
29
-    'http_405'                 => 'Method Not Allowed',
30
-    'http_406'                 => 'Not Acceptable',
31
-    'http_407'                 => 'Proxy Authentication Required',
32
-    'http_408'                 => 'Request Timeout',
33
-    'http_409'                 => 'Conflict',
34
-    'http_410'                 => 'Gone',
35
-    'http_411'                 => 'Length Required',
36
-    'http_412'                 => 'Precondition Failed',
37
-    'http_413'                 => 'Payload Too Large',
38
-    'http_414'                 => 'URI Too Long',
39
-    'http_415'                 => 'Unsupported Media Type',
40
-    'http_416'                 => 'Range Not Satisfiable',
41
-    'http_417'                 => 'Expectation Failed',
42
-    'http_421'                 => 'Misdirected Request',
43
-    'http_422'                 => 'داده معتبر نیست',
44
-    'http_423'                 => 'Locked',
45
-    'http_424'                 => 'Failed Dependency',
46
-    'http_425'                 => 'Too Early',
47
-    'http_426'                 => 'Upgrade Required',
48
-    'http_428'                 => 'Precondition Required',
49
-    'http_429'                 => 'Too Many Requests',
50
-    'http_431'                 => 'Request Header Fields Too Large',
51
-    'http_451'                 => 'Unavailable For Legal Reasons',
52
-    'http_500'                 => 'Internal Server Error',
53
-    'http_501'                 => 'Not Implemented',
54
-    'http_502'                 => 'Bad Gateway',
55
-    'http_503'                 => 'Service Unavailable',
56
-    'http_504'                 => 'Gateway Timeout',
57
-    'http_505'                 => 'HTTP Version Not Supported',
58
-    'http_506'                 => 'Variant Also Negotiates',
59
-    'http_507'                 => 'Insufficient Storage',
60
-    'http_508'                 => 'Loop Detected',
61
-    'http_509'                 => 'Unassigned',
62
-    'http_510'                 => 'Not Extended',
63
-    'http_511'                 => 'Network Authentication Required',
21
+	// HttpException handler (added in 6.4.0)
22
+	// Error messages for HttpException caught w/o custom messages
23
+	// https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
24
+	'http_400'                 => 'Bad Request',
25
+	'http_401'                 => 'اجازه دسترسی ندارید',
26
+	'http_402'                 => 'Payment Required',
27
+	'http_403'                 => 'Forbidden',
28
+	'http_404'                 => 'Not Found',
29
+	'http_405'                 => 'Method Not Allowed',
30
+	'http_406'                 => 'Not Acceptable',
31
+	'http_407'                 => 'Proxy Authentication Required',
32
+	'http_408'                 => 'Request Timeout',
33
+	'http_409'                 => 'Conflict',
34
+	'http_410'                 => 'Gone',
35
+	'http_411'                 => 'Length Required',
36
+	'http_412'                 => 'Precondition Failed',
37
+	'http_413'                 => 'Payload Too Large',
38
+	'http_414'                 => 'URI Too Long',
39
+	'http_415'                 => 'Unsupported Media Type',
40
+	'http_416'                 => 'Range Not Satisfiable',
41
+	'http_417'                 => 'Expectation Failed',
42
+	'http_421'                 => 'Misdirected Request',
43
+	'http_422'                 => 'داده معتبر نیست',
44
+	'http_423'                 => 'Locked',
45
+	'http_424'                 => 'Failed Dependency',
46
+	'http_425'                 => 'Too Early',
47
+	'http_426'                 => 'Upgrade Required',
48
+	'http_428'                 => 'Precondition Required',
49
+	'http_429'                 => 'Too Many Requests',
50
+	'http_431'                 => 'Request Header Fields Too Large',
51
+	'http_451'                 => 'Unavailable For Legal Reasons',
52
+	'http_500'                 => 'Internal Server Error',
53
+	'http_501'                 => 'Not Implemented',
54
+	'http_502'                 => 'Bad Gateway',
55
+	'http_503'                 => 'Service Unavailable',
56
+	'http_504'                 => 'Gateway Timeout',
57
+	'http_505'                 => 'HTTP Version Not Supported',
58
+	'http_506'                 => 'Variant Also Negotiates',
59
+	'http_507'                 => 'Insufficient Storage',
60
+	'http_508'                 => 'Loop Detected',
61
+	'http_509'                 => 'Unassigned',
62
+	'http_510'                 => 'Not Extended',
63
+	'http_511'                 => 'Network Authentication Required',
64 64
 ];
65 65
 
Please login to merge, or discard this patch.
src/Util.php 1 patch
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -15,59 +15,59 @@
 block discarded – undo
15 15
  */
16 16
 final class Util
17 17
 {
18
-    /**
19
-     * Merges the configs together and takes multi-dimensional arrays into account.
20
-     * Support for multi-dimensional config array. Built-in config merge only supports flat arrays.
21
-     * Throws \RuntimeException if arrays stucture causes type conflics (i.e. you want to merge
22
-     * array with int).
23
-     *
24
-     * @param array $original Array to merge other array into. Usually default values to overwrite.
25
-     * @param array $merging  Array with items to be merged into $original, overriding (primitives) or merging
26
-     *                        (arrays) entries in destination array.
27
-     *
28
-     * @return array
29
-     *
30
-     * @throws \RuntimeException
31
-     */
32
-    public static function mergeConfig(array $original, array $merging): array
33
-    {
34
-        $array = $original;
35
-        foreach ($merging as $m_key => $m_val) {
36
-            if (array_key_exists($m_key, $original)) {
37
-                $orig_type = gettype($original[ $m_key ]);
38
-                $m_type = gettype($m_val);
39
-                if ($orig_type !== $m_type) {
40
-                    throw new \RuntimeException(
41
-                        "Incompatible types. Cannot merge {$m_type} into {$orig_type} (key '{$m_key}').");
42
-                }
18
+	/**
19
+	 * Merges the configs together and takes multi-dimensional arrays into account.
20
+	 * Support for multi-dimensional config array. Built-in config merge only supports flat arrays.
21
+	 * Throws \RuntimeException if arrays stucture causes type conflics (i.e. you want to merge
22
+	 * array with int).
23
+	 *
24
+	 * @param array $original Array to merge other array into. Usually default values to overwrite.
25
+	 * @param array $merging  Array with items to be merged into $original, overriding (primitives) or merging
26
+	 *                        (arrays) entries in destination array.
27
+	 *
28
+	 * @return array
29
+	 *
30
+	 * @throws \RuntimeException
31
+	 */
32
+	public static function mergeConfig(array $original, array $merging): array
33
+	{
34
+		$array = $original;
35
+		foreach ($merging as $m_key => $m_val) {
36
+			if (array_key_exists($m_key, $original)) {
37
+				$orig_type = gettype($original[ $m_key ]);
38
+				$m_type = gettype($m_val);
39
+				if ($orig_type !== $m_type) {
40
+					throw new \RuntimeException(
41
+						"Incompatible types. Cannot merge {$m_type} into {$orig_type} (key '{$m_key}').");
42
+				}
43 43
 
44
-                if (is_array($merging[ $m_key ])) {
45
-                    $array[ $m_key ] = static::mergeConfig($original[ $m_key ], $m_val);
46
-                } else {
47
-                    $array[ $m_key ] = $m_val;
48
-                }
49
-            } else {
50
-                $array[ $m_key ] = $m_val;
51
-            }
52
-        }
44
+				if (is_array($merging[ $m_key ])) {
45
+					$array[ $m_key ] = static::mergeConfig($original[ $m_key ], $m_val);
46
+				} else {
47
+					$array[ $m_key ] = $m_val;
48
+				}
49
+			} else {
50
+				$array[ $m_key ] = $m_val;
51
+			}
52
+		}
53 53
 
54
-        return $array;
55
-    }
54
+		return $array;
55
+	}
56 56
 
57
-    /**
58
-     * Sorts array by value, assuming value is an array and contains `pri` key with integer (positive/negative)
59
-     * value which is used for sorting higher -> lower priority.
60
-     *
61
-     * @param array &$array
62
-     */
63
-    public static function sortArrayByPri(array &$array): void
64
-    {
65
-        // we now need to sort 'converter' node by priority
66
-        uasort($array, function($array_a, $array_b) {
67
-            $pri_a = $array_a['pri'] ?? 0;
68
-            $pri_b = $array_b['pri'] ?? 0;
57
+	/**
58
+	 * Sorts array by value, assuming value is an array and contains `pri` key with integer (positive/negative)
59
+	 * value which is used for sorting higher -> lower priority.
60
+	 *
61
+	 * @param array &$array
62
+	 */
63
+	public static function sortArrayByPri(array &$array): void
64
+	{
65
+		// we now need to sort 'converter' node by priority
66
+		uasort($array, function($array_a, $array_b) {
67
+			$pri_a = $array_a['pri'] ?? 0;
68
+			$pri_b = $array_b['pri'] ?? 0;
69 69
 
70
-            return $pri_b <=> $pri_a;
71
-        });
72
-    }
70
+			return $pri_b <=> $pri_a;
71
+		});
72
+	}
73 73
 }
Please login to merge, or discard this patch.
src/ResponseBuilderServiceProvider.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -25,56 +25,56 @@
 block discarded – undo
25 25
 
26 26
 class ResponseBuilderServiceProvider extends ServiceProvider
27 27
 {
28
-    protected $config_files = [
29
-        'response_builder.php',
30
-    ];
28
+	protected $config_files = [
29
+		'response_builder.php',
30
+	];
31 31
 
32
-    /**
33
-     * Register bindings in the container.
34
-     *
35
-     * @return void
36
-     */
37
-    public function register()
38
-    {
39
-        foreach ($this->config_files as $file) {
40
-            $this->mergeConfigFrom(__DIR__ . "/../config/{$file}", ResponseBuilder::CONF_CONFIG);
41
-        }
42
-    }
32
+	/**
33
+	 * Register bindings in the container.
34
+	 *
35
+	 * @return void
36
+	 */
37
+	public function register()
38
+	{
39
+		foreach ($this->config_files as $file) {
40
+			$this->mergeConfigFrom(__DIR__ . "/../config/{$file}", ResponseBuilder::CONF_CONFIG);
41
+		}
42
+	}
43 43
 
44
-    /**
45
-     * Sets up package resources
46
-     *
47
-     * @return void
48
-     */
49
-    public function boot()
50
-    {
51
-        $this->loadTranslationsFrom(__DIR__ . '/lang', 'response-builder');
44
+	/**
45
+	 * Sets up package resources
46
+	 *
47
+	 * @return void
48
+	 */
49
+	public function boot()
50
+	{
51
+		$this->loadTranslationsFrom(__DIR__ . '/lang', 'response-builder');
52 52
 
53
-        foreach ($this->config_files as $file) {
54
-            $this->publishes([__DIR__ . "/../config/{$file}" => config_path($file)]);
55
-        }
56
-    }
53
+		foreach ($this->config_files as $file) {
54
+			$this->publishes([__DIR__ . "/../config/{$file}" => config_path($file)]);
55
+		}
56
+	}
57 57
 
58
-    /**
59
-     * Merge the given configuration with the existing configuration.
60
-     *
61
-     * @param string $path
62
-     * @param string $key
63
-     *
64
-     * @return void
65
-     */
66
-    protected function mergeConfigFrom($path, $key)
67
-    {
68
-        $defaults = require $path;
69
-        $config = $this->app['config']->get($key, []);
58
+	/**
59
+	 * Merge the given configuration with the existing configuration.
60
+	 *
61
+	 * @param string $path
62
+	 * @param string $key
63
+	 *
64
+	 * @return void
65
+	 */
66
+	protected function mergeConfigFrom($path, $key)
67
+	{
68
+		$defaults = require $path;
69
+		$config = $this->app['config']->get($key, []);
70 70
 
71
-        $merged_config = Util::mergeConfig($defaults, $config);
71
+		$merged_config = Util::mergeConfig($defaults, $config);
72 72
 
73
-        if (array_key_exists('converter', $merged_config)) {
74
-            Util::sortArrayByPri($merged_config['converter']);
75
-        }
73
+		if (array_key_exists('converter', $merged_config)) {
74
+			Util::sortArrayByPri($merged_config['converter']);
75
+		}
76 76
 
77
-        $this->app['config']->set($key, $merged_config);
78
-    }
77
+		$this->app['config']->set($key, $merged_config);
78
+	}
79 79
 
80 80
 }
Please login to merge, or discard this patch.
src/Builder.php 2 patches
Indentation   +273 added lines, -273 removed lines patch added patch discarded remove patch
@@ -24,277 +24,277 @@
 block discarded – undo
24 24
  */
25 25
 class Builder
26 26
 {
27
-    /** @var bool */
28
-    protected $success = false;
29
-
30
-    /** @var int|null */
31
-    protected $api_code = null;
32
-
33
-    /** @var int|null */
34
-    protected $http_code = null;
35
-
36
-    /** @var mixed */
37
-    protected $data = null;
38
-
39
-    /** @var string */
40
-    protected $message = null;
41
-
42
-    /** @var array */
43
-    protected $placeholders = [];
44
-
45
-    /** @var int|null */
46
-    protected $json_opts = null;
47
-
48
-    /** @var array */
49
-    protected $debug_data = [];
50
-
51
-    /** @var array */
52
-    protected $http_headers = [];
53
-
54
-    /**
55
-     * Private constructor. use success() and error() methods to obtain instance of Builder.
56
-     *
57
-     * @param bool $success
58
-     * @param int  $api_code
59
-     */
60
-    protected function __construct(bool $success, int $api_code)
61
-    {
62
-        $this->success = $success;
63
-        $this->api_code = $api_code;
64
-    }
65
-
66
-    public static function success(int $api_code = null): self
67
-    {
68
-        return new self(true, $api_code ?? BaseApiCodes::OK());
69
-    }
70
-
71
-    public static function error(int $api_code): self
72
-    {
73
-        $code_ok = BaseApiCodes::OK();
74
-        if ($api_code !== $code_ok) {
75
-            Validator::assertIsIntRange('api_code', $api_code, BaseApiCodes::getMinCode(), BaseApiCodes::getMaxCode());
76
-        }
77
-        if ($api_code === $code_ok) {
78
-            throw new \InvalidArgumentException(
79
-                "Error response cannot use api_code of value {$code_ok} which is reserved for OK");
80
-        }
81
-
82
-        return new self(false, $api_code);
83
-    }
84
-
85
-    public function withHttpCode(int $http_code = null): self
86
-    {
87
-        Validator::assertIsType('http_code', $http_code, [Validator::TYPE_INTEGER,
88
-                                                          Validator::TYPE_NULL]);
89
-        $this->http_code = $http_code;
90
-
91
-        return $this;
92
-    }
93
-
94
-    public function withData($data = null): self
95
-    {
96
-        Validator::assertIsType('data', $data, [Validator::TYPE_ARRAY,
97
-                                                Validator::TYPE_OBJECT,
98
-                                                Validator::TYPE_NULL]);
99
-        $this->data = $data;
100
-
101
-        return $this;
102
-    }
103
-
104
-    public function withJsonOptions(int $json_opts = null): self
105
-    {
106
-        Validator::assertIsType('json_opts', $json_opts, [Validator::TYPE_INTEGER,
107
-                                                          Validator::TYPE_NULL]);
108
-        $this->json_opts = $json_opts;
109
-
110
-        return $this;
111
-    }
112
-
113
-    public function withDebugData(array $debug_data = null): self
114
-    {
115
-        Validator::assertIsType('$debug_data', $debug_data, [Validator::TYPE_ARRAY,
116
-                                                             Validator::TYPE_NULL]);
117
-        $this->debug_data = $debug_data;
118
-
119
-        return $this;
120
-    }
121
-
122
-    public function withMessage(string $msg = null): self
123
-    {
124
-        Validator::assertIsType('message', $msg, [Validator::TYPE_STRING,
125
-                                                  Validator::TYPE_NULL]);
126
-        $this->message = $msg;
127
-
128
-        return $this;
129
-    }
130
-
131
-    public function withPlaceholders(array $placeholders = null): self
132
-    {
133
-        $this->placeholders = $placeholders;
134
-
135
-        return $this;
136
-    }
137
-
138
-    public function withHttpHeaders(array $http_headers = null): self
139
-    {
140
-        $this->http_headers = $http_headers ?? [];
141
-
142
-        return $this;
143
-    }
144
-
145
-    public function build(): HttpResponse
146
-    {
147
-        $api_code = $this->api_code;
148
-        Validator::assertIsInt('api_code', $api_code);
149
-
150
-        $msg_or_api_code = $this->message ?? $api_code;
151
-        $http_headers = $this->http_headers ?? [];
152
-
153
-        if ($this->success) {
154
-            $api_code = $api_code ?? BaseApiCodes::OK();
155
-            $http_code = $this->http_code ?? ResponseBuilder::DEFAULT_HTTP_CODE_OK;
156
-
157
-            Validator::assertOkHttpCode($http_code);
158
-
159
-            $result = $this->make($this->success, $api_code, $msg_or_api_code, $this->data, $http_code,
160
-                $this->placeholders, $http_headers, $this->json_opts);
161
-        } else {
162
-            $http_code = $this->http_code ?? ResponseBuilder::DEFAULT_HTTP_CODE_ERROR;
163
-
164
-            Validator::assertErrorHttpCode($http_code);
165
-
166
-            $result = $this->make(false, $api_code, $msg_or_api_code, $this->data, $http_code,
167
-                $this->placeholders, $this->http_headers, $this->json_opts, $this->debug_data);
168
-
169
-        }
170
-
171
-        return $result;
172
-    }
173
-
174
-
175
-    /**
176
-     * @param boolean           $success         @true if response reports successful operation, @false otherwise.
177
-     * @param integer           $api_code        Your API code to be returned with the response object.
178
-     * @param string|integer    $msg_or_api_code message string or valid API code to get message for
179
-     * @param object|array|null $data            optional additional data to be included in response object
180
-     * @param integer|null      $http_code       HTTP code for the HttpResponse or @null for either DEFAULT_HTTP_CODE_OK
181
-     *                                           or DEFAULT_HTTP_CODE_ERROR depending on the $success.
182
-     * @param array|null        $placeholders    Placeholders passed to Lang::get() for message placeholders
183
-     *                                           substitution or @null if none.
184
-     * @param array|null        $http_headers    Optional HTTP headers to be returned in the response.
185
-     * @param integer|null      $json_opts       See http://php.net/manual/en/function.json-encode.php for supported
186
-     *                                           options or pass @null to use value from your config (or defaults).
187
-     * @param array|null        $debug_data      Optional debug data array to be added to returned JSON.
188
-     *
189
-     * @return HttpResponse
190
-     *
191
-     * @throws \InvalidArgumentException If $api_code is neither a string nor valid integer code.
192
-     * @throws \InvalidArgumentException if $data is an object of class that is not configured in "classes" mapping.
193
-     *
194
-     * @noinspection MoreThanThreeArgumentsInspection
195
-     */
196
-    protected function make(bool $success, int $api_code, $msg_or_api_code, $data = null,
197
-                            int $http_code = null, array $placeholders = null, array $http_headers = null,
198
-                            int $json_opts = null, array $debug_data = null): HttpResponse
199
-    {
200
-        $http_headers = $http_headers ?? [];
201
-        $http_code = $http_code ?? ($success ? ResponseBuilder::DEFAULT_HTTP_CODE_OK : ResponseBuilder::DEFAULT_HTTP_CODE_ERROR);
202
-        $json_opts = $json_opts ?? Config::get(ResponseBuilder::CONF_KEY_ENCODING_OPTIONS, ResponseBuilder::DEFAULT_ENCODING_OPTIONS);
203
-
204
-        Validator::assertIsInt('encoding_options', $json_opts);
205
-
206
-        Validator::assertIsInt('api_code', $api_code);
207
-        if (!BaseApiCodes::isCodeValid($api_code)) {
208
-            Validator::assertIsIntRange('api_code', $api_code, BaseApiCodes::getMinCode(), BaseApiCodes::getMaxCode());
209
-        }
210
-
211
-        return Response::json(
212
-            $this->buildResponse($success, $api_code, $msg_or_api_code, $placeholders, $data, $debug_data),
213
-            $http_code, $http_headers, $json_opts);
214
-    }
215
-
216
-    /**
217
-     * Creates standardised API response array. This is final method called in the whole pipeline before we
218
-     * return final JSON back to client. If you want to manipulate your response, this is the place to do that.
219
-     * If you set APP_DEBUG to true, 'code_hex' field will be additionally added to reported JSON for easier
220
-     * manual debugging.
221
-     *
222
-     * @param boolean           $success         @true if response reports successful operation, @false otherwise.
223
-     * @param integer           $api_code        Your API code to be returned with the response object.
224
-     * @param string|integer    $msg_or_api_code Message string or valid API code to get message for.
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            API response data if any
228
-     * @param array|null        $debug_data      optional debug data array to be added to returned JSON.
229
-     *
230
-     * @return array response ready to be encoded as json and sent back to client
231
-     *
232
-     * @throws \RuntimeException in case of missing or invalid "classes" mapping configuration
233
-     */
234
-    protected function buildResponse(bool $success, int $api_code,
235
-                                     $msg_or_api_code, array $placeholders = null,
236
-                                     $data = null, array $debug_data = null): array
237
-    {
238
-        // ensure $data is either @null, array or object of class with configured mapping.
239
-        $data = (new Converter())->convert($data);
240
-        if ($data !== null && !is_object($data)) {
241
-            // ensure we get object in final JSON structure in data node
242
-            $data = (object)$data;
243
-        }
244
-
245
-        // get human readable message for API code or use message string (if given instead of API code)
246
-        if (is_int($msg_or_api_code)) {
247
-            $message = $this->getMessageForApiCode($success, $msg_or_api_code, $placeholders);
248
-        } else {
249
-            Validator::assertIsString('message', $msg_or_api_code);
250
-            $message = $msg_or_api_code;
251
-        }
252
-
253
-        /** @noinspection PhpUndefinedClassInspection */
254
-        $response = [
255
-            ResponseBuilder::KEY_SUCCESS => $success,
256
-            ResponseBuilder::KEY_CODE    => $api_code,
257
-            ResponseBuilder::KEY_LOCALE  => \App::getLocale(),
258
-            ResponseBuilder::KEY_MESSAGE => $message,
259
-            ResponseBuilder::KEY_DATA    => $data,
260
-        ];
261
-
262
-        if ($debug_data !== null) {
263
-            $debug_key = Config::get(ResponseBuilder::CONF_KEY_DEBUG_DEBUG_KEY, ResponseBuilder::KEY_DEBUG);
264
-            $response[ $debug_key ] = $debug_data;
265
-        }
266
-
267
-        return $response;
268
-    }
269
-
270
-    /**
271
-     * If $msg_or_api_code is integer value, returns human readable message associated with that code (with
272
-     * fallback to built-in default string if no api code mapping is set. If $msg_or_api_code is a string,
273
-     * returns it unaltered.
274
-     *
275
-     * @param boolean    $success      @true if response reports successful operation, @false otherwise.
276
-     * @param integer    $api_code     Your API code to be returned with the response object.
277
-     * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders
278
-     *                                 substitution or @null if none.
279
-     *
280
-     * @return string
281
-     */
282
-    protected function getMessageForApiCode(bool $success, int $api_code, array $placeholders = null): string
283
-    {
284
-        // We got integer value here not a message string, so we need to check if we have the mapping for
285
-        // this string already configured.
286
-        $key = BaseApiCodes::getCodeMessageKey($api_code);
287
-        if ($key === null) {
288
-            // nope, let's get the default one instead, based of
289
-            $fallback_code = $success ? BaseApiCodes::OK() : BaseApiCodes::NO_ERROR_MESSAGE();
290
-            $key = BaseApiCodes::getCodeMessageKey($fallback_code);
291
-        }
292
-
293
-        $placeholders = $placeholders ?? [];
294
-        if (!array_key_exists('api_code', $placeholders)) {
295
-            $placeholders['api_code'] = $api_code;
296
-        }
297
-
298
-        return \Lang::get($key, $placeholders);
299
-    }
27
+	/** @var bool */
28
+	protected $success = false;
29
+
30
+	/** @var int|null */
31
+	protected $api_code = null;
32
+
33
+	/** @var int|null */
34
+	protected $http_code = null;
35
+
36
+	/** @var mixed */
37
+	protected $data = null;
38
+
39
+	/** @var string */
40
+	protected $message = null;
41
+
42
+	/** @var array */
43
+	protected $placeholders = [];
44
+
45
+	/** @var int|null */
46
+	protected $json_opts = null;
47
+
48
+	/** @var array */
49
+	protected $debug_data = [];
50
+
51
+	/** @var array */
52
+	protected $http_headers = [];
53
+
54
+	/**
55
+	 * Private constructor. use success() and error() methods to obtain instance of Builder.
56
+	 *
57
+	 * @param bool $success
58
+	 * @param int  $api_code
59
+	 */
60
+	protected function __construct(bool $success, int $api_code)
61
+	{
62
+		$this->success = $success;
63
+		$this->api_code = $api_code;
64
+	}
65
+
66
+	public static function success(int $api_code = null): self
67
+	{
68
+		return new self(true, $api_code ?? BaseApiCodes::OK());
69
+	}
70
+
71
+	public static function error(int $api_code): self
72
+	{
73
+		$code_ok = BaseApiCodes::OK();
74
+		if ($api_code !== $code_ok) {
75
+			Validator::assertIsIntRange('api_code', $api_code, BaseApiCodes::getMinCode(), BaseApiCodes::getMaxCode());
76
+		}
77
+		if ($api_code === $code_ok) {
78
+			throw new \InvalidArgumentException(
79
+				"Error response cannot use api_code of value {$code_ok} which is reserved for OK");
80
+		}
81
+
82
+		return new self(false, $api_code);
83
+	}
84
+
85
+	public function withHttpCode(int $http_code = null): self
86
+	{
87
+		Validator::assertIsType('http_code', $http_code, [Validator::TYPE_INTEGER,
88
+														  Validator::TYPE_NULL]);
89
+		$this->http_code = $http_code;
90
+
91
+		return $this;
92
+	}
93
+
94
+	public function withData($data = null): self
95
+	{
96
+		Validator::assertIsType('data', $data, [Validator::TYPE_ARRAY,
97
+												Validator::TYPE_OBJECT,
98
+												Validator::TYPE_NULL]);
99
+		$this->data = $data;
100
+
101
+		return $this;
102
+	}
103
+
104
+	public function withJsonOptions(int $json_opts = null): self
105
+	{
106
+		Validator::assertIsType('json_opts', $json_opts, [Validator::TYPE_INTEGER,
107
+														  Validator::TYPE_NULL]);
108
+		$this->json_opts = $json_opts;
109
+
110
+		return $this;
111
+	}
112
+
113
+	public function withDebugData(array $debug_data = null): self
114
+	{
115
+		Validator::assertIsType('$debug_data', $debug_data, [Validator::TYPE_ARRAY,
116
+															 Validator::TYPE_NULL]);
117
+		$this->debug_data = $debug_data;
118
+
119
+		return $this;
120
+	}
121
+
122
+	public function withMessage(string $msg = null): self
123
+	{
124
+		Validator::assertIsType('message', $msg, [Validator::TYPE_STRING,
125
+												  Validator::TYPE_NULL]);
126
+		$this->message = $msg;
127
+
128
+		return $this;
129
+	}
130
+
131
+	public function withPlaceholders(array $placeholders = null): self
132
+	{
133
+		$this->placeholders = $placeholders;
134
+
135
+		return $this;
136
+	}
137
+
138
+	public function withHttpHeaders(array $http_headers = null): self
139
+	{
140
+		$this->http_headers = $http_headers ?? [];
141
+
142
+		return $this;
143
+	}
144
+
145
+	public function build(): HttpResponse
146
+	{
147
+		$api_code = $this->api_code;
148
+		Validator::assertIsInt('api_code', $api_code);
149
+
150
+		$msg_or_api_code = $this->message ?? $api_code;
151
+		$http_headers = $this->http_headers ?? [];
152
+
153
+		if ($this->success) {
154
+			$api_code = $api_code ?? BaseApiCodes::OK();
155
+			$http_code = $this->http_code ?? ResponseBuilder::DEFAULT_HTTP_CODE_OK;
156
+
157
+			Validator::assertOkHttpCode($http_code);
158
+
159
+			$result = $this->make($this->success, $api_code, $msg_or_api_code, $this->data, $http_code,
160
+				$this->placeholders, $http_headers, $this->json_opts);
161
+		} else {
162
+			$http_code = $this->http_code ?? ResponseBuilder::DEFAULT_HTTP_CODE_ERROR;
163
+
164
+			Validator::assertErrorHttpCode($http_code);
165
+
166
+			$result = $this->make(false, $api_code, $msg_or_api_code, $this->data, $http_code,
167
+				$this->placeholders, $this->http_headers, $this->json_opts, $this->debug_data);
168
+
169
+		}
170
+
171
+		return $result;
172
+	}
173
+
174
+
175
+	/**
176
+	 * @param boolean           $success         @true if response reports successful operation, @false otherwise.
177
+	 * @param integer           $api_code        Your API code to be returned with the response object.
178
+	 * @param string|integer    $msg_or_api_code message string or valid API code to get message for
179
+	 * @param object|array|null $data            optional additional data to be included in response object
180
+	 * @param integer|null      $http_code       HTTP code for the HttpResponse or @null for either DEFAULT_HTTP_CODE_OK
181
+	 *                                           or DEFAULT_HTTP_CODE_ERROR depending on the $success.
182
+	 * @param array|null        $placeholders    Placeholders passed to Lang::get() for message placeholders
183
+	 *                                           substitution or @null if none.
184
+	 * @param array|null        $http_headers    Optional HTTP headers to be returned in the response.
185
+	 * @param integer|null      $json_opts       See http://php.net/manual/en/function.json-encode.php for supported
186
+	 *                                           options or pass @null to use value from your config (or defaults).
187
+	 * @param array|null        $debug_data      Optional debug data array to be added to returned JSON.
188
+	 *
189
+	 * @return HttpResponse
190
+	 *
191
+	 * @throws \InvalidArgumentException If $api_code is neither a string nor valid integer code.
192
+	 * @throws \InvalidArgumentException if $data is an object of class that is not configured in "classes" mapping.
193
+	 *
194
+	 * @noinspection MoreThanThreeArgumentsInspection
195
+	 */
196
+	protected function make(bool $success, int $api_code, $msg_or_api_code, $data = null,
197
+							int $http_code = null, array $placeholders = null, array $http_headers = null,
198
+							int $json_opts = null, array $debug_data = null): HttpResponse
199
+	{
200
+		$http_headers = $http_headers ?? [];
201
+		$http_code = $http_code ?? ($success ? ResponseBuilder::DEFAULT_HTTP_CODE_OK : ResponseBuilder::DEFAULT_HTTP_CODE_ERROR);
202
+		$json_opts = $json_opts ?? Config::get(ResponseBuilder::CONF_KEY_ENCODING_OPTIONS, ResponseBuilder::DEFAULT_ENCODING_OPTIONS);
203
+
204
+		Validator::assertIsInt('encoding_options', $json_opts);
205
+
206
+		Validator::assertIsInt('api_code', $api_code);
207
+		if (!BaseApiCodes::isCodeValid($api_code)) {
208
+			Validator::assertIsIntRange('api_code', $api_code, BaseApiCodes::getMinCode(), BaseApiCodes::getMaxCode());
209
+		}
210
+
211
+		return Response::json(
212
+			$this->buildResponse($success, $api_code, $msg_or_api_code, $placeholders, $data, $debug_data),
213
+			$http_code, $http_headers, $json_opts);
214
+	}
215
+
216
+	/**
217
+	 * Creates standardised API response array. This is final method called in the whole pipeline before we
218
+	 * return final JSON back to client. If you want to manipulate your response, this is the place to do that.
219
+	 * If you set APP_DEBUG to true, 'code_hex' field will be additionally added to reported JSON for easier
220
+	 * manual debugging.
221
+	 *
222
+	 * @param boolean           $success         @true if response reports successful operation, @false otherwise.
223
+	 * @param integer           $api_code        Your API code to be returned with the response object.
224
+	 * @param string|integer    $msg_or_api_code Message string or valid API code to get message for.
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            API response data if any
228
+	 * @param array|null        $debug_data      optional debug data array to be added to returned JSON.
229
+	 *
230
+	 * @return array response ready to be encoded as json and sent back to client
231
+	 *
232
+	 * @throws \RuntimeException in case of missing or invalid "classes" mapping configuration
233
+	 */
234
+	protected function buildResponse(bool $success, int $api_code,
235
+									 $msg_or_api_code, array $placeholders = null,
236
+									 $data = null, array $debug_data = null): array
237
+	{
238
+		// ensure $data is either @null, array or object of class with configured mapping.
239
+		$data = (new Converter())->convert($data);
240
+		if ($data !== null && !is_object($data)) {
241
+			// ensure we get object in final JSON structure in data node
242
+			$data = (object)$data;
243
+		}
244
+
245
+		// get human readable message for API code or use message string (if given instead of API code)
246
+		if (is_int($msg_or_api_code)) {
247
+			$message = $this->getMessageForApiCode($success, $msg_or_api_code, $placeholders);
248
+		} else {
249
+			Validator::assertIsString('message', $msg_or_api_code);
250
+			$message = $msg_or_api_code;
251
+		}
252
+
253
+		/** @noinspection PhpUndefinedClassInspection */
254
+		$response = [
255
+			ResponseBuilder::KEY_SUCCESS => $success,
256
+			ResponseBuilder::KEY_CODE    => $api_code,
257
+			ResponseBuilder::KEY_LOCALE  => \App::getLocale(),
258
+			ResponseBuilder::KEY_MESSAGE => $message,
259
+			ResponseBuilder::KEY_DATA    => $data,
260
+		];
261
+
262
+		if ($debug_data !== null) {
263
+			$debug_key = Config::get(ResponseBuilder::CONF_KEY_DEBUG_DEBUG_KEY, ResponseBuilder::KEY_DEBUG);
264
+			$response[ $debug_key ] = $debug_data;
265
+		}
266
+
267
+		return $response;
268
+	}
269
+
270
+	/**
271
+	 * If $msg_or_api_code is integer value, returns human readable message associated with that code (with
272
+	 * fallback to built-in default string if no api code mapping is set. If $msg_or_api_code is a string,
273
+	 * returns it unaltered.
274
+	 *
275
+	 * @param boolean    $success      @true if response reports successful operation, @false otherwise.
276
+	 * @param integer    $api_code     Your API code to be returned with the response object.
277
+	 * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders
278
+	 *                                 substitution or @null if none.
279
+	 *
280
+	 * @return string
281
+	 */
282
+	protected function getMessageForApiCode(bool $success, int $api_code, array $placeholders = null): string
283
+	{
284
+		// We got integer value here not a message string, so we need to check if we have the mapping for
285
+		// this string already configured.
286
+		$key = BaseApiCodes::getCodeMessageKey($api_code);
287
+		if ($key === null) {
288
+			// nope, let's get the default one instead, based of
289
+			$fallback_code = $success ? BaseApiCodes::OK() : BaseApiCodes::NO_ERROR_MESSAGE();
290
+			$key = BaseApiCodes::getCodeMessageKey($fallback_code);
291
+		}
292
+
293
+		$placeholders = $placeholders ?? [];
294
+		if (!array_key_exists('api_code', $placeholders)) {
295
+			$placeholders['api_code'] = $api_code;
296
+		}
297
+
298
+		return \Lang::get($key, $placeholders);
299
+	}
300 300
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
         $data = (new Converter())->convert($data);
240 240
         if ($data !== null && !is_object($data)) {
241 241
             // ensure we get object in final JSON structure in data node
242
-            $data = (object)$data;
242
+            $data = (object) $data;
243 243
         }
244 244
 
245 245
         // get human readable message for API code or use message string (if given instead of API code)
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 
262 262
         if ($debug_data !== null) {
263 263
             $debug_key = Config::get(ResponseBuilder::CONF_KEY_DEBUG_DEBUG_KEY, ResponseBuilder::KEY_DEBUG);
264
-            $response[ $debug_key ] = $debug_data;
264
+            $response[$debug_key] = $debug_data;
265 265
         }
266 266
 
267 267
         return $response;
Please login to merge, or discard this patch.