Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
92.86% |
13 / 14 |
|
75.00% |
3 / 4 |
CRAP | |
0.00% |
0 / 1 |
| ApieCurrentUserContextBuilder | |
92.86% |
13 / 14 |
|
75.00% |
3 / 4 |
6.01 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| process | |
75.00% |
3 / 4 |
|
0.00% |
0 / 1 |
2.06 | |||
| onApieResponseCreated | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
2 | |||
| getSubscribedEvents | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | namespace Apie\LaravelApie\ContextBuilders; |
| 3 | |
| 4 | use Apie\Common\Events\AddAuthenticationCookie; |
| 5 | use Apie\Common\Events\ApieResourceCreated; |
| 6 | use Apie\Common\Events\ApieResourceMethodCalled; |
| 7 | use Apie\Common\Events\ApieResourceModified; |
| 8 | use Apie\Common\Events\ApieResourceRead; |
| 9 | use Apie\Common\Events\ApieResourceReadList; |
| 10 | use Apie\Common\Events\ApieResourceRemoved; |
| 11 | use Apie\Common\Events\ApieResponseCreated; |
| 12 | use Apie\Common\ValueObjects\DecryptedAuthenticatedUser; |
| 13 | use Apie\Core\Context\ApieContext; |
| 14 | use Apie\Core\ContextBuilders\ContextBuilderInterface; |
| 15 | use Apie\LaravelApie\Apie; |
| 16 | use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
| 17 | |
| 18 | class ApieCurrentUserContextBuilder implements ContextBuilderInterface, EventSubscriberInterface |
| 19 | { |
| 20 | public function __construct(private readonly AddAuthenticationCookie $addAuthenticationCookie) |
| 21 | { |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * The problem here is that we are not certain what Laravel middleware is setup to get the current user from the Laravel |
| 26 | * session. We could set the auth middleware in the Apie config, but then all endpoints would require authentication. |
| 27 | * |
| 28 | * So as a workaround we store the current user in the Apie facade, even though it is a terrible solution. |
| 29 | */ |
| 30 | public function process(ApieContext $context): ApieContext |
| 31 | { |
| 32 | $currentUser = Apie::getCurrentUser(); |
| 33 | if ($currentUser) { |
| 34 | $context = $context->withContext(DecryptedAuthenticatedUser::class, $currentUser); |
| 35 | } |
| 36 | return $context; |
| 37 | } |
| 38 | |
| 39 | public function onApieResponseCreated(ApieResponseCreated $event): void |
| 40 | { |
| 41 | if (!$event->context->hasContext(DecryptedAuthenticatedUser::class)) { |
| 42 | $currentUser = Apie::getCurrentUser(); |
| 43 | $event->context = $event->context->withContext(DecryptedAuthenticatedUser::class, $currentUser); |
| 44 | $this->addAuthenticationCookie->onApieResponseCreated( |
| 45 | $event |
| 46 | ); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | public static function getSubscribedEvents(): array |
| 51 | { |
| 52 | return [ |
| 53 | ApieResponseCreated::class => 'onApieResponseCreated', |
| 54 | ]; |
| 55 | } |
| 56 | } |