Completed
Pull Request — master (#114)
by Bart
07:53
created

Fields::getGroupIdByName()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

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