1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Transmission\HttpClient; |
||
6 | |||
7 | use Http\Discovery\Psr17FactoryDiscovery; |
||
8 | use Psr\Http\Message\RequestFactoryInterface; |
||
9 | use Psr\Http\Message\RequestInterface; |
||
10 | use Psr\Http\Message\StreamFactoryInterface; |
||
11 | use Psr\Http\Message\StreamInterface; |
||
12 | |||
13 | /** |
||
14 | * Based on Mailgun's Request Builder. |
||
15 | * |
||
16 | * @author Tobias Nyholm <[email protected]> |
||
17 | */ |
||
18 | class RequestBuilder |
||
19 | { |
||
20 | /** |
||
21 | * @var RequestFactoryInterface|null |
||
22 | */ |
||
23 | private $requestFactory; |
||
24 | |||
25 | /** |
||
26 | * @var StreamFactoryInterface|null |
||
27 | */ |
||
28 | private $streamFactory; |
||
29 | |||
30 | /** |
||
31 | * Creates a new PSR-7 request. |
||
32 | * |
||
33 | * @param string $method |
||
34 | * @param string $uri |
||
35 | * @param array $headers |
||
36 | * @param array|string|null $body Request body. |
||
37 | * |
||
38 | * @return RequestInterface |
||
39 | */ |
||
40 | public function create(string $method, string $uri, array $headers = [], $body = null): RequestInterface |
||
41 | { |
||
42 | $stream = $this->getStreamFactory()->createStream($body); |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
43 | |||
44 | return $this->createRequest($method, $uri, $headers, $stream); |
||
45 | } |
||
46 | |||
47 | private function getRequestFactory(): RequestFactoryInterface |
||
48 | { |
||
49 | if (null === $this->requestFactory) { |
||
50 | $this->requestFactory = Psr17FactoryDiscovery::findRequestFactory(); |
||
51 | } |
||
52 | |||
53 | return $this->requestFactory; |
||
54 | } |
||
55 | |||
56 | public function setRequestFactory(RequestFactoryInterface $requestFactory): self |
||
57 | { |
||
58 | $this->requestFactory = $requestFactory; |
||
59 | |||
60 | return $this; |
||
61 | } |
||
62 | |||
63 | private function getStreamFactory(): StreamFactoryInterface |
||
64 | { |
||
65 | if (null === $this->streamFactory) { |
||
66 | $this->streamFactory = Psr17FactoryDiscovery::findStreamFactory(); |
||
67 | } |
||
68 | |||
69 | return $this->streamFactory; |
||
70 | } |
||
71 | |||
72 | public function setStreamFactory(StreamFactoryInterface $streamFactory): self |
||
73 | { |
||
74 | $this->streamFactory = $streamFactory; |
||
75 | |||
76 | return $this; |
||
77 | } |
||
78 | |||
79 | private function createRequest(string $method, string $uri, array $headers, StreamInterface $stream) |
||
80 | { |
||
81 | $request = $this->getRequestFactory()->createRequest($method, $uri); |
||
82 | $request = $request->withBody($stream); |
||
83 | foreach ($headers as $name => $value) { |
||
84 | $request = $request->withAddedHeader($name, $value); |
||
85 | } |
||
86 | |||
87 | return $request; |
||
88 | } |
||
89 | } |
||
90 |