Test Setup Failed
Pull Request — master (#81)
by Valery
09:57
created

PasswordService::findViolations()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 11
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Service\User;
6
7
use App\Entity\User;
8
use App\Service\Admin\UserService;
9
use Exception;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
12
use Symfony\Component\Validator\Constraints as Assert;
13
use Symfony\Component\Validator\ConstraintViolationListInterface;
14
use Symfony\Component\Validator\Validator\ValidatorInterface;
15
16
final class PasswordService
17
{
18
    private UserService $service;
19
    private TokenStorageInterface $tokenStorage;
20
    private ValidatorInterface $validator;
21
22
    public function __construct(
23
        UserService $service,
24
        TokenStorageInterface $tokenStorage,
25
        ValidatorInterface $validator
26
    ) {
27
        $this->service = $service;
28
        $this->tokenStorage = $tokenStorage;
29
        $this->validator = $validator;
30
    }
31
32
    /**
33
     * @throws Exception
34
     */
35
    public function update(Request $request): void
36
    {
37
        $violations = $this->findViolations($request);
38
39
        if (\count($violations) > 0) {
40
            throw new Exception($violations[0]->getMessage());
41
        }
42
43
        /*** @var $user User */
44
        $user = $this->tokenStorage->getToken()->getUser();
45
        $user->setPassword($request->get('password1'));
46
        $this->service->update($user);
47
    }
48
49
    private function findViolations(Request $request): ConstraintViolationListInterface
50
    {
51
        $password1 = $this->validator->validate($request->get('password1'), [
52
            new Assert\Length(null, 10),
53
        ]);
54
55
        $password2 = $this->validator->validate($request->get('password2'), [
56
            new Assert\EqualTo($request->get('password1'), null, "Passwords Don't Match"),
57
        ]);
58
59
        return \count($password1) > 0 ? $password1 : $password2;
60
    }
61
}
62