Passed
Push — master ( 1d3489...c57d84 )
by Songda
02:23
created

HttpClientFactory::create()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 15
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yansongda\Pay;
6
7
use GuzzleHttp\Client;
8
use Psr\Container\ContainerExceptionInterface;
9
use Psr\Container\ContainerInterface;
10
use Psr\Container\NotFoundExceptionInterface;
11
use Psr\Http\Client\ClientInterface;
12
use Yansongda\Pay\Contract\HttpClientInterface;
13
use Yansongda\Pay\Exception\ContainerException;
14
use Yansongda\Pay\Exception\Exception;
15
use Yansongda\Pay\Exception\InvalidConfigException;
16
17
class HttpClientFactory implements Contract\HttpClientFactoryInterface
18
{
19
    public function __construct(private ContainerInterface $container) {}
20
21
    /**
22
     * @throws ContainerExceptionInterface
23
     * @throws ContainerException
24
     * @throws InvalidConfigException
25
     * @throws NotFoundExceptionInterface
26
     */
27
    public function create(?array $options = []): ClientInterface
28
    {
29
        if ($this->container->has(HttpClientInterface::class)) {
30
            if (($http = $this->container->get(HttpClientInterface::class)) instanceof ClientInterface) {
31
                return $http;
32
            }
33
34
            throw new InvalidConfigException(Exception::CONFIG_HTTP_CLIENT_INVALID, '配置异常: `HttpClient` 不符合 PSR 规范,可能你需要安装 `GuzzleHttp:^7`');
35
        }
36
37
        if (!class_exists(Client::class)) {
38
            throw new InvalidConfigException(Exception::CONFIG_HTTP_CLIENT_INVALID, '配置异常: 没有可用的 `HttpClient`,可能你需要安装 `GuzzleHttp:^7`');
39
        }
40
41
        return new Client($options);
42
    }
43
}
44