File: Server.php

package info (click to toggle)
homer-api 5.0.6%2Bdfsg2-3.3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,612 kB
  • sloc: php: 8,259; javascript: 4,688; sql: 1,212; perl: 984; sh: 318; makefile: 69
file content (1221 lines) | stat: -rw-r--r-- 33,866 bytes parent folder | download | duplicates (4)
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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
<?php

namespace RestService;

/**
 * \RestService\Server - A REST server class for RESTful APIs.
 */

class Server
{
    /**
     * Current routes.
     *
     * structure:
     *  array(
     *    '<uri>' => <callable>
     *  )
     *
     * @var array
     */
    protected $routes = array();

    /**
     * Blacklisted http get arguments.
     *
     * @var array
     */
    protected $blacklistedGetParameters = array('_method', '_suppress_status_code');

    /**
     * Current URL that triggers the controller.
     *
     * @var string
     */
    protected $triggerUrl = '';

    /**
     * Contains the controller object.
     *
     * @var string
     */
    protected $controller = '';

    /**
     * List of sub controllers.
     *
     * @var array
     */
    protected $controllers = array();

    /**
     * Parent controller.
     *
     * @var \RestService\Server
     */
    protected $parentController;

    /**
     * The client
     *
     * @var Client
     */
    protected $client;

    /**
     * List of excluded methods.
     *
     * @var array|string array('methodOne', 'methodTwo') or * for all methods
     */
    protected $collectRoutesExclude = array('__construct');

    /**
     * List of possible methods.
     * @var array
     */
    public $methods = array('get', 'post', 'put', 'delete', 'head', 'options', 'patch');

    /**
     * Check access function/method. Will be fired after the route has been found.
     * Arguments: (url, route)
     *
     * @var callable
     */
    protected $checkAccessFn;

    /**
     * Send exception function/method. Will be fired if a route-method throws a exception.
     * Please die/exit in your function then.
     * Arguments: (exception)
     *
     * @var callable
     */
    protected $sendExceptionFn;

    /**
     * If this is true, we send file, line and backtrace if an exception has been thrown.
     *
     * @var boolean
     */
    protected $debugMode = false;

    /**
     * Sets whether the service should serve route descriptions
     * through the OPTIONS method.
     *
     * @var boolean
     */
    protected $describeRoutes = true;

    /**
     * If this controller can not find a route,
     * we fire this method and send the result.
     *
     * @var string
     */
    protected $fallbackMethod = '';

    /**
     * If the lib should send HTTP status codes.
     * Some Client libs does not support this, you can deactivate it via
     * ->setHttpStatusCodes(false);
     *
     * @var boolean
     */
    protected $withStatusCode = true;

    /**
     * @var callable
     */
    protected $controllerFactory;

    /**
     * Constructor
     *
     * @param string              $pTriggerUrl
     * @param string|object       $pControllerClass
     * @param \RestService\Server $pParentController
     */
    public function __construct($pTriggerUrl, $pControllerClass = null, $pParentController = null)
    {
        
        $this->normalizeUrl($pTriggerUrl);

        if ($pParentController) {
            $this->parentController = $pParentController;
            $this->setClient($pParentController->getClient());

            if ($pParentController->getCheckAccess())
                $this->setCheckAccess($pParentController->getCheckAccess());

            if ($pParentController->getExceptionHandler())
                $this->setExceptionHandler($pParentController->getExceptionHandler());

            if ($pParentController->getDebugMode())
                $this->setDebugMode($pParentController->getDebugMode());

            if ($pParentController->getDescribeRoutes())
                $this->setDescribeRoutes($pParentController->getDescribeRoutes());

            if ($pParentController->getControllerFactory())
                $this->setControllerFactory($pParentController->getControllerFactory());

            $this->setHttpStatusCodes($pParentController->getHttpStatusCodes());

        } else {
            $this->setClient(new Client($this));
        }

        $this->setClass($pControllerClass);
        $this->setTriggerUrl($pTriggerUrl);
    }

    /**
     * Factory.
     *
     * @param string $pTriggerUrl
     * @param string $pControllerClass
     *
     * @return Server $this
     */
    public static function create($pTriggerUrl, $pControllerClass = '')
    {
        $clazz = get_called_class();

        return new $clazz($pTriggerUrl, $pControllerClass);
    }

    /**
     * @param callable $controllerFactory
     *
     * @return Server $this
     */
    public function setControllerFactory(callable $controllerFactory)
    {
        $this->controllerFactory = $controllerFactory;

        return $this;
    }

    /**
     * @return callable
     */
    public function getControllerFactory()
    {
        return $this->controllerFactory;
    }

    /**
     * If the lib should send HTTP status codes.
     * Some Client libs does not support it.
     *
     * @param  boolean $pWithStatusCode
     * @return Server  $this
     */
    public function setHttpStatusCodes($pWithStatusCode)
    {
        $this->withStatusCode = $pWithStatusCode;

        return $this;
    }

    /**
     *
     * @return boolean
     */
    public function getHttpStatusCodes()
    {
        return $this->withStatusCode;
    }

    /**
     * Set the check access function/method.
     * Will fired with arguments: (url, route)
     *
     * @param  callable $pFn
     * @return Server   $this
     */
    public function setCheckAccess($pFn)
    {
        $this->checkAccessFn = $pFn;

        return $this;
    }

    /**
     * Getter for checkAccess
     * @return callable
     */
    public function getCheckAccess()
    {
        return $this->checkAccessFn;
    }

    /**
     * If this controller can not find a route,
     * we fire this method and send the result.
     *
     * @param  string $pFn Methodname of current attached class
     * @return Server $this
     */
    public function setFallbackMethod($pFn)
    {
        $this->fallbackMethod = $pFn;

        return $this;
    }

    /**
     * Getter for fallbackMethod
     * @return string
     */
    public function fallbackMethod()
    {
        return $this->fallbackMethod;
    }

    /**
     * Sets whether the service should serve route descriptions
     * through the OPTIONS method.
     *
     * @param  boolean $pDescribeRoutes
     * @return Server  $this
     */
    public function setDescribeRoutes($pDescribeRoutes)
    {
        $this->describeRoutes = $pDescribeRoutes;
    }

    /**
     * Getter for describeRoutes.
     *
     * @return boolean
     */
    public function getDescribeRoutes()
    {
        return $this->describeRoutes;
    }

    /**
     * Send exception function/method. Will be fired if a route-method throws a exception.
     * Please die/exit in your function then.
     * Arguments: (exception)
     *
     * @param  callable $pFn
     * @return Server   $this
     */
    public function setExceptionHandler($pFn)
    {
        $this->sendExceptionFn = $pFn;

        return $this;
    }

    /**
     * Getter for checkAccess
     * @return callable
     */
    public function getExceptionHandler()
    {
        return $this->sendExceptionFn;
    }

    /**
     * If this is true, we send file, line and backtrace if an exception has been thrown.
     *
     * @param  boolean $pDebugMode
     * @return Server  $this
     */
    public function setDebugMode($pDebugMode)
    {
        $this->debugMode = $pDebugMode;

        return $this;
    }

    /**
     * Getter for checkAccess
     * @return boolean
     */
    public function getDebugMode()
    {
        return $this->debugMode;
    }

    /**
     * Alias for getParentController()
     *
     * @return Server
     */
    public function done()
    {
        return $this->getParentController();
    }

    /**
     * Returns the parent controller
     *
     * @return Server $this
     */
    public function getParentController()
    {
        return $this->parentController;
    }

    /**
     * Set the URL that triggers the controller.
     *
     * @param $pTriggerUrl
     * @return Server
     */
    public function setTriggerUrl($pTriggerUrl)
    {
        $this->triggerUrl = $pTriggerUrl;

        return $this;
    }

    /**
     * Gets the current trigger url.
     *
     * @return string
     */
    public function getTriggerUrl()
    {
        return $this->triggerUrl;
    }

    /**
     * Sets the client.
     *
     * @param  Client|string $pClient
     * @return Server        $this
     */
    public function setClient($pClient)
    {
        if (is_string($pClient)) {
            $pClient = new $pClient($this);
        }

        $this->client = $pClient;
        $this->client->setupFormats();

        return $this;
    }

    /**
     * Get the current client.
     *
     * @return Client
     */
    public function getClient()
    {
        return $this->client;
    }

    /**
     * Sends a 'Bad Request' response to the client.
     *
     * @param $pCode
     * @param $pMessage
     * @throws \Exception
     * @return string
     */
    public function sendBadRequest($pCode, $pMessage)
    {
        if (is_object($pMessage) && $pMessage->xdebug_message) $pMessage = $pMessage->xdebug_message;
        $msg = array('error' => $pCode, 'message' => $pMessage);
        if (!$this->getClient()) throw new \Exception('client_not_found_in_ServerController');
        return $this->getClient()->sendResponse('400', $msg);
    }

    /**
     * Sends a 'Internal Server Error' response to the client.
     * @param $pCode
     * @param $pMessage
     * @throws \Exception
     * @return string
     */
    public function sendError($pCode, $pMessage)
    {
        if (is_object($pMessage) && $pMessage->xdebug_message) $pMessage = $pMessage->xdebug_message;
        $msg = array('error' => $pCode, 'message' => $pMessage);
        if (!$this->getClient()) throw new \Exception('client_not_found_in_ServerController');
        return $this->getClient()->sendResponse('500', $msg);
    }

    /**
     * Sends a exception response to the client.
     * @param $pException
     * @throws \Exception
     */
    public function sendException($pException)
    {
        if ($this->sendExceptionFn) {
            call_user_func_array($this->sendExceptionFn, array($pException));
        }

        $message = $pException->getMessage();
        if (is_object($message) && $message->xdebug_message) $message = $message->xdebug_message;

        $msg = array('error' => get_class($pException), 'message' => $message);

        if ($this->debugMode) {
            $msg['file'] = $pException->getFile();
            $msg['line'] = $pException->getLine();
            $msg['trace'] = $pException->getTraceAsString();
        }

        if (!$this->getClient()) throw new \Exception('Client not found in ServerController');
        return $this->getClient()->sendResponse('500', $msg);

    }

    /**
     * Adds a new route for all http methods (get, post, put, delete, options, head, patch).
     *
     * @param  string          $pUri
     * @param  callable|string $pCb         The method name of the passed controller or a php callable.
     * @param  string          $pHttpMethod If you want to limit to a HTTP method.
     * @return Server
     */
    public function addRoute($pUri, $pCb, $pHttpMethod = '_all_')
    {
        $this->routes[$pUri][ $pHttpMethod ] = $pCb;

        return $this;
    }

    /**
     * Same as addRoute, but limits to GET.
     *
     * @param  string          $pUri
     * @param  callable|string $pCb  The method name of the passed controller or a php callable.
     * @return Server
     */
    public function addGetRoute($pUri, $pCb)
    {
        $this->addRoute($pUri, $pCb, 'get');

        return $this;
    }

    /**
     * Same as addRoute, but limits to POST.
     *
     * @param  string          $pUri
     * @param  callable|string $pCb  The method name of the passed controller or a php callable.
     * @return Server
     */
    public function addPostRoute($pUri, $pCb)
    {
        $this->addRoute($pUri, $pCb, 'post');

        return $this;
    }

    /**
     * Same as addRoute, but limits to PUT.
     *
     * @param  string          $pUri
     * @param  callable|string $pCb  The method name of the passed controller or a php callable.
     * @return Server
     */
    public function addPutRoute($pUri, $pCb)
    {
        $this->addRoute($pUri, $pCb, 'put');

        return $this;
    }

    /**
     * Same as addRoute, but limits to PATCH.
     *
     * @param  string          $pUri
     * @param  callable|string $pCb  The method name of the passed controller or a php callable.
     * @return Server
     */
    public function addPatchRoute($pUri, $pCb)
    {
        $this->addRoute($pUri, $pCb, 'patch');

        return $this;
    }

    /**
     * Same as addRoute, but limits to HEAD.
     *
     * @param  string          $pUri
     * @param  callable|string $pCb  The method name of the passed controller or a php callable.
     * @return Server
     */
    public function addHeadRoute($pUri, $pCb)
    {
        $this->addRoute($pUri, $pCb, 'head');

        return $this;
    }

    /**
     * Same as addRoute, but limits to OPTIONS.
     *
     * @param  string          $pUri
     * @param  callable|string $pCb  The method name of the passed controller or a php callable.
     * @return Server
     */
    public function addOptionsRoute($pUri, $pCb)
    {
        $this->addRoute($pUri, $pCb, 'options');

        return $this;
    }

    /**
     * Same as addRoute, but limits to DELETE.
     *
     * @param  string          $pUri
     * @param  callable|string $pCb  The method name of the passed controller or a php callable.
     * @return Server
     */
    public function addDeleteRoute($pUri, $pCb)
    {
        $this->addRoute($pUri, $pCb, 'delete');

        return $this;
    }

    /**
     * Removes a route.
     *
     * @param  string $pUri
     * @return Server
     */
    public function removeRoute($pUri)
    {
        unset($this->routes[$pUri]);

        return $this;
    }

    /**
     * Sets the controller class.
     *
     * @param string|object $pClass
     */
    public function setClass($pClass)
    {
        if (is_string($pClass)) {
            $this->createControllerClass($pClass);
        } elseif (is_object($pClass)) {
            $this->controller = $pClass;
        } else {
            $this->controller = $this;
        }
    }

    /**
     * Setup the controller class.
     *
     * @param  string    $pClassName
     * @throws \Exception
     */
    protected function createControllerClass($pClassName)
    {
        if ($pClassName != '') {
            try {
                if ($this->controllerFactory) {
                    $this->controller = call_user_func_array($this->controllerFactory, array(
                        $pClassName,
                        $this
                    ));
                } else {
                    $this->controller = new $pClassName($this);
                }
                if (get_parent_class($this->controller) == '\RestService\Server') {
                    $this->controller->setClient($this->getClient());
                }
            } catch (\Exception $e) {
                throw new \Exception('Error during initialisation of '.$pClassName.': '.$e, 0, $e);
            }
        } else {
            $this->controller = $this;
        }
    }

    /**
     * Attach a sub controller.
     *
     * @param string $pTriggerUrl
     * @param mixed  $pControllerClass A class name (autoloader required) or a instance of a class.
     *
     * @return Server new created Server. Use done() to switch the context back to the parent.
     */
    public function addSubController($pTriggerUrl, $pControllerClass = '')
    {
        $this->normalizeUrl($pTriggerUrl);

        $controller = new Server($this->triggerUrl . $pTriggerUrl, $pControllerClass, $this);

        $this->controllers[] = $controller;

        return $controller;
    }

    /**
     * Normalize $pUrl. Cuts of the trailing slash.
     *
     * @param string $pUrl
     */
    public function normalizeUrl(&$pUrl)
    {
        if ('/' === $pUrl) return;
        if (substr($pUrl, -1) == '/') $pUrl = substr($pUrl, 0, -1);
        if (substr($pUrl, 0, 1) != '/') $pUrl = '/' . $pUrl;
    }

    /**
     * Sends data to the client with 200 http code.
     *
     * @param $pData
     */
    public function send($pData)
    {
    
        if(isset($pData['status'])) return $this->getClient()->sendResponse($pData['status'], $pData);
        else return $this->getClient()->sendResponse(200, array('data' => $pData));
    }

    /**
     * @param  string $pValue
     * @return string
     */
    public function camelCase2Dashes($pValue)
    {
        return strtolower(preg_replace('/([a-z])([A-Z])/', '$1-$2', $pValue));
    }

    /**
     * Setup automatic routes.
     *
     * @return Server
     */
    public function collectRoutes()
    {
        if ($this->collectRoutesExclude == '*') return $this;

        $methods = get_class_methods($this->controller);
        foreach ($methods as $method) {
            if (in_array($method, $this->collectRoutesExclude)) continue;

            $info = explode('/', preg_replace('/([a-z]*)(([A-Z]+)([a-zA-Z0-9_]*))/', '$1/$2', $method));
            $uri  = $this->camelCase2Dashes($info[1]);

            $httpMethod  = $info[0];
            if ($httpMethod == 'all') {
                $httpMethod = '_all_';
            }

            $reflectionMethod = new \ReflectionMethod($this->controller, $method);
            if ($reflectionMethod->isPrivate()) continue;

            $phpDocs = $this->getMethodMetaData($reflectionMethod);
            if (isset($phpDocs['url'])) {
                if (isset($phpDocs['url']['url'])) {
                    //only one route
                    $this->routes[$phpDocs['url']['url']][$httpMethod] = $method;
                } else {
                    foreach($phpDocs['url'] as $urlAnnotation) {
                        $this->routes[$urlAnnotation['url']][$httpMethod] = $method;
                    }
                }
            } else {
                $this->routes[$uri][$httpMethod] = $method;
            }

        }

        return $this;
    }

    /**
     * Simulates a HTTP Call.
     *
     * @param  string $pUri
     * @param  string $pMethod The HTTP Method
     * @return string
     */
    public function simulateCall($pUri, $pMethod = 'get')
    {
        if (($idx = strpos($pUri, '?')) !== false) {
            parse_str(substr($pUri, $idx+1), $_GET);
            $pUri = substr($pUri, 0, $idx);
        }
        $this->getClient()->setUrl($pUri);
        $this->getClient()->setMethod($pMethod);

        return $this->run();
    }

    /**
     * Fire the magic!
     *
     * Searches the method and sends the data to the client.
     *
     * @return mixed
     */
    public function run()
    {
        //check sub controller
        foreach ($this->controllers as $controller) {
            if ($result = $controller->run()) {
                return $result;
            }
        }

        $requestedUrl = $this->getClient()->getUrl();
        
        $dataRequest = $this->getClient()->getData();
        
        /**/
        $requestedUrl = $this->getClient()->getUrl();
        
        $this->normalizeUrl($requestedUrl);
        //check if its in our area
        
        if (strpos($requestedUrl, $this->triggerUrl) !== 0) return;
        
        $endPos = $this->triggerUrl === '/' ? 1 : strlen($this->triggerUrl) + 1;
        $uri = substr($requestedUrl, $endPos);

        if (!$uri) $uri = '';

        $route = false;
        $arguments = array();
        $requiredMethod = $this->getClient()->getMethod();

        //does the requested uri exist?
        list($callableMethod, $regexArguments, $method, $routeUri) = $this->findRoute($uri, $requiredMethod);

        if ((!$callableMethod || $method != 'options') && $requiredMethod == 'options') {
            $description = $this->describe($uri);
            $this->send($description);
        }
        
    
        if (!$callableMethod) {
            if (!$this->getParentController()) {
                if ($this->fallbackMethod) {
                    $m = $this->fallbackMethod;
                    $this->send($this->controller->$m());
                } else {
                    return $this->sendBadRequest('RouteNotFoundException', "There is no route for '$uri'.");
                }
            } else {
                return false;
            }
        }
        

        if ($method == '_all_')
            $arguments[] = $method;

        if (is_array($regexArguments)) {
            $arguments = array_merge($arguments, $regexArguments);
        }

        //open class and scan method
        if ($this->controller && is_string($callableMethod)) {
            $ref = new \ReflectionClass($this->controller);

            if (!method_exists($this->controller, $callableMethod)) {
                $this->sendBadRequest('MethodNotFoundException', "There is no method '$callableMethod' in ".
                    get_class($this->controller).".");
            }

            $reflectionMethod = $ref->getMethod($callableMethod);
        } else if (is_callable($callableMethod)) {
            $reflectionMethod = new \ReflectionFunction($callableMethod);
        }

        $params = $reflectionMethod->getParameters();

        if ($method == '_all_') {
            //first parameter is $pMethod
            array_shift($params);
        }

        //remove regex arguments
        for ($i=0; $i<count($regexArguments); $i++) {
            array_shift($params);
        }
        
        //collect arguments
        foreach ($params as $param) {
            $name = $this->argumentName($param->getName());

            if ($name == '_') {
                $thisArgs = array();
                foreach ($_GET as $k => $v) {
                    if (substr($k, 0, 1) == '_' && $k != '_suppress_status_code')
                        $thisArgs[$k] = $v;
                }
                $arguments[] = $thisArgs;
            } else {

                if (!$param->isOptional() && !isset($dataRequest[$name])) {                
                   return $this->sendBadRequest('MissingRequiredArgumentException', sprintf("Argument '%s' is missing.", $name));
                }

                
                $arguments[] = isset($dataRequest[$name]) ? $dataRequest[$name] : $param->getDefaultValue();
            }            
        }

        if ($this->checkAccessFn) {
            $args[] = $this->getClient()->getUrl();
            $args[] = $route;
            $args[] = $arguments;
            try {
                call_user_func_array($this->checkAccessFn, $args);
            } catch (\Exception $e) {
                $this->sendException($e);
            }
        }
        
        //fire method
        $object = $this->controller;

        return $this->fireMethod($callableMethod, $object, $arguments);

    }

    public function fireMethod($pMethod, $pController, $pArguments)
    {
        $callable = false;
        
        if ($pController && is_string($pMethod)) {
            if (!method_exists($pController, $pMethod)) {            
                return $this->sendError('MethodNotFoundException', sprintf('Method %s in class %s not found.', $pMethod, get_class($pController)));
            } else {
                $callable = array($pController, $pMethod);
            }
        } elseif (is_callable($pMethod)) {
            $callable = $pMethod;
        }

        if ($callable) {
            try {
                return $this->send(call_user_func_array($callable, $pArguments));
            } catch (\Exception $e) {
                return $this->sendException($e);
            }
        }
    }

    /**
     * Describe a route or the whole controller with all routes.
     *
     * @param  string  $pUri
     * @param  boolean $pOnlyRoutes
     * @return array
     */
    public function describe($pUri = null, $pOnlyRoutes = false)
    {
        $definition = array();

        if (!$pOnlyRoutes) {
            $definition['parameters'] = array(
                '_method' => array('description' => 'Can be used as HTTP METHOD if the client does not support HTTP methods.', 'type' => 'string',
                                   'values' => 'GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH'),
                '_suppress_status_code' => array('description' => 'Suppress the HTTP status code.', 'type' => 'boolean', 'values' => '1, 0')
            );
        }

        $definition['controller'] = array(
            'entryPoint' => $this->getTriggerUrl()
        );

        foreach ($this->routes as $routeUri => $routeMethods) {

            $matches = array();
            if (!$pUri || ($pUri && preg_match('|^'.$routeUri.'$|', $pUri, $matches))) {

                if ($matches) {
                    array_shift($matches);
                }
                $def = array();
                $def['uri'] = $this->getTriggerUrl().'/'.$routeUri;

                foreach ($routeMethods as $method => $phpMethod) {

                    if (is_string($phpMethod)) {
                        $ref = new \ReflectionClass($this->controller);
                        $refMethod = $ref->getMethod($phpMethod);
                    } else {
                        $refMethod = new \ReflectionFunction($phpMethod);
                    }

                    $def['methods'][strtoupper($method)] = $this->getMethodMetaData($refMethod, $matches);

                }
                $definition['controller']['routes'][$routeUri] = $def;
            }
        }

        if (!$pUri) {
            foreach ($this->controllers as $controller) {
                $definition['subController'][$controller->getTriggerUrl()] = $controller->describe(false, true);
            }
        }

        return $definition;
    }

    /**
     * Fetches all meta data informations as params, return type etc.
     *
     * @param  \ReflectionMethod $pMethod
     * @param  array             $pRegMatches
     * @return array
     */
    public function getMethodMetaData(\ReflectionFunctionAbstract $pMethod, $pRegMatches = null)
    {
        $file = $pMethod->getFileName();
        $startLine = $pMethod->getStartLine();

        $fh = fopen($file, 'r');
        if (!$fh) return false;

        $lineNr = 1;
        $lines = array();
        while (($buffer = fgets($fh)) !== false) {
            if ($lineNr == $startLine) break;
            $lines[$lineNr] = $buffer;
            $lineNr++;
        }
        fclose($fh);

        $phpDoc = '';
        $blockStarted = false;
        while ($line = array_pop($lines)) {

            if ($blockStarted) {
                $phpDoc = $line.$phpDoc;

                //if start comment block: /*
                if (preg_match('/\s*\t*\/\*/', $line)) {
                    break;
                }
                continue;
            } else {
                //we are not in a comment block.
                //if class def, array def or close bracked from fn comes above
                //then we dont have phpdoc
                if (preg_match('/^\s*\t*[a-zA-Z_&\s]*(\$|{|})/', $line)) {
                    break;
                }
            }

            $trimmed = trim($line);
            if ($trimmed == '') continue;

            //if end comment block: */
            if (preg_match('/\*\//', $line)) {
                $phpDoc = $line.$phpDoc;
                $blockStarted = true;
                //one line php doc?
                if (preg_match('/\s*\t*\/\*/', $line)) {
                    break;
                }
            }
        }

        $phpDoc = $this->parsePhpDoc($phpDoc);

        $refParams = $pMethod->getParameters();
        $params = array();

        $fillPhpDocParam = !isset($phpDoc['param']);

        foreach ($refParams as $param) {
            $params[$param->getName()] = $param;
            if ($fillPhpDocParam) {
                $phpDoc['param'][] = array(
                    'name' => $param->getName(),
                    'type' => $param->isArray()?'array':'mixed'
                );
            }
        }

        $parameters = array();

        if (isset($phpDoc['param'])) {
            if (is_array($phpDoc['param']) && is_string(key($phpDoc['param'])))
                $phpDoc['param'] = array($phpDoc['param']);

            $c = 0;
            foreach ($phpDoc['param'] as $phpDocParam) {

                $param = $params[$phpDocParam['name']];
                if (!$param) continue;
                $parameter = array(
                    'type' => $phpDocParam['type']
                );

                if ($pRegMatches && is_array($pRegMatches) && $pRegMatches[$c]) {
                    $parameter['fromRegex'] = '$'.($c+1);
                }

                $parameter['required'] = !$param->isOptional();

                if ($param->isDefaultValueAvailable()) {
                    $parameter['default'] = str_replace(array("\n", ' '), '', var_export($param->getDefaultValue(), true));
                }
                $parameters[$this->argumentName($phpDocParam['name'])] = $parameter;
                $c++;
            }
        }

        if (!isset($phpDoc['return']))
            $phpDoc['return'] = array('type' => 'mixed');

        $result = array(
            'parameters' => $parameters,
            'return' => $phpDoc['return']
        );

        if (isset($phpDoc['description']))
            $result['description'] = $phpDoc['description'];

        if (isset($phpDoc['url']))
            $result['url'] = $phpDoc['url'];

        return $result;
    }

    /**
     * Parse phpDoc string and returns an array.
     *
     * @param  string $pString
     * @return array
     */
    public function parsePhpDoc($pString)
    {
        preg_match('#^/\*\*(.*)\*/#s', trim($pString), $comment);

        if (0 === count($comment)) return array();

        $comment = trim($comment[1]);

        preg_match_all('/^\s*\*(.*)/m', $comment, $lines);
        $lines = $lines[1];

        $tags = array();
        $currentTag = '';
        $currentData = '';

        foreach ($lines as $line) {
            $line = trim($line);

            if (substr($line, 0, 1) == '@') {

                if ($currentTag)
                    $tags[$currentTag][] = $currentData;
                else
                    $tags['description'] = $currentData;

                $currentData = '';
                preg_match('/@([a-zA-Z_]*)/', $line, $match);
                $currentTag = $match[1];
            }

            $currentData = trim($currentData.' '.$line);

        }
        if ($currentTag)
            $tags[$currentTag][] = $currentData;
        else
            $tags['description'] = $currentData;

        //parse tags
        $regex = array(
            'param' => array('/^@param\s*\t*([a-zA-Z_\\\[\]]*)\s*\t*\$([a-zA-Z_]*)\s*\t*(.*)/', array('type', 'name', 'description')),
            'url' => array('/^@url\s*\t*(.+)/', array('url')),
            'return' => array('/^@return\s*\t*([a-zA-Z_\\\[\]]*)\s*\t*(.*)/', array('type', 'description')),
        );
        foreach ($tags as $tag => &$data) {
            if ($tag == 'description') continue;
            foreach ($data as &$item) {
                if ($regex[$tag]) {
                    preg_match($regex[$tag][0], $item, $match);
                    $item = array();
                    $c = count($match);
                    for ($i =1; $i < $c; $i++) {
                        if ($regex[$tag][1][$i-1]) {
                            $item[$regex[$tag][1][$i-1]] = $match[$i];
                        }
                    }
                }
            }
            if (count($data) == 1)
                $data = $data[0];
        }

        return $tags;
    }

    /**
     * If the name is a camelcased one whereas the first char is lowercased,
     * then we remove the first char and set first char to lower case.
     *
     * @param  string $pName
     * @return string
     */
    public function argumentName($pName)
    {
        if (ctype_lower(substr($pName, 0, 1)) && ctype_upper(substr($pName, 1, 1))) {
            return strtolower(substr($pName, 1, 1)).substr($pName, 2);
        } return $pName;
    }

    /**
     * Find and return the route for $pUri.
     *
     * @param  string        $pUri
     * @param  string        $pMethod limit to method.
     * @return array|boolean
     */
    public function findRoute($pUri, $pMethod = '_all_')
    {
        if (isset($this->routes[$pUri][$pMethod]) && $method = $this->routes[$pUri][$pMethod]) {
            return array($method, null, $pMethod, $pUri);
        } elseif ($pMethod != '_all_' && isset($this->routes[$pUri]['_all_']) && $method = $this->routes[$pUri]['_all_']) {
            return array($method, null, $pMethod, $pUri);
        } else {
            //maybe we have a regex uri

            foreach ($this->routes as $routeUri => $routeMethods) {

                if (preg_match('|^'.$routeUri.'$|', $pUri, $matches)) {                

                    if (!isset($routeMethods[$pMethod])) {
                        if (isset($routeMethods['_all_']))
                            $pMethod = '_all_';
                        else
                            continue;
                    }

                    array_shift($matches);
                    foreach ($matches as $match) {
                        $arguments[] = $match;
                    }

                    return array($routeMethods[$pMethod], $arguments, $pMethod, $routeUri);
                }
            }
        }

        return false;
    }

}