1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @package CleverStyle CMS |
4
|
|
|
* @author Nazar Mokrynskyi <[email protected]> |
5
|
|
|
* @copyright Copyright (c) 2016, Nazar Mokrynskyi |
6
|
|
|
* @license MIT License, see license.txt |
7
|
|
|
*/ |
8
|
|
|
namespace cs\Response; |
9
|
|
|
use |
10
|
|
|
Exception; |
11
|
|
|
|
12
|
|
|
trait Psr7 { |
13
|
|
|
/** |
14
|
|
|
* Provides output to PSR-7 response object |
15
|
|
|
* |
16
|
|
|
* @param \Psr\Http\Message\ResponseInterface $response |
17
|
|
|
* |
18
|
|
|
* @return \Psr\Http\Message\ResponseInterface |
19
|
|
|
*/ |
20
|
|
|
function output_to_psr7 ($response) { |
21
|
|
|
$this->to_psr7_body($response); |
22
|
|
|
$response = $this->to_psr7_headers($response); |
23
|
|
|
/** @noinspection ExceptionsAnnotatingAndHandlingInspection */ |
24
|
|
|
return $response |
25
|
|
|
->withProtocolVersion(explode('/', $this->protocol, 2)[1]) |
26
|
|
|
->withStatus($this->code); |
27
|
|
|
} |
28
|
|
|
/** |
29
|
|
|
* @param \Psr\Http\Message\ResponseInterface $response |
30
|
|
|
*/ |
31
|
|
|
protected function to_psr7_body ($response) { |
32
|
|
|
$body = $response->getBody(); |
33
|
|
|
try { |
34
|
|
|
if (is_resource($this->body_stream)) { |
35
|
|
|
$position = ftell($this->body_stream); |
36
|
|
|
rewind($this->body_stream); |
37
|
|
|
while (!feof($this->body_stream)) { |
38
|
|
|
$body->write(fread($this->body_stream, 1024)); |
39
|
|
|
} |
40
|
|
|
fseek($this->body_stream, $position); |
41
|
|
|
} else { |
42
|
|
|
$body->write($this->body); |
43
|
|
|
} |
44
|
|
|
} catch (Exception $e) { |
45
|
|
|
// Do nothing |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
/** |
49
|
|
|
* @param \Psr\Http\Message\ResponseInterface $response |
50
|
|
|
* |
51
|
|
|
* @return \Psr\Http\Message\ResponseInterface $response |
52
|
|
|
*/ |
53
|
|
|
protected function to_psr7_headers ($response) { |
54
|
|
|
foreach ($this->headers as $header => $values) { |
55
|
|
|
try { |
56
|
|
|
$response = $response->withHeader($header, $values); |
57
|
|
|
} catch (Exception $e) { |
58
|
|
|
// Do nothing |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
return $response; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|