ZxcvbnPasswordValidator::validate()   B
last analyzed

Complexity

Conditions 7
Paths 4

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.6026
c 0
b 0
f 0
cc 7
nc 4
nop 2
1
<?php
2
3
namespace Locastic\Component\ZxcvbnPasswordValidator\Validator\Constraints;
4
5
use Symfony\Component\Validator\Constraint;
6
use Symfony\Component\Validator\ConstraintValidator;
7
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
8
use ZxcvbnPhp\Zxcvbn;
9
use Symfony\Component\Translation\Loader\XliffFileLoader;
10
use Symfony\Component\Translation\Translator;
11
use Symfony\Component\Translation\TranslatorInterface;
12
13
/**
14
 * Password strength Validation.
15
 * More info: https://blogs.dropbox.com/tech/2012/04/zxcvbn-realistic-password-strength-estimation/
16
 */
17
class ZxcvbnPasswordValidator extends ConstraintValidator
18
{
19
20
    private $translator;
21
22
    public function __construct(TranslatorInterface $translator = null)
23
    {
24
        // If translator is missing create a new translator.
25
        // With the 'en' locale and 'validators' domain.
26
        if (null === $translator) {
27
            $translator = new Translator('en');
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $translator. This often makes code more readable.
Loading history...
28
            $translator->addLoader('xlf', new XliffFileLoader());
29
            $translator->addResource(
30
                'xlf',
31
                dirname(dirname(__DIR__)).'/Resources/translations/validators.en.xlf',
32
                'en',
33
                'validators'
34
            );
35
        }
36
37
        $this->translator = $translator;
38
    }
39
40
    public function validate($password, Constraint $constraint)
41
    {
42
        if (null === $password || '' === $password) {
43
            return;
44
        }
45
46
        if (!is_scalar($password) && !(is_object($password) && method_exists($password, '__toString'))) {
47
            throw new UnexpectedTypeException($password, 'string');
48
        }
49
50
        $zxcvbn = new Zxcvbn();
51
        $strength = $zxcvbn->passwordStrength($password);
52
53
        if ($strength['entropy'] < $constraint->minEntropy) {
54
            $parameters = [
55
                '{{ min_entropy }}' => $constraint->minEntropy,
56
                '{{ current_entropy }}' => $strength['entropy'],
57
            ];
58
59
            $this->context->buildViolation($this->translator->trans($constraint->message, $parameters, 'validators'))
60
                ->setParameters($parameters)
61
                ->addViolation();
62
        }
63
    }
64
}