Completed
Pull Request — master (#114)
by Bart
16:40 queued 06:39
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 10
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
     * Get section definition.
41
     *
42
     * @param Model $record
43
     *
44
     * @return array
45
     */
46
    protected function getRecordDefinition(Model $record)
47
    {
48
        $definition = parent::getRecordDefinition($record);
49
        if ($record instanceof Field) {
50
            $definition['group'] = $record->group->name;
51
            unset($definition['attributes']['groupId']);
52
            unset($definition['attributes']['layoutId']);
53
            unset($definition['attributes']['tabId']);
54
        }
55
56
        return $definition;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62
    protected function saveRecord(Model $record, array $definition)
63
    {
64
        $record->groupId = $this->getGroupIdByName($definition['group']);
65
        return Craft::$app->fields->saveField($record);
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    protected function deleteRecord(Model $record)
72
    {
73
        return Craft::$app->fields->deleteField($record);
74
    }
75
76
    /**
77
     * Get group id by name
78
     * @param  string $name
79
     * @return
80
     */
81
    private function getGroupIdByName($name)
82
    {
83
        if (!isset($this->groups)) {
84
            $this->groups = [];
85
            foreach (Craft::$app->fields->getAllGroups() as $group) {
86
                $this->groups[$group->name] = $group->id;
87
            }
88
        }
89
        if (!array_key_exists($name, $this->groups)) {
90
            $group = new FieldGroup(['name' => $name]);
91
            if (Craft::$app->fields->saveGroup($group)) {
92
                $this->groups[$name] = $group->id;
93
            } else {
94
                $this->importError($group, $name);
95
            }
96
        }
97
        return $this->groups[$name];
98
    }
99
}
100