AnySource::matchingSource()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
nc 4
nop 0
dl 0
loc 15
ccs 8
cts 8
cp 1
crap 4
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cerbero\LazyJsonPages\Sources;
6
7
use Cerbero\LazyJsonPages\Exceptions\UnsupportedSourceException;
8
use Psr\Http\Message\RequestInterface;
9
use Psr\Http\Message\ResponseInterface;
10
11
/**
12
 * The aggregator of sources.
13
 */
14
class AnySource extends Source
15
{
16
    /**
17
     * @var class-string<Source>[]
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<Source>[] at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<Source>[].
Loading history...
18
     */
19
    protected array $supportedSources = [
20
        CustomSource::class,
21
        Endpoint::class,
22
        LaravelClientRequest::class,
23
        LaravelClientResponse::class,
24
        Psr7Request::class,
25
        SymfonyRequest::class,
26
    ];
27
28
    /**
29
     * The matching source.
30
     */
31
    protected Source $matchingSource;
32
33
    /**
34
     * The cached HTTP response.
35
     */
36
    protected ?ResponseInterface $response;
37
38
    /**
39
     * Retrieve the HTTP request.
40
     */
41 42
    public function request(): RequestInterface
42
    {
43 42
        return $this->matchingSource()->request();
44
    }
45
46
    /**
47
     * Retrieve the matching source.
48
     *
49
     * @throws UnsupportedSourceException
50
     */
51 48
    protected function matchingSource(): Source
52
    {
53 48
        if (isset($this->matchingSource)) {
54 41
            return $this->matchingSource;
55
        }
56
57 48
        foreach ($this->supportedSources as $class) {
58 48
            $source = new $class($this->source);
59
60 48
            if ($source->matches()) {
61 47
                return $this->matchingSource = $source->setClient($this->client);
62
            }
63
        }
64
65 1
        throw new UnsupportedSourceException($this->source);
66
    }
67
68
    /**
69
     * Retrieve the HTTP response.
70
     *
71
     * @return ResponseInterface
72
     */
73 47
    public function response(): ResponseInterface
74
    {
75 47
        return $this->response ??= $this->matchingSource()->response();
76
    }
77
78
    /**
79
     * Retrieve the HTTP response and forget it to save memory.
80
     */
81 47
    public function pullResponse(): ResponseInterface
82
    {
83 47
        $response = $this->response();
84
85 43
        $this->response = null;
86
87 43
        return $response;
88
    }
89
}
90