Completed
Push — master ( d293d6...2e845d )
by Derek Stephen
02:24
created

UserService::setUserClass()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
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\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 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 User
41
    */
42 17
    public function createFromArray(array $data)
43
    {
44
        /** @var User $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(User $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 1
        );
75
    }
76
77
    /**
78
     * @param User $user
79
     * @return User
80
     */
81 18
    public function saveUser(User $user)
82
    {
83 18
        return $this->getUserRepository()->save($user);
84
    }
85
86
    /**
87
     * @param int $id
88
     * @return User|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 User|null
101
     */
102 2 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 2
        $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 4
    public function registerUser(array $data)
127
    {
128 4
        if (!isset($data['email']) || !isset($data['password']) || !isset($data['confirm'])) {
129 1
            throw new InvalidArgumentException();
130
        }
131 3
        if ($data['password'] !== $data['confirm']) {
132 1
            throw new UserException(UserException::WRONG_PASSWORD);
133
        }
134
135 2
        $criteria = new UserCriteria();
136 2
        $criteria->setEmail($data['email']);
137 2
        $user = $this->getUserRepository()->findByCriteria($criteria);
138 2
        if(!empty($user)) {
139 1
            throw new UserException(UserException::USER_EXISTS);
140
        }
141
142 2
        $person = new Person();
143
        /** @var User $user */
144 2
        $user = new $this->userClass();
145 2
        $state = new State(State::STATE_UNACTIVATED);
146 2
        $user->setPerson($person)
147 2
             ->setEmail($data['email'])
148 2
             ->setRegistrationDate(new DateTime())
149 2
             ->setState($state);
150
151 2
        $bcrypt = new Bcrypt();
152 2
        $bcrypt->setCost(14);
153
154 2
        $encryptedPassword = $bcrypt->create($data['password']);
155 2
        $user->setPassword($encryptedPassword);
156
157 2
        $this->saveUser($user);
158 2
        return $user;
159
    }
160
161
    /**
162
     * @param User $user
163
     * @param $password
164
     * @return User
165
     */
166 7
    public function changePassword(User $user, $password)
167
    {
168 7
        $bcrypt = new Bcrypt();
169 7
        $bcrypt->setCost(14);
170
171 7
        $encryptedPassword = $bcrypt->create($password);
172 7
        $user->setPassword($encryptedPassword);
173
174 7
        $this->saveUser($user);
175 7
        return $user;
176
    }
177
178
    /**
179
     * @param User $user
180
     * @param int $expiry_days
181
     * @return EmailLink
182
     */
183 4
    public function generateEmailLink(User $user, $expiry_days = 7)
184
    {
185 4
        $date = new DateTime();
186 4
        $date->modify('+'.$expiry_days.' days');
187 4
        $token = md5(uniqid(rand(), true));
188 4
        $link = new EmailLink();
189 4
        $link->setUser($user);
190 4
        $link->setToken($token);
191 4
        $link->setExpiryDate($date);
192 4
        return $this->getEmailLinkRepository()->save($link);
193
    }
194
195
    /**
196
     * @param EmailLink $link
197
     */
198 4
    public function deleteEmailLink(EmailLink $link)
199
    {
200
        /** @var EmailLink $link */
201 4
        $link = $this->em->merge($link);
202 4
        $this->getEmailLinkRepository()->delete($link);
203 4
    }
204
205
    /**
206
     * @param User $user
207
     */
208 18
    public function deleteUser(User $user, $deletePerson = false)
209
    {
210 18
        $this->getUserRepository()->delete($user,$deletePerson);
211 18
    }
212
213
    /**
214
     * @param $email
215
     * @param $token
216
     * @return EmailLink
217
     * @throws EmailLinkException
218
     */
219 4
    public function findEmailLink($email, $token)
220
    {
221 4
        $link = $this->getEmailLinkRepository()->findByToken($token);
222 4
        if(!$link) {
223 1
            throw new EmailLinkException(EmailLinkException::LINK_NOT_FOUND);
224
        }
225 3
        if($link->getUser()->getEmail() != $email) {
226 1
            throw new EmailLinkException(EmailLinkException::LINK_NO_MATCH);
227
        }
228 2
        if($link->getExpiryDate() < new DateTime()) {
229 1
            throw new EmailLinkException(EmailLinkException::LINK_EXPIRED);
230
        }
231 1
        return $link;
232
    }
233
234
    /**
235
     * @param string $email
236
     * @param string $password
237
     * @return int
238
     * @throws UserException
239
     */
240 6
    public function authenticate($email, $password)
241
    {
242 6
        $criteria = new UserCriteria();
243 6
        $criteria->setEmail($email);
244
245 6
        $user = $this->getUserRepository()->findByCriteria($criteria);
246
247 6
        if(empty($user)) {
248 1
            throw new UserException(UserException::USER_NOT_FOUND);
249
        }
250
251
        /** @var User $user  */
252 5
        $user = $user[0];
253
254 5
        switch($user->getState()->getValue()) {
255 5
            case State::STATE_UNACTIVATED:
256 1
                throw new UserException(UserException::USER_UNACTIVATED);
257 4
            case State::STATE_DISABLED:
258 4
            case State::STATE_SUSPENDED:
259 1
                throw new UserException(UserException::USER_DISABLED);
260 3
            case State::STATE_BANNED:
261 1
                throw new UserException(UserException::USER_BANNED);
262 2
        }
263
264 2
        $bcrypt = new Bcrypt();
265 2
        $bcrypt->setCost(14);
266
267 2
        if(!$bcrypt->verify($password, $user->getPassword()))
268 2
        {
269 1
            throw new UserException(UserException::WRONG_PASSWORD);
270
        }
271
272 1
        return $user->getID();
273
    }
274
275
    /**
276
     * @param UserCriteria $criteria
277
     * @return array
278
     */
279 1
    public function findByCriteria(UserCriteria $criteria)
280
    {
281 1
        return $this->getUserRepository()->findByCriteria($criteria);
282
    }
283
284
    /**
285
     * @param UserCriteria $criteria
286
     * @return User|null
287
     */
288 3
    public function findOneByCriteria(UserCriteria $criteria)
289
    {
290 3
        $results = $this->getUserRepository()->findByCriteria($criteria);
291 3
        return count($results) > 0 ? $results[0] : null;
292
    }
293
294
    /**
295
     * @param User $user
296
     * @param $password
297
     * @return bool
298
     */
299 1
    public function checkPassword(User $user, $password)
300
    {
301 1
        $bcrypt = new Bcrypt();
302 1
        $bcrypt->setCost(14);
303
304 1
        return $bcrypt->verify($password, $user->getPassword());
305
    }
306
307 25
    public function setUserClass($fullyQualifiedClassName)
308
    {
309 25
        $this->userClass = $fullyQualifiedClassName;
310
    }
311
}