Completed
Push — master ( 9ae2e5...71aba4 )
by Nazar
04:07
created

Response::output_to_psr7()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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