Total Complexity | 82 |
Total Lines | 703 |
Duplicated Lines | 0 % |
Changes | 2 | ||
Bugs | 2 | Features | 1 |
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 |
||
95 | { |
||
96 | /** @var \Authentication\Identity|null $user */ |
||
97 | $user = $this->Authentication->getIdentity(); |
||
98 | if (!empty($user)) { |
||
99 | $this->getController()->set('modules', $this->getModules()); |
||
100 | } |
||
101 | |||
102 | return null; |
||
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 |
||
147 | { |
||
148 | $modules = (array)Configure::read('Modules'); |
||
149 | $pluginModules = array_filter($modules, function ($item) { |
||
150 | return !empty($item['route']); |
||
151 | }); |
||
152 | $metaModules = $this->modulesFromMeta() + $this->otherModules; |
||
153 | $modules = array_intersect_key($modules, $metaModules); |
||
154 | array_walk( |
||
155 | $modules, |
||
156 | function (&$data, $key) use ($metaModules) { |
||
157 | $data = array_merge((array)Hash::get($metaModules, $key), $data); |
||
158 | } |
||
159 | ); |
||
160 | $this->modules = array_merge( |
||
161 | $modules, |
||
162 | array_diff_key($metaModules, $modules), |
||
163 | $pluginModules |
||
164 | ); |
||
165 | $this->modulesByAccessControl(); |
||
166 | if (!$this->Schema->tagsInUse()) { |
||
167 | unset($this->modules['tags']); |
||
168 | } |
||
169 | |||
170 | return $this->modules; |
||
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 | if (empty($user) || empty($user->getOriginalData())) { |
||
189 | return; |
||
190 | } |
||
191 | $roles = array_intersect(array_keys($accessControl), (array)$user->get('roles')); |
||
192 | $modules = (array)array_keys($this->modules); |
||
193 | $hidden = []; |
||
194 | $readonly = []; |
||
195 | $write = []; |
||
196 | foreach ($roles as $role) { |
||
197 | $h = (array)Hash::get($accessControl, sprintf('%s.hidden', $role)); |
||
198 | $hidden = empty($hidden) ? $h : array_intersect($hidden, $h); |
||
199 | $r = (array)Hash::get($accessControl, sprintf('%s.readonly', $role)); |
||
200 | $readonly = empty($readonly) ? $r : array_intersect($readonly, $r); |
||
201 | $write = array_unique(array_merge($write, array_diff($modules, $hidden, $readonly))); |
||
202 | } |
||
203 | // Note: https://github.com/bedita/manager/issues/969 Accesses priority is "write" > "read" > "hidden" |
||
204 | $readonly = array_diff($readonly, $write); |
||
205 | $hidden = array_diff($hidden, $readonly, $write); |
||
206 | if (empty($hidden) && empty($readonly)) { |
||
207 | return; |
||
208 | } |
||
209 | // remove "hidden" |
||
210 | $this->modules = array_diff_key($this->modules, array_flip($hidden)); |
||
211 | // make sure $readonly contains valid module names |
||
212 | $readonly = array_intersect($readonly, array_keys($this->modules)); |
||
213 | foreach ($readonly as $key) { |
||
214 | $path = sprintf('%s.hints.allow', $key); |
||
215 | $allow = (array)Hash::get($this->modules, $path); |
||
216 | $this->modules[$key]['hints']['allow'] = array_diff($allow, ['POST', 'PATCH', 'DELETE']); |
||
217 | } |
||
218 | } |
||
219 | |||
220 | /** |
||
221 | * Modules data from `/home` endpoint 'meta' response. |
||
222 | * Modules are object endpoints from BE4 API |
||
223 | * |
||
224 | * @return array |
||
225 | */ |
||
226 | protected function modulesFromMeta(): array |
||
227 | { |
||
228 | /** @var \Authentication\Identity $user */ |
||
229 | $user = $this->Authentication->getIdentity(); |
||
230 | $meta = $this->getMeta($user); |
||
231 | $modules = collection(Hash::get($meta, 'resources', [])) |
||
232 | ->map(function (array $data, $endpoint) { |
||
233 | $name = substr($endpoint, 1); |
||
234 | |||
235 | return $data + compact('name'); |
||
236 | }) |
||
237 | ->reject(function (array $data) { |
||
238 | return Hash::get($data, 'hints.object_type') !== true && !in_array(Hash::get($data, 'name'), ['trash', 'translations']); |
||
239 | }) |
||
240 | ->toList(); |
||
241 | |||
242 | return Hash::combine($modules, '{n}.name', '{n}'); |
||
243 | } |
||
244 | |||
245 | /** |
||
246 | * Get information about current project. |
||
247 | * |
||
248 | * @return array |
||
249 | */ |
||
250 | public function getProject(): array |
||
251 | { |
||
252 | /** @var \Authentication\Identity $user */ |
||
253 | $user = $this->Authentication->getIdentity(); |
||
254 | $meta = $this->getMeta($user); |
||
255 | $project = (array)Configure::read('Project'); |
||
256 | $name = (string)Hash::get($project, 'name', Hash::get($meta, 'project.name')); |
||
257 | $version = Hash::get($meta, 'version', ''); |
||
258 | |||
259 | return compact('name', 'version'); |
||
260 | } |
||
261 | |||
262 | /** |
||
263 | * Check if an object type is abstract or concrete. |
||
264 | * This method MUST NOT be called from `beforeRender` since `$this->modules` array is still not initialized. |
||
265 | * |
||
266 | * @param string $name Name of object type. |
||
267 | * @return bool True if abstract, false if concrete |
||
268 | */ |
||
269 | public function isAbstract(string $name): bool |
||
270 | { |
||
271 | return (bool)Hash::get($this->modules, sprintf('%s.hints.multiple_types', $name), false); |
||
272 | } |
||
273 | |||
274 | /** |
||
275 | * Get list of object types |
||
276 | * This method MUST NOT be called from `beforeRender` since `$this->modules` array is still not initialized. |
||
277 | * |
||
278 | * @param bool|null $abstract Only abstract or concrete types. |
||
279 | * @return array Type names list |
||
280 | */ |
||
281 | public function objectTypes(?bool $abstract = null): array |
||
282 | { |
||
283 | $types = []; |
||
284 | foreach ($this->modules as $name => $data) { |
||
285 | if (empty($data['hints']['object_type'])) { |
||
286 | continue; |
||
287 | } |
||
288 | if ($abstract === null || $data['hints']['multiple_types'] === $abstract) { |
||
289 | $types[] = $name; |
||
290 | } |
||
291 | } |
||
292 | |||
293 | return $types; |
||
294 | } |
||
295 | |||
296 | /** |
||
297 | * Read oEmbed metadata |
||
298 | * |
||
299 | * @param string $url Remote URL |
||
300 | * @return array|null |
||
301 | * @codeCoverageIgnore |
||
302 | */ |
||
303 | protected function oEmbedMeta(string $url): ?array |
||
304 | { |
||
305 | return (new OEmbed())->readMetadata($url); |
||
306 | } |
||
307 | |||
308 | /** |
||
309 | * Upload a file and store it in a media stream |
||
310 | * Or create a remote media trying to get some metadata via oEmbed |
||
311 | * |
||
312 | * @param array $requestData The request data from form |
||
313 | * @return void |
||
314 | */ |
||
315 | public function upload(array &$requestData): void |
||
316 | { |
||
317 | $uploadBehavior = Hash::get($requestData, 'upload_behavior', 'file'); |
||
318 | |||
319 | if ($uploadBehavior === 'embed' && !empty($requestData['remote_url'])) { |
||
320 | $data = $this->oEmbedMeta($requestData['remote_url']); |
||
321 | $requestData = array_filter($requestData) + $data; |
||
322 | |||
323 | return; |
||
324 | } |
||
325 | if (empty($requestData['file'])) { |
||
326 | return; |
||
327 | } |
||
328 | |||
329 | // verify upload form data |
||
330 | if ($this->checkRequestForUpload($requestData)) { |
||
331 | // has another stream? drop it |
||
332 | $this->removeStream($requestData); |
||
333 | |||
334 | /** @var \Laminas\Diactoros\UploadedFile $file */ |
||
335 | $file = $requestData['file']; |
||
336 | |||
337 | // upload file |
||
338 | $filename = basename($file->getClientFileName()); |
||
339 | $filepath = $file->getStream()->getMetadata('uri'); |
||
340 | $headers = ['Content-Type' => $file->getClientMediaType()]; |
||
341 | $apiClient = ApiClientProvider::getApiClient(); |
||
342 | $response = $apiClient->upload($filename, $filepath, $headers); |
||
343 | |||
344 | // assoc stream to media |
||
345 | $streamId = $response['data']['id']; |
||
346 | $requestData['id'] = $this->assocStreamToMedia($streamId, $requestData, $filename); |
||
347 | } |
||
348 | unset($requestData['file'], $requestData['remote_url']); |
||
349 | } |
||
350 | |||
351 | /** |
||
352 | * Remove a stream from a media, if any |
||
353 | * |
||
354 | * @param array $requestData The request data from form |
||
355 | * @return bool |
||
356 | */ |
||
357 | public function removeStream(array $requestData): bool |
||
372 | } |
||
373 | |||
374 | /** |
||
375 | * Associate a stream to a media using API |
||
376 | * If $requestData['id'] is null, create media from stream. |
||
377 | * If $requestData['id'] is not null, replace properly related stream. |
||
378 | * |
||
379 | * @param string $streamId The stream ID |
||
380 | * @param array $requestData The request data |
||
381 | * @param string $defaultTitle The default title for media |
||
382 | * @return string The media ID |
||
383 | */ |
||
384 | public function assocStreamToMedia(string $streamId, array &$requestData, string $defaultTitle): string |
||
385 | { |
||
386 | $apiClient = ApiClientProvider::getApiClient(); |
||
387 | $type = $requestData['model-type']; |
||
388 | if (empty($requestData['id'])) { |
||
389 | // create media from stream |
||
390 | // save only `title` (filename if not set) and `status` in new media object |
||
391 | $attributes = array_filter([ |
||
392 | 'title' => !empty($requestData['title']) ? $requestData['title'] : $defaultTitle, |
||
393 | 'status' => Hash::get($requestData, 'status'), |
||
394 | ]); |
||
395 | $data = compact('type', 'attributes'); |
||
396 | $body = compact('data'); |
||
397 | $response = $apiClient->createMediaFromStream($streamId, $type, $body); |
||
398 | // `title` and `status` saved here, remove from next save |
||
399 | unset($requestData['title'], $requestData['status']); |
||
400 | |||
401 | return (string)Hash::get($response, 'data.id'); |
||
402 | } |
||
403 | |||
404 | // assoc existing media to stream |
||
405 | $id = (string)Hash::get($requestData, 'id'); |
||
406 | $data = compact('id', 'type'); |
||
407 | $apiClient->replaceRelated($streamId, 'streams', 'object', $data); |
||
408 | |||
409 | return $id; |
||
410 | } |
||
411 | |||
412 | /** |
||
413 | * Check request data for upload and return true if upload is boht possible and needed |
||
414 | * |
||
415 | * @param array $requestData The request data |
||
416 | * @return bool true if upload is possible and needed |
||
417 | */ |
||
418 | public function checkRequestForUpload(array $requestData): bool |
||
449 | } |
||
450 | |||
451 | /** |
||
452 | * Check if save can be skipped. |
||
453 | * This is used to avoid saving object with no changes. |
||
454 | * |
||
455 | * @param string $id The object ID |
||
456 | * @param array $requestData The request data |
||
457 | * @return bool True if save can be skipped, false otherwise |
||
458 | */ |
||
459 | public function skipSaveObject(string $id, array &$requestData): bool |
||
460 | { |
||
461 | if (empty($id)) { |
||
462 | return false; |
||
463 | } |
||
464 | if (isset($requestData['date_ranges'])) { |
||
465 | // check if date_ranges has changed |
||
466 | $type = $this->getController()->getRequest()->getParam('object_type'); |
||
467 | $response = ApiClientProvider::getApiClient()->getObject($id, $type, ['fields' => 'date_ranges']); |
||
468 | $actualDateRanges = (array)Hash::get($response, 'data.attributes.date_ranges'); |
||
469 | $dr1 = DateRangesTools::toString($actualDateRanges); |
||
470 | $requestDateRanges = (array)Hash::get($requestData, 'date_ranges'); |
||
471 | $dr2 = DateRangesTools::toString($requestDateRanges); |
||
472 | if ($dr1 === $dr2) { |
||
473 | unset($requestData['date_ranges']); |
||
474 | } else { |
||
475 | return false; |
||
476 | } |
||
477 | } |
||
478 | $data = array_filter($requestData, function ($key) { |
||
479 | return !in_array($key, ['id', 'date_ranges', 'permissions']); |
||
480 | }, ARRAY_FILTER_USE_KEY); |
||
481 | |||
482 | return empty($data); |
||
483 | } |
||
484 | |||
485 | /** |
||
486 | * Check if save related can be skipped. |
||
487 | * This is used to avoid saving object relations with no changes. |
||
488 | * |
||
489 | * @param string $id The object ID |
||
490 | * @param array $relatedData The related data |
||
491 | * @return bool True if save related can be skipped, false otherwise |
||
492 | */ |
||
493 | public function skipSaveRelated(string $id, array &$relatedData): bool |
||
494 | { |
||
495 | if (empty($relatedData)) { |
||
496 | return true; |
||
497 | } |
||
498 | $methods = (array)Hash::extract($relatedData, '{n}.method'); |
||
499 | if (in_array('addRelated', $methods) || in_array('removeRelated', $methods)) { |
||
500 | return false; |
||
501 | } |
||
502 | // check replaceRelated |
||
503 | $type = $this->getController()->getRequest()->getParam('object_type'); |
||
504 | $rr = $relatedData; |
||
505 | foreach ($rr as $method => $data) { |
||
506 | $actualRelated = (array)ApiClientProvider::getApiClient()->getRelated($id, $type, $data['relation']); |
||
507 | $actualRelated = (array)Hash::get($actualRelated, 'data'); |
||
508 | $actualRelated = RelationsTools::toString($actualRelated); |
||
509 | $requestRelated = (array)Hash::get($data, 'relatedIds', []); |
||
510 | $requestRelated = RelationsTools::toString($requestRelated); |
||
511 | if ($actualRelated === $requestRelated) { |
||
512 | unset($relatedData[$method]); |
||
513 | continue; |
||
514 | } |
||
515 | |||
516 | return false; |
||
517 | } |
||
518 | |||
519 | return empty($relatedData); |
||
520 | } |
||
521 | |||
522 | /** |
||
523 | * Check if save permissions can be skipped. |
||
524 | * This is used to avoid saving object permissions with no changes. |
||
525 | * |
||
526 | * @param string $id The object ID |
||
527 | * @param array $requestPermissions The request permissions |
||
528 | * @param array $schema The object type schema |
||
529 | * @return bool True if save permissions can be skipped, false otherwise |
||
530 | */ |
||
531 | public function skipSavePermissions(string $id, array $requestPermissions, array $schema): bool |
||
549 | } |
||
550 | |||
551 | /** |
||
552 | * Set current attributes from loaded $object data in `currentAttributes`. |
||
553 | * |
||
554 | * @param array $object The object. |
||
555 | * @return void |
||
556 | */ |
||
557 | public function setupAttributes(array &$object): void |
||
558 | { |
||
559 | $currentAttributes = json_encode((array)Hash::get($object, 'attributes')); |
||
560 | $this->getController()->set(compact('currentAttributes')); |
||
561 | } |
||
562 | |||
563 | /** |
||
564 | * Setup relations information metadata. |
||
565 | * |
||
566 | * @param array $schema Relations schema. |
||
567 | * @param array $relationships Object relationships. |
||
568 | * @param array $order Ordered names inside 'main' and 'aside' keys. |
||
569 | * @param array $hidden List of hidden relations. |
||
570 | * @param array $readonly List of readonly relations. |
||
571 | * @return void |
||
572 | */ |
||
573 | public function setupRelationsMeta(array $schema, array $relationships, array $order = [], array $hidden = [], array $readonly = []): void |
||
574 | { |
||
575 | // relations between objects |
||
576 | $relationsSchema = $this->relationsSchema($schema, $relationships, $hidden, $readonly); |
||
577 | // relations between objects and resources |
||
578 | $resourceRelations = array_diff(array_keys($relationships), array_keys($relationsSchema), $hidden, self::FIXED_RELATIONSHIPS); |
||
579 | // set objectRelations array with name as key and label as value |
||
580 | $relationNames = array_keys($relationsSchema); |
||
581 | |||
582 | // define 'main' and 'aside' relation groups |
||
583 | $aside = array_intersect((array)Hash::get($order, 'aside'), $relationNames); |
||
584 | $relationNames = array_diff($relationNames, $aside); |
||
585 | $main = array_intersect((array)Hash::get($order, 'main'), $relationNames); |
||
586 | $main = array_unique(array_merge($main, $relationNames)); |
||
587 | |||
588 | $objectRelations = [ |
||
589 | 'main' => $this->relationLabels($relationsSchema, $main), |
||
590 | 'aside' => $this->relationLabels($relationsSchema, $aside), |
||
591 | ]; |
||
592 | |||
593 | $this->getController()->set(compact('relationsSchema', 'resourceRelations', 'objectRelations')); |
||
594 | } |
||
595 | |||
596 | /** |
||
597 | * Relations schema by schema and relationships. |
||
598 | * |
||
599 | * @param array $schema The schema |
||
600 | * @param array $relationships The relationships |
||
601 | * @param array $hidden Hidden relationships |
||
602 | * @param array $readonly Readonly relationships |
||
603 | * @return array |
||
604 | */ |
||
605 | protected function relationsSchema(array $schema, array $relationships, array $hidden = [], array $readonly = []): array |
||
606 | { |
||
607 | $types = $this->objectTypes(false); |
||
608 | sort($types); |
||
609 | $relationsSchema = array_diff_key(array_intersect_key($schema, $relationships), array_flip($hidden)); |
||
610 | |||
611 | foreach ($relationsSchema as $relName => &$relSchema) { |
||
612 | if (in_array('objects', (array)Hash::get($relSchema, 'right'))) { |
||
613 | $relSchema['right'] = $types; |
||
614 | } |
||
615 | if (!empty($relationships[$relName]['readonly']) || in_array($relName, $readonly)) { |
||
616 | $relSchema['readonly'] = true; |
||
617 | } |
||
618 | } |
||
619 | |||
620 | return $relationsSchema; |
||
621 | } |
||
622 | |||
623 | /** |
||
624 | * Retrieve associative array with names as keys and labels as values. |
||
625 | * |
||
626 | * @param array $relationsSchema Relations schema. |
||
627 | * @param array $names Relation names. |
||
628 | * @return array |
||
629 | */ |
||
630 | protected function relationLabels(array &$relationsSchema, array $names): array |
||
631 | { |
||
632 | return (array)array_combine( |
||
633 | $names, |
||
634 | array_map( |
||
635 | function ($r) use ($relationsSchema) { |
||
636 | // return 'label' or 'inverse_label' looking at 'name' |
||
637 | $attributes = $relationsSchema[$r]['attributes']; |
||
638 | if ($r === $attributes['name']) { |
||
639 | return $attributes['label']; |
||
640 | } |
||
641 | |||
642 | return $attributes['inverse_label']; |
||
643 | }, |
||
644 | $names |
||
645 | ) |
||
646 | ); |
||
647 | } |
||
648 | |||
649 | /** |
||
650 | * Get related types from relation name. |
||
651 | * |
||
652 | * @param array $schema Relations schema. |
||
653 | * @param string $relation Relation name. |
||
654 | * @return array |
||
655 | */ |
||
656 | public function relatedTypes(array $schema, string $relation): array |
||
657 | { |
||
658 | $relationsSchema = (array)Hash::get($schema, $relation); |
||
659 | |||
660 | return (array)Hash::get($relationsSchema, 'right'); |
||
661 | } |
||
662 | |||
663 | /** |
||
664 | * Save related objects. |
||
665 | * |
||
666 | * @param string $id Object ID |
||
667 | * @param string $type Object type |
||
668 | * @param array $relatedData Related objects data |
||
669 | * @return void |
||
670 | */ |
||
671 | public function saveRelated(string $id, string $type, array $relatedData): void |
||
672 | { |
||
673 | foreach ($relatedData as $data) { |
||
674 | $this->saveRelatedObjects($id, $type, $data); |
||
675 | $event = new Event('Controller.afterSaveRelated', $this, compact('id', 'type', 'data')); |
||
676 | $this->getController()->getEventManager()->dispatch($event); |
||
677 | } |
||
678 | } |
||
679 | |||
680 | /** |
||
681 | * Save related objects per object by ID. |
||
682 | * |
||
683 | * @param string $id Object ID |
||
684 | * @param string $type Object type |
||
685 | * @param array $data Related object data |
||
686 | * @return array|null |
||
687 | * @throws \Cake\Http\Exception\BadRequestException |
||
688 | */ |
||
689 | public function saveRelatedObjects(string $id, string $type, array $data): ?array |
||
690 | { |
||
691 | $method = (string)Hash::get($data, 'method'); |
||
692 | if (!in_array($method, ['addRelated', 'removeRelated', 'replaceRelated'])) { |
||
693 | throw new BadRequestException(__('Bad related data method')); |
||
694 | } |
||
695 | $relation = (string)Hash::get($data, 'relation'); |
||
696 | $related = $this->getRelated($data); |
||
697 | if ($relation === 'parent' && $type === 'folders') { |
||
698 | return $this->Parents->{$method}($id, $related); |
||
699 | } |
||
700 | if ($relation === 'children' && $type === 'folders') { |
||
701 | return $this->Children->{$method}($id, $related); |
||
702 | } |
||
703 | $lang = I18n::getLocale(); |
||
704 | $headers = ['Accept-Language' => $lang]; |
||
705 | |||
706 | return ApiClientProvider::getApiClient()->{$method}($id, $type, $relation, $related, $headers); |
||
707 | } |
||
708 | |||
709 | /** |
||
710 | * Get related objects. |
||
711 | * If related object has no ID, it will be created. |
||
712 | * |
||
713 | * @param array $data Related object data |
||
714 | * @return array |
||
715 | */ |
||
716 | public function getRelated(array $data): array |
||
744 | } |
||
745 | } |
||
746 |