Total Complexity | 83 |
Total Lines | 714 |
Duplicated Lines | 0 % |
Changes | 2 | ||
Bugs | 1 | Features | 0 |
Complex classes like ModulesComponent 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 ModulesComponent, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
41 | class ModulesComponent extends Component |
||
42 | { |
||
43 | use SchemaTrait; |
||
44 | |||
45 | /** |
||
46 | * Fixed relationships to be loaded for each object |
||
47 | * |
||
48 | * @var array |
||
49 | */ |
||
50 | public const FIXED_RELATIONSHIPS = [ |
||
51 | 'parent', |
||
52 | 'children', |
||
53 | 'parents', |
||
54 | 'translations', |
||
55 | 'streams', |
||
56 | 'roles', |
||
57 | ]; |
||
58 | |||
59 | /** |
||
60 | * @inheritDoc |
||
61 | */ |
||
62 | public $components = ['Authentication', 'Children', 'Config', 'Parents', 'Schema']; |
||
63 | |||
64 | /** |
||
65 | * @inheritDoc |
||
66 | */ |
||
67 | protected $_defaultConfig = [ |
||
68 | 'currentModuleName' => null, |
||
69 | 'clearHomeCache' => false, |
||
70 | ]; |
||
71 | |||
72 | /** |
||
73 | * Project modules for a user from `/home` endpoint |
||
74 | * |
||
75 | * @var array |
||
76 | */ |
||
77 | protected $modules = []; |
||
78 | |||
79 | /** |
||
80 | * Other "logic" modules, non objects |
||
81 | * |
||
82 | * @var array |
||
83 | */ |
||
84 | protected $otherModules = [ |
||
85 | 'tags' => [ |
||
86 | 'name' => 'tags', |
||
87 | 'hints' => ['allow' => ['GET', 'POST', 'PATCH', 'DELETE']], |
||
88 | ], |
||
89 | ]; |
||
90 | |||
91 | /** |
||
92 | * @inheritDoc |
||
93 | */ |
||
94 | public function beforeFilter(EventInterface $event): ?Response |
||
103 | } |
||
104 | |||
105 | /** |
||
106 | * Read modules and project info from `/home' endpoint. |
||
107 | * |
||
108 | * @return void |
||
109 | */ |
||
110 | public function startup(): void |
||
111 | { |
||
112 | /** @var \Authentication\Identity|null $user */ |
||
113 | $user = $this->Authentication->getIdentity(); |
||
114 | if (empty($user) || !$user->get('id')) { |
||
115 | $this->getController()->set(['modules' => [], 'project' => []]); |
||
116 | |||
117 | return; |
||
118 | } |
||
119 | |||
120 | if ($this->getConfig('clearHomeCache')) { |
||
121 | Cache::delete(sprintf('home_%d', $user->get('id'))); |
||
122 | } |
||
123 | |||
124 | $project = $this->getProject(); |
||
125 | $uploadable = (array)Hash::get($this->Schema->objectTypesFeatures(), 'uploadable'); |
||
126 | $this->getController()->set(compact('project', 'uploadable')); |
||
127 | |||
128 | $currentModuleName = $this->getConfig('currentModuleName'); |
||
129 | $modules = (array)$this->getController()->viewBuilder()->getVar('modules'); |
||
130 | if (!empty($currentModuleName)) { |
||
131 | $currentModule = Hash::get($modules, $currentModuleName); |
||
132 | } |
||
133 | |||
134 | if (!empty($currentModule)) { |
||
135 | $this->getController()->set(compact('currentModule')); |
||
136 | } |
||
137 | } |
||
138 | |||
139 | /** |
||
140 | * Create internal list of available modules in `$this->modules` as an array with `name` as key |
||
141 | * and return it. |
||
142 | * Modules are created from configuration and merged with information read from `/home` endpoint |
||
143 | * |
||
144 | * @return array |
||
145 | */ |
||
146 | public function getModules(): array |
||
171 | } |
||
172 | |||
173 | /** |
||
174 | * This filters modules and apply 'AccessControl' config by user role, if any. |
||
175 | * Module can be "hidden": remove from modules. |
||
176 | * Module can be "readonly": adjust "hints.allow" for module. |
||
177 | * |
||
178 | * @return void |
||
179 | */ |
||
180 | protected function modulesByAccessControl(): void |
||
181 | { |
||
182 | $accessControl = (array)Configure::read('AccessControl'); |
||
183 | if (empty($accessControl)) { |
||
184 | return; |
||
185 | } |
||
186 | /** @var \Authentication\Identity|null $user */ |
||
187 | $user = $this->Authentication->getIdentity(); |
||
188 | $userRoles = (array)$user->get('roles'); |
||
189 | if (empty($user) || empty($user->getOriginalData()) || in_array('admin', $userRoles)) { |
||
190 | return; |
||
191 | } |
||
192 | $roles = array_intersect(array_keys($accessControl), $userRoles); |
||
193 | $modules = (array)array_keys($this->modules); |
||
194 | $hidden = []; |
||
195 | $readonly = []; |
||
196 | $write = []; |
||
197 | foreach ($roles as $role) { |
||
198 | $h = (array)Hash::get($accessControl, sprintf('%s.hidden', $role)); |
||
199 | $hidden = empty($hidden) ? $h : array_intersect($hidden, $h); |
||
200 | $r = (array)Hash::get($accessControl, sprintf('%s.readonly', $role)); |
||
201 | $readonly = empty($readonly) ? $r : array_intersect($readonly, $r); |
||
202 | $write = array_unique(array_merge($write, array_diff($modules, $hidden, $readonly))); |
||
203 | } |
||
204 | // Note: https://github.com/bedita/manager/issues/969 Accesses priority is "write" > "read" > "hidden" |
||
205 | $readonly = array_diff($readonly, $write); |
||
206 | $hidden = array_diff($hidden, $readonly, $write); |
||
207 | if (empty($hidden) && empty($readonly)) { |
||
208 | return; |
||
209 | } |
||
210 | // remove "hidden" |
||
211 | $this->modules = array_diff_key($this->modules, array_flip($hidden)); |
||
212 | // make sure $readonly contains valid module names |
||
213 | $readonly = array_intersect($readonly, array_keys($this->modules)); |
||
214 | foreach ($readonly as $key) { |
||
215 | $path = sprintf('%s.hints.allow', $key); |
||
216 | $allow = (array)Hash::get($this->modules, $path); |
||
217 | $this->modules[$key]['hints']['allow'] = array_diff($allow, ['POST', 'PATCH', 'DELETE']); |
||
218 | } |
||
219 | } |
||
220 | |||
221 | /** |
||
222 | * Modules data from `/home` endpoint 'meta' response. |
||
223 | * Modules are object endpoints from BE4 API |
||
224 | * |
||
225 | * @return array |
||
226 | */ |
||
227 | protected function modulesFromMeta(): array |
||
228 | { |
||
229 | /** @var \Authentication\Identity $user */ |
||
230 | $user = $this->Authentication->getIdentity(); |
||
231 | $meta = $this->getMeta($user); |
||
232 | $modules = collection(Hash::get($meta, 'resources', [])) |
||
233 | ->map(function (array $data, $endpoint) { |
||
234 | $name = substr($endpoint, 1); |
||
235 | |||
236 | return $data + compact('name'); |
||
237 | }) |
||
238 | ->reject(function (array $data) { |
||
239 | return Hash::get($data, 'hints.object_type') !== true && !in_array(Hash::get($data, 'name'), ['trash', 'translations']); |
||
240 | }) |
||
241 | ->toList(); |
||
242 | |||
243 | return Hash::combine($modules, '{n}.name', '{n}'); |
||
244 | } |
||
245 | |||
246 | /** |
||
247 | * Get information about current project. |
||
248 | * |
||
249 | * @return array |
||
250 | */ |
||
251 | public function getProject(): array |
||
252 | { |
||
253 | /** @var \Authentication\Identity $user */ |
||
254 | $user = $this->Authentication->getIdentity(); |
||
255 | $api = $this->getMeta($user); |
||
256 | $apiName = (string)Hash::get($api, 'project.name'); |
||
257 | $apiName = str_replace('API', '', $apiName); |
||
258 | $api['project']['name'] = $apiName; |
||
259 | |||
260 | return [ |
||
261 | 'api' => (array)Hash::get($api, 'project'), |
||
262 | 'beditaApi' => [ |
||
263 | 'name' => (string)Hash::get( |
||
264 | (array)Configure::read('Project'), |
||
265 | 'name', |
||
266 | (string)Hash::get($api, 'project.name') |
||
267 | ), |
||
268 | 'version' => (string)Hash::get($api, 'version'), |
||
269 | ], |
||
270 | ]; |
||
271 | } |
||
272 | |||
273 | /** |
||
274 | * Check if an object type is abstract or concrete. |
||
275 | * This method MUST NOT be called from `beforeRender` since `$this->modules` array is still not initialized. |
||
276 | * |
||
277 | * @param string $name Name of object type. |
||
278 | * @return bool True if abstract, false if concrete |
||
279 | */ |
||
280 | public function isAbstract(string $name): bool |
||
281 | { |
||
282 | return (bool)Hash::get($this->modules, sprintf('%s.hints.multiple_types', $name), false); |
||
283 | } |
||
284 | |||
285 | /** |
||
286 | * Get list of object types |
||
287 | * This method MUST NOT be called from `beforeRender` since `$this->modules` array is still not initialized. |
||
288 | * |
||
289 | * @param bool|null $abstract Only abstract or concrete types. |
||
290 | * @return array Type names list |
||
291 | */ |
||
292 | public function objectTypes(?bool $abstract = null): array |
||
293 | { |
||
294 | $types = []; |
||
295 | foreach ($this->modules as $name => $data) { |
||
296 | if (empty($data['hints']['object_type'])) { |
||
297 | continue; |
||
298 | } |
||
299 | if ($abstract === null || $data['hints']['multiple_types'] === $abstract) { |
||
300 | $types[] = $name; |
||
301 | } |
||
302 | } |
||
303 | |||
304 | return $types; |
||
305 | } |
||
306 | |||
307 | /** |
||
308 | * Read oEmbed metadata |
||
309 | * |
||
310 | * @param string $url Remote URL |
||
311 | * @return array|null |
||
312 | * @codeCoverageIgnore |
||
313 | */ |
||
314 | protected function oEmbedMeta(string $url): ?array |
||
315 | { |
||
316 | return (new OEmbed())->readMetadata($url); |
||
317 | } |
||
318 | |||
319 | /** |
||
320 | * Upload a file and store it in a media stream |
||
321 | * Or create a remote media trying to get some metadata via oEmbed |
||
322 | * |
||
323 | * @param array $requestData The request data from form |
||
324 | * @return void |
||
325 | */ |
||
326 | public function upload(array &$requestData): void |
||
360 | } |
||
361 | |||
362 | /** |
||
363 | * Remove a stream from a media, if any |
||
364 | * |
||
365 | * @param array $requestData The request data from form |
||
366 | * @return bool |
||
367 | */ |
||
368 | public function removeStream(array $requestData): bool |
||
383 | } |
||
384 | |||
385 | /** |
||
386 | * Associate a stream to a media using API |
||
387 | * If $requestData['id'] is null, create media from stream. |
||
388 | * If $requestData['id'] is not null, replace properly related stream. |
||
389 | * |
||
390 | * @param string $streamId The stream ID |
||
391 | * @param array $requestData The request data |
||
392 | * @param string $defaultTitle The default title for media |
||
393 | * @return string The media ID |
||
394 | */ |
||
395 | public function assocStreamToMedia(string $streamId, array &$requestData, string $defaultTitle): string |
||
396 | { |
||
397 | $apiClient = ApiClientProvider::getApiClient(); |
||
398 | $type = $requestData['model-type']; |
||
399 | if (empty($requestData['id'])) { |
||
400 | // create media from stream |
||
401 | // save only `title` (filename if not set) and `status` in new media object |
||
402 | $attributes = array_filter([ |
||
403 | 'title' => !empty($requestData['title']) ? $requestData['title'] : $defaultTitle, |
||
404 | 'status' => Hash::get($requestData, 'status'), |
||
405 | ]); |
||
406 | $data = compact('type', 'attributes'); |
||
407 | $body = compact('data'); |
||
408 | $response = $apiClient->createMediaFromStream($streamId, $type, $body); |
||
409 | // `title` and `status` saved here, remove from next save |
||
410 | unset($requestData['title'], $requestData['status']); |
||
411 | |||
412 | return (string)Hash::get($response, 'data.id'); |
||
413 | } |
||
414 | |||
415 | // assoc existing media to stream |
||
416 | $id = (string)Hash::get($requestData, 'id'); |
||
417 | $data = compact('id', 'type'); |
||
418 | $apiClient->replaceRelated($streamId, 'streams', 'object', $data); |
||
419 | |||
420 | return $id; |
||
421 | } |
||
422 | |||
423 | /** |
||
424 | * Check request data for upload and return true if upload is boht possible and needed |
||
425 | * |
||
426 | * @param array $requestData The request data |
||
427 | * @return bool true if upload is possible and needed |
||
428 | */ |
||
429 | public function checkRequestForUpload(array $requestData): bool |
||
460 | } |
||
461 | |||
462 | /** |
||
463 | * Check if save can be skipped. |
||
464 | * This is used to avoid saving object with no changes. |
||
465 | * |
||
466 | * @param string $id The object ID |
||
467 | * @param array $requestData The request data |
||
468 | * @return bool True if save can be skipped, false otherwise |
||
469 | */ |
||
470 | public function skipSaveObject(string $id, array &$requestData): bool |
||
471 | { |
||
472 | if (empty($id)) { |
||
473 | return false; |
||
474 | } |
||
475 | if (isset($requestData['date_ranges'])) { |
||
476 | // check if date_ranges has changed |
||
477 | $type = $this->getController()->getRequest()->getParam('object_type'); |
||
478 | $response = ApiClientProvider::getApiClient()->getObject($id, $type, ['fields' => 'date_ranges']); |
||
479 | $actualDateRanges = (array)Hash::get($response, 'data.attributes.date_ranges'); |
||
480 | $dr1 = DateRangesTools::toString($actualDateRanges); |
||
481 | $requestDateRanges = (array)Hash::get($requestData, 'date_ranges'); |
||
482 | $dr2 = DateRangesTools::toString($requestDateRanges); |
||
483 | if ($dr1 === $dr2) { |
||
484 | unset($requestData['date_ranges']); |
||
485 | } else { |
||
486 | return false; |
||
487 | } |
||
488 | } |
||
489 | $data = array_filter($requestData, function ($key) { |
||
490 | return !in_array($key, ['id', 'date_ranges', 'permissions']); |
||
491 | }, ARRAY_FILTER_USE_KEY); |
||
492 | |||
493 | return empty($data); |
||
494 | } |
||
495 | |||
496 | /** |
||
497 | * Check if save related can be skipped. |
||
498 | * This is used to avoid saving object relations with no changes. |
||
499 | * |
||
500 | * @param string $id The object ID |
||
501 | * @param array $relatedData The related data |
||
502 | * @return bool True if save related can be skipped, false otherwise |
||
503 | */ |
||
504 | public function skipSaveRelated(string $id, array &$relatedData): bool |
||
505 | { |
||
506 | if (empty($relatedData)) { |
||
507 | return true; |
||
508 | } |
||
509 | $methods = (array)Hash::extract($relatedData, '{n}.method'); |
||
510 | if (in_array('addRelated', $methods) || in_array('removeRelated', $methods)) { |
||
511 | return false; |
||
512 | } |
||
513 | // check replaceRelated |
||
514 | $type = $this->getController()->getRequest()->getParam('object_type'); |
||
515 | $rr = $relatedData; |
||
516 | foreach ($rr as $method => $data) { |
||
517 | $actualRelated = (array)ApiClientProvider::getApiClient()->getRelated($id, $type, $data['relation']); |
||
518 | $actualRelated = (array)Hash::get($actualRelated, 'data'); |
||
519 | $actualRelated = RelationsTools::toString($actualRelated); |
||
520 | $requestRelated = (array)Hash::get($data, 'relatedIds', []); |
||
521 | $requestRelated = RelationsTools::toString($requestRelated); |
||
522 | if ($actualRelated === $requestRelated) { |
||
523 | unset($relatedData[$method]); |
||
524 | continue; |
||
525 | } |
||
526 | |||
527 | return false; |
||
528 | } |
||
529 | |||
530 | return empty($relatedData); |
||
531 | } |
||
532 | |||
533 | /** |
||
534 | * Check if save permissions can be skipped. |
||
535 | * This is used to avoid saving object permissions with no changes. |
||
536 | * |
||
537 | * @param string $id The object ID |
||
538 | * @param array $requestPermissions The request permissions |
||
539 | * @param array $schema The object type schema |
||
540 | * @return bool True if save permissions can be skipped, false otherwise |
||
541 | */ |
||
542 | public function skipSavePermissions(string $id, array $requestPermissions, array $schema): bool |
||
560 | } |
||
561 | |||
562 | /** |
||
563 | * Set current attributes from loaded $object data in `currentAttributes`. |
||
564 | * |
||
565 | * @param array $object The object. |
||
566 | * @return void |
||
567 | */ |
||
568 | public function setupAttributes(array &$object): void |
||
569 | { |
||
570 | $currentAttributes = json_encode((array)Hash::get($object, 'attributes')); |
||
571 | $this->getController()->set(compact('currentAttributes')); |
||
572 | } |
||
573 | |||
574 | /** |
||
575 | * Setup relations information metadata. |
||
576 | * |
||
577 | * @param array $schema Relations schema. |
||
578 | * @param array $relationships Object relationships. |
||
579 | * @param array $order Ordered names inside 'main' and 'aside' keys. |
||
580 | * @param array $hidden List of hidden relations. |
||
581 | * @param array $readonly List of readonly relations. |
||
582 | * @return void |
||
583 | */ |
||
584 | public function setupRelationsMeta(array $schema, array $relationships, array $order = [], array $hidden = [], array $readonly = []): void |
||
585 | { |
||
586 | // relations between objects |
||
587 | $relationsSchema = $this->relationsSchema($schema, $relationships, $hidden, $readonly); |
||
588 | // relations between objects and resources |
||
589 | $resourceRelations = array_diff(array_keys($relationships), array_keys($relationsSchema), $hidden, self::FIXED_RELATIONSHIPS); |
||
590 | // set objectRelations array with name as key and label as value |
||
591 | $relationNames = array_keys($relationsSchema); |
||
592 | |||
593 | // define 'main' and 'aside' relation groups |
||
594 | $aside = array_intersect((array)Hash::get($order, 'aside'), $relationNames); |
||
595 | $relationNames = array_diff($relationNames, $aside); |
||
596 | $main = array_intersect((array)Hash::get($order, 'main'), $relationNames); |
||
597 | $main = array_unique(array_merge($main, $relationNames)); |
||
598 | |||
599 | $objectRelations = [ |
||
600 | 'main' => $this->relationLabels($relationsSchema, $main), |
||
601 | 'aside' => $this->relationLabels($relationsSchema, $aside), |
||
602 | ]; |
||
603 | |||
604 | $this->getController()->set(compact('relationsSchema', 'resourceRelations', 'objectRelations')); |
||
605 | } |
||
606 | |||
607 | /** |
||
608 | * Relations schema by schema and relationships. |
||
609 | * |
||
610 | * @param array $schema The schema |
||
611 | * @param array $relationships The relationships |
||
612 | * @param array $hidden Hidden relationships |
||
613 | * @param array $readonly Readonly relationships |
||
614 | * @return array |
||
615 | */ |
||
616 | protected function relationsSchema(array $schema, array $relationships, array $hidden = [], array $readonly = []): array |
||
617 | { |
||
618 | $types = $this->objectTypes(false); |
||
619 | sort($types); |
||
620 | $relationsSchema = array_diff_key(array_intersect_key($schema, $relationships), array_flip($hidden)); |
||
621 | |||
622 | foreach ($relationsSchema as $relName => &$relSchema) { |
||
623 | if (in_array('objects', (array)Hash::get($relSchema, 'right'))) { |
||
624 | $relSchema['right'] = $types; |
||
625 | } |
||
626 | if (!empty($relationships[$relName]['readonly']) || in_array($relName, $readonly)) { |
||
627 | $relSchema['readonly'] = true; |
||
628 | } |
||
629 | } |
||
630 | |||
631 | return $relationsSchema; |
||
632 | } |
||
633 | |||
634 | /** |
||
635 | * Retrieve associative array with names as keys and labels as values. |
||
636 | * |
||
637 | * @param array $relationsSchema Relations schema. |
||
638 | * @param array $names Relation names. |
||
639 | * @return array |
||
640 | */ |
||
641 | protected function relationLabels(array &$relationsSchema, array $names): array |
||
642 | { |
||
643 | return (array)array_combine( |
||
644 | $names, |
||
645 | array_map( |
||
646 | function ($r) use ($relationsSchema) { |
||
647 | // return 'label' or 'inverse_label' looking at 'name' |
||
648 | $attributes = $relationsSchema[$r]['attributes']; |
||
649 | if ($r === $attributes['name']) { |
||
650 | return $attributes['label']; |
||
651 | } |
||
652 | |||
653 | return $attributes['inverse_label']; |
||
654 | }, |
||
655 | $names |
||
656 | ) |
||
657 | ); |
||
658 | } |
||
659 | |||
660 | /** |
||
661 | * Get related types from relation name. |
||
662 | * |
||
663 | * @param array $schema Relations schema. |
||
664 | * @param string $relation Relation name. |
||
665 | * @return array |
||
666 | */ |
||
667 | public function relatedTypes(array $schema, string $relation): array |
||
668 | { |
||
669 | $relationsSchema = (array)Hash::get($schema, $relation); |
||
670 | |||
671 | return (array)Hash::get($relationsSchema, 'right'); |
||
672 | } |
||
673 | |||
674 | /** |
||
675 | * Save related objects. |
||
676 | * |
||
677 | * @param string $id Object ID |
||
678 | * @param string $type Object type |
||
679 | * @param array $relatedData Related objects data |
||
680 | * @return void |
||
681 | */ |
||
682 | public function saveRelated(string $id, string $type, array $relatedData): void |
||
683 | { |
||
684 | foreach ($relatedData as $data) { |
||
685 | $this->saveRelatedObjects($id, $type, $data); |
||
686 | $event = new Event('Controller.afterSaveRelated', $this, compact('id', 'type', 'data')); |
||
687 | $this->getController()->getEventManager()->dispatch($event); |
||
688 | } |
||
689 | } |
||
690 | |||
691 | /** |
||
692 | * Save related objects per object by ID. |
||
693 | * |
||
694 | * @param string $id Object ID |
||
695 | * @param string $type Object type |
||
696 | * @param array $data Related object data |
||
697 | * @return array|null |
||
698 | * @throws \Cake\Http\Exception\BadRequestException |
||
699 | */ |
||
700 | public function saveRelatedObjects(string $id, string $type, array $data): ?array |
||
701 | { |
||
702 | $method = (string)Hash::get($data, 'method'); |
||
703 | if (!in_array($method, ['addRelated', 'removeRelated', 'replaceRelated'])) { |
||
704 | throw new BadRequestException(__('Bad related data method')); |
||
705 | } |
||
706 | $relation = (string)Hash::get($data, 'relation'); |
||
707 | $related = $this->getRelated($data); |
||
708 | if ($relation === 'parent' && $type === 'folders') { |
||
709 | return $this->Parents->{$method}($id, $related); |
||
710 | } |
||
711 | if ($relation === 'children' && $type === 'folders') { |
||
712 | return $this->Children->{$method}($id, $related); |
||
713 | } |
||
714 | $lang = I18n::getLocale(); |
||
715 | $headers = ['Accept-Language' => $lang]; |
||
716 | |||
717 | return ApiClientProvider::getApiClient()->{$method}($id, $type, $relation, $related, $headers); |
||
718 | } |
||
719 | |||
720 | /** |
||
721 | * Get related objects. |
||
722 | * If related object has no ID, it will be created. |
||
723 | * |
||
724 | * @param array $data Related object data |
||
725 | * @return array |
||
726 | */ |
||
727 | public function getRelated(array $data): array |
||
755 | } |
||
756 | } |
||
757 |