Passed
Pull Request — dev (#124)
by Marcin
02:31
created
src/ResponseBuilderServiceProvider.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -25,56 +25,56 @@
 block discarded – undo
25 25
 
26 26
 class ResponseBuilderServiceProvider extends ServiceProvider
27 27
 {
28
-    protected $config_files = [
29
-        'response_builder.php',
30
-    ];
28
+	protected $config_files = [
29
+		'response_builder.php',
30
+	];
31 31
 
32
-    /**
33
-     * Register bindings in the container.
34
-     *
35
-     * @return void
36
-     */
37
-    public function register()
38
-    {
39
-        foreach ($this->config_files as $file) {
40
-            $this->mergeConfigFrom(__DIR__ . "/../config/{$file}", ResponseBuilder::CONF_CONFIG);
41
-        }
42
-    }
32
+	/**
33
+	 * Register bindings in the container.
34
+	 *
35
+	 * @return void
36
+	 */
37
+	public function register()
38
+	{
39
+		foreach ($this->config_files as $file) {
40
+			$this->mergeConfigFrom(__DIR__ . "/../config/{$file}", ResponseBuilder::CONF_CONFIG);
41
+		}
42
+	}
43 43
 
44
-    /**
45
-     * Sets up package resources
46
-     *
47
-     * @return void
48
-     */
49
-    public function boot()
50
-    {
51
-        $this->loadTranslationsFrom(__DIR__ . '/lang', 'response-builder');
44
+	/**
45
+	 * Sets up package resources
46
+	 *
47
+	 * @return void
48
+	 */
49
+	public function boot()
50
+	{
51
+		$this->loadTranslationsFrom(__DIR__ . '/lang', 'response-builder');
52 52
 
53
-        foreach ($this->config_files as $file) {
54
-            $this->publishes([__DIR__ . "/../config/{$file}" => config_path($file)]);
55
-        }
56
-    }
53
+		foreach ($this->config_files as $file) {
54
+			$this->publishes([__DIR__ . "/../config/{$file}" => config_path($file)]);
55
+		}
56
+	}
57 57
 
58
-    /**
59
-     * Merge the given configuration with the existing configuration.
60
-     *
61
-     * @param string $path
62
-     * @param string $key
63
-     *
64
-     * @return void
65
-     */
66
-    protected function mergeConfigFrom($path, $key)
67
-    {
68
-        $defaults = require $path;
69
-        $config = $this->app['config']->get($key, []);
58
+	/**
59
+	 * Merge the given configuration with the existing configuration.
60
+	 *
61
+	 * @param string $path
62
+	 * @param string $key
63
+	 *
64
+	 * @return void
65
+	 */
66
+	protected function mergeConfigFrom($path, $key)
67
+	{
68
+		$defaults = require $path;
69
+		$config = $this->app['config']->get($key, []);
70 70
 
71
-        $merged_config = Util::mergeConfig($defaults, $config);
71
+		$merged_config = Util::mergeConfig($defaults, $config);
72 72
 
73
-        if (array_key_exists('converter', $merged_config)) {
74
-            Util::sortArrayByPri($merged_config['converter']);
75
-        }
73
+		if (array_key_exists('converter', $merged_config)) {
74
+			Util::sortArrayByPri($merged_config['converter']);
75
+		}
76 76
 
77
-        $this->app['config']->set($key, $merged_config);
78
-    }
77
+		$this->app['config']->set($key, $merged_config);
78
+	}
79 79
 
80 80
 }
Please login to merge, or discard this patch.
config/response_builder.php 1 patch
Indentation   +74 added lines, -74 removed lines patch added patch discarded remove patch
@@ -12,66 +12,66 @@  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
-        \Illuminate\Database\Eloquent\Model::class          => [
41
-            'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
42
-            // 'key'     => 'item',
43
-            'pri'     => 0,
44
-        ],
45
-        \Illuminate\Support\Collection::class               => [
46
-            'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
47
-            // 'key'     => 'item',
48
-            'pri'     => 0,
49
-        ],
50
-        \Illuminate\Database\Eloquent\Collection::class     => [
51
-            'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
52
-            // 'key'     => 'item',
53
-            'pri'     => 0,
54
-        ],
55
-        \Illuminate\Http\Resources\Json\JsonResource::class => [
56
-            'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
57
-            // 'key'     => 'item',
58
-            'pri'     => 0,
59
-        ],
60
-        \JsonSerializable::class                            => [
61
-            'handler' => \MarcinOrlowski\ResponseBuilder\Converters\JsonSerializableConverter::class,
62
-            // 'key'     => 'item',
63
-            'pri'     => -10,
64
-        ],
65
-    ],
39
+	'converter'         => [
40
+		\Illuminate\Database\Eloquent\Model::class          => [
41
+			'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
42
+			// 'key'     => 'item',
43
+			'pri'     => 0,
44
+		],
45
+		\Illuminate\Support\Collection::class               => [
46
+			'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
47
+			// 'key'     => 'item',
48
+			'pri'     => 0,
49
+		],
50
+		\Illuminate\Database\Eloquent\Collection::class     => [
51
+			'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
52
+			// 'key'     => 'item',
53
+			'pri'     => 0,
54
+		],
55
+		\Illuminate\Http\Resources\Json\JsonResource::class => [
56
+			'handler' => \MarcinOrlowski\ResponseBuilder\Converters\ToArrayConverter::class,
57
+			// 'key'     => 'item',
58
+			'pri'     => 0,
59
+		],
60
+		\JsonSerializable::class                            => [
61
+			'handler' => \MarcinOrlowski\ResponseBuilder\Converters\JsonSerializableConverter::class,
62
+			// 'key'     => 'item',
63
+			'pri'     => -10,
64
+		],
65
+	],
66 66
 
67
-    /*
67
+	/*
68 68
     |-----------------------------------------------------------------------------------------------------------
69 69
     | Exception handler error codes
70 70
     |-----------------------------------------------------------------------------------------------------------
71 71
     |
72 72
     */
73
-    'exception_handler' => [
74
-        /*
73
+	'exception_handler' => [
74
+		/*
75 75
          * The following options can be used for each entry specified:
76 76
          * `api_code`   : (int) mandatory api_code to be used for given exception
77 77
          * `http_code`  : (int) optional HTTP code. If not specified, exception's HTTP status code will be used.
@@ -84,8 +84,8 @@  discard block
 block discarded – undo
84 84
          *                `msg_key` is set, or message referenced by `msg_key` completely ignoring exception
85 85
          *                message ($ex->getMessage()).
86 86
          */
87
-        'map' => [
88
-            /*
87
+		'map' => [
88
+			/*
89 89
              * HTTP Exceptions
90 90
              * ---------------
91 91
              * Configure how you want Http Exception to be handled based on its Http status code.
@@ -93,51 +93,51 @@  discard block
 block discarded – undo
93 93
              * Additionally, you can specify `http_code` to be any valid 400-599 HTTP status code, otherwise
94 94
              * code set in the exception will be used.
95 95
              */
96
-            //            HttpException::class => [
97
-            //                // used by unauthenticated() to obtain api and http code for the exception
98
-            //                HttpResponse::HTTP_UNAUTHORIZED         => [
99
-            //                    'api_code'  => ApiCodes::YOUR_API_CODE_FOR_UNATHORIZED_EXCEPTION,
100
-            //                ],
101
-            //                // Required by ValidationException handler
102
-            //                HttpResponse::HTTP_UNPROCESSABLE_ENTITY => [
103
-            //                    'api_code'  => ApiCodes::YOUR_API_CODE_FOR_VALIDATION_EXCEPTION,
104
-            //                ],
105
-            //                // default handler is mandatory and MUST have both `api_code` and `http_code` set.
106
-            //                'default'                               => [
107
-            //                    'api_code'  => ApiCodes::YOUR_API_CODE_FOR_GENERIC_HTTP_EXCEPTION,
108
-            //                    'http_code' => HttpResponse::HTTP_BAD_REQUEST,
109
-            //                ],
110
-            //            ],
111
-            //            // This is final exception handler. If ex is not dealt with yet this is its last stop.
112
-            //            // default handler is mandatory and MUST have both `api_code` and `http_code` set.
113
-            //            'default'            => [
114
-            //                'api_code'  => ApiCodes::YOUR_API_CODE_FOR_UNHANDLED_EXCEPTION,
115
-            //                'http_code' => HttpResponse::HTTP_INTERNAL_SERVER_ERROR,
116
-            //            ],
117
-            //        ],
118
-        ],
119
-    ],
96
+			//            HttpException::class => [
97
+			//                // used by unauthenticated() to obtain api and http code for the exception
98
+			//                HttpResponse::HTTP_UNAUTHORIZED         => [
99
+			//                    'api_code'  => ApiCodes::YOUR_API_CODE_FOR_UNATHORIZED_EXCEPTION,
100
+			//                ],
101
+			//                // Required by ValidationException handler
102
+			//                HttpResponse::HTTP_UNPROCESSABLE_ENTITY => [
103
+			//                    'api_code'  => ApiCodes::YOUR_API_CODE_FOR_VALIDATION_EXCEPTION,
104
+			//                ],
105
+			//                // default handler is mandatory and MUST have both `api_code` and `http_code` set.
106
+			//                'default'                               => [
107
+			//                    'api_code'  => ApiCodes::YOUR_API_CODE_FOR_GENERIC_HTTP_EXCEPTION,
108
+			//                    'http_code' => HttpResponse::HTTP_BAD_REQUEST,
109
+			//                ],
110
+			//            ],
111
+			//            // This is final exception handler. If ex is not dealt with yet this is its last stop.
112
+			//            // default handler is mandatory and MUST have both `api_code` and `http_code` set.
113
+			//            'default'            => [
114
+			//                'api_code'  => ApiCodes::YOUR_API_CODE_FOR_UNHANDLED_EXCEPTION,
115
+			//                'http_code' => HttpResponse::HTTP_INTERNAL_SERVER_ERROR,
116
+			//            ],
117
+			//        ],
118
+		],
119
+	],
120 120
 
121
-    /*
121
+	/*
122 122
     |-----------------------------------------------------------------------------------------------------------
123 123
     | data-to-json encoding options
124 124
     |-----------------------------------------------------------------------------------------------------------
125 125
     |
126 126
     */
127
-    'encoding_options'  => JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE,
127
+	'encoding_options'  => JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE,
128 128
 
129
-    /*
129
+	/*
130 130
     |-----------------------------------------------------------------------------------------------------------
131 131
     | Debug config
132 132
     |-----------------------------------------------------------------------------------------------------------
133 133
     |
134 134
     */
135
-    'debug'             => [
136
-        'debug_key'         => 'debug',
137
-        'exception_handler' => [
138
-            'trace_key'     => 'trace',
139
-            'trace_enabled' => env('APP_DEBUG', false),
140
-        ],
141
-    ],
135
+	'debug'             => [
136
+		'debug_key'         => 'debug',
137
+		'exception_handler' => [
138
+			'trace_key'     => 'trace',
139
+			'trace_enabled' => env('APP_DEBUG', false),
140
+		],
141
+	],
142 142
 
143 143
 ];
Please login to merge, or discard this patch.
src/ResponseBuilder.php 1 patch
Indentation   +327 added lines, -327 removed lines patch added patch discarded remove patch
@@ -24,351 +24,351 @@
 block discarded – undo
24 24
  */
25 25
 class ResponseBuilder
26 26
 {
27
-    /**
28
-     * Default HTTP code to be used with success responses
29
-     *
30
-     * @var int
31
-     */
32
-    public const DEFAULT_HTTP_CODE_OK = HttpResponse::HTTP_OK;
27
+	/**
28
+	 * Default HTTP code to be used with success responses
29
+	 *
30
+	 * @var int
31
+	 */
32
+	public const DEFAULT_HTTP_CODE_OK = HttpResponse::HTTP_OK;
33 33
 
34
-    /**
35
-     * Default HTTP code to be used with error responses
36
-     *
37
-     * @var int
38
-     */
39
-    public const DEFAULT_HTTP_CODE_ERROR = HttpResponse::HTTP_BAD_REQUEST;
34
+	/**
35
+	 * Default HTTP code to be used with error responses
36
+	 *
37
+	 * @var int
38
+	 */
39
+	public const DEFAULT_HTTP_CODE_ERROR = HttpResponse::HTTP_BAD_REQUEST;
40 40
 
41
-    /**
42
-     * Min allowed HTTP code for errorXXX()
43
-     *
44
-     * @var int
45
-     */
46
-    public const ERROR_HTTP_CODE_MIN = 400;
41
+	/**
42
+	 * Min allowed HTTP code for errorXXX()
43
+	 *
44
+	 * @var int
45
+	 */
46
+	public const ERROR_HTTP_CODE_MIN = 400;
47 47
 
48
-    /**
49
-     * Max allowed HTTP code for errorXXX()
50
-     *
51
-     * @var int
52
-     */
53
-    public const ERROR_HTTP_CODE_MAX = 599;
48
+	/**
49
+	 * Max allowed HTTP code for errorXXX()
50
+	 *
51
+	 * @var int
52
+	 */
53
+	public const ERROR_HTTP_CODE_MAX = 599;
54 54
 
55
-    /**
56
-     * Configuration keys
57
-     */
58
-    public const CONF_CONFIG                     = 'response-builder';
59
-    public const CONF_KEY_DEBUG_DEBUG_KEY        = self::CONF_CONFIG . '.debug.debug_key';
60
-    public const CONF_KEY_DEBUG_EX_TRACE_ENABLED = self::CONF_CONFIG . '.debug.exception_handler.trace_enabled';
61
-    public const CONF_KEY_DEBUG_EX_TRACE_KEY     = self::CONF_CONFIG . '.debug.exception_handler.trace_key';
62
-    public const CONF_KEY_MAP                    = self::CONF_CONFIG . '.map';
63
-    public const CONF_KEY_ENCODING_OPTIONS       = self::CONF_CONFIG . '.encoding_options';
64
-    public const CONF_KEY_CONVERTER              = self::CONF_CONFIG . '.converter';
65
-    public const CONF_KEY_MIN_CODE               = self::CONF_CONFIG . '.min_code';
66
-    public const CONF_KEY_MAX_CODE               = self::CONF_CONFIG . '.max_code';
67
-    public const CONF_KEY_EXCEPTION_HANDLER      = self::CONF_CONFIG . '.exception_handler';
55
+	/**
56
+	 * Configuration keys
57
+	 */
58
+	public const CONF_CONFIG                     = 'response-builder';
59
+	public const CONF_KEY_DEBUG_DEBUG_KEY        = self::CONF_CONFIG . '.debug.debug_key';
60
+	public const CONF_KEY_DEBUG_EX_TRACE_ENABLED = self::CONF_CONFIG . '.debug.exception_handler.trace_enabled';
61
+	public const CONF_KEY_DEBUG_EX_TRACE_KEY     = self::CONF_CONFIG . '.debug.exception_handler.trace_key';
62
+	public const CONF_KEY_MAP                    = self::CONF_CONFIG . '.map';
63
+	public const CONF_KEY_ENCODING_OPTIONS       = self::CONF_CONFIG . '.encoding_options';
64
+	public const CONF_KEY_CONVERTER              = self::CONF_CONFIG . '.converter';
65
+	public const CONF_KEY_MIN_CODE               = self::CONF_CONFIG . '.min_code';
66
+	public const CONF_KEY_MAX_CODE               = self::CONF_CONFIG . '.max_code';
67
+	public const CONF_KEY_EXCEPTION_HANDLER      = self::CONF_CONFIG . '.exception_handler';
68 68
 
69
-    /**
70
-     * Default keys to be used by exception handler while adding debug information
71
-     */
72
-    public const KEY_DEBUG   = 'debug';
73
-    public const KEY_TRACE   = 'trace';
74
-    public const KEY_CLASS   = 'class';
75
-    public const KEY_FILE    = 'file';
76
-    public const KEY_LINE    = 'line';
77
-    public const KEY_KEY     = 'key';
78
-    public const KEY_PRI     = 'pri';
79
-    public const KEY_HANDLER = 'handler';
80
-    public const KEY_SUCCESS = 'success';
81
-    public const KEY_CODE    = 'code';
82
-    public const KEY_LOCALE  = 'locale';
83
-    public const KEY_MESSAGE = 'message';
84
-    public const KEY_DATA    = 'data';
69
+	/**
70
+	 * Default keys to be used by exception handler while adding debug information
71
+	 */
72
+	public const KEY_DEBUG   = 'debug';
73
+	public const KEY_TRACE   = 'trace';
74
+	public const KEY_CLASS   = 'class';
75
+	public const KEY_FILE    = 'file';
76
+	public const KEY_LINE    = 'line';
77
+	public const KEY_KEY     = 'key';
78
+	public const KEY_PRI     = 'pri';
79
+	public const KEY_HANDLER = 'handler';
80
+	public const KEY_SUCCESS = 'success';
81
+	public const KEY_CODE    = 'code';
82
+	public const KEY_LOCALE  = 'locale';
83
+	public const KEY_MESSAGE = 'message';
84
+	public const KEY_DATA    = 'data';
85 85
 
86
-    /**
87
-     * Default key to be used by exception handler while processing ValidationException
88
-     * to return all the error messages
89
-     *
90
-     * @var string
91
-     */
92
-    public const KEY_MESSAGES = 'messages';
86
+	/**
87
+	 * Default key to be used by exception handler while processing ValidationException
88
+	 * to return all the error messages
89
+	 *
90
+	 * @var string
91
+	 */
92
+	public const KEY_MESSAGES = 'messages';
93 93
 
94
-    /**
95
-     * Default JSON encoding options. Must be specified as final value (i.e. 271) and NOT
96
-     * PHP expression i.e. `JSON_HEX_TAG|JSON_HEX_APOS|...` as such syntax is not yet supported
97
-     * by PHP.
98
-     *
99
-     * 271 = JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE
100
-     *
101
-     * @var int
102
-     */
103
-    public const DEFAULT_ENCODING_OPTIONS = 271;
94
+	/**
95
+	 * Default JSON encoding options. Must be specified as final value (i.e. 271) and NOT
96
+	 * PHP expression i.e. `JSON_HEX_TAG|JSON_HEX_APOS|...` as such syntax is not yet supported
97
+	 * by PHP.
98
+	 *
99
+	 * 271 = JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE
100
+	 *
101
+	 * @var int
102
+	 */
103
+	public const DEFAULT_ENCODING_OPTIONS = 271;
104 104
 
105 105
 
106
-    /**
107
-     * Returns success
108
-     *
109
-     * @param object|array|null $data          Array of primitives and supported objects to be returned in 'data' node
110
-     *                                         of the JSON response, single supported object or @null if there's no
111
-     *                                         to be returned.
112
-     * @param integer|null      $api_code      API code to be returned or @null to use value of BaseApiCodes::OK().
113
-     * @param array|null        $placeholders  Placeholders passed to Lang::get() for message placeholders
114
-     *                                         substitution or @null if none.
115
-     * @param integer|null      $http_code     HTTP code to be used for HttpResponse sent or @null
116
-     *                                         for default DEFAULT_HTTP_CODE_OK.
117
-     * @param integer|null      $json_opts     See http://php.net/manual/en/function.json-encode.php for supported
118
-     *                                         options or pass @null to use value from your config (or defaults).
119
-     *
120
-     * @return HttpResponse
121
-     */
122
-    public static function success($data = null, $api_code = null, array $placeholders = null,
123
-                                   int $http_code = null, int $json_opts = null): HttpResponse
124
-    {
125
-        return Builder::success($api_code)
126
-            ->withData($data)
127
-            ->withPlaceholders($placeholders)
128
-            ->withHttpCode($http_code)
129
-            ->withJsonOptions($json_opts)
130
-            ->build();
131
-    }
106
+	/**
107
+	 * Returns success
108
+	 *
109
+	 * @param object|array|null $data          Array of primitives and supported objects to be returned in 'data' node
110
+	 *                                         of the JSON response, single supported object or @null if there's no
111
+	 *                                         to be returned.
112
+	 * @param integer|null      $api_code      API code to be returned or @null to use value of BaseApiCodes::OK().
113
+	 * @param array|null        $placeholders  Placeholders passed to Lang::get() for message placeholders
114
+	 *                                         substitution or @null if none.
115
+	 * @param integer|null      $http_code     HTTP code to be used for HttpResponse sent or @null
116
+	 *                                         for default DEFAULT_HTTP_CODE_OK.
117
+	 * @param integer|null      $json_opts     See http://php.net/manual/en/function.json-encode.php for supported
118
+	 *                                         options or pass @null to use value from your config (or defaults).
119
+	 *
120
+	 * @return HttpResponse
121
+	 */
122
+	public static function success($data = null, $api_code = null, array $placeholders = null,
123
+								   int $http_code = null, int $json_opts = null): HttpResponse
124
+	{
125
+		return Builder::success($api_code)
126
+			->withData($data)
127
+			->withPlaceholders($placeholders)
128
+			->withHttpCode($http_code)
129
+			->withJsonOptions($json_opts)
130
+			->build();
131
+	}
132 132
 
133
-    /**
134
-     * Returns success
135
-     *
136
-     * @param integer|null $api_code      API code to be returned or @null to use value of BaseApiCodes::OK().
137
-     * @param array|null   $placeholders  Placeholders passed to Lang::get() for message placeholders
138
-     *                                    substitution or @null if none.
139
-     * @param integer|null $http_code     HTTP code to be used for HttpResponse sent or @null
140
-     *                                    for default DEFAULT_HTTP_CODE_OK.
141
-     *
142
-     * @return HttpResponse
143
-     *
144
-     * @deprecated Please use Builder class.
145
-     */
146
-    public static function successWithCode(int $api_code = null, array $placeholders = null,
147
-                                           int $http_code = null): HttpResponse
148
-    {
149
-        return Builder::success($api_code)
150
-            ->withPlaceholders($placeholders)
151
-            ->withHttpCode($http_code)
152
-            ->build();
153
-    }
133
+	/**
134
+	 * Returns success
135
+	 *
136
+	 * @param integer|null $api_code      API code to be returned or @null to use value of BaseApiCodes::OK().
137
+	 * @param array|null   $placeholders  Placeholders passed to Lang::get() for message placeholders
138
+	 *                                    substitution or @null if none.
139
+	 * @param integer|null $http_code     HTTP code to be used for HttpResponse sent or @null
140
+	 *                                    for default DEFAULT_HTTP_CODE_OK.
141
+	 *
142
+	 * @return HttpResponse
143
+	 *
144
+	 * @deprecated Please use Builder class.
145
+	 */
146
+	public static function successWithCode(int $api_code = null, array $placeholders = null,
147
+										   int $http_code = null): HttpResponse
148
+	{
149
+		return Builder::success($api_code)
150
+			->withPlaceholders($placeholders)
151
+			->withHttpCode($http_code)
152
+			->build();
153
+	}
154 154
 
155
-    /**
156
-     * @param string            $message       Custom message to be returned as part of the response.
157
-     * @param object|array|null $data          Array of primitives and supported objects to be returned in 'data' node
158
-     *                                         of the JSON response, single supported object or @null if there's no
159
-     *                                         to be returned.
160
-     * @param integer|null      $http_code     HTTP code to be used for HttpResponse sent or @null
161
-     *                                         for default DEFAULT_HTTP_CODE_OK.
162
-     *
163
-     * @return HttpResponse
164
-     *
165
-     * @deprecated Please use Builder class.
166
-     */
167
-    public static function successWithMessage(string $message, $data = null, int $api_code = null,
168
-                                              int $http_code = null): HttpResponse
169
-    {
170
-        return Builder::success($api_code)
171
-            ->withMessage($message)
172
-            ->withData($data)
173
-            ->withHttpCode($http_code)
174
-            ->build();
175
-    }
155
+	/**
156
+	 * @param string            $message       Custom message to be returned as part of the response.
157
+	 * @param object|array|null $data          Array of primitives and supported objects to be returned in 'data' node
158
+	 *                                         of the JSON response, single supported object or @null if there's no
159
+	 *                                         to be returned.
160
+	 * @param integer|null      $http_code     HTTP code to be used for HttpResponse sent or @null
161
+	 *                                         for default DEFAULT_HTTP_CODE_OK.
162
+	 *
163
+	 * @return HttpResponse
164
+	 *
165
+	 * @deprecated Please use Builder class.
166
+	 */
167
+	public static function successWithMessage(string $message, $data = null, int $api_code = null,
168
+											  int $http_code = null): HttpResponse
169
+	{
170
+		return Builder::success($api_code)
171
+			->withMessage($message)
172
+			->withData($data)
173
+			->withHttpCode($http_code)
174
+			->build();
175
+	}
176 176
 
177
-    /**
178
-     * @param object|array|null $data          Array of primitives and supported objects to be returned in 'data' node.
179
-     *                                         of the JSON response, single supported object or @null if there's no
180
-     *                                         to be returned.
181
-     * @param integer|null      $api_code      API code to be returned or @null to use value of BaseApiCodes::OK().
182
-     * @param array|null        $placeholders  Placeholders passed to Lang::get() for message placeholders
183
-     *                                         substitution or @null if none.
184
-     * @param integer|null      $http_code     HTTP code to be used for HttpResponse sent or @null
185
-     *                                         for default DEFAULT_HTTP_CODE_OK.
186
-     * @param integer|null      $json_opts     See http://php.net/manual/en/function.json-encode.php for supported
187
-     *                                         options or pass @null to use value from your config (or defaults).
188
-     *
189
-     * @return HttpResponse
190
-     *
191
-     * @deprecated Please use Builder class.
192
-     */
193
-    public static function successWithHttpCode(int $http_code = null): HttpResponse
194
-    {
195
-        return Builder::success()
196
-            ->withHttpCode($http_code)
197
-            ->build();
198
-    }
177
+	/**
178
+	 * @param object|array|null $data          Array of primitives and supported objects to be returned in 'data' node.
179
+	 *                                         of the JSON response, single supported object or @null if there's no
180
+	 *                                         to be returned.
181
+	 * @param integer|null      $api_code      API code to be returned or @null to use value of BaseApiCodes::OK().
182
+	 * @param array|null        $placeholders  Placeholders passed to Lang::get() for message placeholders
183
+	 *                                         substitution or @null if none.
184
+	 * @param integer|null      $http_code     HTTP code to be used for HttpResponse sent or @null
185
+	 *                                         for default DEFAULT_HTTP_CODE_OK.
186
+	 * @param integer|null      $json_opts     See http://php.net/manual/en/function.json-encode.php for supported
187
+	 *                                         options or pass @null to use value from your config (or defaults).
188
+	 *
189
+	 * @return HttpResponse
190
+	 *
191
+	 * @deprecated Please use Builder class.
192
+	 */
193
+	public static function successWithHttpCode(int $http_code = null): HttpResponse
194
+	{
195
+		return Builder::success()
196
+			->withHttpCode($http_code)
197
+			->build();
198
+	}
199 199
 
200
-    /**
201
-     * Builds error Response object. Supports optional arguments passed to Lang::get() if associated error
202
-     * message uses placeholders as well as return data payload
203
-     *
204
-     * @param integer           $api_code      Your API code to be returned with the response object.
205
-     * @param array|null        $placeholders  Placeholders passed to Lang::get() for message placeholders
206
-     *                                         substitution or @null if none.
207
-     * @param object|array|null $data          Array of primitives and supported objects to be returned in 'data' node
208
-     *                                         of the JSON response, single supported object or @null if there's no
209
-     *                                         to be returned.
210
-     * @param integer|null      $http_code     HTTP code to be used for HttpResponse sent or @null
211
-     *                                         for default DEFAULT_HTTP_CODE_ERROR.
212
-     * @param integer|null      $json_opts     See http://php.net/manual/en/function.json-encode.php for supported
213
-     *                                         options or pass @null to use value from your config (or defaults).
214
-     *
215
-     * @return HttpResponse
216
-     */
217
-    public static function error(int $api_code, array $placeholders = null, $data = null, int $http_code = null,
218
-                                 int $json_opts = null): HttpResponse
219
-    {
220
-        return Builder::error($api_code)
221
-            ->withPlaceholders($placeholders)
222
-            ->withData($data)
223
-            ->withHttpCode($http_code)
224
-            ->withJsonOptions($json_opts)
225
-            ->build();
226
-    }
200
+	/**
201
+	 * Builds error Response object. Supports optional arguments passed to Lang::get() if associated error
202
+	 * message uses placeholders as well as return data payload
203
+	 *
204
+	 * @param integer           $api_code      Your API code to be returned with the response object.
205
+	 * @param array|null        $placeholders  Placeholders passed to Lang::get() for message placeholders
206
+	 *                                         substitution or @null if none.
207
+	 * @param object|array|null $data          Array of primitives and supported objects to be returned in 'data' node
208
+	 *                                         of the JSON response, single supported object or @null if there's no
209
+	 *                                         to be returned.
210
+	 * @param integer|null      $http_code     HTTP code to be used for HttpResponse sent or @null
211
+	 *                                         for default DEFAULT_HTTP_CODE_ERROR.
212
+	 * @param integer|null      $json_opts     See http://php.net/manual/en/function.json-encode.php for supported
213
+	 *                                         options or pass @null to use value from your config (or defaults).
214
+	 *
215
+	 * @return HttpResponse
216
+	 */
217
+	public static function error(int $api_code, array $placeholders = null, $data = null, int $http_code = null,
218
+								 int $json_opts = null): HttpResponse
219
+	{
220
+		return Builder::error($api_code)
221
+			->withPlaceholders($placeholders)
222
+			->withData($data)
223
+			->withHttpCode($http_code)
224
+			->withJsonOptions($json_opts)
225
+			->build();
226
+	}
227 227
 
228
-    /**
229
-     * @param integer           $api_code      Your API code to be returned with the response object.
230
-     * @param object|array|null $data          Array of primitives and supported objects to be returned in 'data' node
231
-     *                                         of the JSON response, single supported object or @null if there's no
232
-     *                                         to be returned.
233
-     * @param array|null        $placeholders  Placeholders passed to Lang::get() for message placeholders
234
-     *                                         substitution or @null if none.
235
-     * @param integer|null      $json_opts     See http://php.net/manual/en/function.json-encode.php for supported
236
-     *                                         options or pass @null to use value from your config (or defaults).
237
-     *
238
-     * @return HttpResponse
239
-     *
240
-     * @deprecated Please use Builder class.
241
-     */
242
-    public static function errorWithData(int $api_code, $data, array $placeholders = null,
243
-                                         int $json_opts = null): HttpResponse
244
-    {
245
-        return Builder::error($api_code)
246
-            ->withData($data)
247
-            ->withPlaceholders($placeholders)
248
-            ->withJsonOptions($json_opts)
249
-            ->build();
250
-    }
228
+	/**
229
+	 * @param integer           $api_code      Your API code to be returned with the response object.
230
+	 * @param object|array|null $data          Array of primitives and supported objects to be returned in 'data' node
231
+	 *                                         of the JSON response, single supported object or @null if there's no
232
+	 *                                         to be returned.
233
+	 * @param array|null        $placeholders  Placeholders passed to Lang::get() for message placeholders
234
+	 *                                         substitution or @null if none.
235
+	 * @param integer|null      $json_opts     See http://php.net/manual/en/function.json-encode.php for supported
236
+	 *                                         options or pass @null to use value from your config (or defaults).
237
+	 *
238
+	 * @return HttpResponse
239
+	 *
240
+	 * @deprecated Please use Builder class.
241
+	 */
242
+	public static function errorWithData(int $api_code, $data, array $placeholders = null,
243
+										 int $json_opts = null): HttpResponse
244
+	{
245
+		return Builder::error($api_code)
246
+			->withData($data)
247
+			->withPlaceholders($placeholders)
248
+			->withJsonOptions($json_opts)
249
+			->build();
250
+	}
251 251
 
252
-    /**
253
-     * @param integer           $api_code      Your API code to be returned with the response object.
254
-     * @param object|array|null $data          Array of primitives and supported objects to be returned in 'data' node
255
-     *                                         of the JSON response, single supported object or @null if there's no
256
-     *                                         to be returned.
257
-     * @param integer           $http_code     HTTP code to be used for HttpResponse sent.
258
-     * @param array|null        $placeholders  Placeholders passed to Lang::get() for message placeholders
259
-     *                                         substitution or @null if none.
260
-     * @param integer|null      $json_opts     See http://php.net/manual/en/function.json-encode.php for supported
261
-     *                                         options or pass @null to use value from your config (or defaults).
262
-     *
263
-     * @return HttpResponse
264
-     *
265
-     * @throws \InvalidArgumentException if http_code is @null
266
-     *
267
-     * @deprecated Please use Builder class.
268
-     */
269
-    public static function errorWithDataAndHttpCode(int $api_code, $data, int $http_code, array $placeholders = null,
270
-                                                    int $json_opts = null): HttpResponse
271
-    {
272
-        return Builder::error($api_code)
273
-            ->withData($data)
274
-            ->withHttpCode($http_code)
275
-            ->withPlaceholders($placeholders)
276
-            ->withJsonOptions($json_opts)
277
-            ->build();
278
-    }
252
+	/**
253
+	 * @param integer           $api_code      Your API code to be returned with the response object.
254
+	 * @param object|array|null $data          Array of primitives and supported objects to be returned in 'data' node
255
+	 *                                         of the JSON response, single supported object or @null if there's no
256
+	 *                                         to be returned.
257
+	 * @param integer           $http_code     HTTP code to be used for HttpResponse sent.
258
+	 * @param array|null        $placeholders  Placeholders passed to Lang::get() for message placeholders
259
+	 *                                         substitution or @null if none.
260
+	 * @param integer|null      $json_opts     See http://php.net/manual/en/function.json-encode.php for supported
261
+	 *                                         options or pass @null to use value from your config (or defaults).
262
+	 *
263
+	 * @return HttpResponse
264
+	 *
265
+	 * @throws \InvalidArgumentException if http_code is @null
266
+	 *
267
+	 * @deprecated Please use Builder class.
268
+	 */
269
+	public static function errorWithDataAndHttpCode(int $api_code, $data, int $http_code, array $placeholders = null,
270
+													int $json_opts = null): HttpResponse
271
+	{
272
+		return Builder::error($api_code)
273
+			->withData($data)
274
+			->withHttpCode($http_code)
275
+			->withPlaceholders($placeholders)
276
+			->withJsonOptions($json_opts)
277
+			->build();
278
+	}
279 279
 
280
-    /**
281
-     * @param integer    $api_code     Your API code to be returned with the response object.
282
-     * @param integer    $http_code    HTTP code to be used for HttpResponse sent or @null
283
-     *                                 for default DEFAULT_HTTP_CODE_ERROR.
284
-     * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders
285
-     *                                 substitution or @null if none.
286
-     *
287
-     * @return HttpResponse
288
-     *
289
-     * @throws \InvalidArgumentException if http_code is @null
290
-     *
291
-     * @deprecated Please use Builder class.
292
-     */
293
-    public static function errorWithHttpCode(int $api_code, int $http_code, array $placeholders = null): HttpResponse
294
-    {
295
-        return Builder::error($api_code)
296
-            ->withHttpCode($http_code)
297
-            ->withPlaceholders($placeholders)
298
-            ->build();
299
-    }
280
+	/**
281
+	 * @param integer    $api_code     Your API code to be returned with the response object.
282
+	 * @param integer    $http_code    HTTP code to be used for HttpResponse sent or @null
283
+	 *                                 for default DEFAULT_HTTP_CODE_ERROR.
284
+	 * @param array|null $placeholders Placeholders passed to Lang::get() for message placeholders
285
+	 *                                 substitution or @null if none.
286
+	 *
287
+	 * @return HttpResponse
288
+	 *
289
+	 * @throws \InvalidArgumentException if http_code is @null
290
+	 *
291
+	 * @deprecated Please use Builder class.
292
+	 */
293
+	public static function errorWithHttpCode(int $api_code, int $http_code, array $placeholders = null): HttpResponse
294
+	{
295
+		return Builder::error($api_code)
296
+			->withHttpCode($http_code)
297
+			->withPlaceholders($placeholders)
298
+			->build();
299
+	}
300 300
 
301
-    /**
302
-     * @param integer           $api_code  Your API code to be returned with the response object.
303
-     * @param string            $message   Custom message to be returned as part of error response
304
-     * @param object|array|null $data      Array of primitives and supported objects to be returned in 'data' node
305
-     *                                     of the JSON response, single supported object or @null if there's no
306
-     *                                     to be returned.
307
-     * @param integer|null      $http_code Optional HTTP status code to be used for HttpResponse sent
308
-     *                                     or @null for DEFAULT_HTTP_CODE_ERROR
309
-     * @param integer|null      $json_opts See http://php.net/manual/en/function.json-encode.php for supported
310
-     *                                     options or pass @null to use value from your config (or defaults).
311
-     *
312
-     * @return HttpResponse
313
-     *
314
-     * @deprecated Please use Builder class.
315
-     */
316
-    public static function errorWithMessageAndData(int $api_code, string $message, $data,
317
-                                                   int $http_code = null, int $json_opts = null): HttpResponse
318
-    {
319
-        return Builder::error($api_code)
320
-            ->withMessage($message)
321
-            ->withData($data)
322
-            ->withHttpCode($http_code)
323
-            ->withJsonOptions($json_opts)
324
-            ->build();
325
-    }
301
+	/**
302
+	 * @param integer           $api_code  Your API code to be returned with the response object.
303
+	 * @param string            $message   Custom message to be returned as part of error response
304
+	 * @param object|array|null $data      Array of primitives and supported objects to be returned in 'data' node
305
+	 *                                     of the JSON response, single supported object or @null if there's no
306
+	 *                                     to be returned.
307
+	 * @param integer|null      $http_code Optional HTTP status code to be used for HttpResponse sent
308
+	 *                                     or @null for DEFAULT_HTTP_CODE_ERROR
309
+	 * @param integer|null      $json_opts See http://php.net/manual/en/function.json-encode.php for supported
310
+	 *                                     options or pass @null to use value from your config (or defaults).
311
+	 *
312
+	 * @return HttpResponse
313
+	 *
314
+	 * @deprecated Please use Builder class.
315
+	 */
316
+	public static function errorWithMessageAndData(int $api_code, string $message, $data,
317
+												   int $http_code = null, int $json_opts = null): HttpResponse
318
+	{
319
+		return Builder::error($api_code)
320
+			->withMessage($message)
321
+			->withData($data)
322
+			->withHttpCode($http_code)
323
+			->withJsonOptions($json_opts)
324
+			->build();
325
+	}
326 326
 
327
-    /**
328
-     * @param integer           $api_code   Your API code to be returned with the response object.
329
-     * @param string            $message    custom message to be returned as part of error response
330
-     * @param object|array|null $data       Array of primitives and supported objects to be returned in 'data' node
331
-     *                                      of the JSON response, single supported object or @null if there's no
332
-     *                                      to be returned.
333
-     * @param integer|null      $http_code  HTTP code to be used for HttpResponse sent or @null
334
-     *                                      for default DEFAULT_HTTP_CODE_ERROR.
335
-     * @param integer|null      $json_opts  See http://php.net/manual/en/function.json-encode.php for supported
336
-     *                                      options or pass @null to use value from your config (or defaults).
337
-     * @param array|null        $debug_data optional debug data array to be added to returned JSON.
338
-     *
339
-     * @return HttpResponse
340
-     *
341
-     * @deprecated Please use Builder class.
342
-     */
343
-    public static function errorWithMessageAndDataAndDebug(int $api_code, string $message, $data,
344
-                                                           int $http_code = null, int $json_opts = null,
345
-                                                           array $debug_data = null): HttpResponse
346
-    {
347
-        return Builder::error($api_code)
348
-            ->withMessage($message)
349
-            ->withData($data)
350
-            ->withHttpCode($http_code)
351
-            ->withJsonOptions($json_opts)
352
-            ->withDebugData($debug_data)
353
-            ->build();
354
-    }
327
+	/**
328
+	 * @param integer           $api_code   Your API code to be returned with the response object.
329
+	 * @param string            $message    custom message to be returned as part of error response
330
+	 * @param object|array|null $data       Array of primitives and supported objects to be returned in 'data' node
331
+	 *                                      of the JSON response, single supported object or @null if there's no
332
+	 *                                      to be returned.
333
+	 * @param integer|null      $http_code  HTTP code to be used for HttpResponse sent or @null
334
+	 *                                      for default DEFAULT_HTTP_CODE_ERROR.
335
+	 * @param integer|null      $json_opts  See http://php.net/manual/en/function.json-encode.php for supported
336
+	 *                                      options or pass @null to use value from your config (or defaults).
337
+	 * @param array|null        $debug_data optional debug data array to be added to returned JSON.
338
+	 *
339
+	 * @return HttpResponse
340
+	 *
341
+	 * @deprecated Please use Builder class.
342
+	 */
343
+	public static function errorWithMessageAndDataAndDebug(int $api_code, string $message, $data,
344
+														   int $http_code = null, int $json_opts = null,
345
+														   array $debug_data = null): HttpResponse
346
+	{
347
+		return Builder::error($api_code)
348
+			->withMessage($message)
349
+			->withData($data)
350
+			->withHttpCode($http_code)
351
+			->withJsonOptions($json_opts)
352
+			->withDebugData($debug_data)
353
+			->build();
354
+	}
355 355
 
356
-    /**
357
-     * @param integer      $api_code  Your API code to be returned with the response object.
358
-     * @param string       $message   Custom message to be returned as part of error response
359
-     * @param integer|null $http_code HTTP code to be used with final response sent or @null
360
-     *                                for default DEFAULT_HTTP_CODE_ERROR.
361
-     *
362
-     * @return HttpResponse
363
-     *
364
-     * @deprecated Please use Builder class.
365
-     */
366
-    public static function errorWithMessage(int $api_code, string $message, int $http_code = null): HttpResponse
367
-    {
368
-        return Builder::error($api_code)
369
-            ->withMessage($message)
370
-            ->withHttpCode($http_code)
371
-            ->build();
372
-    }
356
+	/**
357
+	 * @param integer      $api_code  Your API code to be returned with the response object.
358
+	 * @param string       $message   Custom message to be returned as part of error response
359
+	 * @param integer|null $http_code HTTP code to be used with final response sent or @null
360
+	 *                                for default DEFAULT_HTTP_CODE_ERROR.
361
+	 *
362
+	 * @return HttpResponse
363
+	 *
364
+	 * @deprecated Please use Builder class.
365
+	 */
366
+	public static function errorWithMessage(int $api_code, string $message, int $http_code = null): HttpResponse
367
+	{
368
+		return Builder::error($api_code)
369
+			->withMessage($message)
370
+			->withHttpCode($http_code)
371
+			->build();
372
+	}
373 373
 
374 374
 }
Please login to merge, or discard this patch.
src/Converter.php 2 patches
Indentation   +176 added lines, -176 removed lines patch added patch discarded remove patch
@@ -22,180 +22,180 @@
 block discarded – undo
22 22
  */
23 23
 class Converter
24 24
 {
25
-    /**
26
-     * @var array
27
-     */
28
-    protected $classes = [];
29
-
30
-    /**
31
-     * Converter constructor.
32
-     *
33
-     * @throws \RuntimeException
34
-     */
35
-    public function __construct()
36
-    {
37
-        $this->classes = static::getClassesMapping() ?? [];
38
-    }
39
-
40
-    /**
41
-     * Returns local copy of configuration mapping for the classes.
42
-     *
43
-     * @return array
44
-     */
45
-    public function getClasses(): array
46
-    {
47
-        return $this->classes;
48
-    }
49
-
50
-    /**
51
-     * Checks if we have "classes" mapping configured for $data object class.
52
-     * Returns @true if there's valid config for this class.
53
-     * Throws \RuntimeException if there's no config "classes" mapping entry for this object configured.
54
-     * Throws \InvalidArgumentException if No data conversion mapping configured for given class.
55
-     *
56
-     * @param object $data Object to check mapping for.
57
-     *
58
-     * @return array
59
-     *
60
-     * @throws \InvalidArgumentException
61
-     */
62
-    protected function getClassMappingConfigOrThrow(object $data): array
63
-    {
64
-        $result = null;
65
-
66
-        // check for exact class name match...
67
-        $cls = get_class($data);
68
-        if (array_key_exists($cls, $this->classes)) {
69
-            $result = $this->classes[ $cls ];
70
-        } else {
71
-            // no exact match, then lets try with `instanceof`
72
-            foreach (array_keys($this->getClasses()) as $class_name) {
73
-                if ($data instanceof $class_name) {
74
-                    $result = $this->classes[ $class_name ];
75
-                    break;
76
-                }
77
-            }
78
-        }
79
-
80
-        if ($result === null) {
81
-            throw new \InvalidArgumentException(sprintf('No data conversion mapping configured for "%s" class.', $cls));
82
-        }
83
-
84
-        return $result;
85
-    }
86
-
87
-    /**
88
-     * We need to prepare source data
89
-     *
90
-     * @param object|array|null $data
91
-     *
92
-     * @return array|null
93
-     *
94
-     * @throws \InvalidArgumentException
95
-     */
96
-    public function convert($data = null): ?array
97
-    {
98
-        if ($data === null) {
99
-            return null;
100
-        }
101
-
102
-        Validator::assertIsType('data', $data, [Validator::TYPE_ARRAY,
103
-                                                Validator::TYPE_OBJECT]);
104
-
105
-        if (is_object($data)) {
106
-            $cfg = $this->getClassMappingConfigOrThrow($data);
107
-            $worker = new $cfg[ ResponseBuilder::KEY_HANDLER ]();
108
-            if (array_key_exists(ResponseBuilder::KEY_KEY, $cfg)) {
109
-                $data = [$cfg[ ResponseBuilder::KEY_KEY ] => $worker->convert($data, $cfg)];
110
-            } else {
111
-                $data = $worker->convert($data, $cfg);
112
-            }
113
-        } else {
114
-            $data = $this->convertArray($data);
115
-        }
116
-
117
-        return $data;
118
-    }
119
-
120
-    /**
121
-     * Recursively walks $data array and converts all known objects if found. Note
122
-     * $data array is passed by reference so source $data array may be modified.
123
-     *
124
-     * @param array $data array to recursively convert known elements of
125
-     *
126
-     * @return array
127
-     *
128
-     * @throws \RuntimeException
129
-     */
130
-    protected function convertArray(array $data): array
131
-    {
132
-        // This is to ensure that we either have array with user provided keys i.e. ['foo'=>'bar'], which will then
133
-        // be turned into JSON object or array without user specified keys (['bar']) which we would return as JSON
134
-        // array. But you can't mix these two as the final JSON would not produce predictable results.
135
-        $string_keys_cnt = 0;
136
-        $int_keys_cnt = 0;
137
-        foreach ($data as $key => $val) {
138
-            if (is_int($key)) {
139
-                $int_keys_cnt++;
140
-            } else {
141
-                $string_keys_cnt++;
142
-            }
143
-
144
-            if (($string_keys_cnt > 0) && ($int_keys_cnt > 0)) {
145
-                throw new \RuntimeException(
146
-                    'Invalid data array. Either set own keys for all the items or do not specify any keys at all. ' .
147
-                    'Arrays with mixed keys are not supported by design.');
148
-            }
149
-        }
150
-
151
-        foreach ($data as $key => $val) {
152
-            if (is_array($val)) {
153
-                $data[ $key ] = $this->convertArray($val);
154
-            } elseif (is_object($val)) {
155
-                $cls = get_class($val);
156
-                if (array_key_exists($cls, $this->classes)) {
157
-                    $cfg = $this->classes[ $cls ];
158
-                    $worker = new $cfg[ ResponseBuilder::KEY_HANDLER ]();
159
-                    $converted_data = $worker->convert($val, $cfg);
160
-                    $data[ $key ] = $converted_data;
161
-                }
162
-            }
163
-        }
164
-
165
-        return $data;
166
-    }
167
-
168
-    /**
169
-     * Reads and validates "classes" config mapping
170
-     *
171
-     * @return array Classes mapping as specified in configuration or empty array if configuration found
172
-     *
173
-     * @throws \RuntimeException if "classes" mapping is technically invalid (i.e. not array etc).
174
-     */
175
-    protected static function getClassesMapping(): array
176
-    {
177
-        $classes = Config::get(ResponseBuilder::CONF_KEY_CONVERTER);
178
-
179
-        if ($classes !== null) {
180
-            if (!is_array($classes)) {
181
-                throw new \RuntimeException(
182
-                    sprintf('CONFIG: "classes" mapping must be an array (%s given)', gettype($classes)));
183
-            }
184
-
185
-            $mandatory_keys = [
186
-                ResponseBuilder::KEY_HANDLER,
187
-            ];
188
-            foreach ($classes as $class_name => $class_config) {
189
-                foreach ($mandatory_keys as $key_name) {
190
-                    if (!array_key_exists($key_name, $class_config)) {
191
-                        throw new \RuntimeException("CONFIG: Missing '{$key_name}' for '{$class_name}' class mapping");
192
-                    }
193
-                }
194
-            }
195
-        } else {
196
-            $classes = [];
197
-        }
198
-
199
-        return $classes;
200
-    }
25
+	/**
26
+	 * @var array
27
+	 */
28
+	protected $classes = [];
29
+
30
+	/**
31
+	 * Converter constructor.
32
+	 *
33
+	 * @throws \RuntimeException
34
+	 */
35
+	public function __construct()
36
+	{
37
+		$this->classes = static::getClassesMapping() ?? [];
38
+	}
39
+
40
+	/**
41
+	 * Returns local copy of configuration mapping for the classes.
42
+	 *
43
+	 * @return array
44
+	 */
45
+	public function getClasses(): array
46
+	{
47
+		return $this->classes;
48
+	}
49
+
50
+	/**
51
+	 * Checks if we have "classes" mapping configured for $data object class.
52
+	 * Returns @true if there's valid config for this class.
53
+	 * Throws \RuntimeException if there's no config "classes" mapping entry for this object configured.
54
+	 * Throws \InvalidArgumentException if No data conversion mapping configured for given class.
55
+	 *
56
+	 * @param object $data Object to check mapping for.
57
+	 *
58
+	 * @return array
59
+	 *
60
+	 * @throws \InvalidArgumentException
61
+	 */
62
+	protected function getClassMappingConfigOrThrow(object $data): array
63
+	{
64
+		$result = null;
65
+
66
+		// check for exact class name match...
67
+		$cls = get_class($data);
68
+		if (array_key_exists($cls, $this->classes)) {
69
+			$result = $this->classes[ $cls ];
70
+		} else {
71
+			// no exact match, then lets try with `instanceof`
72
+			foreach (array_keys($this->getClasses()) as $class_name) {
73
+				if ($data instanceof $class_name) {
74
+					$result = $this->classes[ $class_name ];
75
+					break;
76
+				}
77
+			}
78
+		}
79
+
80
+		if ($result === null) {
81
+			throw new \InvalidArgumentException(sprintf('No data conversion mapping configured for "%s" class.', $cls));
82
+		}
83
+
84
+		return $result;
85
+	}
86
+
87
+	/**
88
+	 * We need to prepare source data
89
+	 *
90
+	 * @param object|array|null $data
91
+	 *
92
+	 * @return array|null
93
+	 *
94
+	 * @throws \InvalidArgumentException
95
+	 */
96
+	public function convert($data = null): ?array
97
+	{
98
+		if ($data === null) {
99
+			return null;
100
+		}
101
+
102
+		Validator::assertIsType('data', $data, [Validator::TYPE_ARRAY,
103
+												Validator::TYPE_OBJECT]);
104
+
105
+		if (is_object($data)) {
106
+			$cfg = $this->getClassMappingConfigOrThrow($data);
107
+			$worker = new $cfg[ ResponseBuilder::KEY_HANDLER ]();
108
+			if (array_key_exists(ResponseBuilder::KEY_KEY, $cfg)) {
109
+				$data = [$cfg[ ResponseBuilder::KEY_KEY ] => $worker->convert($data, $cfg)];
110
+			} else {
111
+				$data = $worker->convert($data, $cfg);
112
+			}
113
+		} else {
114
+			$data = $this->convertArray($data);
115
+		}
116
+
117
+		return $data;
118
+	}
119
+
120
+	/**
121
+	 * Recursively walks $data array and converts all known objects if found. Note
122
+	 * $data array is passed by reference so source $data array may be modified.
123
+	 *
124
+	 * @param array $data array to recursively convert known elements of
125
+	 *
126
+	 * @return array
127
+	 *
128
+	 * @throws \RuntimeException
129
+	 */
130
+	protected function convertArray(array $data): array
131
+	{
132
+		// This is to ensure that we either have array with user provided keys i.e. ['foo'=>'bar'], which will then
133
+		// be turned into JSON object or array without user specified keys (['bar']) which we would return as JSON
134
+		// array. But you can't mix these two as the final JSON would not produce predictable results.
135
+		$string_keys_cnt = 0;
136
+		$int_keys_cnt = 0;
137
+		foreach ($data as $key => $val) {
138
+			if (is_int($key)) {
139
+				$int_keys_cnt++;
140
+			} else {
141
+				$string_keys_cnt++;
142
+			}
143
+
144
+			if (($string_keys_cnt > 0) && ($int_keys_cnt > 0)) {
145
+				throw new \RuntimeException(
146
+					'Invalid data array. Either set own keys for all the items or do not specify any keys at all. ' .
147
+					'Arrays with mixed keys are not supported by design.');
148
+			}
149
+		}
150
+
151
+		foreach ($data as $key => $val) {
152
+			if (is_array($val)) {
153
+				$data[ $key ] = $this->convertArray($val);
154
+			} elseif (is_object($val)) {
155
+				$cls = get_class($val);
156
+				if (array_key_exists($cls, $this->classes)) {
157
+					$cfg = $this->classes[ $cls ];
158
+					$worker = new $cfg[ ResponseBuilder::KEY_HANDLER ]();
159
+					$converted_data = $worker->convert($val, $cfg);
160
+					$data[ $key ] = $converted_data;
161
+				}
162
+			}
163
+		}
164
+
165
+		return $data;
166
+	}
167
+
168
+	/**
169
+	 * Reads and validates "classes" config mapping
170
+	 *
171
+	 * @return array Classes mapping as specified in configuration or empty array if configuration found
172
+	 *
173
+	 * @throws \RuntimeException if "classes" mapping is technically invalid (i.e. not array etc).
174
+	 */
175
+	protected static function getClassesMapping(): array
176
+	{
177
+		$classes = Config::get(ResponseBuilder::CONF_KEY_CONVERTER);
178
+
179
+		if ($classes !== null) {
180
+			if (!is_array($classes)) {
181
+				throw new \RuntimeException(
182
+					sprintf('CONFIG: "classes" mapping must be an array (%s given)', gettype($classes)));
183
+			}
184
+
185
+			$mandatory_keys = [
186
+				ResponseBuilder::KEY_HANDLER,
187
+			];
188
+			foreach ($classes as $class_name => $class_config) {
189
+				foreach ($mandatory_keys as $key_name) {
190
+					if (!array_key_exists($key_name, $class_config)) {
191
+						throw new \RuntimeException("CONFIG: Missing '{$key_name}' for '{$class_name}' class mapping");
192
+					}
193
+				}
194
+			}
195
+		} else {
196
+			$classes = [];
197
+		}
198
+
199
+		return $classes;
200
+	}
201 201
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -66,12 +66,12 @@  discard block
 block discarded – undo
66 66
         // check for exact class name match...
67 67
         $cls = get_class($data);
68 68
         if (array_key_exists($cls, $this->classes)) {
69
-            $result = $this->classes[ $cls ];
69
+            $result = $this->classes[$cls];
70 70
         } else {
71 71
             // no exact match, then lets try with `instanceof`
72 72
             foreach (array_keys($this->getClasses()) as $class_name) {
73 73
                 if ($data instanceof $class_name) {
74
-                    $result = $this->classes[ $class_name ];
74
+                    $result = $this->classes[$class_name];
75 75
                     break;
76 76
                 }
77 77
             }
@@ -104,9 +104,9 @@  discard block
 block discarded – undo
104 104
 
105 105
         if (is_object($data)) {
106 106
             $cfg = $this->getClassMappingConfigOrThrow($data);
107
-            $worker = new $cfg[ ResponseBuilder::KEY_HANDLER ]();
107
+            $worker = new $cfg[ResponseBuilder::KEY_HANDLER]();
108 108
             if (array_key_exists(ResponseBuilder::KEY_KEY, $cfg)) {
109
-                $data = [$cfg[ ResponseBuilder::KEY_KEY ] => $worker->convert($data, $cfg)];
109
+                $data = [$cfg[ResponseBuilder::KEY_KEY] => $worker->convert($data, $cfg)];
110 110
             } else {
111 111
                 $data = $worker->convert($data, $cfg);
112 112
             }
@@ -150,14 +150,14 @@  discard block
 block discarded – undo
150 150
 
151 151
         foreach ($data as $key => $val) {
152 152
             if (is_array($val)) {
153
-                $data[ $key ] = $this->convertArray($val);
153
+                $data[$key] = $this->convertArray($val);
154 154
             } elseif (is_object($val)) {
155 155
                 $cls = get_class($val);
156 156
                 if (array_key_exists($cls, $this->classes)) {
157
-                    $cfg = $this->classes[ $cls ];
158
-                    $worker = new $cfg[ ResponseBuilder::KEY_HANDLER ]();
157
+                    $cfg = $this->classes[$cls];
158
+                    $worker = new $cfg[ResponseBuilder::KEY_HANDLER]();
159 159
                     $converted_data = $worker->convert($val, $cfg);
160
-                    $data[ $key ] = $converted_data;
160
+                    $data[$key] = $converted_data;
161 161
                 }
162 162
             }
163 163
         }
Please login to merge, or discard this patch.
src/Converters/ToArrayConverter.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -18,8 +18,8 @@
 block discarded – undo
18 18
 
19 19
 class ToArrayConverter implements ConverterContract
20 20
 {
21
-    public function convert($obj, /** @scrutinizer ignore-unused */ array $config): array
22
-    {
23
-        return $obj->toArray();
24
-    }
21
+	public function convert($obj, /** @scrutinizer ignore-unused */ array $config): array
22
+	{
23
+		return $obj->toArray();
24
+	}
25 25
 }
Please login to merge, or discard this patch.
src/Converters/JsonSerializableConverter.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -18,18 +18,18 @@
 block discarded – undo
18 18
 
19 19
 class JsonSerializableConverter implements ConverterContract
20 20
 {
21
-    /**
22
-     * @param \JsonSerializable $obj
23
-     * @param array             $config
24
-     *
25
-     * @return array
26
-     */
27
-    public function convert($obj, /** @scrutinizer ignore-unused */ array $config): array
28
-    {
29
-        if (!($obj instanceof \JsonSerializable)) {
30
-            throw new \RuntimeException('Expected instance of JsonSerializable, got ' . get_class($obj));
31
-        }
21
+	/**
22
+	 * @param \JsonSerializable $obj
23
+	 * @param array             $config
24
+	 *
25
+	 * @return array
26
+	 */
27
+	public function convert($obj, /** @scrutinizer ignore-unused */ array $config): array
28
+	{
29
+		if (!($obj instanceof \JsonSerializable)) {
30
+			throw new \RuntimeException('Expected instance of JsonSerializable, got ' . get_class($obj));
31
+		}
32 32
 
33
-        return ['val' => json_decode($obj->jsonSerialize(), true)];
34
-    }
33
+		return ['val' => json_decode($obj->jsonSerialize(), true)];
34
+	}
35 35
 }
Please login to merge, or discard this patch.