1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace TMV\HTTPlugModule\DIFactory; |
6
|
|
|
|
7
|
|
|
use Psr\Http\Client\ClientInterface; |
8
|
|
|
use Http\Client\Common\FlexibleHttpClient; |
9
|
|
|
use Psr\Container\ContainerInterface; |
10
|
|
|
use InvalidArgumentException; |
11
|
|
|
use Laminas\ServiceManager\Exception\ServiceNotCreatedException; |
12
|
|
|
use Laminas\ServiceManager\Exception\ServiceNotFoundException; |
13
|
|
|
use Laminas\ServiceManager\Factory\AbstractFactoryInterface; |
14
|
|
|
|
15
|
|
|
use function explode; |
16
|
|
|
use function preg_match; |
17
|
|
|
|
18
|
|
|
class FlexibleClientAbstractFactory implements AbstractFactoryInterface |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* Can the factory create an instance for the service? |
22
|
|
|
* |
23
|
|
|
* @param string $requestedName |
24
|
|
|
*/ |
25
|
|
|
public function canCreate(ContainerInterface $container, $requestedName): bool |
26
|
|
|
{ |
27
|
|
|
if (! preg_match('/^httplug\.clients\.[^.]+\.flexible$/', $requestedName)) { |
28
|
|
|
return false; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
[,, $clientName] = explode('.', $requestedName); |
32
|
|
|
|
33
|
|
|
return $container->has('httplug.clients.' . $clientName); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Create an object. |
38
|
|
|
* |
39
|
|
|
* @param string $requestedName |
40
|
|
|
* @param null|array<mixed> $options |
41
|
|
|
* |
42
|
|
|
* @throws ServiceNotFoundException if unable to resolve the service |
43
|
|
|
* @throws ServiceNotCreatedException if an exception is raised when |
44
|
|
|
* creating a service |
45
|
|
|
*/ |
46
|
|
|
public function __invoke(ContainerInterface $container, $requestedName, array $options = null): FlexibleHttpClient |
47
|
|
|
{ |
48
|
|
|
if (! preg_match('/^httplug\.clients\.[^.]+\.flexible$/', $requestedName)) { |
49
|
|
|
throw new InvalidArgumentException('Invalid service name'); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
[,, $clientName] = explode('.', $requestedName); |
53
|
|
|
|
54
|
|
|
/** @var ClientInterface $httpClient */ |
55
|
|
|
$httpClient = $container->get('httplug.clients.' . $clientName); |
56
|
|
|
|
57
|
|
|
return new FlexibleHttpClient($httpClient); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|