Completed
Push — master ( 2e845d...f1d84d )
by Derek Stephen
08:19
created

UserService   B

Complexity

Total Complexity 45

Size/Duplication

Total Lines 292
Duplicated Lines 4.79 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 45
lcom 1
cbo 11
dl 14
loc 292
ccs 0
cts 174
cp 0
rs 8.3673
c 0
b 0
f 0

19 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B createFromArray() 0 14 8
A toArray() 0 13 3
A saveUser() 0 4 1
A findUserById() 7 7 2
A findUserByEmail() 7 7 2
A getUserRepository() 0 4 1
A getEmailLinkRepository() 0 4 1
B registerUser() 0 34 6
A changePassword() 0 11 1
A generateEmailLink() 0 11 1
A deleteEmailLink() 0 6 1
A deleteUser() 0 4 1
A findEmailLink() 0 14 4
C authenticate() 0 34 7
A findByCriteria() 0 4 1
A findOneByCriteria() 0 5 2
A checkPassword() 0 7 1
A setUserClass() 0 4 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like UserService often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use UserService, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Del\Service;
4
5
use DateTime;
6
use Del\Criteria\UserCriteria;
7
use Del\Entity\EmailLink;
8
use Del\Person\Entity\Person;
9
use Del\Entity\User;
10
use Del\Exception\EmailLinkException;
11
use Del\Exception\UserException;
12
use Del\Repository\UserRepository;
13
use Del\Person\Service\PersonService;
14
use Del\Value\User\State;
15
use Doctrine\ORM\EntityManager;
16
use InvalidArgumentException;
17
use Pimple\Container;
18
use Zend\Crypt\Password\Bcrypt;
19
20
class UserService
21
{
22
    /** @var EntityManager $em */
23
    protected $em;
24
25
    /** @var  PersonService */
26
    private $personSvc;
27
28
    /** @var string $userClass */
29
    private $userClass;
30
31
    public function __construct(Container $c)
32
    {
33
        $this->em = $c['doctrine.entity_manager'];
34
        $this->personSvc = $c['service.person'];
35
        $this->setUserClass('\Del\Entity\User');
36
    }
37
38
   /** 
39
    * @param array $data
40
    * @return User
41
    */
42
    public function createFromArray(array $data)
43
    {
44
        /** @var User $user */
45
        $user = new $this->userClass();
46
        $person = isset($data['person']) ? $data['person'] : new Person();
47
        $user->setPerson($person);
48
        isset($data['id']) ? $user->setId($data['id']) : null;
49
        isset($data['email']) ? $user->setEmail($data['email']) : null;
50
        isset($data['password']) ? $user->setPassword($data['password']) : null;
51
        isset($data['state']) ? $user->setState(new State($data['state'])) : null;
52
        isset($data['registrationDate']) ? $user->setRegistrationDate(new DateTime($data['registrationDate'])) : null;
53
        isset($data['lastLogin']) ? $user->setLastLogin(new DateTime($data['lastLogin'])) : null;
54
        return $user;
55
    }
56
57
58
59
60
    /**
61
     * @return array
62
     */
63
    public function toArray(User $user)
64
    {
65
        return array
66
        (
67
            'id' => $user->getID(),
68
            'email' => $user->getEmail(),
69
            'person' => $user->getPerson(),
70
            'password' => $user->getPassword(),
71
            'state' => $user->getState()->getValue(),
72
            'registrationDate' => is_null($user->getRegistrationDate()) ? null : $user->getRegistrationDate()->format('Y-m-d H:i:s'),
73
            'lastLoginDate' => is_null($user->getLastLoginDate()) ? null : $user->getLastLoginDate()->format('Y-m-d H:i:s'),
74
        );
75
    }
76
77
    /**
78
     * @param User $user
79
     * @return User
80
     */
81
    public function saveUser(User $user)
82
    {
83
        return $this->getUserRepository()->save($user);
84
    }
85
86
    /**
87
     * @param int $id
88
     * @return User|null
89
     */
90 View Code Duplication
    public function findUserById($id)
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...
91
    {
92
        $criteria = new UserCriteria();
93
        $criteria->setId($id);
94
        $results = $this->getUserRepository()->findByCriteria($criteria);
95
        return (count($results)) ? $results[0] : null;
96
    }
97
98
    /**
99
     * @param string $email
100
     * @return User|null
101
     */
102 View Code Duplication
    public function findUserByEmail($email)
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...
103
    {
104
        $criteria = new UserCriteria();
105
        $criteria->setEmail($email);
106
        $result = $this->getUserRepository()->findByCriteria($criteria);
107
        return count($result) ? $result[0] : null;
108
    }
109
110
   /**
111
    * @return UserRepository
112
    */
113
    private function getUserRepository()
114
    {
115
        return $this->em->getRepository($this->userClass);
116
    }
117
118
    /**
119
     * @return \Del\Repository\EmailLink
120
     */
121
    private function getEmailLinkRepository()
122
    {
123
        return $this->em->getRepository('Del\Entity\EmailLink');
124
    }
125
126
    public function registerUser(array $data)
127
    {
128
        if (!isset($data['email']) || !isset($data['password']) || !isset($data['confirm'])) {
129
            throw new InvalidArgumentException();
130
        }
131
        if ($data['password'] !== $data['confirm']) {
132
            throw new UserException(UserException::WRONG_PASSWORD);
133
        }
134
135
        $criteria = new UserCriteria();
136
        $criteria->setEmail($data['email']);
137
        $user = $this->getUserRepository()->findByCriteria($criteria);
138
        if(!empty($user)) {
139
            throw new UserException(UserException::USER_EXISTS);
140
        }
141
142
        $person = new Person();
143
        /** @var User $user */
144
        $user = new $this->userClass();
145
        $state = new State(State::STATE_UNACTIVATED);
146
        $user->setPerson($person)
147
             ->setEmail($data['email'])
148
             ->setRegistrationDate(new DateTime())
149
             ->setState($state);
150
151
        $bcrypt = new Bcrypt();
152
        $bcrypt->setCost(14);
153
154
        $encryptedPassword = $bcrypt->create($data['password']);
155
        $user->setPassword($encryptedPassword);
156
157
        $this->saveUser($user);
158
        return $user;
159
    }
160
161
    /**
162
     * @param User $user
163
     * @param $password
164
     * @return User
165
     */
166
    public function changePassword(User $user, $password)
167
    {
168
        $bcrypt = new Bcrypt();
169
        $bcrypt->setCost(14);
170
171
        $encryptedPassword = $bcrypt->create($password);
172
        $user->setPassword($encryptedPassword);
173
174
        $this->saveUser($user);
175
        return $user;
176
    }
177
178
    /**
179
     * @param User $user
180
     * @param int $expiry_days
181
     * @return EmailLink
182
     */
183
    public function generateEmailLink(User $user, $expiry_days = 7)
184
    {
185
        $date = new DateTime();
186
        $date->modify('+'.$expiry_days.' days');
187
        $token = md5(uniqid(rand(), true));
188
        $link = new EmailLink();
189
        $link->setUser($user);
190
        $link->setToken($token);
191
        $link->setExpiryDate($date);
192
        return $this->getEmailLinkRepository()->save($link);
193
    }
194
195
    /**
196
     * @param EmailLink $link
197
     */
198
    public function deleteEmailLink(EmailLink $link)
199
    {
200
        /** @var EmailLink $link */
201
        $link = $this->em->merge($link);
202
        $this->getEmailLinkRepository()->delete($link);
203
    }
204
205
    /**
206
     * @param User $user
207
     */
208
    public function deleteUser(User $user, $deletePerson = false)
209
    {
210
        $this->getUserRepository()->delete($user,$deletePerson);
211
    }
212
213
    /**
214
     * @param $email
215
     * @param $token
216
     * @return EmailLink
217
     * @throws EmailLinkException
218
     */
219
    public function findEmailLink($email, $token)
220
    {
221
        $link = $this->getEmailLinkRepository()->findByToken($token);
222
        if(!$link) {
223
            throw new EmailLinkException(EmailLinkException::LINK_NOT_FOUND);
224
        }
225
        if($link->getUser()->getEmail() != $email) {
226
            throw new EmailLinkException(EmailLinkException::LINK_NO_MATCH);
227
        }
228
        if($link->getExpiryDate() < new DateTime()) {
229
            throw new EmailLinkException(EmailLinkException::LINK_EXPIRED);
230
        }
231
        return $link;
232
    }
233
234
    /**
235
     * @param string $email
236
     * @param string $password
237
     * @return int
238
     * @throws UserException
239
     */
240
    public function authenticate($email, $password)
241
    {
242
        $criteria = new UserCriteria();
243
        $criteria->setEmail($email);
244
245
        $user = $this->getUserRepository()->findByCriteria($criteria);
246
247
        if(empty($user)) {
248
            throw new UserException(UserException::USER_NOT_FOUND);
249
        }
250
251
        /** @var User $user  */
252
        $user = $user[0];
253
254
        switch($user->getState()->getValue()) {
255
            case State::STATE_UNACTIVATED:
256
                throw new UserException(UserException::USER_UNACTIVATED);
257
            case State::STATE_DISABLED:
258
            case State::STATE_SUSPENDED:
259
                throw new UserException(UserException::USER_DISABLED);
260
            case State::STATE_BANNED:
261
                throw new UserException(UserException::USER_BANNED);
262
        }
263
264
        $bcrypt = new Bcrypt();
265
        $bcrypt->setCost(14);
266
267
        if(!$bcrypt->verify($password, $user->getPassword()))
268
        {
269
            throw new UserException(UserException::WRONG_PASSWORD);
270
        }
271
272
        return $user->getID();
273
    }
274
275
    /**
276
     * @param UserCriteria $criteria
277
     * @return array
278
     */
279
    public function findByCriteria(UserCriteria $criteria)
280
    {
281
        return $this->getUserRepository()->findByCriteria($criteria);
282
    }
283
284
    /**
285
     * @param UserCriteria $criteria
286
     * @return User|null
287
     */
288
    public function findOneByCriteria(UserCriteria $criteria)
289
    {
290
        $results = $this->getUserRepository()->findByCriteria($criteria);
291
        return count($results) > 0 ? $results[0] : null;
292
    }
293
294
    /**
295
     * @param User $user
296
     * @param $password
297
     * @return bool
298
     */
299
    public function checkPassword(User $user, $password)
300
    {
301
        $bcrypt = new Bcrypt();
302
        $bcrypt->setCost(14);
303
304
        return $bcrypt->verify($password, $user->getPassword());
305
    }
306
307
    public function setUserClass($fullyQualifiedClassName)
308
    {
309
        $this->userClass = $fullyQualifiedClassName;
310
    }
311
}