1 <?php
2
3 /*
4 * This file is part of the ICanBoogie package.
5 *
6 * (c) Olivier Laviale <olivier.laviale@gmail.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace ICanBoogie\HTTP;
13
14 /**
15 * Patchable helpers of the HTTP package.
16 *
17 * The following helpers can be patched:
18 *
19 * - {@link dispatch}
20 * - {@link get_dispatcher}
21 */
22 class Helpers
23 {
24 static private $jumptable = array
25 (
26 'dispatch' => array(__CLASS__, 'dispatch'),
27 'get_dispatcher' => array(__CLASS__, 'get_dispatcher'),
28 'get_initial_request' => array(__CLASS__, 'get_initial_request')
29 );
30
31 /**
32 * Calls the callback of a patchable function.
33 *
34 * @param string $name Name of the function.
35 * @param array $arguments Arguments.
36 *
37 * @return mixed
38 */
39 static public function __callstatic($name, array $arguments)
40 {
41 return call_user_func_array(self::$jumptable[$name], $arguments);
42 }
43
44 /**
45 * Patches a patchable function.
46 *
47 * @param string $name Name of the function.
48 * @param collable $callback Callback.
49 *
50 * @throws \RuntimeException in attempt to patch an undefined function.
51 */
52 static public function patch($name, $callback)
53 {
54 if (empty(self::$jumptable[$name]))
55 {
56 throw new \RuntimeException("Undefined patchable: $name.");
57 }
58
59 self::$jumptable[$name] = $callback;
60 }
61
62 /*
63 * Fallbacks
64 */
65
66 /**
67 * Fallback for the {@link get_dispatcher()} function.
68 */
69 static private function get_dispatcher()
70 {
71 static $dispatcher;
72
73 if (!$dispatcher)
74 {
75 $dispatcher = new Dispatcher;
76 }
77
78 return $dispatcher;
79 }
80
81 /**
82 * Fallback for the {@link dispatch()} function.
83 */
84 static private function dispatch(Request $request)
85 {
86 $dispatcher = get_dispatcher();
87
88 return $dispatcher($request);
89 }
90
91 /**
92 * Fallback for the {@link get_initial_request()} function.
93 */
94 static private function get_initial_request()
95 {
96 static $request;
97
98 if (!$request)
99 {
100 $request = Request::from($_SERVER);
101 }
102
103 return $request;
104 }
105 }
106
107 /**
108 * Dispatches a request.
109 *
110 * @param Request $request
111 *
112 * @return Response
113 */
114 function dispatch(Request $request)
115 {
116 return Helpers::dispatch($request);
117 }
118
119 /**
120 * Returns shared request dispatcher.
121 *
122 * @return Dispatcher
123 */
124 function get_dispatcher()
125 {
126 return Helpers::get_dispatcher();
127 }
128
129 /**
130 * Returns the initial request.
131 *
132 * The initial request is created once from the `$_SERVER` array.
133 *
134 * @return Request
135 */
136 function get_initial_request()
137 {
138 return Helpers::get_initial_request();
139 }