-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathApiPlug.php
More file actions
235 lines (217 loc) · 7.55 KB
/
Copy pathApiPlug.php
File metadata and controls
235 lines (217 loc) · 7.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
<?php declare(strict_types=1);
/**
* MindTouch HTTP
* Copyright (C) 2006-2018 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace MindTouch\Http;
use Closure;
use Exception;
use MindTouch\Http\Exception\ApiResultException;
use modethirteen\Http\Content\IContent;
use modethirteen\Http\Exception\PlugUriHostRequiredException;
use modethirteen\Http\Exception\ResultParserContentExceedsMaxContentLengthException;
use modethirteen\Http\Plug;
use modethirteen\Http\Result;
use modethirteen\Http\IMutableHeaders;
use modethirteen\Http\Parser\SerializedPhpArrayParser;
use modethirteen\Http\XUri;
use modethirteen\TypeEx\StringEx;
/**
* Class ApiPlug - builder and invocation for MindTouch API requests
*
* @package MindTouch\Http
* @method ApiResult get()
* @method ApiResult head()
* @method ApiResult post(IContent|null $content = null)
* @method ApiResult delete()
* @method ApiResult invoke(string $method, IContent|null $content = null)
*/
class ApiPlug extends Plug {
const DREAM_FORMAT_PHP = 'php';
const DREAM_FORMAT_JSON = 'json';
const DREAM_FORMAT_XML = 'xml';
/**
* Path segments that should not be url encoded
*
* @var string[]
*/
private static $rawUriPathSegments = [
'files,subpages',
'children,siblings'
];
/**
* @param string $string - string to url encode
* @param bool $doubleEncode - if true, the string will be urlencoded twice
* @return string
*/
public static function urlEncode(string $string, bool $doubleEncode = false) : string {
// encode trailing dots (. => %2E)
for($i = strlen($string) - 1, $dots = 0; $i >= 0; $dots++, $i--) {
if(substr($string, $i, 1) !== '.') {
break;
}
}
$string = urlencode(substr($string, 0, $i + 1)) . str_repeat('%2E', $dots);
// we don't need to apply our custom encodings on the second pass
if($doubleEncode) {
$string = urlencode($string);
}
return $string;
}
/**
* @var IApiToken|null
*/
protected $token = null;
/**
* @var Closure|null
*/
protected $postInvokeErrorHandler = null;
/**
* @param XUri $uri - target uri
* @param string $format
* @throws PlugUriHostRequiredException
*/
public function __construct(XUri $uri, string $format = self::DREAM_FORMAT_PHP) {
parent::__construct($uri);
$this->uri = $this->uri->withQueryParam('dream.out.format', $format);
$this->setResultParser(new SerializedPhpArrayParser());
}
/**
* The api requires double urlencoded titles. This method will do it automatically for you.
* @see #AtRaw() for creating unencoded path components
*
* @param mixed ...$segments - path segments to add to the request (ex: $this->at('foo', 'bar', 'baz'))
* @return static
*/
public function at(...$segments) : object {
$plug = clone $this;
$path = $plug->uri->getPath();
foreach($segments as $segment) {
$segment = StringEx::stringify($segment);
if(!in_array($segment, self::$rawUriPathSegments)) {
$string = new StringEx($segment);
// auto-double encode, check for '=' or ':' sign
$segment = $string->startsWith('=') || $string->startsWith(':')
? substr($segment, 0, 1) . self::urlEncode(substr($segment, 1), true)
: self::urlEncode($segment, true);
}
$path .= '/' . ltrim($segment, '/');
}
$plug->uri = $plug->uri->withPath($path);
return $plug;
}
/**
* Appends a single path parameter to the plug, unencoded.
*
* @note Do not use this method unless you have to (you probably don't).
* A real need occurs when initially creating the plug baseuri and an
* unencoded "@api" is required.
*
* @see #At() for creating urlencoded paths
* @param string $segment
* @return static
*/
public function atRaw(string $segment) : object {
$plug = clone $this;
$plug->uri = $plug->uri->at($segment);
return $plug;
}
/**
* Return an instance with a server API token to the request
*
* @link https://success.mindtouch.com/Integrations/API/API_Tokens/Use_a_server_API_token_with_an_integration
* @param IApiToken $token
* @return static
*/
public function withApiToken(IApiToken $token) : object {
$plug = clone $this;
$plug->token = $token;
return $plug;
}
/**
* Return an instance with a post-invoke unsuccessful result handler
* Adding the handler supresses the default exception behavior if (bool)true is returned
* Only one error handler can be set, executing this method will return an instance with the handler replaced
*
* @param Closure $handler - $handler(ApiResultException $exception) : bool
* @return static
*/
public function withResultErrorHandler(Closure $handler) : object {
$plug = clone $this;
$plug->postInvokeErrorHandler = $handler;
return $plug;
}
/**
* Return an instance with the post-invoke unsuccessful result handler removed
*
* @return static
*/
public function withoutResultErrorHandler() : object {
$plug = clone $this;
$plug->postInvokeErrorHandler = null;
return $plug;
}
/**
* Performs a PUT request
*
* @param IContent|null $content - optionally send a content body with the request
* @return ApiResult
* @throws ResultParserContentExceedsMaxContentLengthException
*/
public function put(IContent $content = null) : object {
$plug = $this->with('dream.in.verb', 'PUT');
return $plug->invoke(self::METHOD_POST, $content);
}
/**
* @param IMutableHeaders $headers
* @return void
*/
protected function invokeApplyCredentials(IMutableHeaders $headers) : void {
parent::invokeApplyCredentials($headers);
if($this->token !== null) {
$headers->setHeader('X-Deki-Token', $this->token->toSignature());
}
}
/**
* Return the formatted invocation result
*
* @param Result $result
* @return ApiResult
* @throws ApiResultException
*/
protected function invokeComplete(Result $result) : object {
$exception = null;
try {
$result = parent::invokeComplete($result);
} catch(Exception $e) {
$exception = $e;
}
$result = new ApiResult($result->toArray());
if($exception === null && !$result->isSuccess()) {
$exception = new ApiResultException($result);
}
if($exception !== null) {
if($this->postInvokeErrorHandler !== null) {
$handler = $this->postInvokeErrorHandler;
if($handler($exception) === true) {
return $result;
}
}
throw $exception;
}
return $result;
}
}