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