1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Robbie\Psr7; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\MessageInterface; |
6
|
|
|
use SilverStripe\Control\HTTPRequest; |
7
|
|
|
use SilverStripe\Control\HTTPResponse; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Provides common functionality used between Request and Response objects |
11
|
|
|
* |
12
|
|
|
* @package psr7-adapters |
13
|
|
|
*/ |
14
|
|
|
abstract class AbstractHttpAdapter |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var string |
18
|
|
|
*/ |
19
|
|
|
protected $protocolVersion; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Perform a conversion from a HTTPResponse or HTTPRequest into the corresponding PSR-7 interface |
23
|
|
|
* |
24
|
|
|
* @param HTTPRequest|HTTPResponse $input |
25
|
|
|
* @return MessageInterface |
26
|
|
|
*/ |
27
|
|
|
abstract public function toPsr7($input); |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Perform a conversion from a PSR-7 interface to the corresponding HTTPRequest or HTTPResponse class |
31
|
|
|
* |
32
|
|
|
* @param MessageInterface $input |
33
|
|
|
* @return HTTPRequest|HTTPResponse |
34
|
|
|
*/ |
35
|
|
|
abstract public function fromPsr7($input); |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* PSR-7 interfaces support multiple headers per type, whereas SilverStripe classes do not. |
39
|
|
|
* |
40
|
|
|
* This method will assign headers as a comma delimited string from the PSR-7 interface to the SilverStripe class |
41
|
|
|
* |
42
|
|
|
* @param MessageInterface $from |
43
|
|
|
* @param HTTPRequest|HTTPResponse $to |
44
|
|
|
*/ |
45
|
|
|
public function importHeaders(MessageInterface $from, $to) |
46
|
|
|
{ |
47
|
|
|
foreach ($from->getHeaders() as $key => $headers) { |
48
|
|
|
foreach ($headers as $header) { |
49
|
|
|
$to->addHeader($key, $from->getHeaderLine($key)); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Get the protocol version - either from a previously set value, or from the server |
56
|
|
|
* |
57
|
|
|
* @return string E.g. "1.1" |
58
|
|
|
*/ |
59
|
|
|
public function getProtocolVersion() |
|
|
|
|
60
|
|
|
{ |
61
|
|
|
if ($this->protocolVersion) { |
62
|
|
|
return $this->protocolVersion; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
$protocolAndVersion = $_SERVER['SERVER_PROTOCOL']; |
66
|
|
|
list($protocol, $version) = explode('/', $protocolAndVersion); |
|
|
|
|
67
|
|
|
return $version; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Set the protocol version |
72
|
|
|
* |
73
|
|
|
* @param string $version |
74
|
|
|
* @return $this |
75
|
|
|
*/ |
76
|
|
|
public function setProtocolVersion($version = '1.1') |
77
|
|
|
{ |
78
|
|
|
$this->protocolVersion = $version; |
79
|
|
|
return $this; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: