Completed
Pull Request — master (#114)
by Bart
05:42
created

Sites::saveRecord()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
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
        $record->groupId = $this->getGroupIdByName($definition['group']);
58
        return Craft::$app->sites->saveSite($record);
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    protected function deleteRecord(Model $record)
65
    {
66
        return Craft::$app->sites->deleteSiteById($record->id);
67
    }
68
69
    /**
70
     * Get group id by name
71
     *
72
     * @param  string $name
73
     * @return
74
     */
75
    private function getGroupIdByName($name)
76
    {
77
        if (!isset($this->groups)) {
78
            $this->groups = [];
79
            foreach (Craft::$app->sites->getAllGroups() as $group) {
80
                $this->groups[$group->name] = $group->id;
81
            }
82
        }
83
        if (!array_key_exists($name, $this->groups)) {
84
            $group = new SiteGroup(['name' => $name]);
85
            if (Craft::$app->sites->saveGroup($group)) {
86
                $this->groups[$name] = $group->id;
87
            } else {
88
                $this->importError($group, $name);
89
            }
90
        }
91
        return $this->groups[$name];
92
    }
93
}
94