Issues (1)

src/Rule/Length.php (1 issue)

1
<?php
2
/*
3
    Password Strength Library
4
    Copyright (C) 2019 CustomerGauge
5
    [email protected]
6
7
    This program is free software; you can redistribute it and/or
8
    modify it under the terms of the GNU Lesser General Public
9
    License as published by the Free Software Foundation; either
10
    version 3 of the License, or (at your option) any later version.
11
12
    This program is distributed in the hope that it will be useful,
13
    but WITHOUT ANY WARRANTY; without even the implied warranty of
14
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
    Lesser General Public License for more details.
16
17
    You should have received a copy of the GNU Lesser General Public License
18
    along with this program; if not, write to the Free Software Foundation,
19
    Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
*/
21
22
declare(strict_types=1);
23
24
namespace CustomerGauge\Password\Rule;
25
26
use CustomerGauge\Password\Exception\InvalidLength;
27
use CustomerGauge\Password\Rule;
28
29
use function mb_strlen;
30
31
final class Length implements Rule
32
{
33
    private int $min;
34
35
    private ?int $max = null;
36
37
    private string $encoding;
38
39 2
    public function __construct(int $min, ?int $max = null, string $encoding = 'utf8')
40
    {
41 2
        $this->min      = $min;
42 2
        $this->max      = $max;
43 2
        $this->encoding = $encoding;
44 2
    }
45
46 2
    public function __invoke(string $password): void
47
    {
48 2
        $length = (int) mb_strlen($password, $this->encoding);
49
50 2
        if ($length < $this->min) {
51 1
            throw InvalidLength::requires('min', $this->min, $length);
52
        }
53
54 1
        if ($this->max && $length > $this->max) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->max of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
55 1
            throw InvalidLength::requires('max', $this->max, $length);
56
        }
57
    }
58
}
59