Completed
Pull Request — master (#114)
by Bart
12:35 queued 03:19
created

Field::getGroupIdByName()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 12
nc 6
nop 1
1
<?php
2
3
namespace NerdsAndCompany\Schematic\Converters\Base;
4
5
use Craft;
6
use craft\base\Model;
7
use craft\models\FieldGroup;
8
use NerdsAndCompany\Schematic\Converters\Models\Base;
9
10
/**
11
 * Schematic Fields 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 Field extends Base
22
{
23
    /**
24
     * @var number[]
25
     */
26
    private $groups;
27
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public function getRecordDefinition(Model $record)
32
    {
33
        $definition = parent::getRecordDefinition($record);
34
35
        if ($record->groupId) {
36
            $definition['group'] = $record->group->name;
37
        }
38
39
        $definition['attributes']['required'] = $definition['attributes']['required'] == true;
40
        unset($definition['attributes']['context']);
41
        unset($definition['attributes']['groupId']);
42
        unset($definition['attributes']['layoutId']);
43
        unset($definition['attributes']['tabId']);
44
45
        return $definition;
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function saveRecord(Model $record, array $definition)
52
    {
53
        if (array_key_exists('group', $definition)) {
54
            $record->groupId = $this->getGroupIdByName($definition['group']);
55
        }
56
57
        return Craft::$app->fields->saveField($record);
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function deleteRecord(Model $record)
64
    {
65
        return Craft::$app->fields->deleteField($record);
66
    }
67
68
    /**
69
     * Get group id by name.
70
     *
71
     * @param string $name
72
     *
73
     * @return
74
     */
75
    private function getGroupIdByName($name)
76
    {
77
        if (!isset($this->groups)) {
78
            $this->groups = [];
79
            foreach (Craft::$app->fields->getAllGroups() as $group) {
80
                $this->groups[$group->name] = $group->id;
81
            }
82
        }
83
        if (!array_key_exists($name, $this->groups)) {
84
            $group = new FieldGroup(['name' => $name]);
85
            if (Craft::$app->fields->saveGroup($group)) {
86
                $this->groups[$name] = $group->id;
87
            } else {
88
                return Schematic::importError($group, $name);
89
            }
90
        }
91
92
        return $this->groups[$name];
93
    }
94
}
95