Total Complexity | 43 |
Total Lines | 271 |
Duplicated Lines | 0 % |
Changes | 8 | ||
Bugs | 0 | Features | 0 |
Complex classes like Json often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Json, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
27 | class Json extends JsonAbstract |
||
28 | { |
||
29 | private $isCollection = false; |
||
30 | private $meta = []; |
||
31 | |||
32 | /** |
||
33 | * @param $relations \Illuminate\Database\Eloquent\Collection |
||
34 | * @param string $entity |
||
35 | * @return array JSON API rels compatible array |
||
36 | */ |
||
37 | public static function getRelations($relations, string $entity): array |
||
38 | { |
||
39 | $jsonArr = []; |
||
40 | if ($relations instanceof \Illuminate\Database\Eloquent\Collection) { |
||
41 | $cnt = \count($relations); |
||
42 | if ($cnt > 1) { |
||
43 | foreach ($relations as $v) { |
||
44 | $attrs = $v->getAttributes(); |
||
45 | $jsonArr[] = [ApiInterface::RAML_TYPE => $entity, |
||
46 | ApiInterface::RAML_ID => $attrs[ApiInterface::RAML_ID]]; |
||
47 | } |
||
48 | } else { |
||
49 | foreach ($relations as $v) { |
||
50 | $attrs = $v->getAttributes(); |
||
51 | $jsonArr = [ApiInterface::RAML_TYPE => $entity, |
||
52 | ApiInterface::RAML_ID => $attrs[ApiInterface::RAML_ID]]; |
||
53 | } |
||
54 | } |
||
55 | } elseif ($relations instanceof Model) { |
||
56 | $attrs = $relations->getAttributes(); |
||
57 | $jsonArr = [ApiInterface::RAML_TYPE => $entity, |
||
58 | ApiInterface::RAML_ID => $attrs[ApiInterface::RAML_ID]]; |
||
59 | } |
||
60 | |||
61 | return $jsonArr; |
||
62 | } |
||
63 | |||
64 | /** |
||
65 | * Output errors in JSON API compatible format |
||
66 | * @param array $errors |
||
67 | * @param bool $return |
||
68 | * @return string |
||
69 | */ |
||
70 | public static function outputErrors(array $errors, bool $return = false) |
||
71 | { |
||
72 | $arr[JSONApiInterface::CONTENT_ERRORS] = []; |
||
73 | if (empty($errors) === false) { |
||
74 | $arr[JSONApiInterface::CONTENT_ERRORS] = $errors; |
||
75 | } |
||
76 | // errors and codes must be clear with readable json |
||
77 | $encoded = self::encode($arr, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT); |
||
78 | if ($return === false && env('APP_ENV') !== 'dev') { |
||
79 | echo $encoded; |
||
80 | exit(JSONApiInterface::EXIT_STATUS_ERROR); |
||
81 | } |
||
82 | return $encoded; |
||
83 | } |
||
84 | |||
85 | /** |
||
86 | * |
||
87 | * @param array $errors |
||
88 | * @return string |
||
89 | */ |
||
90 | public function getErrors(array $errors): string |
||
91 | { |
||
92 | $arr[JSONApiInterface::CONTENT_ERRORS] = []; |
||
93 | if (empty($errors) === false) { |
||
94 | $arr[JSONApiInterface::CONTENT_ERRORS] = $errors; |
||
95 | } |
||
96 | |||
97 | return self::encode($arr, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT); |
||
98 | } |
||
99 | |||
100 | /** |
||
101 | * Returns composition of relations |
||
102 | * |
||
103 | * @param Request $request |
||
104 | * @param array $data |
||
105 | * @return string |
||
106 | */ |
||
107 | public static function prepareSerializedRelations(Request $request, array $data): string |
||
108 | { |
||
109 | $arr[JSONApiInterface::CONTENT_LINKS] = [ |
||
110 | JSONApiInterface::CONTENT_SELF => $request->getUri(), |
||
111 | ]; |
||
112 | |||
113 | $arr[JSONApiInterface::CONTENT_DATA] = $data; |
||
114 | |||
115 | return self::encode($arr); |
||
116 | } |
||
117 | |||
118 | /** |
||
119 | * @param BaseFormRequest $formRequest |
||
120 | * @param $model |
||
121 | * @param string $entity |
||
122 | * |
||
123 | * @return Collection|Item |
||
124 | */ |
||
125 | public function getResource(BaseFormRequest $formRequest, $model, string $entity) |
||
126 | { |
||
127 | $transformer = new DefaultTransformer($formRequest); |
||
128 | if ($this->isCollection === true) { |
||
129 | $collection = new Collection($model, $transformer, strtolower($entity)); |
||
130 | if (empty($this->meta) === false) { |
||
131 | $collection->setMeta($this->meta); |
||
132 | } |
||
133 | |||
134 | if ($model instanceof LengthAwarePaginator) { // only for paginator |
||
135 | $collection->setPaginator(new IlluminatePaginatorAdapter($model)); |
||
136 | } |
||
137 | |||
138 | return $collection; |
||
139 | } |
||
140 | |||
141 | $item = new Item($model, $transformer, strtolower($entity)); |
||
142 | $item->setMeta($this->meta); |
||
143 | |||
144 | return $item; |
||
145 | } |
||
146 | |||
147 | /** |
||
148 | * Prepares data to output in json-api format |
||
149 | * |
||
150 | * @param ResourceInterface $resource |
||
151 | * @param array $data |
||
152 | * @return string |
||
153 | */ |
||
154 | public static function prepareSerializedData(ResourceInterface $resource, $data = ModelsInterface::DEFAULT_DATA): string |
||
155 | { |
||
156 | if (empty($resource->getData())) { // preventing 3d party libs (League etc) from crash on empty data |
||
157 | return self::encode([ |
||
158 | ModelsInterface::PARAM_DATA => [] |
||
159 | ]); |
||
160 | } |
||
161 | |||
162 | $manager = new Manager(); |
||
163 | if (isset($_GET['include'])) { |
||
164 | $manager->parseIncludes($_GET['include']); |
||
165 | } |
||
166 | |||
167 | $manager->setSerializer(new JsonApiSerializer((new Req())->getBasePath())); |
||
168 | return self::getSelectedData($manager->createData($resource)->toJson(), $data); |
||
169 | } |
||
170 | |||
171 | /** |
||
172 | * Gets data only with those elements of object/array that should be provided as output |
||
173 | * |
||
174 | * @param string $json |
||
175 | * @param array $data |
||
176 | * @return string |
||
177 | */ |
||
178 | private static function getSelectedData(string $json, array $data): string |
||
179 | { |
||
180 | if (current($data) === PhpInterface::ASTERISK) {// do nothing - grab all fields |
||
181 | return $json; |
||
182 | } |
||
183 | |||
184 | $jsonArr = self::decode($json); |
||
185 | $current = current($jsonArr[ApiInterface::RAML_DATA]); |
||
186 | |||
187 | if (empty($current[JSONApiInterface::CONTENT_ATTRIBUTES]) === false) {// this is an array of values |
||
188 | self::unsetArray($jsonArr, $data); |
||
189 | } else {// this is just one element |
||
190 | self::unsetObject($jsonArr, $data); |
||
191 | } |
||
192 | |||
193 | return self::encode($jsonArr); |
||
194 | } |
||
195 | |||
196 | /** |
||
197 | * Unsets objects from array that shouldn't be provided as output |
||
198 | * |
||
199 | * @param array &$json |
||
200 | * @param array $data |
||
201 | */ |
||
202 | private static function unsetArray(array &$json, array $data): void |
||
214 | } |
||
215 | } |
||
216 | } |
||
217 | } |
||
218 | } |
||
219 | } |
||
220 | } |
||
221 | |||
222 | /** |
||
223 | * Unsets objects that shouldn't be provided as output |
||
224 | * |
||
225 | * @param array $json |
||
226 | * @param array $data |
||
227 | */ |
||
228 | private static function unsetObject(array &$json, array $data): void |
||
229 | { |
||
230 | $isDataAndAttrs = empty($json[JSONApiInterface::CONTENT_DATA]) === false |
||
231 | && empty($json[JSONApiInterface::CONTENT_DATA][JSONApiInterface::CONTENT_ATTRIBUTES]) === false; |
||
232 | |||
233 | if ($isDataAndAttrs) { |
||
234 | $attrsCase = ConfigHelper::getParam(ConfigInterface::ATTRIBUTES_CASE); |
||
235 | foreach ($json[JSONApiInterface::CONTENT_DATA][JSONApiInterface::CONTENT_ATTRIBUTES] as $k => $v) { |
||
236 | if (\in_array($k, $data, true) === false) { |
||
237 | unset($json[JSONApiInterface::CONTENT_DATA][JSONApiInterface::CONTENT_ATTRIBUTES][$k]); |
||
238 | } else if ($attrsCase !== ConfigInterface::DEFAULT_CASE) { |
||
239 | $changedKey = $k; |
||
240 | if ($attrsCase === ConfigInterface::CAMEL_CASE) { |
||
241 | $changedKey = self::changeParamKeyToLowerCamelCase($k); |
||
242 | } else if ($attrsCase === ConfigInterface::LISP_CASE) { |
||
243 | $changedKey = self::changeParamKeyToLispCase($k); |
||
244 | } |
||
245 | |||
246 | $json[JSONApiInterface::CONTENT_DATA][JSONApiInterface::CONTENT_ATTRIBUTES][$changedKey] = $v; |
||
247 | if ($changedKey !== $k) { |
||
248 | unset($json[JSONApiInterface::CONTENT_DATA][JSONApiInterface::CONTENT_ATTRIBUTES][$k]); |
||
249 | } |
||
250 | } |
||
251 | } |
||
252 | } |
||
253 | } |
||
254 | |||
255 | /** |
||
256 | * @param string $param |
||
257 | * @return string |
||
258 | */ |
||
259 | public static function changeParamKeyToLowerCamelCase(string $param): string |
||
260 | { |
||
261 | return lcfirst( |
||
262 | str_replace(' ', '', ucwords( |
||
263 | str_replace('_', ' ', $param) |
||
264 | ) |
||
265 | ) |
||
266 | ); |
||
267 | } |
||
268 | |||
269 | /** |
||
270 | * @param string $param |
||
271 | * @return string |
||
272 | */ |
||
273 | public static function changeParamKeyToLispCase(string $param): string |
||
276 | } |
||
277 | |||
278 | /** |
||
279 | * @param bool $isCollection |
||
280 | * @return Json |
||
281 | */ |
||
282 | public function setIsCollection(bool $isCollection): Json |
||
287 | } |
||
288 | |||
289 | /** |
||
290 | * @param array $meta |
||
291 | * @return Json |
||
292 | */ |
||
293 | public function setMeta(array $meta): Json |
||
298 | } |
||
299 | } |
Let?s assume that you have a directory layout like this:
and let?s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: