1
|
|
|
<?php |
2
|
|
|
namespace Wandu\Router\Responsifier; |
3
|
|
|
|
4
|
|
|
use Generator; |
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
6
|
|
|
use RuntimeException; |
7
|
|
|
use Wandu\Router\Contracts\ResponsifierInterface; |
8
|
|
|
use function Wandu\Http\response; |
9
|
|
|
|
10
|
|
|
class PsrResponsifier implements ResponsifierInterface |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* {@inheritdoc} |
14
|
|
|
*/ |
15
|
35 |
|
public function responsify($response) |
16
|
|
|
{ |
17
|
35 |
|
if ($response instanceof ResponseInterface) { |
18
|
6 |
|
return $response; |
19
|
|
|
} |
20
|
|
|
|
21
|
34 |
|
if (!isset($response)) { |
22
|
1 |
|
$response = ''; |
23
|
|
|
} |
24
|
34 |
|
while (is_callable($response)) { |
25
|
3 |
|
$nextResponse = call_user_func($response); |
26
|
3 |
|
$response = $nextResponse; |
27
|
|
|
} |
28
|
|
|
// int, float, boolean, string |
29
|
34 |
|
if (is_scalar($response)) { |
30
|
28 |
|
if ($response === true) { |
31
|
1 |
|
$response = 'true'; |
32
|
27 |
|
} elseif ($response === false) { |
33
|
1 |
|
$response = 'false'; |
34
|
|
|
} |
35
|
28 |
|
return response()->create((string)$response); |
36
|
|
|
} |
37
|
6 |
|
if ($response instanceof Generator) { |
38
|
2 |
|
return response()->generator($response); |
39
|
|
|
} |
40
|
4 |
|
if (is_array($response) || is_object($response)) { |
41
|
2 |
|
return response()->json($response); |
|
|
|
|
42
|
|
|
} |
43
|
2 |
|
if (is_resource($response)) { |
44
|
2 |
|
if ('stream' === get_resource_type($response)) { |
45
|
2 |
|
$mode = stream_get_meta_data($response)['mode']; |
46
|
|
|
// @todo use Stream |
47
|
2 |
|
if (strpos($mode, 'r') !== false || strpos($mode, '+') !== false) { |
48
|
1 |
|
$contents = ''; |
49
|
1 |
|
while (!feof($response)) { |
50
|
1 |
|
$contents .= fread($response, 1024); |
51
|
|
|
} |
52
|
1 |
|
return response()->create($contents); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
1 |
|
throw new RuntimeException('Unsupported Type of Response.'); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:
If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.