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 = [
25
26 'dispatch' => [ __CLASS__, 'dispatch' ],
27 'get_dispatcher' => [ __CLASS__, 'get_dispatcher' ],
28 'get_initial_request' => [ __CLASS__, 'get_initial_request' ]
29
30 ];
31
32 /**
33 * Calls the callback of a patchable function.
34 *
35 * @param string $name Name of the function.
36 * @param array $arguments Arguments.
37 *
38 * @return mixed
39 */
40 static public function __callStatic($name, array $arguments)
41 {
42 return call_user_func_array(self::$jumptable[$name], $arguments);
43 }
44
45 /**
46 * Patches a patchable function.
47 *
48 * @param string $name Name of the function.
49 * @param callable $callback Callback.
50 *
51 * @return callable Previous callable.
52 *
53 * @throws \LogicException in attempt to patch an undefined function.
54 */
55 static public function patch($name, $callback)
56 {
57 if (empty(self::$jumptable[$name]))
58 {
59 throw new \LogicException("Undefined patchable: $name.");
60 }
61
62 $previous = self::$jumptable[$name];
63
64 self::$jumptable[$name] = $callback;
65
66 return $previous;
67 }
68
69 /*
70 * Fallbacks
71 */
72
73 /**
74 * Fallback for the {@link get_dispatcher()} function.
75 */
76 static private function get_dispatcher()
77 {
78 static $dispatcher;
79
80 if (!$dispatcher)
81 {
82 $dispatcher = new Dispatcher;
83 }
84
85 return $dispatcher;
86 }
87
88 /**
89 * Fallback for the {@link dispatch()} function.
90 *
91 * @param Request $request
92 */
93 static private function dispatch(Request $request)
94 {
95 $dispatcher = get_dispatcher();
96
97 return $dispatcher($request);
98 }
99
100 /**
101 * Fallback for the {@link get_initial_request()} function.
102 */
103 static private function get_initial_request()
104 {
105 static $request;
106
107 if (!$request)
108 {
109 $request = Request::from($_SERVER);
110 }
111
112 return $request;
113 }
114 }
115