forked from phpro/http-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormUrlencodedEncoder.php
More file actions
45 lines (36 loc) · 1.16 KB
/
FormUrlencodedEncoder.php
File metadata and controls
45 lines (36 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
declare(strict_types=1);
namespace Phpro\HttpTools\Encoding\FormUrlencoded;
use Http\Discovery\Psr17FactoryDiscovery;
use const PHP_QUERY_RFC1738;
use Phpro\HttpTools\Encoding\EncoderInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\StreamFactoryInterface;
/**
* @implements EncoderInterface<array|null>
*/
final class FormUrlencodedEncoder implements EncoderInterface
{
private StreamFactoryInterface $streamFactory;
public function __construct(StreamFactoryInterface $streamFactory)
{
$this->streamFactory = $streamFactory;
}
public static function createWithAutodiscoveredPsrFactories(): self
{
return new self(
Psr17FactoryDiscovery::findStreamFactory()
);
}
/**
* @param array|null $data
*/
public function __invoke(RequestInterface $request, $data): RequestInterface
{
return $request
->withAddedHeader('Content-Type', 'application/x-www-form-urlencoded')
->withBody($this->streamFactory->createStream(
null !== $data ? http_build_query($data, encoding_type: PHP_QUERY_RFC1738) : ''
));
}
}