Completed
Push — 4-cactus ( 5614e8...d450f9 )
by Stefano
20s queued 10s
created

UpdateRelatedObjectsAction::prepareData()   A

Complexity

Conditions 6
Paths 3

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 12
nc 3
nop 1
dl 0
loc 19
rs 9.2222
c 0
b 0
f 0
1
<?php
2
/**
3
 * BEdita, API-first content management framework
4
 * Copyright 2017 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
14
namespace BEdita\Core\Model\Action;
15
16
use BEdita\Core\Model\Entity\Folder;
17
18
/**
19
 * Abstract class for updating relations between BEdita objects.
20
 *
21
 * @since 4.0.0
22
 *
23
 * @property \BEdita\Core\ORM\Association\RelatedTo $Association
24
 */
25
abstract class UpdateRelatedObjectsAction extends UpdateAssociatedAction
26
{
27
28
    /**
29
     * {@inheritDoc}
30
     */
31
    public function execute(array $data = [])
32
    {
33
        $data = $this->prepareData($data);
34
35
        return parent::execute($data);
36
    }
37
38
    /**
39
     * Get the right entity for the action.
40
     *
41
     * For `Folder` entity with `Parents` association changes the point of view
42
     * using `Tree` entity with `ParentObjects` association assuring to
43
     * always use a "to one" relation.
44
     *
45
     * @param array $data Action data.
46
     * @return array
47
     */
48
    protected function prepareData(array $data)
49
    {
50
        if (empty($data['entity']) || !($data['entity'] instanceof Folder) || $this->Association->getName() !== 'Parents') {
51
            return $data;
52
        }
53
54
        $table = $this->Association->junction();
55
        $entity = $table->find()
56
            ->where([$table->association('Objects')->getForeignKey() => $data['entity']->id])
57
            ->firstOrFail();
58
        $relatedEntities = $data['relatedEntities'];
59
        if (is_array($relatedEntities) && count($relatedEntities) === 1) {
60
            $relatedEntities = reset($relatedEntities);
61
        }
62
63
        $this->Association = $table->association('ParentObjects');
64
        $this->setConfig('association', $this->Association);
65
66
        return compact('entity', 'relatedEntities') + $data;
67
    }
68
}
69