Passed
Push — dev ( b15eee...dd69e8 )
by Marcin
09:01
created
src/ResponseBuilder.php 2 patches
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 	 * @return HttpResponse
86 86
 	 */
87 87
 	public static function success($data = null, $api_code = null, array $placeholders = null,
88
-	                               int $http_code = null, int $json_opts = null): HttpResponse
88
+								   int $http_code = null, int $json_opts = null): HttpResponse
89 89
 	{
90 90
 		return static::asSuccess($api_code)
91 91
 			->withData($data)
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
 	 * @return HttpResponse
114 114
 	 */
115 115
 	public static function error(int $api_code, array $placeholders = null, $data = null, int $http_code = null,
116
-	                             int $json_opts = null): HttpResponse
116
+								 int $json_opts = null): HttpResponse
117 117
 	{
118 118
 		return static::asError($api_code)
119 119
 			->withPlaceholders($placeholders)
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 	public function withHttpCode(int $http_code = null): self
163 163
 	{
164 164
 		Validator::assertIsType('http_code', $http_code, [Type::INTEGER,
165
-		                                                  Type::NULL]);
165
+														  Type::NULL]);
166 166
 		$this->http_code = $http_code;
167 167
 
168 168
 		return $this;
@@ -176,8 +176,8 @@  discard block
 block discarded – undo
176 176
 	public function withData($data = null): self
177 177
 	{
178 178
 		Validator::assertIsType('data', $data, [Type::ARRAY,
179
-		                                        Type::OBJECT,
180
-		                                        Type::NULL]);
179
+												Type::OBJECT,
180
+												Type::NULL]);
181 181
 		$this->data = $data;
182 182
 
183 183
 		return $this;
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 	public function withJsonOptions(int $json_opts = null): self
192 192
 	{
193 193
 		Validator::assertIsType('json_opts', $json_opts, [Type::INTEGER,
194
-		                                                  Type::NULL]);
194
+														  Type::NULL]);
195 195
 		$this->json_opts = $json_opts;
196 196
 
197 197
 		return $this;
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 	public function withDebugData(array $debug_data = null): self
206 206
 	{
207 207
 		Validator::assertIsType('$debug_data', $debug_data, [Type::ARRAY,
208
-		                                                     Type::NULL]);
208
+															 Type::NULL]);
209 209
 		$this->debug_data = $debug_data;
210 210
 
211 211
 		return $this;
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 	public function withMessage(string $msg = null): self
220 220
 	{
221 221
 		Validator::assertIsType('message', $msg, [Type::STRING,
222
-		                                          Type::NULL]);
222
+												  Type::NULL]);
223 223
 		$this->message = $msg;
224 224
 
225 225
 		return $this;
@@ -306,8 +306,8 @@  discard block
 block discarded – undo
306 306
 	 * @noinspection PhpTooManyParametersInspection
307 307
 	 */
308 308
 	protected function make(bool $success, int $api_code, $msg_or_api_code, $data = null,
309
-	                        int $http_code = null, array $placeholders = null, array $http_headers = null,
310
-	                        int $json_opts = null, array $debug_data = null): HttpResponse
309
+							int $http_code = null, array $placeholders = null, array $http_headers = null,
310
+							int $json_opts = null, array $debug_data = null): HttpResponse
311 311
 	{
312 312
 		$http_headers = $http_headers ?? [];
313 313
 		$http_code = $http_code ?? ($success ? RB::DEFAULT_HTTP_CODE_OK : RB::DEFAULT_HTTP_CODE_ERROR);
@@ -346,8 +346,8 @@  discard block
 block discarded – undo
346 346
 	 * @noinspection PhpTooManyParametersInspection
347 347
 	 */
348 348
 	protected function buildResponse(bool $success, int $api_code,
349
-	                                 $msg_or_api_code, array $placeholders = null,
350
-	                                 $data = null, array $debug_data = null): array
349
+									 $msg_or_api_code, array $placeholders = null,
350
+									 $data = null, array $debug_data = null): array
351 351
 	{
352 352
 		// ensure $data is either @null, array or object of class with configured mapping.
353 353
 		$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
@@ -375,7 +375,7 @@
 block discarded – undo
375 375
 
376 376
 		if ($debug_data !== null) {
377 377
 			$debug_key = Config::get(RB::CONF_KEY_DEBUG_DEBUG_KEY, RB::KEY_DEBUG);
378
-			$response[ $debug_key ] = $debug_data;
378
+			$response[$debug_key] = $debug_data;
379 379
 		}
380 380
 
381 381
 		return $response;
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}", RB::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}", RB::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/Converter.php 2 patches
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[ RB::KEY_HANDLER ]();
150
-		    $result = [$cfg[ RB::KEY_KEY ] => $worker->convert($data, $cfg)];
149
+		    $worker = new $cfg[RB::KEY_HANDLER]();
150
+		    $result = [$cfg[RB::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[ RB::KEY_KEY ] => $this->convertArray($data)];
159
+		        $result = [$cfg[RB::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)[ RB::KEY_KEY ] => $data];
163
+	    if (\is_bool($data) || \is_float($data) || \is_int($data) || \is_string($data)) {
164
+		    $result = [$this->getPrimitiveMappingConfigOrThrow($data)[RB::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[ RB::KEY_HANDLER ]();
224
+                $worker = new $cfg[RB::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.
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(RB::CONF_KEY_DEBUG_CONVERTER_DEBUG_ENABLED, false);
46
-    }
45
+		$this->debug_enabled = Config::get(RB::CONF_KEY_DEBUG_CONVERTER_DEBUG_ENABLED, 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[RB::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[RB::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[RB::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
-		    Type::ARRAY,
140
-		    Type::BOOLEAN,
141
-		    Type::DOUBLE,
142
-		    Type::INTEGER,
143
-		    Type::STRING,
144
-		    Type::OBJECT,
145
-	    ]);
146
-
147
-	    if ($result === null && \is_object($data)) {
148
-		    $cfg = $this->getClassMappingConfigOrThrow($data);
149
-		    $worker = new $cfg[ RB::KEY_HANDLER ]();
150
-		    $result = [$cfg[ RB::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[ RB::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)[ RB::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
+			Type::ARRAY,
140
+			Type::BOOLEAN,
141
+			Type::DOUBLE,
142
+			Type::INTEGER,
143
+			Type::STRING,
144
+			Type::OBJECT,
145
+		]);
146
+
147
+		if ($result === null && \is_object($data)) {
148
+			$cfg = $this->getClassMappingConfigOrThrow($data);
149
+			$worker = new $cfg[ RB::KEY_HANDLER ]();
150
+			$result = [$cfg[ RB::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[ RB::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)[ RB::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[ RB::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(RB::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)', RB::CONF_KEY_CONVERTER_CLASSES, \gettype($classes)));
247
-	    }
248
-
249
-	    if (!empty($classes)) {
250
-		    $mandatory_keys = [
251
-			    RB::KEY_HANDLER,
252
-			    RB::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[ RB::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(RB::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)', RB::CONF_KEY_CONVERTER_CLASSES, \gettype($classes)));
247
+		}
248
+
249
+		if (!empty($classes)) {
250
+			$mandatory_keys = [
251
+				RB::KEY_HANDLER,
252
+				RB::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.
src/Validator.php 1 patch
Indentation   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -17,165 +17,165 @@
 block discarded – undo
17 17
  */
18 18
 class Validator
19 19
 {
20
-    /**
21
-     * Checks if given $val is of type boolean
22
-     *
23
-     * @param string $var_name Name of the key to be used if exception is thrown.
24
-     * @param mixed  $value    Variable to be asserted.
25
-     *
26
-     * @return void
27
-     *
28
-     * @throws \InvalidArgumentException
29
-     */
30
-    public static function assertIsBool(string $var_name, $value): void
31
-    {
32
-        self::assertIsType($var_name, $value, [Type::BOOLEAN]);
33
-    }
20
+	/**
21
+	 * Checks if given $val is of type boolean
22
+	 *
23
+	 * @param string $var_name Name of the key to be used if exception is thrown.
24
+	 * @param mixed  $value    Variable to be asserted.
25
+	 *
26
+	 * @return void
27
+	 *
28
+	 * @throws \InvalidArgumentException
29
+	 */
30
+	public static function assertIsBool(string $var_name, $value): void
31
+	{
32
+		self::assertIsType($var_name, $value, [Type::BOOLEAN]);
33
+	}
34 34
 
35
-    /**
36
-     * Checks if given $val is of type integer
37
-     *
38
-     * @param string $key   Name of the key to be used if exception is thrown.
39
-     * @param mixed  $value Variable to be asserted.
40
-     *
41
-     * @return void
42
-     *
43
-     * @throws \InvalidArgumentException
44
-     */
45
-    public static function assertIsInt(string $key, $value): void
46
-    {
47
-        self::assertIsType($key, $value, [Type::INTEGER]);
48
-    }
35
+	/**
36
+	 * Checks if given $val is of type integer
37
+	 *
38
+	 * @param string $key   Name of the key to be used if exception is thrown.
39
+	 * @param mixed  $value Variable to be asserted.
40
+	 *
41
+	 * @return void
42
+	 *
43
+	 * @throws \InvalidArgumentException
44
+	 */
45
+	public static function assertIsInt(string $key, $value): void
46
+	{
47
+		self::assertIsType($key, $value, [Type::INTEGER]);
48
+	}
49 49
 
50
-    /**
51
-     * Checks if given $val is of type array
52
-     *
53
-     * @param string $var_name Name of the key to be used if exception is thrown.
54
-     * @param mixed  $value    Variable to be asserted.
55
-     *
56
-     * @return void
57
-     *
58
-     * @throws \InvalidArgumentException
59
-     */
60
-    public static function assertIsArray(string $var_name, $value): void
61
-    {
62
-        self::assertIsType($var_name, $value, [Type::ARRAY]);
63
-    }
50
+	/**
51
+	 * Checks if given $val is of type array
52
+	 *
53
+	 * @param string $var_name Name of the key to be used if exception is thrown.
54
+	 * @param mixed  $value    Variable to be asserted.
55
+	 *
56
+	 * @return void
57
+	 *
58
+	 * @throws \InvalidArgumentException
59
+	 */
60
+	public static function assertIsArray(string $var_name, $value): void
61
+	{
62
+		self::assertIsType($var_name, $value, [Type::ARRAY]);
63
+	}
64 64
 
65
-    /**
66
-     * Checks if given $val is an object
67
-     *
68
-     * @param string $var_name Name of the key to be used if exception is thrown.
69
-     * @param mixed  $value    Variable to be asserted.
70
-     *
71
-     * @return void
72
-     *
73
-     * @throws \InvalidArgumentException
74
-     */
75
-    public static function assertIsObject(string $var_name, $value): void
76
-    {
77
-        self::assertIsType($var_name, $value, [Type::OBJECT]);
78
-    }
65
+	/**
66
+	 * Checks if given $val is an object
67
+	 *
68
+	 * @param string $var_name Name of the key to be used if exception is thrown.
69
+	 * @param mixed  $value    Variable to be asserted.
70
+	 *
71
+	 * @return void
72
+	 *
73
+	 * @throws \InvalidArgumentException
74
+	 */
75
+	public static function assertIsObject(string $var_name, $value): void
76
+	{
77
+		self::assertIsType($var_name, $value, [Type::OBJECT]);
78
+	}
79 79
 
80
-    /**
81
-     * Checks if given $val is of type string
82
-     *
83
-     * @param string $name  Label or name of the variable to be used in exception message (if thrown).
84
-     * @param mixed  $value Variable to be asserted.
85
-     *
86
-     * @return void
87
-     *
88
-     * @throws \InvalidArgumentException
89
-     */
90
-    public static function assertIsString(string $name, $value): void
91
-    {
92
-        self::assertIsType($name, $value, [Type::STRING]);
93
-    }
80
+	/**
81
+	 * Checks if given $val is of type string
82
+	 *
83
+	 * @param string $name  Label or name of the variable to be used in exception message (if thrown).
84
+	 * @param mixed  $value Variable to be asserted.
85
+	 *
86
+	 * @return void
87
+	 *
88
+	 * @throws \InvalidArgumentException
89
+	 */
90
+	public static function assertIsString(string $name, $value): void
91
+	{
92
+		self::assertIsType($name, $value, [Type::STRING]);
93
+	}
94 94
 
95
-    /**
96
-     * @param string $var_name Label or name of the variable to be used in exception message (if thrown).
97
-     * @param mixed  $value    Variable to be asserted.
98
-     * @param int    $min      Min allowed value (inclusive)
99
-     * @param int    $max      Max allowed value (inclusive)
100
-     *
101
-     * @return void
102
-     *
103
-     * @throws \InvalidArgumentException
104
-     * @throws \RuntimeException
105
-     */
106
-    public static function assertIsIntRange(string $var_name, $value, int $min, int $max): void
107
-    {
108
-        self::assertIsInt($var_name, $value);
95
+	/**
96
+	 * @param string $var_name Label or name of the variable to be used in exception message (if thrown).
97
+	 * @param mixed  $value    Variable to be asserted.
98
+	 * @param int    $min      Min allowed value (inclusive)
99
+	 * @param int    $max      Max allowed value (inclusive)
100
+	 *
101
+	 * @return void
102
+	 *
103
+	 * @throws \InvalidArgumentException
104
+	 * @throws \RuntimeException
105
+	 */
106
+	public static function assertIsIntRange(string $var_name, $value, int $min, int $max): void
107
+	{
108
+		self::assertIsInt($var_name, $value);
109 109
 
110
-        if ($min > $max) {
111
-            throw new \RuntimeException(
112
-                \sprintf('%s: Invalid range for "%s". Ensure bound values are not swapped.', __FUNCTION__, $var_name));
113
-        }
110
+		if ($min > $max) {
111
+			throw new \RuntimeException(
112
+				\sprintf('%s: Invalid range for "%s". Ensure bound values are not swapped.', __FUNCTION__, $var_name));
113
+		}
114 114
 
115
-        if (($min > $value) || ($value > $max)) {
116
-            throw new \InvalidArgumentException(
117
-                \sprintf('Invalid value of "%s" (%d). Must be between %d-%d inclusive.', $var_name, $value, $min, $max));
118
-        }
119
-    }
115
+		if (($min > $value) || ($value > $max)) {
116
+			throw new \InvalidArgumentException(
117
+				\sprintf('Invalid value of "%s" (%d). Must be between %d-%d inclusive.', $var_name, $value, $min, $max));
118
+		}
119
+	}
120 120
 
121
-    /**
122
-     * Checks if $item (of name $key) is of type that is include in $allowed_types.
123
-     *
124
-     * @param string $var_name      Label or name of the variable to be used in exception message (if thrown).
125
-     * @param mixed  $value         Variable to be asserted.
126
-     * @param array  $allowed_types Array of allowed types for $var, i.e. [Type::INTEGER]
127
-     *
128
-     * @return void
129
-     *
130
-     * @throws \InvalidArgumentException
131
-     */
132
-    public static function assertIsType(string $var_name, $value, array $allowed_types): void
133
-    {
134
-        $type = \gettype($value);
135
-        if (!\in_array($type, $allowed_types, true)) {
136
-            throw new \InvalidArgumentException(
137
-                \sprintf('"%s" must be one of allowed types: %s (%s given)',
138
-                    $var_name, implode(', ', $allowed_types), \gettype($value))
139
-            );
140
-        }
141
-    }
121
+	/**
122
+	 * Checks if $item (of name $key) is of type that is include in $allowed_types.
123
+	 *
124
+	 * @param string $var_name      Label or name of the variable to be used in exception message (if thrown).
125
+	 * @param mixed  $value         Variable to be asserted.
126
+	 * @param array  $allowed_types Array of allowed types for $var, i.e. [Type::INTEGER]
127
+	 *
128
+	 * @return void
129
+	 *
130
+	 * @throws \InvalidArgumentException
131
+	 */
132
+	public static function assertIsType(string $var_name, $value, array $allowed_types): void
133
+	{
134
+		$type = \gettype($value);
135
+		if (!\in_array($type, $allowed_types, true)) {
136
+			throw new \InvalidArgumentException(
137
+				\sprintf('"%s" must be one of allowed types: %s (%s given)',
138
+					$var_name, implode(', ', $allowed_types), \gettype($value))
139
+			);
140
+		}
141
+	}
142 142
 
143
-    /**
144
-     * Ensures given $http_code is valid code for error response.
145
-     *
146
-     * @param int $http_code
147
-     */
148
-    public static function assertErrorHttpCode(int $http_code): void
149
-    {
150
-        self::assertIsInt('http_code', $http_code);
151
-        self::assertIsIntRange('http_code', $http_code,
152
-            RB::ERROR_HTTP_CODE_MIN, RB::ERROR_HTTP_CODE_MAX);
153
-    }
143
+	/**
144
+	 * Ensures given $http_code is valid code for error response.
145
+	 *
146
+	 * @param int $http_code
147
+	 */
148
+	public static function assertErrorHttpCode(int $http_code): void
149
+	{
150
+		self::assertIsInt('http_code', $http_code);
151
+		self::assertIsIntRange('http_code', $http_code,
152
+			RB::ERROR_HTTP_CODE_MIN, RB::ERROR_HTTP_CODE_MAX);
153
+	}
154 154
 
155
-    /**
156
-     * Ensures given $http_code is valid for response indicating sucessful operation.
157
-     *
158
-     * @param int $http_code
159
-     */
160
-    public static function assertOkHttpCode(int $http_code): void
161
-    {
162
-        self::assertIsInt('http_code', $http_code);
163
-        self::assertIsIntRange('http_code', $http_code, 200, 299);
164
-    }
155
+	/**
156
+	 * Ensures given $http_code is valid for response indicating sucessful operation.
157
+	 *
158
+	 * @param int $http_code
159
+	 */
160
+	public static function assertOkHttpCode(int $http_code): void
161
+	{
162
+		self::assertIsInt('http_code', $http_code);
163
+		self::assertIsIntRange('http_code', $http_code, 200, 299);
164
+	}
165 165
 
166
-    /**
167
-     * Ensures $obj (that is value coming from variable, which name is passed in $label) is instance of $cls class.
168
-     *
169
-     * @param string $var_name Name of variable that the $obj value is coming from. Used for exception message.
170
-     * @param object $obj      Object to check instance of
171
-     * @param string $cls      Target class we want to check $obj agains.
172
-     */
173
-    public static function assertInstanceOf(string $var_name, object $obj, string $cls): void
174
-    {
175
-        if (!($obj instanceof $cls)) {
176
-            throw new \InvalidArgumentException(
177
-                \sprintf('"%s" must be instance of "%s".', $var_name, $cls)
178
-            );
179
-        }
180
-    }
166
+	/**
167
+	 * Ensures $obj (that is value coming from variable, which name is passed in $label) is instance of $cls class.
168
+	 *
169
+	 * @param string $var_name Name of variable that the $obj value is coming from. Used for exception message.
170
+	 * @param object $obj      Object to check instance of
171
+	 * @param string $cls      Target class we want to check $obj agains.
172
+	 */
173
+	public static function assertInstanceOf(string $var_name, object $obj, string $cls): void
174
+	{
175
+		if (!($obj instanceof $cls)) {
176
+			throw new \InvalidArgumentException(
177
+				\sprintf('"%s" must be instance of "%s".', $var_name, $cls)
178
+			);
179
+		}
180
+	}
181 181
 }
Please login to merge, or discard this patch.
src/Contracts/ConverterContract.php 1 patch
Indentation   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -15,14 +15,14 @@
 block discarded – undo
15 15
  */
16 16
 interface ConverterContract
17 17
 {
18
-    /**
19
-     * Returns array representation of the object.
20
-     *
21
-     * @param object $obj    Object to be converted
22
-     * @param array  $config Converter config array to be used for this object (based on exact class
23
-     *                       name match or inheritance).
24
-     *
25
-     * @return array
26
-     */
27
-    public function convert(object $obj, array $config): array;
18
+	/**
19
+	 * Returns array representation of the object.
20
+	 *
21
+	 * @param object $obj    Object to be converted
22
+	 * @param array  $config Converter config array to be used for this object (based on exact class
23
+	 *                       name match or inheritance).
24
+	 *
25
+	 * @return array
26
+	 */
27
+	public function convert(object $obj, array $config): array;
28 28
 }
Please login to merge, or discard this patch.
src/Converters/ToArrayConverter.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -19,19 +19,19 @@
 block discarded – undo
19 19
 
20 20
 final class ToArrayConverter implements ConverterContract
21 21
 {
22
-    /**
23
-     * Returns array representation of the object.
24
-     *
25
-     * @param object $obj    Object to be converted
26
-     * @param array  $config Converter config array to be used for this object (based on exact class
27
-     *                       name match or inheritance).
28
-     *
29
-     * @return array
30
-     */
31
-    public function convert(object $obj, /** @scrutinizer ignore-unused */ array $config): array
32
-    {
33
-        Validator::assertIsObject('obj', $obj);
22
+	/**
23
+	 * Returns array representation of the object.
24
+	 *
25
+	 * @param object $obj    Object to be converted
26
+	 * @param array  $config Converter config array to be used for this object (based on exact class
27
+	 *                       name match or inheritance).
28
+	 *
29
+	 * @return array
30
+	 */
31
+	public function convert(object $obj, /** @scrutinizer ignore-unused */ array $config): array
32
+	{
33
+		Validator::assertIsObject('obj', $obj);
34 34
 
35
-        return $obj->toArray();
36
-    }
35
+		return $obj->toArray();
36
+	}
37 37
 }
Please login to merge, or discard this patch.
src/Converters/ArrayableConverter.php 1 patch
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -19,19 +19,19 @@
 block discarded – undo
19 19
 
20 20
 final class ArrayableConverter implements ConverterContract
21 21
 {
22
-    /**
23
-     * Returns array representation of the object implementing Arrayable interface
24
-     *
25
-     * @param Arrayable $obj    Object to be converted
26
-     * @param array     $config Converter config array to be used for this object (based on exact class
27
-     *                          name match or inheritance).
28
-     *
29
-     * @return array
30
-     */
31
-    public function convert(object $obj, /** @scrutinizer ignore-unused */ array $config): array
32
-    {
33
-        Validator::assertInstanceOf('obj', $obj, Arrayable::class);
22
+	/**
23
+	 * Returns array representation of the object implementing Arrayable interface
24
+	 *
25
+	 * @param Arrayable $obj    Object to be converted
26
+	 * @param array     $config Converter config array to be used for this object (based on exact class
27
+	 *                          name match or inheritance).
28
+	 *
29
+	 * @return array
30
+	 */
31
+	public function convert(object $obj, /** @scrutinizer ignore-unused */ array $config): array
32
+	{
33
+		Validator::assertInstanceOf('obj', $obj, Arrayable::class);
34 34
 
35
-        return $obj->toArray();
36
-    }
35
+		return $obj->toArray();
36
+	}
37 37
 }
Please login to merge, or discard this patch.