Completed
Push — master ( 8ca163...b47f16 )
by Nazar
04:14
created

Psr7   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 1
Bugs 1 Features 1
Metric Value
wmc 8
c 1
b 1
f 1
lcom 0
cbo 0
dl 0
loc 52
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A to_psr7() 0 8 1
A to_psr7_body() 0 17 4
A to_psr7_headers() 0 10 3
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
	 * Initialize request from PSR-7 request object
15
	 *
16
	 * @param \Psr\Http\Message\ResponseInterface $response
17
	 *
18
	 * @return \Psr\Http\Message\ResponseInterface
19
	 */
20
	function 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