Passed
Push — dev ( 424ba7...b88f8d )
by Marcin
07:00
created
src/lang/en/builder.php 1 patch
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -10,56 +10,56 @@
 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',
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 51
 
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',
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/lang/pl/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'         => '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',
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 51
 
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',
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
 ];
Please login to merge, or discard this patch.
src/ExceptionHandlers/HttpExceptionHandler.php 1 patch
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -42,12 +42,12 @@
 block discarded – undo
42 42
 		$config = \array_replace($default_config, $user_config);
43 43
 
44 44
 		$http_code = $ex->getStatusCode();
45
-		$result = $config[ $http_code ] ?? null;
45
+		$result = $config[$http_code] ?? null;
46 46
 
47 47
 		// If we do not have dedicated entry fort this particular http_code,
48 48
 		// fall back to default value.
49 49
 		if ($result === null) {
50
-			$result = $config[ ResponseBuilder::KEY_DEFAULT ];
50
+			$result = $config[ResponseBuilder::KEY_DEFAULT];
51 51
 		}
52 52
 
53 53
 		// Some defaults to fall back to if not set in user config.
Please login to merge, or discard this patch.
src/ResponseBuilder.php 2 patches
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
 	 * @return HttpResponse
85 85
 	 */
86 86
 	public static function success($data = null, $api_code = null, array $placeholders = null,
87
-	                               int $http_code = null, int $json_opts = null): HttpResponse
87
+								   int $http_code = null, int $json_opts = null): HttpResponse
88 88
 	{
89 89
 		return static::asSuccess($api_code)
90 90
 			->withData($data)
@@ -112,7 +112,7 @@  discard block
 block discarded – undo
112 112
 	 * @return HttpResponse
113 113
 	 */
114 114
 	public static function error(int $api_code, array $placeholders = null, $data = null, int $http_code = null,
115
-	                             int $json_opts = null): HttpResponse
115
+								 int $json_opts = null): HttpResponse
116 116
 	{
117 117
 		return static::asError($api_code)
118 118
 			->withPlaceholders($placeholders)
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
 	public function withHttpCode(int $http_code = null): self
162 162
 	{
163 163
 		Validator::assertIsType('http_code', $http_code, [Validator::TYPE_INTEGER,
164
-		                                                  Validator::TYPE_NULL]);
164
+														  Validator::TYPE_NULL]);
165 165
 		$this->http_code = $http_code;
166 166
 
167 167
 		return $this;
@@ -175,8 +175,8 @@  discard block
 block discarded – undo
175 175
 	public function withData($data = null): self
176 176
 	{
177 177
 		Validator::assertIsType('data', $data, [Validator::TYPE_ARRAY,
178
-		                                        Validator::TYPE_OBJECT,
179
-		                                        Validator::TYPE_NULL]);
178
+												Validator::TYPE_OBJECT,
179
+												Validator::TYPE_NULL]);
180 180
 		$this->data = $data;
181 181
 
182 182
 		return $this;
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
 	public function withJsonOptions(int $json_opts = null): self
191 191
 	{
192 192
 		Validator::assertIsType('json_opts', $json_opts, [Validator::TYPE_INTEGER,
193
-		                                                  Validator::TYPE_NULL]);
193
+														  Validator::TYPE_NULL]);
194 194
 		$this->json_opts = $json_opts;
195 195
 
196 196
 		return $this;
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
 	public function withDebugData(array $debug_data = null): self
205 205
 	{
206 206
 		Validator::assertIsType('$debug_data', $debug_data, [Validator::TYPE_ARRAY,
207
-		                                                     Validator::TYPE_NULL]);
207
+															 Validator::TYPE_NULL]);
208 208
 		$this->debug_data = $debug_data;
209 209
 
210 210
 		return $this;
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 	public function withMessage(string $msg = null): self
219 219
 	{
220 220
 		Validator::assertIsType('message', $msg, [Validator::TYPE_STRING,
221
-		                                          Validator::TYPE_NULL]);
221
+												  Validator::TYPE_NULL]);
222 222
 		$this->message = $msg;
223 223
 
224 224
 		return $this;
@@ -305,8 +305,8 @@  discard block
 block discarded – undo
305 305
 	 * @noinspection PhpTooManyParametersInspection
306 306
 	 */
307 307
 	protected function make(bool $success, int $api_code, $msg_or_api_code, $data = null,
308
-	                        int $http_code = null, array $placeholders = null, array $http_headers = null,
309
-	                        int $json_opts = null, array $debug_data = null): HttpResponse
308
+							int $http_code = null, array $placeholders = null, array $http_headers = null,
309
+							int $json_opts = null, array $debug_data = null): HttpResponse
310 310
 	{
311 311
 		$http_headers = $http_headers ?? [];
312 312
 		$http_code = $http_code ?? ($success ? ResponseBuilder::DEFAULT_HTTP_CODE_OK : ResponseBuilder::DEFAULT_HTTP_CODE_ERROR);
@@ -345,8 +345,8 @@  discard block
 block discarded – undo
345 345
 	 * @noinspection PhpTooManyParametersInspection
346 346
 	 */
347 347
 	protected function buildResponse(bool $success, int $api_code,
348
-	                                 $msg_or_api_code, array $placeholders = null,
349
-	                                 $data = null, array $debug_data = null): array
348
+									 $msg_or_api_code, array $placeholders = null,
349
+									 $data = null, array $debug_data = null): array
350 350
 	{
351 351
 		// ensure $data is either @null, array or object of class with configured mapping.
352 352
 		$data = (new Converter())->convert($data);
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -374,7 +374,7 @@
 block discarded – undo
374 374
 
375 375
 		if ($debug_data !== null) {
376 376
 			$debug_key = Config::get(ResponseBuilder::CONF_KEY_DEBUG_DEBUG_KEY, ResponseBuilder::KEY_DEBUG);
377
-			$response[ $debug_key ] = $debug_data;
377
+			$response[$debug_key] = $debug_data;
378 378
 		}
379 379
 
380 380
 		return $response;
Please login to merge, or discard this patch.
src/Validator.php 1 patch
Indentation   +173 added lines, -173 removed lines patch added patch discarded remove patch
@@ -15,186 +15,186 @@
 block discarded – undo
15 15
  */
16 16
 class Validator
17 17
 {
18
-    /** @var string */
19
-    public const TYPE_STRING = 'string';
18
+	/** @var string */
19
+	public const TYPE_STRING = 'string';
20 20
 
21
-    /** @var string */
22
-    public const TYPE_INTEGER = 'integer';
21
+	/** @var string */
22
+	public const TYPE_INTEGER = 'integer';
23 23
 
24
-    /** @var string */
25
-    public const TYPE_BOOL = 'boolean';
24
+	/** @var string */
25
+	public const TYPE_BOOL = 'boolean';
26 26
 
27
-    /** @var string */
28
-    public const TYPE_ARRAY = 'array';
27
+	/** @var string */
28
+	public const TYPE_ARRAY = 'array';
29 29
 
30
-    /** @var string */
31
-    public const TYPE_OBJECT = 'object';
30
+	/** @var string */
31
+	public const TYPE_OBJECT = 'object';
32 32
 
33 33
 	/** @var string */
34 34
 	public const TYPE_DOUBLE = 'double';
35 35
 
36 36
 	/** @var string */
37
-    public const TYPE_NULL = 'NULL';
38
-
39
-    /**
40
-     * Checks if given $val is of type boolean
41
-     *
42
-     * @param string $key Name of the key to be used if exception is thrown.
43
-     * @param mixed  $var Variable to be asserted.
44
-     *
45
-     * @return void
46
-     *
47
-     * @throws \InvalidArgumentException
48
-     */
49
-    public static function assertIsBool(string $key, $var): void
50
-    {
51
-        self::assertIsType($key, $var, [self::TYPE_BOOL]);
52
-    }
53
-
54
-    /**
55
-     * Checks if given $val is of type integer
56
-     *
57
-     * @param string $key Name of the key to be used if exception is thrown.
58
-     * @param mixed  $var Variable to be asserted.
59
-     *
60
-     * @return void
61
-     *
62
-     * @throws \InvalidArgumentException
63
-     */
64
-    public static function assertIsInt(string $key, $var): void
65
-    {
66
-        self::assertIsType($key, $var, [self::TYPE_INTEGER]);
67
-    }
68
-
69
-    /**
70
-     * Checks if given $val is of type array
71
-     *
72
-     * @param string $key Name of the key to be used if exception is thrown.
73
-     * @param mixed  $var Variable to be asserted.
74
-     *
75
-     * @return void
76
-     *
77
-     * @throws \InvalidArgumentException
78
-     */
79
-    public static function assertIsArray(string $key, $var): void
80
-    {
81
-        self::assertIsType($key, $var, [self::TYPE_ARRAY]);
82
-    }
83
-
84
-    /**
85
-     * Checks if given $val is an object
86
-     *
87
-     * @param string $key Name of the key to be used if exception is thrown.
88
-     * @param mixed  $var Variable to be asserted.
89
-     *
90
-     * @return void
91
-     *
92
-     * @throws \InvalidArgumentException
93
-     */
94
-    public static function assertIsObject(string $key, $var): void
95
-    {
96
-        self::assertIsType($key, $var, [self::TYPE_OBJECT]);
97
-    }
98
-
99
-    /**
100
-     * Checks if given $val is of type string
101
-     *
102
-     * @param string $name Label or name of the variable to be used in exception message (if thrown).
103
-     * @param mixed  $var  Variable to be asserted.
104
-     *
105
-     * @return void
106
-     *
107
-     * @throws \InvalidArgumentException
108
-     */
109
-    public static function assertIsString(string $name, $var): void
110
-    {
111
-        self::assertIsType($name, $var, [self::TYPE_STRING]);
112
-    }
113
-
114
-    /**
115
-     * @param string $name Label or name of the variable to be used in exception message (if thrown).
116
-     * @param mixed  $var  Variable to be asserted.
117
-     * @param int    $min  Min allowed value (inclusive)
118
-     * @param int    $max  Max allowed value (inclusive)
119
-     *
120
-     * @return void
121
-     *
122
-     * @throws \InvalidArgumentException
123
-     * @throws \RuntimeException
124
-     */
125
-    public static function assertIsIntRange(string $name, $var, int $min, int $max): void
126
-    {
127
-        self::assertIsInt($name, $var);
128
-
129
-        if ($min > $max) {
130
-            throw new \RuntimeException(
131
-                \sprintf('%s: Invalid range for "%s". Ensure bound values are not swapped.', __FUNCTION__, $name));
132
-        }
133
-
134
-        if (($min > $var) || ($var > $max)) {
135
-            throw new \InvalidArgumentException(
136
-                \sprintf('Invalid value of "%s" (%d). Must be between %d-%d inclusive.', $name, $var, $min, $max));
137
-        }
138
-    }
139
-
140
-    /**
141
-     * Checks if $item (of name $key) is of type that is include in $allowed_types.
142
-     *
143
-     * @param string $name          Label or name of the variable to be used in exception message (if thrown).
144
-     * @param mixed  $var           Variable to be asserted.
145
-     * @param array  $allowed_types Array of allowed types for $var, i.e. [Validator::TYPE_INTEGER]
146
-     *
147
-     * @return void
148
-     *
149
-     * @throws \InvalidArgumentException
150
-     */
151
-    public static function assertIsType(string $name, $var, array $allowed_types): void
152
-    {
153
-        $type = \gettype($var);
154
-        if (!\in_array($type, $allowed_types, true)) {
155
-            throw new \InvalidArgumentException(
156
-                \sprintf('"%s" must be one of allowed types: %s (%s given)',
157
-                    $name, implode(', ', $allowed_types), \gettype($var))
158
-            );
159
-        }
160
-    }
161
-
162
-    /**
163
-     * Ensures given $http_code is valid code for error response.
164
-     *
165
-     * @param int $http_code
166
-     */
167
-    public static function assertErrorHttpCode(int $http_code): void
168
-    {
169
-        self::assertIsInt('http_code', $http_code);
170
-        self::assertIsIntRange('http_code', $http_code,
171
-            ResponseBuilder::ERROR_HTTP_CODE_MIN, ResponseBuilder::ERROR_HTTP_CODE_MAX);
172
-    }
173
-
174
-    /**
175
-     * Ensures given $http_code is valid for response indicating sucessful operation.
176
-     *
177
-     * @param int $http_code
178
-     */
179
-    public static function assertOkHttpCode(int $http_code): void
180
-    {
181
-        self::assertIsInt('http_code', $http_code);
182
-        self::assertIsIntRange('http_code', $http_code, 200, 299);
183
-    }
184
-
185
-    /**
186
-     * Ensures $obj is instance of $cls.
187
-     *
188
-     * @param string $name
189
-     * @param object $obj
190
-     * @param string $cls
191
-     */
192
-    public static function assertInstanceOf(string $name, object $obj, string $cls): void
193
-    {
194
-        if (!($obj instanceof $cls)) {
195
-            throw new \InvalidArgumentException(
196
-                \sprintf('"%s" must be instance of "%s".', $name, $cls)
197
-            );
198
-        }
199
-    }
37
+	public const TYPE_NULL = 'NULL';
38
+
39
+	/**
40
+	 * Checks if given $val is of type boolean
41
+	 *
42
+	 * @param string $key Name of the key to be used if exception is thrown.
43
+	 * @param mixed  $var Variable to be asserted.
44
+	 *
45
+	 * @return void
46
+	 *
47
+	 * @throws \InvalidArgumentException
48
+	 */
49
+	public static function assertIsBool(string $key, $var): void
50
+	{
51
+		self::assertIsType($key, $var, [self::TYPE_BOOL]);
52
+	}
53
+
54
+	/**
55
+	 * Checks if given $val is of type integer
56
+	 *
57
+	 * @param string $key Name of the key to be used if exception is thrown.
58
+	 * @param mixed  $var Variable to be asserted.
59
+	 *
60
+	 * @return void
61
+	 *
62
+	 * @throws \InvalidArgumentException
63
+	 */
64
+	public static function assertIsInt(string $key, $var): void
65
+	{
66
+		self::assertIsType($key, $var, [self::TYPE_INTEGER]);
67
+	}
68
+
69
+	/**
70
+	 * Checks if given $val is of type array
71
+	 *
72
+	 * @param string $key Name of the key to be used if exception is thrown.
73
+	 * @param mixed  $var Variable to be asserted.
74
+	 *
75
+	 * @return void
76
+	 *
77
+	 * @throws \InvalidArgumentException
78
+	 */
79
+	public static function assertIsArray(string $key, $var): void
80
+	{
81
+		self::assertIsType($key, $var, [self::TYPE_ARRAY]);
82
+	}
83
+
84
+	/**
85
+	 * Checks if given $val is an object
86
+	 *
87
+	 * @param string $key Name of the key to be used if exception is thrown.
88
+	 * @param mixed  $var Variable to be asserted.
89
+	 *
90
+	 * @return void
91
+	 *
92
+	 * @throws \InvalidArgumentException
93
+	 */
94
+	public static function assertIsObject(string $key, $var): void
95
+	{
96
+		self::assertIsType($key, $var, [self::TYPE_OBJECT]);
97
+	}
98
+
99
+	/**
100
+	 * Checks if given $val is of type string
101
+	 *
102
+	 * @param string $name Label or name of the variable to be used in exception message (if thrown).
103
+	 * @param mixed  $var  Variable to be asserted.
104
+	 *
105
+	 * @return void
106
+	 *
107
+	 * @throws \InvalidArgumentException
108
+	 */
109
+	public static function assertIsString(string $name, $var): void
110
+	{
111
+		self::assertIsType($name, $var, [self::TYPE_STRING]);
112
+	}
113
+
114
+	/**
115
+	 * @param string $name Label or name of the variable to be used in exception message (if thrown).
116
+	 * @param mixed  $var  Variable to be asserted.
117
+	 * @param int    $min  Min allowed value (inclusive)
118
+	 * @param int    $max  Max allowed value (inclusive)
119
+	 *
120
+	 * @return void
121
+	 *
122
+	 * @throws \InvalidArgumentException
123
+	 * @throws \RuntimeException
124
+	 */
125
+	public static function assertIsIntRange(string $name, $var, int $min, int $max): void
126
+	{
127
+		self::assertIsInt($name, $var);
128
+
129
+		if ($min > $max) {
130
+			throw new \RuntimeException(
131
+				\sprintf('%s: Invalid range for "%s". Ensure bound values are not swapped.', __FUNCTION__, $name));
132
+		}
133
+
134
+		if (($min > $var) || ($var > $max)) {
135
+			throw new \InvalidArgumentException(
136
+				\sprintf('Invalid value of "%s" (%d). Must be between %d-%d inclusive.', $name, $var, $min, $max));
137
+		}
138
+	}
139
+
140
+	/**
141
+	 * Checks if $item (of name $key) is of type that is include in $allowed_types.
142
+	 *
143
+	 * @param string $name          Label or name of the variable to be used in exception message (if thrown).
144
+	 * @param mixed  $var           Variable to be asserted.
145
+	 * @param array  $allowed_types Array of allowed types for $var, i.e. [Validator::TYPE_INTEGER]
146
+	 *
147
+	 * @return void
148
+	 *
149
+	 * @throws \InvalidArgumentException
150
+	 */
151
+	public static function assertIsType(string $name, $var, array $allowed_types): void
152
+	{
153
+		$type = \gettype($var);
154
+		if (!\in_array($type, $allowed_types, true)) {
155
+			throw new \InvalidArgumentException(
156
+				\sprintf('"%s" must be one of allowed types: %s (%s given)',
157
+					$name, implode(', ', $allowed_types), \gettype($var))
158
+			);
159
+		}
160
+	}
161
+
162
+	/**
163
+	 * Ensures given $http_code is valid code for error response.
164
+	 *
165
+	 * @param int $http_code
166
+	 */
167
+	public static function assertErrorHttpCode(int $http_code): void
168
+	{
169
+		self::assertIsInt('http_code', $http_code);
170
+		self::assertIsIntRange('http_code', $http_code,
171
+			ResponseBuilder::ERROR_HTTP_CODE_MIN, ResponseBuilder::ERROR_HTTP_CODE_MAX);
172
+	}
173
+
174
+	/**
175
+	 * Ensures given $http_code is valid for response indicating sucessful operation.
176
+	 *
177
+	 * @param int $http_code
178
+	 */
179
+	public static function assertOkHttpCode(int $http_code): void
180
+	{
181
+		self::assertIsInt('http_code', $http_code);
182
+		self::assertIsIntRange('http_code', $http_code, 200, 299);
183
+	}
184
+
185
+	/**
186
+	 * Ensures $obj is instance of $cls.
187
+	 *
188
+	 * @param string $name
189
+	 * @param object $obj
190
+	 * @param string $cls
191
+	 */
192
+	public static function assertInstanceOf(string $name, object $obj, string $cls): void
193
+	{
194
+		if (!($obj instanceof $cls)) {
195
+			throw new \InvalidArgumentException(
196
+				\sprintf('"%s" must be instance of "%s".', $name, $cls)
197
+			);
198
+		}
199
+	}
200 200
 }
Please login to merge, or discard this patch.
config/response_builder.php 1 patch
Indentation   +99 added lines, -99 removed lines patch added patch discarded remove patch
@@ -12,100 +12,100 @@  discard block
 block discarded – undo
12 12
  */
13 13
 
14 14
 return [
15
-    /*
15
+	/*
16 16
     |-----------------------------------------------------------------------------------------------------------
17 17
     | Code range settings
18 18
     |-----------------------------------------------------------------------------------------------------------
19 19
     */
20
-    'min_code'          => 100,
21
-    'max_code'          => 1024,
20
+	'min_code'          => 100,
21
+	'max_code'          => 1024,
22 22
 
23
-    /*
23
+	/*
24 24
     |-----------------------------------------------------------------------------------------------------------
25 25
     | Error code to message mapping
26 26
     |-----------------------------------------------------------------------------------------------------------
27 27
     |
28 28
     */
29
-    'map'               => [
30
-        // YOUR_API_CODE => '<MESSAGE_KEY>',
31
-    ],
29
+	'map'               => [
30
+		// YOUR_API_CODE => '<MESSAGE_KEY>',
31
+	],
32 32
 
33
-    /*
33
+	/*
34 34
     |-----------------------------------------------------------------------------------------------------------
35 35
     | Response Builder data converter
36 36
     |-----------------------------------------------------------------------------------------------------------
37 37
     |
38 38
     */
39
-    'converter'         => [
40
-	    'primitives' => [
41
-		    /* Configuration for primitives used when such data is passed directly as payload (i.e. `success(15)`;) */
42
-		    'array'   => [
43
-			    'key' => 'values',
44
-		    ],
45
-		    'boolean' => [
46
-			    'key' => 'value',
47
-		    ],
48
-		    'double'  => [
49
-			    'key' => 'value',
50
-		    ],
51
-		    'integer' => [
52
-			    'key' => 'value',
53
-		    ],
54
-		    'string'  => [
55
-			    'key' => 'value',
56
-		    ],
57
-	    ],
39
+	'converter'         => [
40
+		'primitives' => [
41
+			/* Configuration for primitives used when such data is passed directly as payload (i.e. `success(15)`;) */
42
+			'array'   => [
43
+				'key' => 'values',
44
+			],
45
+			'boolean' => [
46
+				'key' => 'value',
47
+			],
48
+			'double'  => [
49
+				'key' => 'value',
50
+			],
51
+			'integer' => [
52
+				'key' => 'value',
53
+			],
54
+			'string'  => [
55
+				'key' => 'value',
56
+			],
57
+		],
58 58
 
59
-	    /* Object converters configuration for supported classes */
60
-    	'classes' => [
61
-	        \Illuminate\Database\Eloquent\Model::class          => [
62
-	            'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
63
-	            'key'     => 'item',
64
-	            'pri'     => 0,
65
-	        ],
66
-	        \Illuminate\Support\Collection::class               => [
67
-	            'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
68
-	            'key'     => 'items',
69
-	            'pri'     => 0,
70
-	        ],
71
-	        \Illuminate\Database\Eloquent\Collection::class     => [
72
-	            'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
73
-	            'key'     => 'items',
74
-	            'pri'     => 0,
75
-	        ],
76
-	        \Illuminate\Http\Resources\Json\JsonResource::class => [
77
-	            'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
78
-	            'key'     => 'item',
79
-	            'pri'     => 0,
80
-	        ],
59
+		/* Object converters configuration for supported classes */
60
+		'classes' => [
61
+			\Illuminate\Database\Eloquent\Model::class          => [
62
+				'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
63
+				'key'     => 'item',
64
+				'pri'     => 0,
65
+			],
66
+			\Illuminate\Support\Collection::class               => [
67
+				'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
68
+				'key'     => 'items',
69
+				'pri'     => 0,
70
+			],
71
+			\Illuminate\Database\Eloquent\Collection::class     => [
72
+				'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
73
+				'key'     => 'items',
74
+				'pri'     => 0,
75
+			],
76
+			\Illuminate\Http\Resources\Json\JsonResource::class => [
77
+				'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
78
+				'key'     => 'item',
79
+				'pri'     => 0,
80
+			],
81 81
 
82
-	        /*
82
+			/*
83 83
 	        |-----------------------------------------------------------------------------------------------------------
84 84
 	        | Generic converters should have lower pri to allow dedicated ones to kick in first when class matches
85 85
 	        |-----------------------------------------------------------------------------------------------------------
86 86
 	        */
87
-	        \JsonSerializable::class                            => [
88
-	            'handler' => \MarcinOrlowski\ResponseBuilder\Converters\JsonSerializableConverter::class,
89
-	             'key'     => 'item',
90
-	            'pri'     => -10,
91
-	        ],
92
-	        \Illuminate\Contracts\Support\Arrayable::class      => [
93
-	            'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ArrayableConverter::class,
94
-	            'key'     => 'items',
95
-	            'pri'     => -10,
96
-	        ],
97
-        ],
87
+			\JsonSerializable::class                            => [
88
+				'handler' => \MarcinOrlowski\ResponseBuilder\Converters\JsonSerializableConverter::class,
89
+				 'key'     => 'item',
90
+				'pri'     => -10,
91
+			],
92
+			\Illuminate\Contracts\Support\Arrayable::class      => [
93
+				'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ArrayableConverter::class,
94
+				'key'     => 'items',
95
+				'pri'     => -10,
96
+			],
97
+		],
98 98
 
99
-    ],
99
+	],
100 100
 
101
-    /*
101
+	/*
102 102
     |-----------------------------------------------------------------------------------------------------------
103 103
     | Exception handler error codes
104 104
     |-----------------------------------------------------------------------------------------------------------
105 105
     |
106 106
     */
107
-    'exception_handler' => [
108
-	    /*
107
+	'exception_handler' => [
108
+		/*
109 109
 	     * The following keys are supported for each handler specified.
110 110
 	     *   `handler`
111 111
 	     *   `pri`
@@ -125,19 +125,19 @@  discard block
 block discarded – undo
125 125
 		 *                  message ($ex->getMessage()).
126 126
 		 */
127 127
 
128
-    	\Illuminate\Validation\ValidationException::class => [
129
-		    'handler' => \MarcinOrlowski\ResponseBuilder\ExceptionHandlers\ValidationExceptionHandler::class,
130
-		    'pri'     => -100,
131
-		    'config' => [
128
+		\Illuminate\Validation\ValidationException::class => [
129
+			'handler' => \MarcinOrlowski\ResponseBuilder\ExceptionHandlers\ValidationExceptionHandler::class,
130
+			'pri'     => -100,
131
+			'config' => [
132 132
 //		        'api_code'  => ApiCodes::YOUR_API_CODE_FOR_VALIDATION_EXCEPTION,
133 133
 //		        'http_code' => HttpResponse::HTTP_UNPROCESSABLE_ENTITY,
134
-		    	],
135
-	    ],
134
+				],
135
+		],
136 136
 
137 137
 		\Symfony\Component\HttpKernel\Exception\HttpException::class => [
138
-	        'handler' => \MarcinOrlowski\ResponseBuilder\ExceptionHandlers\HttpExceptionHandler::class,
139
-	        'pri'     => -100,
140
-	        'config'  => [
138
+			'handler' => \MarcinOrlowski\ResponseBuilder\ExceptionHandlers\HttpExceptionHandler::class,
139
+			'pri'     => -100,
140
+			'config'  => [
141 141
 //		        HttpException::class => [
142 142
 //			        // used by unauthenticated() to obtain api and http code for the exception
143 143
 //			        HttpResponse::HTTP_UNAUTHORIZED         => [
@@ -153,47 +153,47 @@  discard block
 block discarded – undo
153 153
 //				        'http_code' => HttpResponse::HTTP_BAD_REQUEST,
154 154
 //			        ],
155 155
 //		        ],
156
-	        ],
156
+			],
157 157
 //	        // This is final exception handler. If ex is not dealt with yet this is its last stop.
158
-	        // default handler is mandatory and MUST have both `api_code` and `http_code` set.
158
+			// default handler is mandatory and MUST have both `api_code` and `http_code` set.
159 159
 
160
-	        'default' => [
161
-		        'handler' => \MarcinOrlowski\ResponseBuilder\ExceptionHandlers\HttpExceptionHandler::class,
162
-		        'pri'     => -127,
163
-		        'config'  => [
160
+			'default' => [
161
+				'handler' => \MarcinOrlowski\ResponseBuilder\ExceptionHandlers\HttpExceptionHandler::class,
162
+				'pri'     => -127,
163
+				'config'  => [
164 164
 //			        'api_code'  => ApiCodes::YOUR_API_CODE_FOR_UNHANDLED_EXCEPTION,
165 165
 //			        'http_code' => HttpResponse::HTTP_INTERNAL_SERVER_ERROR,
166
-		        ],
167
-	        ],
168
-	    ],
169
-    ],
166
+				],
167
+			],
168
+		],
169
+	],
170 170
 
171
-    /*
171
+	/*
172 172
     |-----------------------------------------------------------------------------------------------------------
173 173
     | data-to-json encoding options
174 174
     |-----------------------------------------------------------------------------------------------------------
175 175
     |
176 176
     */
177
-    'encoding_options'  => JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE,
177
+	'encoding_options'  => JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE,
178 178
 
179
-    /*
179
+	/*
180 180
     |-----------------------------------------------------------------------------------------------------------
181 181
     | Debug config
182 182
     |-----------------------------------------------------------------------------------------------------------
183 183
     |
184 184
     */
185
-    'debug'             => [
186
-        'debug_key'         => 'debug',
187
-        'exception_handler' => [
188
-            'trace_key'     => 'trace',
189
-            'trace_enabled' => env('APP_DEBUG', false),
190
-        ],
185
+	'debug'             => [
186
+		'debug_key'         => 'debug',
187
+		'exception_handler' => [
188
+			'trace_key'     => 'trace',
189
+			'trace_enabled' => env('APP_DEBUG', false),
190
+		],
191 191
 
192
-        // Controls debugging features of payload converter class.
193
-        'converter' => [
194
-        	// Set to true to figure out what converter is used for given data payload and why.
195
-        	'debug_enabled' => env('RB_CONVERTER_DEBUG', false),
196
-        ],
197
-    ],
192
+		// Controls debugging features of payload converter class.
193
+		'converter' => [
194
+			// Set to true to figure out what converter is used for given data payload and why.
195
+			'debug_enabled' => env('RB_CONVERTER_DEBUG', false),
196
+		],
197
+	],
198 198
 
199 199
 ];
Please login to merge, or discard this patch.
src/Converter.php 2 patches
Indentation   +217 added lines, -217 removed lines patch added patch discarded remove patch
@@ -23,27 +23,27 @@  discard block
 block discarded – undo
23 23
  */
24 24
 class Converter
25 25
 {
26
-    /** @var array */
27
-    protected $classes = [];
26
+	/** @var array */
27
+	protected $classes = [];
28 28
 
29
-    /** @var array */
30
-    protected $primitives = [];
29
+	/** @var array */
30
+	protected $primitives = [];
31 31
 
32
-    /** @var bool */
33
-    protected $debug_enabled = false;
32
+	/** @var bool */
33
+	protected $debug_enabled = false;
34 34
 
35
-    /**
36
-     * Converter constructor.
37
-     *
38
-     * @throws \RuntimeException
39
-     */
40
-    public function __construct()
41
-    {
42
-        $this->classes = static::getClassesMapping() ?? [];
43
-        $this->primitives = static::getPrimitivesMapping() ?? [];
35
+	/**
36
+	 * Converter constructor.
37
+	 *
38
+	 * @throws \RuntimeException
39
+	 */
40
+	public function __construct()
41
+	{
42
+		$this->classes = static::getClassesMapping() ?? [];
43
+		$this->primitives = static::getPrimitivesMapping() ?? [];
44 44
 
45
-	    $this->debug_enabled = Config::get(ResponseBuilder::CONF_KEY_CONVERTER_DEBUG_KEY, false);
46
-    }
45
+		$this->debug_enabled = Config::get(ResponseBuilder::CONF_KEY_CONVERTER_DEBUG_KEY, false);
46
+	}
47 47
 
48 48
 	/**
49 49
 	 * Returns "converter/primitives" entry for given primitive object or throws exception if no config found.
@@ -56,116 +56,116 @@  discard block
 block discarded – undo
56 56
 	 *
57 57
 	 * @throws \InvalidArgumentException
58 58
 	 */
59
-    protected function getPrimitiveMappingConfigOrThrow($data): array
60
-    {
61
-	    $result = null;
62
-
63
-	    $type = \gettype($data);
64
-	    $result = $this->primitives[ $type ] ?? null;
65
-	    if ($result === null) {
66
-		    throw new \InvalidArgumentException(sprintf('No data conversion mapping configured for "%s" primitive.', $type));
67
-	    }
68
-
69
-	    if ($this->debug_enabled) {
70
-		    Log::debug(__CLASS__ . ": Converting primitive type of '{$type}' to data node '{$result[ResponseBuilder::KEY_KEY]}'.");
71
-	    }
72
-
73
-	    return $result;
74
-    }
75
-
76
-    /**
77
-     * Returns "converter/map" mapping configured for given $data object class or throws exception if not found.
78
-     * Throws \RuntimeException if there's no config "classes" mapping entry for this object configured.
79
-     * Throws \InvalidArgumentException if No data conversion mapping configured for given class.
80
-     *
81
-     * @param object $data Object to get config for.
82
-     *
83
-     * @return array
84
-     *
85
-     * @throws \InvalidArgumentException
86
-     */
87
-    protected function getClassMappingConfigOrThrow(object $data): array
88
-    {
89
-        $result = null;
90
-        $debug_result = '';
91
-
92
-        // check for exact class name match...
93
-        $cls = \get_class($data);
94
-        if (\is_string($cls)) {
95
-	        if (\array_key_exists($cls, $this->classes)) {
96
-		        $result = $this->classes[ $cls ];
97
-		        $debug_result = 'exact config match';
98
-	        } else {
99
-		        // no exact match, then lets try with `instanceof`
100
-		        foreach (\array_keys($this->classes) as $class_name) {
101
-			        if ($data instanceof $class_name) {
102
-				        $result = $this->classes[ $class_name ];
103
-				        $debug_result = "subclass of {$class_name}";
104
-				        break;
105
-			        }
106
-		        }
107
-	        }
108
-        }
109
-
110
-        if ($result === null) {
111
-            throw new \InvalidArgumentException(sprintf('No data conversion mapping configured for "%s" class.', $cls));
112
-        }
113
-
114
-        if ($this->debug_enabled) {
59
+	protected function getPrimitiveMappingConfigOrThrow($data): array
60
+	{
61
+		$result = null;
62
+
63
+		$type = \gettype($data);
64
+		$result = $this->primitives[ $type ] ?? null;
65
+		if ($result === null) {
66
+			throw new \InvalidArgumentException(sprintf('No data conversion mapping configured for "%s" primitive.', $type));
67
+		}
68
+
69
+		if ($this->debug_enabled) {
70
+			Log::debug(__CLASS__ . ": Converting primitive type of '{$type}' to data node '{$result[ResponseBuilder::KEY_KEY]}'.");
71
+		}
72
+
73
+		return $result;
74
+	}
75
+
76
+	/**
77
+	 * Returns "converter/map" mapping configured for given $data object class or throws exception if not found.
78
+	 * Throws \RuntimeException if there's no config "classes" mapping entry for this object configured.
79
+	 * Throws \InvalidArgumentException if No data conversion mapping configured for given class.
80
+	 *
81
+	 * @param object $data Object to get config for.
82
+	 *
83
+	 * @return array
84
+	 *
85
+	 * @throws \InvalidArgumentException
86
+	 */
87
+	protected function getClassMappingConfigOrThrow(object $data): array
88
+	{
89
+		$result = null;
90
+		$debug_result = '';
91
+
92
+		// check for exact class name match...
93
+		$cls = \get_class($data);
94
+		if (\is_string($cls)) {
95
+			if (\array_key_exists($cls, $this->classes)) {
96
+				$result = $this->classes[ $cls ];
97
+				$debug_result = 'exact config match';
98
+			} else {
99
+				// no exact match, then lets try with `instanceof`
100
+				foreach (\array_keys($this->classes) as $class_name) {
101
+					if ($data instanceof $class_name) {
102
+						$result = $this->classes[ $class_name ];
103
+						$debug_result = "subclass of {$class_name}";
104
+						break;
105
+					}
106
+				}
107
+			}
108
+		}
109
+
110
+		if ($result === null) {
111
+			throw new \InvalidArgumentException(sprintf('No data conversion mapping configured for "%s" class.', $cls));
112
+		}
113
+
114
+		if ($this->debug_enabled) {
115 115
 			Log::debug(__CLASS__ . ": Converting {$cls} using {$result[ResponseBuilder::KEY_HANDLER]} because: {$debug_result}.");
116
-        }
117
-
118
-	    return $result;
119
-    }
120
-
121
-    /**
122
-     * Main entry for data conversion
123
-     *
124
-     * @param object|array|null $data
125
-     *
126
-     * @return mixed|null
127
-     *
128
-     * @throws \InvalidArgumentException
129
-     */
130
-    public function convert($data = null): ?array
131
-    {
132
-        if ($data === null) {
133
-            return null;
134
-        }
135
-
136
-        $result = null;
137
-
138
-	    Validator::assertIsType('data', $data, [
139
-		    Validator::TYPE_ARRAY,
140
-		    Validator::TYPE_BOOL,
141
-		    Validator::TYPE_DOUBLE,
142
-		    Validator::TYPE_INTEGER,
143
-		    Validator::TYPE_STRING,
144
-		    Validator::TYPE_OBJECT,
145
-	    ]);
146
-
147
-	    if ($result === null && \is_object($data)) {
148
-		    $cfg = $this->getClassMappingConfigOrThrow($data);
149
-		    $worker = new $cfg[ ResponseBuilder::KEY_HANDLER ]();
150
-		    $result = [$cfg[ ResponseBuilder::KEY_KEY ] => $worker->convert($data, $cfg)];
151
-	    }
152
-
153
-	    if ($result === null && \is_array($data)) {
154
-	        $cfg = $this->getPrimitiveMappingConfigOrThrow($data);
155
-
156
-	        if ($this->hasNonNumericKeys($data)){
157
-		        $result = $this->convertArray($data);
158
-	        } else {
159
-		        $result = [$cfg[ ResponseBuilder::KEY_KEY ] => $this->convertArray($data)];
160
-	        }
161
-        }
162
-
163
-	    if ( \is_bool($data) || \is_float($data) || \is_int($data) || \is_string($data)) {
164
-		    $result = [$this->getPrimitiveMappingConfigOrThrow($data)[ ResponseBuilder::KEY_KEY ] => $data];
165
-	    }
166
-
167
-	    return $result;
168
-    }
116
+		}
117
+
118
+		return $result;
119
+	}
120
+
121
+	/**
122
+	 * Main entry for data conversion
123
+	 *
124
+	 * @param object|array|null $data
125
+	 *
126
+	 * @return mixed|null
127
+	 *
128
+	 * @throws \InvalidArgumentException
129
+	 */
130
+	public function convert($data = null): ?array
131
+	{
132
+		if ($data === null) {
133
+			return null;
134
+		}
135
+
136
+		$result = null;
137
+
138
+		Validator::assertIsType('data', $data, [
139
+			Validator::TYPE_ARRAY,
140
+			Validator::TYPE_BOOL,
141
+			Validator::TYPE_DOUBLE,
142
+			Validator::TYPE_INTEGER,
143
+			Validator::TYPE_STRING,
144
+			Validator::TYPE_OBJECT,
145
+		]);
146
+
147
+		if ($result === null && \is_object($data)) {
148
+			$cfg = $this->getClassMappingConfigOrThrow($data);
149
+			$worker = new $cfg[ ResponseBuilder::KEY_HANDLER ]();
150
+			$result = [$cfg[ ResponseBuilder::KEY_KEY ] => $worker->convert($data, $cfg)];
151
+		}
152
+
153
+		if ($result === null && \is_array($data)) {
154
+			$cfg = $this->getPrimitiveMappingConfigOrThrow($data);
155
+
156
+			if ($this->hasNonNumericKeys($data)){
157
+				$result = $this->convertArray($data);
158
+			} else {
159
+				$result = [$cfg[ ResponseBuilder::KEY_KEY ] => $this->convertArray($data)];
160
+			}
161
+		}
162
+
163
+		if ( \is_bool($data) || \is_float($data) || \is_int($data) || \is_string($data)) {
164
+			$result = [$this->getPrimitiveMappingConfigOrThrow($data)[ ResponseBuilder::KEY_KEY ] => $data];
165
+		}
166
+
167
+		return $result;
168
+	}
169 169
 
170 170
 	/**
171 171
 	 * Checks if given array uses custom (non numeric) keys.
@@ -174,97 +174,97 @@  discard block
 block discarded – undo
174 174
 	 *
175 175
 	 * @return bool
176 176
 	 */
177
-    protected function hasNonNumericKeys(array $data): bool
178
-    {
179
-	    foreach (\array_keys($data) as $key) {
180
-	    	if (!\is_int($key)) {
181
-	    		return true;
182
-		    }
183
-    	}
184
-
185
-	    return false;
186
-    }
187
-
188
-    /**
189
-     * Recursively walks $data array and converts all known objects if found. Note
190
-     * $data array is passed by reference so source $data array may be modified.
191
-     *
192
-     * @param array $data array to recursively convert known elements of
193
-     *
194
-     * @return array
195
-     *
196
-     * @throws \RuntimeException
197
-     */
198
-    protected function convertArray(array $data): array
199
-    {
200
-        // This is to ensure that we either have array with user provided keys i.e. ['foo'=>'bar'], which will then
201
-        // be turned into JSON object or array without user specified keys (['bar']) which we would return as JSON
202
-        // array. But you can't mix these two as the final JSON would not produce predictable results.
203
-        $string_keys_cnt = 0;
204
-        $int_keys_cnt = 0;
205
-        foreach ($data as $key => $val) {
206
-            if (\is_int($key)) {
207
-                $int_keys_cnt++;
208
-            } else {
209
-                $string_keys_cnt++;
210
-            }
211
-
212
-            if (($string_keys_cnt > 0) && ($int_keys_cnt > 0)) {
213
-                throw new \RuntimeException(
214
-                    'Invalid data array. Either set own keys for all the items or do not specify any keys at all. ' .
215
-                    'Arrays with mixed keys are not supported by design.');
216
-            }
217
-        }
218
-
219
-        foreach ($data as $key => $val) {
220
-            if (\is_array($val)) {
221
-                $data[ $key ] = $this->convertArray($val);
222
-            } elseif (\is_object($val)) {
223
-                $cfg = $this->getClassMappingConfigOrThrow($val);
224
-                $worker = new $cfg[ ResponseBuilder::KEY_HANDLER ]();
225
-                $converted_data = $worker->convert($val, $cfg);
226
-                $data[ $key ] = $converted_data;
227
-            }
228
-        }
229
-
230
-        return $data;
231
-    }
232
-
233
-    /**
234
-     * Reads and validates "converter/map" config mapping
235
-     *
236
-     * @return array Classes mapping as specified in configuration or empty array if configuration found
237
-     *
238
-     * @throws \RuntimeException if config mapping is technically invalid (i.e. not array etc).
239
-     */
240
-    protected static function getClassesMapping(): array
241
-    {
242
-        $classes = Config::get(ResponseBuilder::CONF_KEY_CONVERTER_CLASSES) ?? [];
243
-
244
-	    if (!\is_array($classes)) {
245
-		    throw new \RuntimeException(
246
-			    \sprintf('CONFIG: "%s" mapping must be an array (%s given)', ResponseBuilder::CONF_KEY_CONVERTER_CLASSES, \gettype($classes)));
247
-	    }
248
-
249
-	    if (!empty($classes)) {
250
-		    $mandatory_keys = [
251
-			    ResponseBuilder::KEY_HANDLER,
252
-			    ResponseBuilder::KEY_KEY,
253
-		    ];
254
-		    foreach ($classes as $class_name => $class_config) {
255
-			    if (!\is_array($class_config)) {
256
-				    throw new \InvalidArgumentException(sprintf("CONFIG: Config for '{$class_name}' class must be an array (%s given).", \gettype($class_config)));
257
-			    }
258
-			    foreach ($mandatory_keys as $key_name) {
259
-				    if (!\array_key_exists($key_name, $class_config)) {
260
-					    throw new \RuntimeException("CONFIG: Missing '{$key_name}' for '{$class_name}' class mapping");
261
-				    }
262
-			    }
263
-		    }
264
-	    }
265
-
266
-        return $classes;
267
-    }
177
+	protected function hasNonNumericKeys(array $data): bool
178
+	{
179
+		foreach (\array_keys($data) as $key) {
180
+			if (!\is_int($key)) {
181
+				return true;
182
+			}
183
+		}
184
+
185
+		return false;
186
+	}
187
+
188
+	/**
189
+	 * Recursively walks $data array and converts all known objects if found. Note
190
+	 * $data array is passed by reference so source $data array may be modified.
191
+	 *
192
+	 * @param array $data array to recursively convert known elements of
193
+	 *
194
+	 * @return array
195
+	 *
196
+	 * @throws \RuntimeException
197
+	 */
198
+	protected function convertArray(array $data): array
199
+	{
200
+		// This is to ensure that we either have array with user provided keys i.e. ['foo'=>'bar'], which will then
201
+		// be turned into JSON object or array without user specified keys (['bar']) which we would return as JSON
202
+		// array. But you can't mix these two as the final JSON would not produce predictable results.
203
+		$string_keys_cnt = 0;
204
+		$int_keys_cnt = 0;
205
+		foreach ($data as $key => $val) {
206
+			if (\is_int($key)) {
207
+				$int_keys_cnt++;
208
+			} else {
209
+				$string_keys_cnt++;
210
+			}
211
+
212
+			if (($string_keys_cnt > 0) && ($int_keys_cnt > 0)) {
213
+				throw new \RuntimeException(
214
+					'Invalid data array. Either set own keys for all the items or do not specify any keys at all. ' .
215
+					'Arrays with mixed keys are not supported by design.');
216
+			}
217
+		}
218
+
219
+		foreach ($data as $key => $val) {
220
+			if (\is_array($val)) {
221
+				$data[ $key ] = $this->convertArray($val);
222
+			} elseif (\is_object($val)) {
223
+				$cfg = $this->getClassMappingConfigOrThrow($val);
224
+				$worker = new $cfg[ ResponseBuilder::KEY_HANDLER ]();
225
+				$converted_data = $worker->convert($val, $cfg);
226
+				$data[ $key ] = $converted_data;
227
+			}
228
+		}
229
+
230
+		return $data;
231
+	}
232
+
233
+	/**
234
+	 * Reads and validates "converter/map" config mapping
235
+	 *
236
+	 * @return array Classes mapping as specified in configuration or empty array if configuration found
237
+	 *
238
+	 * @throws \RuntimeException if config mapping is technically invalid (i.e. not array etc).
239
+	 */
240
+	protected static function getClassesMapping(): array
241
+	{
242
+		$classes = Config::get(ResponseBuilder::CONF_KEY_CONVERTER_CLASSES) ?? [];
243
+
244
+		if (!\is_array($classes)) {
245
+			throw new \RuntimeException(
246
+				\sprintf('CONFIG: "%s" mapping must be an array (%s given)', ResponseBuilder::CONF_KEY_CONVERTER_CLASSES, \gettype($classes)));
247
+		}
248
+
249
+		if (!empty($classes)) {
250
+			$mandatory_keys = [
251
+				ResponseBuilder::KEY_HANDLER,
252
+				ResponseBuilder::KEY_KEY,
253
+			];
254
+			foreach ($classes as $class_name => $class_config) {
255
+				if (!\is_array($class_config)) {
256
+					throw new \InvalidArgumentException(sprintf("CONFIG: Config for '{$class_name}' class must be an array (%s given).", \gettype($class_config)));
257
+				}
258
+				foreach ($mandatory_keys as $key_name) {
259
+					if (!\array_key_exists($key_name, $class_config)) {
260
+						throw new \RuntimeException("CONFIG: Missing '{$key_name}' for '{$class_name}' class mapping");
261
+					}
262
+				}
263
+			}
264
+		}
265
+
266
+		return $classes;
267
+	}
268 268
 
269 269
 	/**
270 270
 	 * Reads and validates "converter/primitives" config mapping
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
 	    $result = null;
62 62
 
63 63
 	    $type = \gettype($data);
64
-	    $result = $this->primitives[ $type ] ?? null;
64
+	    $result = $this->primitives[$type] ?? null;
65 65
 	    if ($result === null) {
66 66
 		    throw new \InvalidArgumentException(sprintf('No data conversion mapping configured for "%s" primitive.', $type));
67 67
 	    }
@@ -93,13 +93,13 @@  discard block
 block discarded – undo
93 93
         $cls = \get_class($data);
94 94
         if (\is_string($cls)) {
95 95
 	        if (\array_key_exists($cls, $this->classes)) {
96
-		        $result = $this->classes[ $cls ];
96
+		        $result = $this->classes[$cls];
97 97
 		        $debug_result = 'exact config match';
98 98
 	        } else {
99 99
 		        // no exact match, then lets try with `instanceof`
100 100
 		        foreach (\array_keys($this->classes) as $class_name) {
101 101
 			        if ($data instanceof $class_name) {
102
-				        $result = $this->classes[ $class_name ];
102
+				        $result = $this->classes[$class_name];
103 103
 				        $debug_result = "subclass of {$class_name}";
104 104
 				        break;
105 105
 			        }
@@ -146,22 +146,22 @@  discard block
 block discarded – undo
146 146
 
147 147
 	    if ($result === null && \is_object($data)) {
148 148
 		    $cfg = $this->getClassMappingConfigOrThrow($data);
149
-		    $worker = new $cfg[ ResponseBuilder::KEY_HANDLER ]();
150
-		    $result = [$cfg[ ResponseBuilder::KEY_KEY ] => $worker->convert($data, $cfg)];
149
+		    $worker = new $cfg[ResponseBuilder::KEY_HANDLER]();
150
+		    $result = [$cfg[ResponseBuilder::KEY_KEY] => $worker->convert($data, $cfg)];
151 151
 	    }
152 152
 
153 153
 	    if ($result === null && \is_array($data)) {
154 154
 	        $cfg = $this->getPrimitiveMappingConfigOrThrow($data);
155 155
 
156
-	        if ($this->hasNonNumericKeys($data)){
156
+	        if ($this->hasNonNumericKeys($data)) {
157 157
 		        $result = $this->convertArray($data);
158 158
 	        } else {
159
-		        $result = [$cfg[ ResponseBuilder::KEY_KEY ] => $this->convertArray($data)];
159
+		        $result = [$cfg[ResponseBuilder::KEY_KEY] => $this->convertArray($data)];
160 160
 	        }
161 161
         }
162 162
 
163
-	    if ( \is_bool($data) || \is_float($data) || \is_int($data) || \is_string($data)) {
164
-		    $result = [$this->getPrimitiveMappingConfigOrThrow($data)[ ResponseBuilder::KEY_KEY ] => $data];
163
+	    if (\is_bool($data) || \is_float($data) || \is_int($data) || \is_string($data)) {
164
+		    $result = [$this->getPrimitiveMappingConfigOrThrow($data)[ResponseBuilder::KEY_KEY] => $data];
165 165
 	    }
166 166
 
167 167
 	    return $result;
@@ -218,12 +218,12 @@  discard block
 block discarded – undo
218 218
 
219 219
         foreach ($data as $key => $val) {
220 220
             if (\is_array($val)) {
221
-                $data[ $key ] = $this->convertArray($val);
221
+                $data[$key] = $this->convertArray($val);
222 222
             } elseif (\is_object($val)) {
223 223
                 $cfg = $this->getClassMappingConfigOrThrow($val);
224
-                $worker = new $cfg[ ResponseBuilder::KEY_HANDLER ]();
224
+                $worker = new $cfg[ResponseBuilder::KEY_HANDLER]();
225 225
                 $converted_data = $worker->convert($val, $cfg);
226
-                $data[ $key ] = $converted_data;
226
+                $data[$key] = $converted_data;
227 227
             }
228 228
         }
229 229
 
Please login to merge, or discard this patch.