Completed
Push — master ( 60435e...1588c9 )
by Derek Stephen
02:22
created

UserService::generateEmailLink()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

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