Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
ContextBuilderFactory
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
4 / 4
6
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 createBaseContext
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 createGeneralContext
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 createFromRequest
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2namespace Apie\Core\ContextBuilders;
3
4use Apie\Core\Context\ApieContext;
5use Apie\Core\Enums\RequestMethod;
6use Psr\Http\Message\ServerRequestInterface;
7
8/**
9 * Creates an ApieContext from a list of builders. The context object is used everywhere as a mediator.
10 */
11final class ContextBuilderFactory
12{
13    /**
14     * @var ContextBuilderInterface[]
15     */
16    private array $builders;
17
18    public function __construct(ContextBuilderInterface... $builders)
19    {
20        $this->builders = $builders;
21    }
22
23    /**
24     * @param array<string|int, mixed> $additionalData
25     */
26    private function createBaseContext(array $additionalData): ApieContext
27    {
28        return new ApieContext([
29            ...$additionalData,
30            ContextBuilderFactory::class => $this,
31        ]);
32    }
33
34    /**
35     * @param array<string|int, mixed> $additionalData
36     */
37    public function createGeneralContext(array $additionalData): ApieContext
38    {
39        $context = $this->createBaseContext($additionalData);
40        foreach ($this->builders as $builder) {
41            $context = $builder->process($context);
42        }
43        return $context;
44    }
45
46    /**
47     * @param array<string|int, mixed> $additionalData
48     */
49    public function createFromRequest(ServerRequestInterface $request, array $additionalData = []): ApieContext
50    {
51        $context = $this->createBaseContext([...$additionalData, ...$request->getAttributes()])
52            ->registerInstance($request)
53            ->withContext(RequestMethod::class, RequestMethod::from($request->getMethod()));
54        foreach ($this->builders as $builder) {
55            $context = $builder->process($context);
56        }
57        return $context;
58    }
59}