/
Request.php
executable file
·734 lines (651 loc) · 19.7 KB
/
Request.php
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
<?php
/**
* Apify - Copyright (c) 2011, Kewnode Ltd. All rights reserved.
*
* THIS COPYRIGHT INFORMATION MUST REMAIN INTACT AND MAY NOT BE MODIFIED IN ANY WAY.
*
* THIS SOFTWARE IS PROVIDED BY KEWNODE LTD "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL KEWNODE LTD BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category Library
* @package Request
* @author Federico Cargnelutti <federico@kewnode.com>
* @copyright Copyright (c) 2011 Kewnode Ltd.
* @version $Id: $
*/
class Request
{
const CONTROLLER_INDEX = 'Index';
const ACTION_INDEX = 'index';
const ACTION_CREATE = 'create';
const ACTION_SHOW = 'show';
const ACTION_UPDATE = 'update';
const ACTION_DESTROY = 'destroy';
const METHOD_POST = 'POST';
const METHOD_GET = 'GET';
const METHOD_PUT = 'PUT';
const METHOD_DELETE = 'DELETE';
/**
* @var boolean
*/
protected $isUrlRewritingEnabled = false;
/**
* @var boolean
*/
protected $isRestfulMappingEnabled = false;
/**
* @var null|Router
*/
protected $router;
/**
* @var null|string
*/
protected $urlKeyword;
/**
* null: auto-detect keyword
* 0: keyword is in domain name
* 1: keyword is in the first segment of the URL path
* 2: keyword is in the second segment of the URL path
*
* @var null|int
*/
protected $urlSegment;
/**
* @var null|string
*/
protected $urlPath;
/**
* @var null|array
*/
protected $urlParts;
/**
* @var string
*/
protected $contentType = 'html';
/**
* @var string
*/
protected $controller = self::CONTROLLER_INDEX;
/**
* @var string
*/
protected $action = self::ACTION_INDEX;
/**
* @var array
*/
protected $params = array();
/**
* @var Response
*/
protected $response;
/**
* Class constructor.
*/
public function __construct()
{
$this->setParams(array_merge($_GET, $_POST));
}
/**
* @params string $keyword
* @return Request
*/
public function setUrlKeyword($keyword)
{
$this->urlKeyword = $keyword;
return $this;
}
/**
* @params int $segment
* @return Request
*/
public function setUrlSegment($segment)
{
if (is_numeric($segment)) {
$this->urlSegment = $segment;
}
return $this;
}
/**
* @return Request
*/
public function enableRestfulMapping()
{
$this->isRestfulMappingEnabled = true;
return $this;
}
/**
* @return Request
*/
public function enableUrlRewriting()
{
$this->isUrlRewritingEnabled = true;
return $this;
}
/**
* @param array $routes
* @return Request
*/
public function addRoutes(array $routes)
{
if (! ($this->router instanceof Router)) {
$this->router = new Router($this->getParams());
}
$this->router->addRoutes($routes);
return $this;
}
/**
* @return Router
*/
public function getRouter()
{
return $this->router;
}
/**
* @param string $name
*/
public function setController($name)
{
if (null !== $name && '' !== $name) {
$strUtil = Loader::getInstance()->get('StringUtil');
$this->controller = $strUtil->camelize($name);
}
}
/**
* @return string
*/
public function getController()
{
return $this->controller;
}
/**
* @param string $name
*/
public function setAction($name)
{
if (null !== $name && '' !== $name) {
$strUtil = Loader::getInstance()->get('StringUtil');
$name = $strUtil->camelize($name);
$name{0} = strtolower($name{0});
$this->action = $name;
}
}
/**
* @return string
*/
public function getAction()
{
return $this->action;
}
/**
* @param null|string $controllerName
* @param null|string $actionName
* @return void
* @throws RuntimeException
*/
public function dispatch($controllerName = null, $actionName = null)
{
if ($this->isUrlRewritingEnabled && $this->router instanceof Router) {
$this->getRouter()->route($this);
} else if ($this->isUrlRewritingEnabled) {
$this->parseUrl();
} else {
$this->parseQueryString();
}
$controllerName = isset($controllerName) ? $controllerName : $this->getController();
$actionName = isset($actionName) ? $actionName : $this->getAction();
$response = $this->handleRequest($controllerName, $actionName);
$this->setResponse($response);
$renderer = new Renderer();
$renderer->render($this);
}
/**
* When a Controller has been found, the handleRequest method will be invoked,
* which is responsible for handling the actual request and - if applicable - returning
* an appropriate Response. So actually, this method is the main entrypoint for the
* dispatch loop which delegates requests to controllers.
*
* @param string $controllerName
* @param string $actionName
* @return mixed
* @throws RequestException
* @throws RuntimeException
*/
public function handleRequest($controllerName, $actionName)
{
try {
$controller = Loader::getInstance()->getController($controllerName);
} catch (LoaderException $e) {
throw new RequestException($e->getMessage(), Response::NOT_FOUND);
}
if (method_exists($controller, 'setRequest')) {
$controller->setRequest($this);
}
$controllerResponse = null;
if (method_exists($controller, 'init')) {
$controllerResponse = $controller->init($this);
}
if (! isset($controllerResponse)) {
if (! method_exists($controller, $actionName . 'Action')) {
$m = sprintf('Method "%s" not found', $actionName);
throw new RequestException($m, Response::NOT_FOUND);
}
$controllerResponse = $controller->{$actionName . 'Action'}($this);
}
$this->setController($controllerName);
$this->setAction($actionName);
if ($controllerResponse instanceof View) {
$this->setContentType('html');
$response = new Response();
$response->setView($controllerResponse);
return $response;
} else if ($controllerResponse instanceof Response) {
return $controllerResponse;
} else {
$m = sprintf('Method "%s::%sAction()" contains an invalid return type', $controllerName, $actionName);
throw new RuntimeException($m);
}
}
/**
* @param Exception $e
* @return void
* @throws Exception
*/
public function handleException(Exception $e)
{
// don't render runtime exceptions
if ($e instanceof RuntimeException) {
throw $e;
}
$response = new Response();
$response->setException($e);
$this->setResponse($response);
try {
$this->dispatch('Error', 'error');
} catch (Exception $e) {
throw $e;
}
}
/**
* @return void
*/
public function parseUrl()
{
$parts = $this->getUrlParts();
$partsCount = count($parts);
$controller = isset($parts[0]) ? $parts[0] : $this->getController();
$action = null;
$method = $this->getMethod();
$methods = array(
self::METHOD_GET => self::ACTION_SHOW,
self::METHOD_PUT => self::ACTION_UPDATE,
self::METHOD_DELETE => self::ACTION_DESTROY
);
$params = array();
$offset = 1;
if (!isset($parts[1]) && self::METHOD_GET === $method) {
$action = $this->getAction();
} else if (!isset($parts[1]) && self::METHOD_POST === $method) {
$action = self::ACTION_CREATE;
} else if (isset($parts[1]) && isset($methods[$method])) {
$offset = 2;
$this->setParam('id', $parts[1]);
$action = $methods[$method];
} else {
throw new RequestException('Method not allowed', Response::NOT_ALLOWED);
}
$params = array_slice($parts, $offset);
for ($i = 0; $i < count($params); $i++) {
$this->setParam('key'.$i, $params[$i]);
}
if (null === $action) {
$action = isset($parts[1]) ? $parts[1] : $this->getAction();
}
$this->setController($controller);
$this->setAction($action);
}
/**
* @return void
* @throws RequestException
*/
public function parseQueryString()
{
$path = preg_replace('/[^a-z.]/i', '', rtrim($this->getParam('method', ''), '.'));
$parts = explode('.', $path);
$controller = isset($parts[0]) ? $parts[0] : $this->getController();
$action = isset($parts[1]) ? $parts[1] : $this->getAction();
if ($this->isRestfulMappingEnabled) {
$method = $this->getMethod();
$methods = array(
self::METHOD_GET => self::ACTION_SHOW,
self::METHOD_PUT => self::ACTION_UPDATE,
self::METHOD_DELETE => self::ACTION_DESTROY
);
if (!$this->hasParam('id') && self::METHOD_GET === $method) {
$action = $this->getAction();
} else if (!$this->hasParam('id') && self::METHOD_POST === $method) {
$action = self::ACTION_CREATE;
} else if ($this->hasParam('id') && isset($methods[$method])) {
$action = $methods[$method];
} else {
throw new RequestException('Method not allowed', Response::NOT_ALLOWED);
}
}
$urlPath = '?method=' . $path;
$urlPath .= $this->hasParam('id') ? '&id=' . $this->getParam('id') : '';
$this->setUrlPath($urlPath);
$this->setController($controller);
$this->setAction($action);
if ($this->hasParam('format')) {
$this->setContentType($this->getParam('format'));
}
}
/**
* @param array $parts
*/
public function setUrlParts(array $parts)
{
$this->urlParts = $parts;
}
/**
* Parses the URL path and returns an array of strings containing the
* segments found after the keyword. For example:
*
* http://www.mysite.com/foo/api/users/1/show -> array('users', '1', 'show')
*
* @return array
* @throws RuntimeException
* @throws RequestException
*/
public function getUrlParts()
{
if (null !== $this->urlParts) {
return $this->urlParts;
}
$parts = array();
$baseUrl = $this->getBaseUrl();
$urlPath = $this->getUrlPath();
$urlPathArray = explode('/', ltrim($urlPath, '\/'));
if (null === $this->urlKeyword) {
$parts = $urlPathArray;
} else if (null !== $this->urlSegment) {
// position defined by the user
if (0 === $this->urlSegment) {
$parts = $urlPathArray;
} else if (isset($urlPathArray[$this->urlSegment-1])
&& $this->urlKeyword === $urlPathArray[$this->urlSegment-1]) {
$parts = array_slice($urlPathArray, $this->urlSegment);
} else {
throw new RuntimeException(sprintf('Keyword "%s" not found in URL', $this->urlKeyword));
}
} else {
// find keyword
$keywordHost = $this->urlKeyword . '.';
$keywordPath = '/' . $this->urlKeyword;
if ($keywordHost === substr($baseUrl, 0, strlen($keywordHost))) {
// keyword found in host name
$parts = $urlPathArray;
} else if (false !== strpos($urlPath, $keywordPath)) {
// keyword found in url path
$found = false;
for ($i = 0; $i < count($urlPathArray); $i++) {
if ($found) {
$parts[] = $urlPathArray[$i];
} else if ($this->urlKeyword == $urlPathArray[$i]) {
$found = true;
}
}
} else {
throw new RuntimeException(sprintf('Keyword "%s" not found in URL', $this->urlKeyword));
}
}
$this->setUrlParts($parts);
return $parts;
}
/**
* @return string
*/
public function getBaseUrl()
{
return sprintf('%s://%s', isset($_SERVER['HTTPS']) ? 'https' : 'http', $_SERVER['SERVER_NAME']);
}
/**
* @return string
*/
public function setUrlPath($path)
{
$this->urlPath = $path;
}
/**
* @return string
* @throws RuntimeException
*/
public function getUrlPath()
{
if (null !== $this->urlPath) {
return $this->urlPath;
}
$urlPath = '';
if (isset($_SERVER['REQUEST_URI'])) {
$urlPath = $_SERVER['REQUEST_URI'];
$strPos = strpos($urlPath, '?');
if (false !== $strPos) {
$urlPath = substr($urlPath, 0, $strPos);
}
} else {
$filename = (isset($_SERVER['SCRIPT_FILENAME'])) ? basename($_SERVER['SCRIPT_FILENAME']) : '';
if (isset($_SERVER['SCRIPT_NAME']) && basename($_SERVER['SCRIPT_NAME']) === $filename) {
$urlPath = $_SERVER['SCRIPT_NAME'];
} else {
if (isset($_SERVER['PHP_SELF']) && basename($_SERVER['PHP_SELF']) === $filename) {
$urlPath = $_SERVER['PHP_SELF'];
}
}
}
if (empty($urlPath)) {
throw new RuntimeException('URL path is undefined');
}
// content negotiation
$extensionPos = strrpos(basename($urlPath), '.');
if (false !== $extensionPos) {
$contentType = substr(basename($urlPath), $extensionPos+1);
$this->setContentType($contentType);
$urlPath = substr($urlPath, 0, strrpos($urlPath, '.'));
} else if ($this->hasParam('format')){
$contentType = $this->getParam('format');
} else if ($this->isRestfulMappingEnabled) {
$contentType = $this->getAcceptHeader();
if (null !== $contentType) {
$this->setContentType($contentType);
}
}
$urlPath = preg_replace('/\/+/', '\1/', rtrim($urlPath, '\/'));
if (empty($urlPath)) {
$urlPath = '/';
}
$this->setUrlPath(urldecode($urlPath));
return $this->urlPath;
}
/**
* @param string $key
* @param mixed $default Default value to use if key not found
* @return mixed
*/
public function getParam($key, $default = null)
{
if (! array_key_exists($key, $this->params)) {
return $default;
}
return $this->params[$key];
}
/**
* @param string $key
* @param mixed $value
* @return Request
*/
public function setParam($key, $value)
{
$this->params[$key] = $value;
return $this;
}
/**
* @param string $key
* @return boolean
*/
public function hasParam($key)
{
return array_key_exists($key, $this->params);
}
/**
* @param array $params
* @return Request
*/
public function setParams(array $params)
{
$this->params = $params;
return $this;
}
/**
* @return array
*/
public function getParams()
{
return $this->params;
}
/**
* @param array $params
* @return Request
*/
public function setPost(array $params)
{
$_POST = $params;
return $this;
}
/**
* @param string $key
* @return boolean
*/
public function hasPost($key)
{
return array_key_exists($key, $_POST);
}
/**
* @param string $key
* @param mixed $default Default value to use if key not found
* @return mixed Returns null if key does not exist
*/
public function getPost($key = null, $default = null)
{
if (null === $key) {
return $_POST;
}
return isset($_POST[$key]) ? $_POST[$key] : $default;
}
/**
* @return string
*/
public function getMethod()
{
return $_SERVER['REQUEST_METHOD'];
}
/**
* @param string $type
* @return Request
*/
public function setContentType($type)
{
$this->contentType = $type;
return $this;
}
/**
* @return string
*/
public function getContentType()
{
return $this->contentType;
}
/**
* @return boolean
*/
public function hasContentType()
{
return null !== $this->contentType;
}
/**
* Restricts the Content Types allowed.
*
* @param array $types
* @return void
* @throws RequestException
*/
public function acceptContentTypes(array $types)
{
if (! in_array($this->getContentType(), $types)) {
$this->setContentType('html');
throw new RequestException('Not Acceptable', Response::NOT_ACCEPTABLE);
}
}
/**
* @return null|string
*/
public function getAcceptHeader()
{
$accept = explode(',', $_SERVER['HTTP_ACCEPT']);
$type = null;
if (isset($accept[0])) {
$response = new Response();
$mimeTypes = $response->getMimeTypes();
$type = array_search($accept[0], $mimeTypes);
if (false === $type) {
$type = null;
}
}
return $type;
}
/**
* @return Session
*/
public function getSession()
{
return Loader::getInstance()->get('Session');
}
/**
* Return the Response object
*
* @return Response
*/
public function getResponse()
{
return $this->response;
}
/**
* Set the Response object
*
* @param Response $response
* @return self
*/
public function setResponse(Response $response)
{
$this->response = $response;
return $this;
}
/**
* @param string $uri
* @param integer $code HTTP status codes
* @return void
*/
public function redirect($uri, $code = Response::FOUND)
{
$response = new Response();
$response->setCode($code);
$response->addHeader('Location: ' . $uri);
$response->sendHeaders();
exit;
}
}