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