1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace CHStudio\Raven\Http\Factory; |
4
|
|
|
|
5
|
|
|
use CHStudio\Raven\Http\Factory\RequestFactoryInterface as InternalRequestFactoryInterface; |
6
|
|
|
use Psr\Http\Message\RequestFactoryInterface; |
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use Psr\Http\Message\RequestInterface; |
9
|
|
|
use Psr\Http\Message\StreamFactoryInterface; |
10
|
|
|
|
11
|
|
|
class RequestFactory implements InternalRequestFactoryInterface |
12
|
|
|
{ |
13
|
8 |
|
public function __construct( |
14
|
|
|
private readonly RequestFactoryInterface $requestFactory, |
15
|
|
|
private readonly StreamFactoryInterface $streamFactory |
16
|
|
|
) { |
17
|
8 |
|
} |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param array<string, mixed> $data |
21
|
|
|
*/ |
22
|
7 |
|
public function fromArray(array $data): RequestInterface |
23
|
|
|
{ |
24
|
7 |
|
if (!isset($data['uri'])) { |
25
|
1 |
|
throw new InvalidArgumentException('"uri" key must be defined foreach Request.'); |
26
|
|
|
} |
27
|
|
|
|
28
|
6 |
|
$uri = new Uri($data['uri']); |
29
|
6 |
|
$headers = new Headers($data['headers'] ?? []); |
30
|
6 |
|
$method = (isset($data['method']) && \is_string($data['method'])) ? $data['method'] : 'GET'; |
31
|
|
|
|
32
|
6 |
|
$request = $this->requestFactory->createRequest($method, (string) $uri); |
33
|
6 |
|
foreach ($headers as $name => $value) { |
34
|
4 |
|
$request = $request->withHeader($name, $value); |
35
|
|
|
} |
36
|
|
|
|
37
|
6 |
|
if (isset($data['body'])) { |
38
|
5 |
|
if (\is_string($data['body'])) { |
39
|
1 |
|
$body = $data['body']; |
40
|
4 |
|
} elseif (\is_array($data['body'])) { |
41
|
4 |
|
$body = match ($headers->first('Content-Type')) { |
42
|
4 |
|
'application/json' => json_encode($data['body'], JSON_THROW_ON_ERROR), |
43
|
4 |
|
'multipart/form-data' => http_build_query($data['body']), |
44
|
4 |
|
default => json_encode($data['body'], JSON_THROW_ON_ERROR) |
45
|
4 |
|
}; |
46
|
|
|
} |
47
|
|
|
|
48
|
5 |
|
if (isset($body)) { |
49
|
5 |
|
$request = $request->withBody( |
50
|
5 |
|
$this->streamFactory->createStream($body) |
51
|
5 |
|
); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
6 |
|
return $request; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
Let?s assume that you have a directory layout like this:
and let?s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: