Completed
Pull Request — master (#114)
by Bart
04:23
created

Site::getGroupIdByName()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 8.7624
c 0
b 0
f 0
cc 5
eloc 13
nc 6
nop 1
1
<?php
2
3
namespace NerdsAndCompany\Schematic\Converters\Models;
4
5
use Craft;
6
use craft\models\SiteGroup;
7
use craft\base\Model;
8
use NerdsAndCompany\Schematic\Schematic;
9
10
/**
11
 * Schematic Sites Converter.
12
 *
13
 * Sync Craft Setups.
14
 *
15
 * @author    Nerds & Company
16
 * @copyright Copyright (c) 2015-2018, Nerds & Company
17
 * @license   MIT
18
 *
19
 * @see      http://www.nerds.company
20
 */
21
class Site extends Base
22
{
23
    /**
24
     * @var number[]
25
     */
26
    private $groups;
27
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public function getRecordDefinition(Model $record): array
32
    {
33
        $definition = parent::getRecordDefinition($record);
34
35
        if ($record->groupId) {
36
            $definition['group'] = $record->group->name;
37
        }
38
        unset($definition['attributes']['groupId']);
39
40
        return $definition;
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public function saveRecord(Model $record, array $definition): bool
47
    {
48
        if ($definition['group']) {
49
            $record->groupId = $this->getGroupIdByName($definition['group']);
50
        }
51
52
        return Craft::$app->sites->saveSite($record);
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function deleteRecord(Model $record): bool
59
    {
60
        return Craft::$app->sites->deleteSiteById($record->id);
61
    }
62
63
    /**
64
     * Get group id by name.
65
     *
66
     * @param string $name
67
     *
68
     * @return int|null
69
     */
70
    public function getGroupIdByName($name)
71
    {
72
        if (!isset($this->groups)) {
73
            $this->groups = [];
74
            foreach (Craft::$app->sites->getAllGroups() as $group) {
75
                $this->groups[$group->name] = $group->id;
76
            }
77
        }
78
        if (!array_key_exists($name, $this->groups)) {
79
            $group = new SiteGroup(['name' => $name]);
80
            if (Craft::$app->sites->saveGroup($group)) {
81
                $this->groups[$name] = $group->id;
82
            } else {
83
                Schematic::importError($group, $name);
84
85
                return null;
86
            }
87
        }
88
89
        return $this->groups[$name];
90
    }
91
}
92