1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Kreta package. |
5
|
|
|
* |
6
|
|
|
* (c) Beñat Espiña <[email protected]> |
7
|
|
|
* (c) Gorka Laucirica <[email protected]> |
8
|
|
|
* |
9
|
|
|
* For the full copyright and license information, please view the LICENSE |
10
|
|
|
* file that was distributed with this source code. |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
declare(strict_types=1); |
14
|
|
|
|
15
|
|
|
namespace Kreta\IdentityAccess\Domain\Model\User; |
16
|
|
|
|
17
|
|
|
use BenGorUser\User\Domain\Model\UserEmail; |
18
|
|
|
|
19
|
|
|
class Username |
20
|
|
|
{ |
21
|
|
|
private const MAX_LENGTH = 20; |
22
|
|
|
private const MIN_LENGTH = 3; |
23
|
|
|
|
24
|
|
|
private $username; |
25
|
|
|
|
26
|
|
|
public static function fromEmail(UserEmail $email) : self |
27
|
|
|
{ |
28
|
|
|
$localPart = $email->localPart(); |
29
|
|
|
$localPart = mb_substr($localPart, 0, self::MAX_LENGTH); |
30
|
|
|
|
31
|
|
|
$username = sprintf('%s%d', $localPart, mt_rand(1111, 9999)); |
32
|
|
|
|
33
|
|
|
return new self($username, true); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public static function from(string $username) : self |
37
|
|
|
{ |
38
|
|
|
return new self($username, false); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
private function __construct(string $username, bool $isFromEmail) |
42
|
|
|
{ |
43
|
|
|
$this->setUsername($username, $isFromEmail); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
private function setUsername(string $username, bool $isFromEmail) : void |
47
|
|
|
{ |
48
|
|
|
if (false === $isFromEmail) { |
49
|
|
|
$this->checkIsValidUsername($username); |
50
|
|
|
} |
51
|
|
|
$this->username = $username; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
private function checkIsValidUsername(string $username) : void |
55
|
|
|
{ |
56
|
|
|
$regex = sprintf('/^[a-z0-9_.-]{%d,%d}$/', self::MIN_LENGTH, self::MAX_LENGTH); |
57
|
|
|
|
58
|
|
|
if (!preg_match($regex, $username)) { |
59
|
|
|
throw new UsernameInvalidException($username); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function username() : string |
64
|
|
|
{ |
65
|
|
|
return $this->username; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
public function __toString() : string |
69
|
|
|
{ |
70
|
|
|
return (string) $this->username; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|