Skip to content

Commit 9dac2b3

Browse files
committed
Support UserLoaded event
can be used to set roles at runtime
1 parent 4c90085 commit 9dac2b3

2 files changed

Lines changed: 35 additions & 2 deletions

File tree

src/Event/UserLoadedEvent.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
namespace UserBase\Client\Event;
4+
5+
use Symfony\Component\EventDispatcher\Event;
6+
use UserBase\Client\Model\User;
7+
8+
class UserLoadedEvent extends Event
9+
{
10+
public const NAME = 'userbase.user_loaded';
11+
12+
protected $user;
13+
14+
public function __construct(User $user)
15+
{
16+
$this->user = $user;
17+
}
18+
19+
public function getUser()
20+
{
21+
return $this->user;
22+
}
23+
}

src/UserProvider.php

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,24 +8,34 @@
88
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
99
use Symfony\Component\Security\Core\User\UserInterface;
1010
use Symfony\Component\Security\Core\User\UserProviderInterface;
11+
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
1112

1213
use UserBase\Client\Model\User;
14+
use UserBase\Client\Event\UserLoadedEvent;
15+
1316

1417
class UserProvider implements UserProviderInterface
1518
{
1619
private $client;
1720
private $shouldRefresh;
21+
private $dispatcher;
1822

19-
public function __construct(Client $client, $shouldRefresh = true)
23+
public function __construct(Client $client, $shouldRefresh = true, EventDispatcherInterface $dispatcher = null)
2024
{
2125
$this->client = $client;
2226
$this->shouldRefresh = (bool) $shouldRefresh;
27+
$this->dispatcher = $dispatcher;
2328
}
2429

2530
public function loadUserByUsername($username)
2631
{
2732
try {
28-
return $this->client->getUserByUsername($username);
33+
$user = $this->client->getUserByUsername($username);
34+
if ($this->dispatcher) {
35+
$event = new UserLoadedEvent($user);
36+
$this->dispatcher->dispatch('userbase.user_loaded', $event);
37+
}
38+
return $user;
2939
} catch (RuntimeException $e) {
3040
throw new UsernameNotFoundException(
3141
"A User named \"{$username}\" cannot be found in Userbase.",

0 commit comments

Comments
 (0)