REST API initial commit
[lhc/web/wiklou.git] / includes / Rest / RequestBase.php
1 <?php
2
3 namespace MediaWiki\Rest;
4
5 /**
6 * Shared code between RequestData and RequestFromGlobals
7 */
8 abstract class RequestBase implements RequestInterface {
9 /**
10 * @var HeaderContainer|null
11 */
12 private $headerCollection;
13
14 /** @var array */
15 private $attributes = [];
16
17 /** @var string */
18 private $cookiePrefix;
19
20 /**
21 * @internal
22 * @param string $cookiePrefix
23 */
24 protected function __construct( $cookiePrefix ) {
25 $this->cookiePrefix = $cookiePrefix;
26 }
27
28 /**
29 * Override this in the implementation class if lazy initialisation of
30 * header values is desired. It should call setHeaders().
31 *
32 * @internal
33 */
34 protected function initHeaders() {
35 }
36
37 public function __clone() {
38 if ( $this->headerCollection !== null ) {
39 $this->headerCollection = clone $this->headerCollection;
40 }
41 }
42
43 /**
44 * Erase any existing headers and replace them with the specified header
45 * lines.
46 *
47 * Call this either from the constructor or from initHeaders() of the
48 * implementing class.
49 *
50 * @internal
51 * @param string[] $headers The header lines
52 */
53 protected function setHeaders( $headers ) {
54 $this->headerCollection = new HeaderContainer;
55 $this->headerCollection->resetHeaders( $headers );
56 }
57
58 public function getHeaders() {
59 if ( $this->headerCollection === null ) {
60 $this->initHeaders();
61 }
62 return $this->headerCollection->getHeaders();
63 }
64
65 public function getHeader( $name ) {
66 if ( $this->headerCollection === null ) {
67 $this->initHeaders();
68 }
69 return $this->headerCollection->getHeader( $name );
70 }
71
72 public function hasHeader( $name ) {
73 if ( $this->headerCollection === null ) {
74 $this->initHeaders();
75 }
76 return $this->headerCollection->hasHeader( $name );
77 }
78
79 public function getHeaderLine( $name ) {
80 if ( $this->headerCollection === null ) {
81 $this->initHeaders();
82 }
83 return $this->headerCollection->getHeaderLine( $name );
84 }
85
86 public function setAttributes( $attributes ) {
87 $this->attributes = $attributes;
88 }
89
90 public function getAttributes() {
91 return $this->attributes;
92 }
93
94 public function getAttribute( $name, $default = null ) {
95 if ( array_key_exists( $name, $this->attributes ) ) {
96 return $this->attributes[$name];
97 } else {
98 return $default;
99 }
100 }
101
102 public function getCookiePrefix() {
103 return $this->cookiePrefix;
104 }
105
106 public function getCookie( $name, $default = null ) {
107 $cookies = $this->getCookieParams();
108 $prefixedName = $this->getCookiePrefix() . $name;
109 if ( array_key_exists( $prefixedName, $cookies ) ) {
110 return $cookies[$prefixedName];
111 } else {
112 return $default;
113 }
114 }
115 }