Completed
Pull Request — 1.0 (#53)
by Harald
06:58
created

UserManager::find()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 16
Code Lines 8

Duplication

Lines 16
Ratio 100 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 4
Bugs 1 Features 0
Metric Value
c 4
b 1
f 0
dl 16
loc 16
ccs 9
cts 9
cp 1
rs 9.2
cc 4
eloc 8
nc 6
nop 1
crap 4
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\ObjectNotFoundException;
21
use Transfer\EzPlatform\Exception\UnsupportedObjectOperationException;
22
use Transfer\EzPlatform\Repository\Values\UserGroupObject;
23
use Transfer\EzPlatform\Repository\Values\UserObject;
24
use Transfer\EzPlatform\Repository\Manager\Type\CreatorInterface;
25
use Transfer\EzPlatform\Repository\Manager\Type\FinderInterface;
26
use Transfer\EzPlatform\Repository\Manager\Type\RemoverInterface;
27
use Transfer\EzPlatform\Repository\Manager\Type\UpdaterInterface;
28
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
29
use eZ\Publish\API\Repository\Exceptions\InvalidArgumentException;
30
31
/**
32
 * User manager.
33
 *
34
 * @internal
35
 */
36
class UserManager implements LoggerAwareInterface, CreatorInterface, UpdaterInterface, RemoverInterface, FinderInterface
37
{
38
    /**
39
     * @var Repository
40
     */
41
    private $repository;
42
43
    /**
44
     * @var LoggerInterface
45
     */
46
    private $logger;
47
48
    /**
49
     * @var UserService
50
     */
51
    private $userService;
52
53
    /**
54
     * @var UserGroupManager
55
     */
56
    private $userGroupManager;
57
58
    /**
59
     * @param Repository       $repository
60
     * @param UserGroupManager $userGroupManager
61
     */
62 3
    public function __construct(Repository $repository, UserGroupManager $userGroupManager)
63
    {
64 3
        $this->repository = $repository;
65 3
        $this->userService = $repository->getUserService();
66 3
        $this->userGroupManager = $userGroupManager;
67 3
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72 19
    public function setLogger(LoggerInterface $logger)
73
    {
74 19
        $this->logger = $logger;
75 19
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80 7 View Code Duplication
    public function find(ValueObject $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...
81 2
    {
82
        try {
83 7
            if (isset($object->data['username'])) {
84 7
                $user = $this->userService->loadUserByLogin($object->data['username']);
85 6
            }
86 7
        } catch (NotFoundException $notFoundException) {
87
            // We'll throw our own exception later instead.
88
        }
89
90 7
        if (!isset($user)) {
91 2
            throw new ObjectNotFoundException(User::class, array('username'));
92
        }
93
94 6
        return $user;
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100 3
    public function create(ObjectInterface $object)
101
    {
102 3
        if (!$object instanceof UserObject) {
103 1
            throw new UnsupportedObjectOperationException(UserObject::class, get_class($object));
104
        }
105
106 2
        $userCreateStruct = $this->userService->newUserCreateStruct(
107 2
            $object->data['username'],
108 2
            $object->data['email'],
109 2
            $object->data['password'],
110 2
            $object->data['main_language_code']
111 2
        );
112
113 2
        $object->getMapper()->getNewUserCreateStruct($userCreateStruct);
114
115 2
        $groups = [];
116 2
        foreach ($object->parents as $userGroup) {
117 2
            $userGroup = $this->userGroupManager->createOrUpdate($userGroup);
118 2
            if ($userGroup instanceof UserGroupObject) {
119 2
                $groups[] = $this->userGroupManager->find($userGroup);
120 2
            }
121 2
        }
122
123 2
        $user = $this->userService->createUser($userCreateStruct, $groups);
124 2
        $object->data['id'] = $user->getUserId();
125
126 2
        return $object;
127
    }
128
129
    /**
130
     * {@inheritdoc}
131
     */
132 6
    public function update(ObjectInterface $object)
133
    {
134 6
        if (!$object instanceof UserObject) {
135 1
            throw new UnsupportedObjectOperationException(UserObject::class, get_class($object));
136
        }
137
138 6
        $user = $this->find($object, true);
0 ignored issues
show
Unused Code introduced by
The call to UserManager::find() has too many arguments starting with true.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
139
140 6
        if ($user) {
141
            // Populate struct
142 6
            $userUpdateStruct = $this->userService->newUserUpdateStruct();
143 6
            $object->getMapper()->getNewUserUpdateStruct($userUpdateStruct);
144
145
            // Update user
146 6
            $user = $this->userService->updateUser($user, $userUpdateStruct);
147
148
            // Assign user to usergroups
149 6
            $userGroups = $this->assignUserToUserGroups($user, $object->parents);
150
151
            // Unassign user from usergroups
152 6
            $this->unassignUserFromUserGroups($user, $userGroups);
153 6
        }
154
155 6
        return $object;
156
    }
157
158
    /**
159
     * {@inheritdoc}
160
     */
161 7
    public function createOrUpdate(ObjectInterface $object)
162
    {
163 7
        if (!$object instanceof UserObject) {
164 1
            throw new UnsupportedObjectOperationException(UserObject::class, get_class($object));
165
        }
166
167
        try {
168 7
            $this->find($object);
169
170 6
            return $this->update($object);
171 2
        } catch (NotFoundException $notFound) {
172 2
            return $this->create($object);
173
        }
174
    }
175
176
    /**
177
     * {@inheritdoc}
178
     */
179 2
    public function remove(ObjectInterface $object)
180
    {
181 2
        if (!$object instanceof UserObject) {
182 1
            throw new UnsupportedObjectOperationException(UserObject::class, get_class($object));
183
        }
184
185 1
        $user = $this->find($object);
186
187 1
        if ($user) {
188 1
            $this->userService->deleteUser($user);
189 1
        }
190
191 1
        return true;
192
    }
193
194
    /**
195
     * Assigns a collection of Transfer user groups from an eZ user, and returns the once who were added.
196
     *
197
     * @param User              $user
198
     * @param UserGroupObject[] $userGroupObjects
199
     *
200
     * @return UserGroup[]
201
     */
202 6
    protected function assignUserToUserGroups(User $user, array $userGroupObjects)
203
    {
204 6
        $ezUserGroups = [];
205 6
        foreach ($userGroupObjects as $userGroup) {
206 6
            $userGroup = $this->userGroupManager->createOrUpdate($userGroup);
207 6
            if ($userGroup instanceof UserGroupObject) {
208 6
                $ezUserGroup = $this->userGroupManager->find($userGroup);
209 6
                if ($ezUserGroup) {
210 6
                    $ezUserGroups[$ezUserGroup->id] = $ezUserGroup;
211
                    try {
212 6
                        $this->userService->assignUserToUserGroup($user, $ezUserGroup);
213 6
                    } catch (InvalidArgumentException $alreadyAssignedException) {
214
                        // Ignore error about: user already assigned to usergroup.
215
                    }
216 6
                }
217 6
            }
218 6
        }
219
220 6
        return $ezUserGroups;
221
    }
222
223
    /**
224
     * Unassigns a collection of eZ UserGroups from an eZ User.
225
     *
226
     * @param User        $user
227
     * @param UserGroup[] $userGroups
228
     */
229 6
    protected function unassignUserFromUserGroups(User $user, array $userGroups)
230
    {
231 6
        $existingUserGroups = $this->userService->loadUserGroupsOfUser($user);
232 6
        foreach ($existingUserGroups as $existingUserGroup) {
233 6
            if (!array_key_exists($existingUserGroup->id, $userGroups)) {
234 5
                $this->userService->unAssignUserFromUserGroup($user, $existingUserGroup);
235 5
            }
236 6
        }
237 6
    }
238
}
239