Passed
Push — hypernext ( 890c40...5967fc )
by Nico
14:36
created

PasswordValidator   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 16
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 6
c 1
b 0
f 1
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 10 3
A __construct() 0 2 1
1
<?php declare(strict_types=1);
2
/**
3
 * @author Nicolas CARPi <[email protected]>
4
 * @copyright 2024 Nicolas CARPi
5
 * @see https://www.elabftw.net Official website
6
 * @license AGPL-3.0
7
 * @package elabftw
8
 */
9
10
namespace Elabftw\Services;
11
12
use Elabftw\Enums\PasswordComplexity;
13
use Elabftw\Exceptions\ImproperActionException;
14
15
use function mb_strlen;
16
17
/**
18
 * Validate a password against instance configuration for length and complexity
19
 */
20
class PasswordValidator
21
{
22 7
    public function __construct(private int $minLength, private PasswordComplexity $passwordComplexity)
23
    {
24 7
    }
25
26 7
    public function validate(string $password): bool
27
    {
28 7
        if (mb_strlen($password) < $this->minLength) {
29 1
            throw new ImproperActionException(sprintf(_('Password must contain at least %d characters.'), $this->minLength));
30
        }
31 6
        $pattern = PasswordComplexity::toPhPattern($this->passwordComplexity);
32 6
        if (((bool) preg_match($pattern, $password)) === false) {
33 3
            throw new ImproperActionException(sprintf(_('Password does not match requirement: %s'), PasswordComplexity::toHuman($this->passwordComplexity)));
34
        }
35 5
        return true;
36
    }
37
}
38