ModulesComponent::setupAttributes()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * BEdita, API-first content management framework
4
 * Copyright 2022 ChannelWeb Srl, Chialab Srl
5
 *
6
 * This file is part of BEdita: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as published
8
 * by the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
12
 */
13
namespace App\Controller\Component;
14
15
use App\Core\Exception\UploadException;
16
use App\Utility\DateRangesTools;
17
use App\Utility\OEmbed;
18
use App\Utility\RelationsTools;
19
use App\Utility\SchemaTrait;
20
use BEdita\WebTools\ApiClientProvider;
21
use Cake\Cache\Cache;
22
use Cake\Controller\Component;
23
use Cake\Core\Configure;
24
use Cake\Event\Event;
25
use Cake\Event\EventInterface;
26
use Cake\Http\Client\Response;
27
use Cake\Http\Exception\BadRequestException;
28
use Cake\Http\Exception\InternalErrorException;
29
use Cake\I18n\I18n;
30
use Cake\Utility\Hash;
31
32
/**
33
 * Component to load available modules.
34
 *
35
 * @property \Authentication\Controller\Component\AuthenticationComponent $Authentication
36
 * @property \App\Controller\Component\ChildrenComponent $Children
37
 * @property \App\Controller\Component\ConfigComponent $Config
38
 * @property \App\Controller\Component\ParentsComponent $Parents
39
 * @property \App\Controller\Component\SchemaComponent $Schema
40
 */
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
        $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
327
    {
328
        $uploadBehavior = Hash::get($requestData, 'upload_behavior', 'file');
329
330
        if ($uploadBehavior === 'embed' && !empty($requestData['remote_url'])) {
331
            $data = $this->oEmbedMeta($requestData['remote_url']);
332
            $requestData = array_filter($requestData) + $data;
333
334
            return;
335
        }
336
        if (empty($requestData['file'])) {
337
            return;
338
        }
339
340
        // verify upload form data
341
        if ($this->checkRequestForUpload($requestData)) {
342
            // has another stream? drop it
343
            $this->removeStream($requestData);
344
345
            /** @var \Laminas\Diactoros\UploadedFile $file */
346
            $file = $requestData['file'];
347
348
            // upload file
349
            $filename = basename($file->getClientFileName());
350
            $filepath = $file->getStream()->getMetadata('uri');
351
            $headers = ['Content-Type' => $file->getClientMediaType()];
352
            $apiClient = ApiClientProvider::getApiClient();
353
            $response = $apiClient->upload($filename, $filepath, $headers);
354
355
            // assoc stream to media
356
            $streamId = $response['data']['id'];
357
            $requestData['id'] = $this->assocStreamToMedia($streamId, $requestData, $filename);
358
        }
359
        unset($requestData['file'], $requestData['remote_url']);
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
369
    {
370
        if (empty($requestData['id'])) {
371
            return false;
372
        }
373
374
        $apiClient = ApiClientProvider::getApiClient();
375
        $response = $apiClient->get(sprintf('/%s/%s/streams', $requestData['model-type'], $requestData['id']));
376
        if (empty($response['data'])) { // no streams for media
377
            return false;
378
        }
379
        $streamId = Hash::get($response, 'data.0.id');
380
        $apiClient->deleteObject($streamId, 'streams');
381
382
        return true;
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
430
    {
431
        /** @var \Laminas\Diactoros\UploadedFile $file */
432
        $file = $requestData['file'];
433
        $error = $file->getError();
434
        // check if change file is empty
435
        if ($error === UPLOAD_ERR_NO_FILE) {
436
            return false;
437
        }
438
439
        // if upload error, throw exception
440
        if ($error !== UPLOAD_ERR_OK) {
441
            throw new UploadException(null, $error);
442
        }
443
444
        // verify presence and value of 'name', 'tmp_name', 'type'
445
        $name = $file->getClientFileName();
446
        if (empty($name)) {
447
            throw new InternalErrorException('Invalid form data: file.name');
448
        }
449
        $uri = $file->getStream()->getMetadata('uri');
450
        if (empty($uri)) {
451
            throw new InternalErrorException('Invalid form data: file.tmp_name');
452
        }
453
454
        // verify 'model-type'
455
        if (empty($requestData['model-type']) || !is_string($requestData['model-type'])) {
456
            throw new InternalErrorException('Invalid form data: model-type');
457
        }
458
459
        return true;
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
543
    {
544
        if (!in_array('Permissions', (array)Hash::get($schema, 'associations'))) {
545
            return true;
546
        }
547
        $requestPermissions = array_map(
548
            function ($role) {
549
                return (int)$role;
550
            },
551
            $requestPermissions
552
        );
553
        sort($requestPermissions);
554
        $query = ['filter' => ['object_id' => $id], 'page_size' => 100];
555
        $objectPermissions = (array)ApiClientProvider::getApiClient()->getObjects('object_permissions', $query);
556
        $actualPermissions = (array)Hash::extract($objectPermissions, 'data.{n}.attributes.role_id');
557
        sort($actualPermissions);
558
559
        return $actualPermissions === $requestPermissions;
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
728
    {
729
        $related = (array)Hash::get($data, 'relatedIds');
730
        if (empty($related)) {
731
            return [];
732
        }
733
        $relatedObjects = [];
734
        foreach ($related as $obj) {
735
            if (!empty($obj['id'])) {
736
                $relatedObjects[] = [
737
                    'id' => $obj['id'],
738
                    'type' => $obj['type'],
739
                    'meta' => (array)Hash::get($obj, 'meta'),
740
                ];
741
                continue;
742
            }
743
            $response = ApiClientProvider::getApiClient()->save(
744
                (string)Hash::get($obj, 'type'),
745
                (array)Hash::get($obj, 'attributes')
746
            );
747
            $relatedObjects[] = [
748
                'id' => Hash::get($response, 'data.id'),
749
                'type' => Hash::get($response, 'data.type'),
750
                'meta' => (array)Hash::get($response, 'data.meta'),
751
            ];
752
        }
753
754
        return $relatedObjects;
755
    }
756
}
757