@@ -36,6 +36,8 @@ class UserBadge implements BadgeInterface
3636 private UserInterface $ user ;
3737 private ?array $ attributes ;
3838
39+ private ?\Closure $ identifierNormalizer = null ;
40+
3941 /**
4042 * Initializes the user badge.
4143 *
@@ -49,19 +51,30 @@ class UserBadge implements BadgeInterface
4951 * is thrown). If this is not set, the default user provider will be used with
5052 * $userIdentifier as username.
5153 */
52- public function __construct (string $ userIdentifier , callable $ userLoader = null , array $ attributes = null )
54+ public function __construct (string $ userIdentifier , callable $ userLoader = null , array $ attributes = null , ? \ Closure $ identifierNormalizer = null )
5355 {
5456 if (\strlen ($ userIdentifier ) > self ::MAX_USERNAME_LENGTH ) {
5557 throw new BadCredentialsException ('Username too long. ' );
5658 }
59+ if ($ identifierNormalizer ) {
60+ $ this ->identifierNormalizer = static fn () => $ identifierNormalizer ($ userIdentifier );
61+ } else {
62+ $ this ->userIdentifier = $ userIdentifier ;
63+ }
5764
58- $ this ->userIdentifier = $ userIdentifier ;
5965 $ this ->userLoader = $ userLoader ;
6066 $ this ->attributes = $ attributes ;
6167 }
6268
6369 public function getUserIdentifier (): string
6470 {
71+ if (isset ($ this ->userIdentifier )) {
72+ return $ this ->userIdentifier ;
73+ }
74+
75+ $ this ->userIdentifier = ($ this ->identifierNormalizer )();
76+ $ this ->identifierNormalizer = null ;
77+
6578 return $ this ->userIdentifier ;
6679 }
6780
@@ -84,15 +97,15 @@ public function getUser(): UserInterface
8497 }
8598
8699 if (null === $ this ->getAttributes ()) {
87- $ user = ($ this ->userLoader )($ this ->userIdentifier );
100+ $ user = ($ this ->userLoader )($ this ->getUserIdentifier () );
88101 } else {
89- $ user = ($ this ->userLoader )($ this ->userIdentifier , $ this ->getAttributes ());
102+ $ user = ($ this ->userLoader )($ this ->getUserIdentifier () , $ this ->getAttributes ());
90103 }
91104
92105 // No user has been found via the $this->userLoader callback
93106 if (null === $ user ) {
94107 $ exception = new UserNotFoundException ();
95- $ exception ->setUserIdentifier ($ this ->userIdentifier );
108+ $ exception ->setUserIdentifier ($ this ->getUserIdentifier () );
96109
97110 throw $ exception ;
98111 }
0 commit comments