TreeTrait::setParent()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 7
c 2
b 1
f 0
dl 0
loc 10
rs 10
cc 1
nc 1
nop 2
1
<?php
2
declare(strict_types=1);
3
4
/**
5
 * BEdita, API-first content management framework
6
 * Copyright 2023 Atlas Srl, Chialab Srl
7
 *
8
 * This file is part of BEdita: you can redistribute it and/or modify
9
 * it under the terms of the GNU Lesser General Public License as published
10
 * by the Free Software Foundation, either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
14
 */
15
16
namespace BEdita\ImportTools\Utility;
17
18
use BEdita\Core\Model\Action\SetRelatedObjectsAction;
19
use BEdita\Core\Model\Entity\ObjectEntity;
20
21
/**
22
 * Trait for share Tree stuff.
23
 *
24
 * This provides `setParent` method to save the parent for a specified entity.
25
 *
26
 * Usage example:
27
 * ```php
28
 * use BEdita\ImportTools\Utility\TreeTrait;
29
 *
30
 * class MyImporter
31
 * {
32
 *     use TreeTrait;
33
 *
34
 *     public function import(string $filename, string $destination): void
35
 *     {
36
 *         foreach ($this->readCsv($filename) as $obj) {
37
 *             $this->setParent($obj, $destination);
38
 *         }
39
 *     }
40
 * }
41
 * ```
42
 */
43
trait TreeTrait
44
{
45
    /**
46
     * Set parent folder
47
     *
48
     * @param \BEdita\Core\Model\Entity\ObjectEntity $entity Entity
49
     * @param string $folder Folder uname or ID
50
     * @return void
51
     */
52
    protected function setParent(ObjectEntity $entity, string $folder): void
53
    {
54
        /** @var \BEdita\Core\Model\Table\FoldersTable $foldersTable */
55
        $foldersTable = $this->fetchTable('Folders');
56
        $parentId = $foldersTable->getId($folder);
57
        $parentEntity = $foldersTable->get($parentId);
58
        $association = $entity->getTable()->associations()->getByProperty('parents');
59
        $action = new SetRelatedObjectsAction(compact('association'));
60
        $relatedEntities = [$parentEntity];
61
        $action(compact('entity', 'relatedEntities'));
62
    }
63
}
64