Completed
Pull Request — master (#624)
by Stig
03:38
created

Dispatcher::getAPIResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 1
eloc 7
nc 1
nop 2
1
<?php
2
/**
3
 * Dispatcher provides functionality to make it easier to work with frontend React components.
4
 * See deploynaut/docs/dispatcher.md for more information.
5
 *
6
 * @todo: currently we can't have more than one component mounted in parallel on any given Dispatcher,
7
 * because the SecurityID will diverge as soon as one of these components submit.
8
 */
9
10
abstract class Dispatcher extends DNRoot {
11
12
	/**
13
	 * The CSRF token name that is used for all frondend dispatchers
14
	 */
15
	const SECURITY_TOKEN_NAME = 'DispatcherSecurityID';
16
17
	/**
18
	 * Generate the data structure used by the frontend component.
19
	 *
20
	 * @param string $name of the component
21
	 * @return array
22
	 */
23
	abstract public function getModel($name);
24
25
	/**
26
	 * Renders the initial HTML needed to bootstrap the react component.
27
	 *
28
	 * Usage: $getReactComponent(YourComponent);
29
	 *
30
	 * @param string $name Used to name the DOM elements and obtain the initial model.
31
	 * @return string A snippet good for adding to a SS template.
32
	 */
33
	public function getReactComponent($name) {
34
		$model = $this->getModel($name);
35
		$model['InitialSecurityID'] = $this->getSecurityToken()->getValue();
36
37
		return $this->customise([
38
			'Name' => $name,
39
			'Model' => htmlentities(json_encode($model))
40
		])->renderWith('ReactTemplate');
41
	}
42
43
	/**
44
	 * We want to separate the dispatchers security token from the static HTML
45
	 * security token since it's possible that they get out of sync with eachother.
46
	 *
47
	 * We do this by giving the token a separate name.
48
	 *
49
	 * Don't manually reset() this token, that will cause issues when people have
50
	 * several tabs open. The token will be recreated when the user session times
51
	 * out.
52
	 *
53
	 * @return SecurityToken
54
	 */
55
	protected function getSecurityToken() {
56
		return new \SecurityToken(self::SECURITY_TOKEN_NAME);
57
	}
58
59
	/**
60
	 * @see getSecurityToken()
61
	 */
62
	protected function checkSecurityToken() {
63
		$securityToken = $this->getSecurityToken();
64
		if(!$securityToken->check($this->request->postVar(self::SECURITY_TOKEN_NAME))) {
65
			$this->httpError(403, 'Invalid security token, try reloading the page.');
66
		}
67
	}
68
69
	/**
70
	 * Return the validator errors as AJAX response.
71
	 *
72
	 * @param int $code HTTP status code.
73
	 * @param array $validatorErrors Result of calling Validator::validate, e.g.
74
	 *	[{"fieldName":"Name","message":"Message.","messageType":"bad"}]
75
	 * @return \SS_HTTPResponse
76
	 */
77
	public function asJSONValidatorErrors($code, $validatorErrors) {
78
		$fieldErrors = [];
79
		foreach ($validatorErrors as $error) {
80
			$fieldErrors[$error['fieldName']] = $error['message'];
81
		}
82
		return $this->asJSONFormFieldErrors($code, $fieldErrors);
83
	}
84
85
	/**
86
	 * Return field-specific errors as AJAX response.
87
	 *
88
	 * @param int $code HTTP status code.
89
	 * @param array $fieldErrors FieldName => message structure.
90
	 * @return \SS_HTTPResponse
91
	 */
92
	public function asJSONFormFieldErrors($code, $fieldErrors) {
93
		$response = $this->getResponse();
94
		$response->addHeader('Content-Type', 'application/json');
95
		$response->setBody(json_encode([
96
			'InputErrors' => $fieldErrors
97
		]));
98
		$response->setStatusCode($code);
99
		return $response;
100
	}
101
102
	/**
103
	 * Respond to an AJAX request.
104
	 * Automatically updates the security token and proxy pending redirects.
105
	 *
106
	 * @deprecated the use of getAPIResponse() is encouraged
107
	 * @param array $data Data to be passed to the frontend.
108
	 *
109
	 * @return SS_HTTPResponse
110
	 */
111
	public function asJSON($data = []) {
112
		$securityToken = $this->getSecurityToken();
113
		$securityToken->reset();
114
		$data['NewSecurityID'] = $securityToken->getValue();
115
116
		$response = $this->getResponse();
117
118
		// If we received an AJAX request, we can't redirect in an ordinary way: the browser will
119
		// interpret the 302 responses internally and the response will never reach JS.
120
		//
121
		// To get around that, upon spotting an active redirect, we change the response code to 200,
122
		// and move the redirect into the "RedirectTo" field in the JSON response. Frontend can
123
		// then interpret this and trigger a redirect.
124
		if ($this->redirectedTo()) {
125
			$data['RedirectTo'] = $this->response->getHeader('Location');
126
			// Pop off the header - we are no longer redirecting via the usual mechanism.
127
			$this->response->removeHeader('Location');
128
		}
129
130
		$response->addHeader('Content-Type', 'application/json');
131
		$response->setBody(json_encode($data));
132
		$response->setStatusCode(200);
133
		return $response;
134
	}
135
136
	/**
137
	 * Return an XHR response object without any CSRF token information
138
	 *
139
	 * @param array $output
140
	 * @param int $statusCode
141
	 * @return SS_HTTPResponse
142
	 */
143
	protected function getAPIResponse($output, $statusCode) {
144
		$output['status_code'] = $statusCode;
145
		$response = $this->getResponse();
146
		$response->addHeader('Content-Type', 'application/json');
147
		$response->setBody(json_encode($output, JSON_PRETTY_PRINT));
148
		$response->setStatusCode($statusCode);
149
		return $response;
150
	}
151
152
	/**
153
	 * Decode the data submitted by the Form.jsx control.
154
	 *
155
	 * @return array
156
	 */
157
	protected function getFormData() {
158
		return $this->stripNonPrintables(json_decode($this->request->postVar('Details'), true));
159
	}
160
161
	/**
162
	 * @param string|array
163
	 * @return string|array
164
	 */
165 View Code Duplication
	protected function trimWhitespace($val) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
166
		if(is_array($val)) {
167
			foreach($val as $k => $v) $val[$k] = $this->trimWhitespace($v);
168
			return $val;
169
		} else {
170
			return trim($val);
171
		}
172
	}
173
174
	/**
175
	 * Remove control characters from the input.
176
	 *
177
	 * @param string|array
178
	 * @return string|array
179
	 */
180 View Code Duplication
	protected function stripNonPrintables($val) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
181
		if(is_array($val)) {
182
			foreach($val as $k => $v) $val[$k] = $this->stripNonPrintables($v);
183
			return $val;
184
		} else {
185
			return preg_replace('/[[:cntrl:]]/', '', $val);
186
		}
187
	}
188
189
}
190