CurlFactory::createClient()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.0342

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 22
ccs 8
cts 9
cp 0.8889
rs 9.6111
cc 5
nc 5
nop 1
crap 5.0342
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TMV\HTTPlugModule\ClientFactory;
6
7
use Psr\Http\Client\ClientInterface;
8
use Http\Client\Curl\Client;
9
use LogicException;
10
use Psr\Http\Message\ResponseFactoryInterface;
11
use Psr\Http\Message\StreamFactoryInterface;
12
13
use function class_exists;
14
use function constant;
15
use function is_string;
16
use function sprintf;
17
18
class CurlFactory implements ClientFactory
19
{
20
    private ResponseFactoryInterface $responseFactory;
21
22
    private StreamFactoryInterface $streamFactory;
23
24
    public function __construct(ResponseFactoryInterface $responseFactory, StreamFactoryInterface $streamFactory)
25
    {
26
        $this->responseFactory = $responseFactory;
27
        $this->streamFactory = $streamFactory;
28
    }
29 1
30
    public function createClient(array $config = []): ClientInterface
31 1
    {
32 1
        if (! class_exists(Client::class)) {
33 1
            throw new LogicException('To use the Curl client you need to install the "php-http/curl-client" package.');
34
        }
35
36
        // Try to resolve curl constant names
37
        foreach ($config as $key => $value) {
38
            // If the $key is a string we assume it is a constant
39
            if (! is_string($key)) {
40 1
                continue;
41
            }
42 1
43
            if (null === ($constantValue = constant($key))) {
44
                throw new LogicException(sprintf('Key %s is not an int nor a CURL constant', $key));
45
            }
46
47 1
            unset($config[$key]);
48
            $config[$constantValue] = $value;
49 1
        }
50 1
51
        return new Client($this->responseFactory, $this->streamFactory, $config);
52
    }
53
}
54