1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Shoman4eg\Nalog; |
5
|
|
|
|
6
|
|
|
use Http\Discovery\Psr17FactoryDiscovery; |
7
|
|
|
use Psr\Http\Message\RequestFactoryInterface; |
8
|
|
|
use Psr\Http\Message\RequestInterface; |
9
|
|
|
use Psr\Http\Message\StreamFactoryInterface; |
10
|
|
|
use Psr\Http\Message\StreamInterface; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @author Tobias Nyholm <[email protected]> |
14
|
|
|
* |
15
|
|
|
* @internal this class should not be used outside the API Client, it is not part of the BC promise |
16
|
|
|
*/ |
17
|
|
|
final class RequestBuilder |
18
|
|
|
{ |
19
|
|
|
private RequestFactoryInterface $requestFactory; |
20
|
|
|
private StreamFactoryInterface $streamFactory; |
21
|
|
|
|
22
|
|
|
public function __construct( |
23
|
|
|
?RequestFactoryInterface $requestFactory = null, |
24
|
|
|
?StreamFactoryInterface $streamFactory = null |
25
|
|
|
) { |
26
|
|
|
$this->requestFactory = $requestFactory ?: Psr17FactoryDiscovery::findRequestFactory(); |
27
|
|
|
$this->streamFactory = $streamFactory ?: Psr17FactoryDiscovery::findStreamFactory(); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Creates a new PSR-7 request. |
32
|
|
|
* |
33
|
|
|
* @param array<string, array|string> $headers name => value or name=>[value] |
34
|
|
|
* @param null|StreamInterface|string $body request body |
35
|
|
|
*/ |
36
|
|
|
public function create(string $method, string $uri, array $headers = [], $body = null): RequestInterface |
37
|
|
|
{ |
38
|
|
|
$request = $this->requestFactory->createRequest($method, $uri); |
39
|
|
|
foreach ($headers as $name => $value) { |
40
|
|
|
$request = $request->withHeader($name, $value); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
if ($body !== null) { |
44
|
|
|
if (!$body instanceof StreamInterface) { |
45
|
|
|
$body = $this->streamFactory->createStream($body); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
$request = $request->withBody($body); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $request; |
|
|
|
|
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|