Completed
Pull Request — master (#114)
by Bart
02:14
created

Sites   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 3
dl 0
loc 78
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getRecords() 0 4 1
A getRecordDefinition() 0 10 2
A saveRecord() 0 8 2
A deleteRecord() 0 4 1
B getGroupIdByName() 0 19 5
1
<?php
2
3
namespace NerdsAndCompany\Schematic\Services;
4
5
use Craft;
6
use craft\models\Site;
7
use craft\models\SiteGroup;
8
use craft\base\Model;
9
10
/**
11
 * Schematic Globals Service.
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 Sites extends Base
22
{
23
    /**
24
     * @var number[]
25
     */
26
    private $groups;
27
28
    /**
29
     * Get all sites.
30
     *
31
     * @return Site[]
32
     */
33
    protected function getRecords()
34
    {
35
        return Craft::$app->sites->getAllSites();
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    protected function getRecordDefinition(Model $record)
42
    {
43
        $definition = parent::getRecordDefinition($record);
44
        if ($record instanceof Site) {
45
            $definition['group'] = $record->group->name;
46
            unset($definition['attributes']['groupId']);
47
        }
48
49
        return $definition;
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    protected function saveRecord(Model $record, array $definition)
56
    {
57
        if ($definition['group']) {
58
            $record->groupId = $this->getGroupIdByName($definition['group']);
59
        }
60
61
        return Craft::$app->sites->saveSite($record);
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    protected function deleteRecord(Model $record)
68
    {
69
        return Craft::$app->sites->deleteSiteById($record->id);
70
    }
71
72
    /**
73
     * Get group id by name.
74
     *
75
     * @param string $name
76
     *
77
     * @return
78
     */
79
    private function getGroupIdByName($name)
80
    {
81
        if (!isset($this->groups)) {
82
            $this->groups = [];
83
            foreach (Craft::$app->sites->getAllGroups() as $group) {
84
                $this->groups[$group->name] = $group->id;
85
            }
86
        }
87
        if (!array_key_exists($name, $this->groups)) {
88
            $group = new SiteGroup(['name' => $name]);
89
            if (Craft::$app->sites->saveGroup($group)) {
90
                $this->groups[$name] = $group->id;
91
            } else {
92
                return $this->importError($group, $name);
93
            }
94
        }
95
96
        return $this->groups[$name];
97
    }
98
}
99