Completed
Pull Request — master (#114)
by Bart
16:27 queued 06:28
created

UserGroups::import()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 33
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 8.439
c 0
b 0
f 0
ccs 13
cts 13
cp 1
cc 6
eloc 17
nc 10
nop 2
crap 6
1
<?php
2
3
namespace NerdsAndCompany\Schematic\Services;
4
5
use Craft;
6
use craft\base\Model;
7
use craft\models\UserGroup;
8
9
/**
10
 * Schematic User Groups Service.
11
 *
12
 * Sync Craft Setups.
13
 *
14
 * @author    Nerds & Company
15
 * @copyright Copyright (c) 2015-2018, Nerds & Company
16
 * @license   MIT
17
 *
18
 * @see      http://www.nerds.company
19
 */
20
class UserGroups extends Base
21
{
22
    /** @var string[] */
23
    private $mappedPermissions = [];
24
25
    //==============================================================================================================
26
    //================================================  EXPORT  ====================================================
27
    //==============================================================================================================
28
29
    /**
30
     * Get all section records
31
     *
32
     * @return UserGroup[]
33
     */
34
    protected function getRecords()
35 4
    {
36
        $this->mappedPermissions = $this->getAllMappedPermissions();
37 4
38
        return Craft::$app->userGroups->getAllGroups();
39 4
    }
40
41 4
    /**
42
     * Get group definition.
43 4
     *
44 3
     * @param UserGroupModel $group
0 ignored issues
show
Bug introduced by
There is no parameter named $group. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
45 4
     *
46
     * @return array
47 4
     */
48
    protected function getRecordDefinition(Model $record)
49
    {
50
        $attributes = parent::getRecordDefinition($record);
51
        $attributes['permissions'] = $this->getGroupPermissionDefinitions($record);
52
        return $attributes;
53
    }
54
55
    /**
56
     * Get group permissions.
57 3
     *
58
     * @param $group
59
     *
60 3
     * @return array|string
61 3
     */
62 3
    private function getGroupPermissionDefinitions($group)
63
    {
64
        $permissionDefinitions = [];
65
        $groupPermissions = Craft::$app->userPermissions->getPermissionsByGroupId($group->id);
66
67
        foreach ($groupPermissions as $permission) {
68
            if (array_key_exists($permission, $this->mappedPermissions)) {
69
                $permission = $this->mappedPermissions[$permission];
70
                $permissionDefinitions[] = $this->getSource(false, $permission, 'id', 'handle');
0 ignored issues
show
Documentation Bug introduced by
The method getSource does not exist on object<NerdsAndCompany\S...ic\Services\UserGroups>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
71
            }
72 3
        }
73
        sort($permissionDefinitions);
74 3
75 3
        return $permissionDefinitions;
76
    }
77 3
78 1
    /**
79 1
     * Get a mapping of all permissions from lowercase to camelcase
80 1
     * savePermissions only accepts camelcase.
81 1
     *
82 3
     * @return array
83 3
     */
84
    private function getAllMappedPermissions()
85 3
    {
86
        $mappedPermissions = [];
87
        foreach (Craft::$app->userPermissions->getAllPermissions() as $permissions) {
88
            $mappedPermissions = array_merge($mappedPermissions, $this->getMappedPermissions($permissions));
89
        }
90
91
        return $mappedPermissions;
92
    }
93
94 4
    /**
95
     * @param array $permissions
96 4
     *
97 4
     * @return array
98 4
     */
99 4
    private function getMappedPermissions(array $permissions)
100
    {
101 4
        $mappedPermissions = [];
102
        foreach ($permissions as $permission => $options) {
103
            $mappedPermissions[strtolower($permission)] = $permission;
104
            if (array_key_exists('nested', $options)) {
105
                $mappedPermissions = array_merge($mappedPermissions, $this->getMappedPermissions($options['nested']));
106
            }
107
        }
108
109 4
        return $mappedPermissions;
110
    }
111 4
112 4
    //==============================================================================================================
113 4
    //================================================  IMPORT  ====================================================
114 4
    //==============================================================================================================
115 4
116 4
    /**
117 4
     * Import usergroups.
118
     *
119 4
     * @param array $groupDefinitions
120
     * @param bool  $force            if set to true items not in the import will be deleted
121
     *
122
     * @return Result
123
     */
124
    public function import($force = false, array $groupDefinitions = null)
125
    {
126
        Craft::info('Importing User Groups', 'schematic');
127
128
        $userGroups = Craft::$app->userGroups->getAllGroups('handle');
129
130
        foreach ($groupDefinitions as $groupHandle => $groupDefinition) {
0 ignored issues
show
Bug introduced by
The expression $groupDefinitions of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
131
            $group = array_key_exists($groupHandle, $userGroups) ? $userGroups[$groupHandle] : new UserGroupModel();
132
133
            unset($userGroups[$groupHandle]);
134 9
135
            $group->name = $groupDefinition['name'];
136 9
            $group->handle = $groupHandle;
137
138 9
            if (!Craft::$app->userGroups->saveGroup($group)) {
139
                $this->addErrors($group->getAllErrors());
0 ignored issues
show
Documentation Bug introduced by
The method addErrors does not exist on object<NerdsAndCompany\S...ic\Services\UserGroups>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
140 9
141 6
                continue;
142
            }
143 6
144
            $permissions = $this->getPermissions($groupDefinition['permissions']);
145 6
146 6
            Craft::$app->userPermissions->saveGroupPermissions($group->id, $permissions);
147
        }
148 6
149 2
        if ($force) {
150
            foreach ($userGroups as $group) {
151 2
                Craft::$app->userGroups->deleteGroupById($group->id);
152
            }
153
        }
154 4
155
        return $this->getResultModel();
0 ignored issues
show
Documentation Bug introduced by
The method getResultModel does not exist on object<NerdsAndCompany\S...ic\Services\UserGroups>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
156 4
    }
157 9
158
    /**
159 9
     * Get permissions.
160 3
     *
161 3
     * @param array $permissionDefinitions
162 3
     *
163 3
     * @return array
164
     */
165 9
    private function getPermissions(array $permissionDefinitions)
166
    {
167
        $permissions = [];
168
        foreach ($permissionDefinitions as $permissionDefinition) {
169
            $permissions[] = Craft::$app->schematic_sources->getSource(false, $permissionDefinition, 'handle', 'id');
170
        }
171
172
        return $permissions;
173
    }
174
}
175