Completed
Pull Request — 1.0 (#53)
by Harald
07:00
created

UserManager::assignUserToUserGroups()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 20
ccs 14
cts 14
cp 1
rs 8.8571
cc 5
eloc 12
nc 5
nop 2
crap 5
1
<?php
2
3
/*
4
 * This file is part of Transfer.
5
 *
6
 * For the full copyright and license information, please view the LICENSE file located
7
 * in the root directory.
8
 */
9
10
namespace Transfer\EzPlatform\Repository\Manager;
11
12
use eZ\Publish\API\Repository\Repository;
13
use eZ\Publish\API\Repository\UserService;
14
use eZ\Publish\API\Repository\Values\User\User;
15
use eZ\Publish\API\Repository\Values\User\UserGroup;
16
use Psr\Log\LoggerAwareInterface;
17
use Psr\Log\LoggerInterface;
18
use Transfer\Data\ObjectInterface;
19
use Transfer\Data\ValueObject;
20
use Transfer\EzPlatform\Exception\UnsupportedObjectOperationException;
21
use Transfer\EzPlatform\Repository\Values\UserGroupObject;
22
use Transfer\EzPlatform\Repository\Values\UserObject;
23
use Transfer\EzPlatform\Repository\Manager\Type\CreatorInterface;
24
use Transfer\EzPlatform\Repository\Manager\Type\FinderInterface;
25
use Transfer\EzPlatform\Repository\Manager\Type\RemoverInterface;
26
use Transfer\EzPlatform\Repository\Manager\Type\UpdaterInterface;
27
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
28
use eZ\Publish\API\Repository\Exceptions\InvalidArgumentException;
29
30
/**
31
 * User manager.
32
 *
33
 * @internal
34
 */
35
class UserManager implements LoggerAwareInterface, CreatorInterface, UpdaterInterface, RemoverInterface, FinderInterface
36
{
37
    /**
38
     * @var Repository
39
     */
40
    private $repository;
41
42
    /**
43
     * @var LoggerInterface
44
     */
45
    private $logger;
46
47
    /**
48
     * @var UserService
49
     */
50
    private $userService;
51
52
    /**
53
     * @var UserGroupManager
54
     */
55
    private $userGroupManager;
56
57
    /**
58
     * @param Repository       $repository
59
     * @param UserGroupManager $userGroupManager
60
     */
61 3
    public function __construct(Repository $repository, UserGroupManager $userGroupManager)
62
    {
63 3
        $this->repository = $repository;
64 3
        $this->userService = $repository->getUserService();
65 3
        $this->userGroupManager = $userGroupManager;
66 3
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71 19
    public function setLogger(LoggerInterface $logger)
72
    {
73 19
        $this->logger = $logger;
74 19
    }
75
76
    /**
77
     * Finds user object by username.
78
     *
79
     * @param ValueObject $object
80
     * @param bool        $throwException
81
     *
82
     * @return User|false
83
     *
84
     * @throws NotFoundException
85
     */
86 7 View Code Duplication
    public function find(ValueObject $object, $throwException = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
87
    {
88
        try {
89 7
            if (isset($object->data['username'])) {
90 7
                $user = $this->userService->loadUserByLogin($object->data['username']);
91 6
            }
92 7
        } catch (NotFoundException $notFoundException) {
93 2
            $exception = $notFoundException;
94
        }
95
96 7
        if (!isset($user)) {
97 2
            if (isset($exception) && $throwException) {
98 1
                throw $exception;
99
            }
100
101 2
            return false;
102
        }
103
104 6
        return $user;
105
    }
106
107
    /**
108
     * {@inheritdoc}
109
     */
110 7
    public function create(ObjectInterface $object)
111
    {
112 3
        if (!$object instanceof UserObject) {
113 1
            throw new UnsupportedObjectOperationException(UserObject::class, get_class($object));
114
        }
115
116 2
        $userCreateStruct = $this->userService->newUserCreateStruct(
117 2
            $object->data['username'],
118 2
            $object->data['email'],
119 2
            $object->data['password'],
120 2
            $object->data['main_language_code']
121 2
        );
122
123 2
        $object->getMapper()->getNewUserCreateStruct($userCreateStruct);
124
125 2
        $groups = [];
126 2
        foreach ($object->parents as $userGroup) {
127 2
            $userGroup = $this->userGroupManager->createOrUpdate($userGroup);
128 7
            if ($userGroup instanceof UserGroupObject) {
129 2
                $groups[] = $this->userGroupManager->find($userGroup);
130 2
            }
131 2
        }
132
133 2
        $user = $this->userService->createUser($userCreateStruct, $groups);
134 2
        $object->data['id'] = $user->getUserId();
135
136 2
        return $object;
137
    }
138
139
    /**
140
     * {@inheritdoc}
141
     */
142 7
    public function update(ObjectInterface $object)
143
    {
144 6
        if (!$object instanceof UserObject) {
145 1
            throw new UnsupportedObjectOperationException(UserObject::class, get_class($object));
146
        }
147
148 7
        $user = $this->find($object, true);
149
150
        // Populate struct
151 6
        $userUpdateStruct = $this->userService->newUserUpdateStruct();
152 6
        $object->getMapper()->getNewUserUpdateStruct($userUpdateStruct);
153
154
        // Update user
155 6
        $ezuser = $this->userService->updateUser($user, $userUpdateStruct);
0 ignored issues
show
Security Bug introduced by
It seems like $user defined by $this->find($object, true) on line 148 can also be of type false; however, eZ\Publish\API\Repositor...erService::updateUser() does only seem to accept object<eZ\Publish\API\Re...itory\Values\User\User>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
156
157
        // Assign user to usergroups
158 6
        $ezUserGroups = $this->assignUserToUserGroups($ezuser, $object->parents);
159
160
        // Unassign user from usergroups
161 6
        $this->unassignUserFromUserGroups($ezuser, $ezUserGroups);
162
163 6
        return $object;
164
    }
165
166
    /**
167
     * {@inheritdoc}
168
     */
169 7
    public function createOrUpdate(ObjectInterface $object)
170
    {
171 7
        if (!$object instanceof UserObject) {
172 1
            throw new UnsupportedObjectOperationException(UserObject::class, get_class($object));
173
        }
174
175 7
        if (!$this->find($object)) {
176 2
            return $this->create($object);
177
        } else {
178 6
            return $this->update($object);
179
        }
180
    }
181
182
    /**
183
     * {@inheritdoc}
184
     */
185 2 View Code Duplication
    public function remove(ObjectInterface $object)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
186
    {
187 2
        if (!$object instanceof UserObject) {
188 1
            throw new UnsupportedObjectOperationException(UserObject::class, get_class($object));
189
        }
190
191 1
        $user = $this->find($object);
192
193 1
        if ($user) {
194 1
            $this->userService->deleteUser($user);
195 1
        }
196
197 1
        return true;
198
    }
199
200
    /**
201
     * Assigns a collection of Transfer user groups from an eZ user, and returns the once who were added.
202
     *
203
     * @param User              $user
204
     * @param UserGroupObject[] $userGroupObjects
205
     *
206
     * @return UserGroup[]
207
     */
208 6
    protected function assignUserToUserGroups(User $user, array $userGroupObjects)
209
    {
210 6
        $ezUserGroups = [];
211 6
        foreach ($userGroupObjects as $userGroup) {
212 6
            $userGroup = $this->userGroupManager->createOrUpdate($userGroup);
213 6
            if ($userGroup instanceof UserGroupObject) {
214 6
                $ezUserGroup = $this->userGroupManager->find($userGroup);
215 6
                if ($ezUserGroup) {
216 6
                    $ezUserGroups[$ezUserGroup->id] = $ezUserGroup;
217
                    try {
218 6
                        $this->userService->assignUserToUserGroup($user, $ezUserGroup);
219 6
                    } catch (InvalidArgumentException $alreadyAssignedException) {
220
                        // Ignore error about: user already assigned to usergroup.
221
                    }
222 6
                }
223 6
            }
224 6
        }
225
226 6
        return $ezUserGroups;
227
    }
228
229
    /**
230
     * Unassigns a collection of eZ UserGroups from an eZ User.
231
     *
232
     * @param User        $user
233
     * @param UserGroup[] $userGroups
234
     */
235 6
    protected function unassignUserFromUserGroups(User $user, array $userGroups)
236
    {
237 6
        $existingUserGroups = $this->userService->loadUserGroupsOfUser($user);
238 6
        foreach ($existingUserGroups as $existingUserGroup) {
239 6
            if (!array_key_exists($existingUserGroup->id, $userGroups)) {
240 5
                $this->userService->unAssignUserFromUserGroup($user, $existingUserGroup);
241 5
            }
242 6
        }
243 6
    }
244
}
245