-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathRequestBuilderTrait.php
72 lines (65 loc) · 1.9 KB
/
RequestBuilderTrait.php
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
declare(strict_types=1);
namespace Cundd\Rest\Tests;
use Cundd\Rest\Domain\Model\Format;
use Cundd\Rest\Domain\Model\ResourceType;
use Cundd\Rest\Http\RestRequestInterface;
use Cundd\Rest\Request;
use Zend\Diactoros\ServerRequest;
use Zend\Diactoros\Uri;
trait RequestBuilderTrait
{
/**
* @param string $url
* @param string|null $method
* @param array $params
* @param array $headers
* @param mixed $rawBody
* @param array|null $parsedBody
* @param string|null $format
* @return RestRequestInterface
*/
public static function buildTestRequest(
string $url,
?string $method = null,
array $params = [],
array $headers = [],
$rawBody = null,
?array $parsedBody = null,
?string $format = null
): RestRequestInterface {
$path = self::getPathFromUri($url);
$resourceType = new ResourceType((string)strtok($path, '/'));
if (null === $format) {
$format = Format::DEFAULT_FORMAT;
}
if ($rawBody) {
$stream = fopen('php://temp', 'a+');
fputs($stream, (string)$rawBody);
} else {
$stream = 'php://input';
}
$uri = new Uri($url);
$originalRequest = new ServerRequest(
$_SERVER,
[],
$uri,
$method,
$stream,
$headers,
[],
$params,
$parsedBody ?: $_POST,
'1.1'
);
return new Request($originalRequest, $uri->withPath($path), $path, $resourceType, new Format($format));
}
private static function getPathFromUri(string $url): string
{
if ('http://' === substr($url, 0, 7) || 'https://' === substr($url, 0, 8)) {
return (string)substr(strstr(substr($url, 8), '/'), 0);
} else {
return $url;
}
}
}