1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Phypes\Type; |
4
|
|
|
|
5
|
|
|
use Phypes\Exception\InvalidValue; |
6
|
|
|
use Phypes\Result\Failure; |
7
|
|
|
use Phypes\Validator\PasswordValidator; |
8
|
|
|
use Phypes\Validator\Validator; |
9
|
|
|
use function Phypes\getOptionalValue; |
10
|
|
|
|
11
|
|
|
class Password implements Type |
12
|
|
|
{ |
13
|
|
|
const OPT_MIN_LENGTH = 0; |
14
|
|
|
const OPT_MIN_CHAR_VARIETY = 1; |
15
|
|
|
/** |
16
|
|
|
* @var string $password |
17
|
|
|
*/ |
18
|
|
|
private $password; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Create an password object if data is valid. |
22
|
|
|
* @param string $password |
23
|
|
|
* @param array $options |
24
|
|
|
* @param Validator $validator |
25
|
|
|
* @throws InvalidValue |
26
|
|
|
* @throws \Phypes\Exception\InvalidRule |
27
|
|
|
*/ |
28
|
|
|
public function __construct(string $password, $options =[], Validator $validator = null) |
29
|
|
|
{ |
30
|
|
|
if ($validator == null) { |
31
|
|
|
// use the default validator |
32
|
|
|
$validator = new PasswordValidator( |
33
|
|
|
getOptionalValue(self::OPT_MIN_LENGTH, $options, 8), |
34
|
|
|
getOptionalValue(self::OPT_MIN_CHAR_VARIETY, $options, 2)); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$result = $validator->validate($password); |
38
|
|
|
|
39
|
|
|
if (!$result->isValid()) { |
40
|
|
|
/** |
41
|
|
|
* @var Failure $result |
42
|
|
|
*/ |
43
|
|
|
throw new InvalidValue($result->getFirstError()->getMessage(), $result->getErrors()); |
44
|
|
|
} |
45
|
|
|
$this->password = $password; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Get string representation of the password object. |
50
|
|
|
* @return string |
51
|
|
|
*/ |
52
|
|
|
public function __toString(): string |
53
|
|
|
{ |
54
|
|
|
return $this->password; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Get real value of the password object. |
59
|
|
|
* @return string |
60
|
|
|
*/ |
61
|
|
|
public function getValue() : string |
62
|
|
|
{ |
63
|
|
|
return $this->password; |
64
|
|
|
} |
65
|
|
|
} |