Skip to content

Commit 8fe9137

Browse files
committed
Corrections as suggested
1 parent db5642d commit 8fe9137

File tree

1 file changed

+14
-15
lines changed

1 file changed

+14
-15
lines changed

src/Symfony/Component/Validator/Constraints/PasswordStrengthValidator.php

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@
1818

1919
final class PasswordStrengthValidator extends ConstraintValidator
2020
{
21+
/**
22+
* @param (\Closure(string):PasswordStrength::STRENGTH_*)|null $passwordStrengthEstimator
23+
*/
2124
public function __construct(
2225
private readonly ?\Closure $passwordStrengthEstimator = null,
2326
) {
@@ -36,7 +39,7 @@ public function validate(#[\SensitiveParameter] mixed $value, Constraint $constr
3639
if (!\is_string($value)) {
3740
throw new UnexpectedValueException($value, 'string');
3841
}
39-
$passwordStrengthEstimator = $this->passwordStrengthEstimator ?? $this->estimate(...);
42+
$passwordStrengthEstimator = $this->passwordStrengthEstimator ?? self::estimateStrength(...);
4043
$strength = $passwordStrengthEstimator($value);
4144

4245
if ($strength < $constraint->minScore) {
@@ -47,26 +50,22 @@ public function validate(#[\SensitiveParameter] mixed $value, Constraint $constr
4750
}
4851

4952
/**
50-
* Returns the estimated strength of a password between 0 and 4.
53+
* Returns the estimated strength of a password.
5154
* The higher the value, the stronger the password.
5255
*
53-
* @return int<0, 4>
56+
* @return PasswordStrength::STRENGTH_*
5457
*/
55-
private static function estimate(#[\SensitiveParameter] string $password): int
58+
private static function estimateStrength(#[\SensitiveParameter] string $password): int
5659
{
57-
$criteria = [
58-
['score' => PasswordStrength::STRENGTH_VERY_STRONG, 'minEntropy' => 120],
59-
['score' => PasswordStrength::STRENGTH_STRONG, 'minEntropy' => 100],
60-
['score' => PasswordStrength::STRENGTH_REASONABLE, 'minEntropy' => 80],
61-
['score' => PasswordStrength::STRENGTH_WEAK, 'minEntropy' => 60],
62-
['score' => PasswordStrength::STRENGTH_VERY_WEAK, 'minEntropy' => 0],
63-
];
6460
$uniqueChars = array_unique(str_split($password));
6561
$entropy = log(\count($uniqueChars) ** \strlen($password), 2);
66-
$fulfilledCriteria = array_filter($criteria, function (array $option) use ($entropy) {
67-
return $entropy >= $option['minEntropy'];
68-
});
6962

70-
return current($fulfilledCriteria)['score'] ?? PasswordStrength::STRENGTH_VERY_WEAK;
63+
return match (true) {
64+
$entropy >= 120 => PasswordStrength::STRENGTH_VERY_STRONG,
65+
$entropy >= 100 => PasswordStrength::STRENGTH_STRONG,
66+
$entropy >= 80 => PasswordStrength::STRENGTH_REASONABLE,
67+
$entropy >= 60 => PasswordStrength::STRENGTH_WEAK,
68+
default => PasswordStrength::STRENGTH_VERY_WEAK,
69+
};
7170
}
7271
}

0 commit comments

Comments
 (0)