Completed
Push — 4.0 ( 866ac0...53586d )
by Marco
10:57
created

Dispatcher::pathGetAbsolute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 2
nc 1
nop 0
1
<?php namespace Comodojo\Dispatcher;
2
3
use \Monolog\Logger;
4
use \Comodojo\Dispatcher\Components\Configuration;
5
use \Comodojo\Dispatcher\Request\Model as Request;
6
use \Comodojo\Dispatcher\Router\Collector as RouteCollector;
7
use \Comodojo\Dispatcher\Routes\RoutingTable;
8
use \Comodojo\Dispatcher\Response\Model as Response;
9
use \Comodojo\Dispatcher\Extra\Model as Extra;
10
use \Comodojo\Dispatcher\Components\Timestamp as TimestampTrait;
11
use \Comodojo\Dispatcher\Output\Processor;
12
use \Comodojo\Dispatcher\Events\DispatcherEvent;
13
use \Comodojo\Dispatcher\Events\ServiceEvent;
14
use \Comodojo\Dispatcher\Router\RoutingTableInterface;
15
use \Comodojo\Dispatcher\Log\DispatcherLogger;
16
use \Comodojo\Dispatcher\Cache\DispatcherCache;
17
use \Comodojo\Cache\CacheManager;
18
use \League\Event\Emitter;
19
use \Comodojo\Exception\DispatcherException;
20
use \Exception;
21
22
/**
23
 * @package     Comodojo Dispatcher
24
 * @author      Marco Giovinazzi <[email protected]>
25
 * @author      Marco Castiello <[email protected]>
26
 * @license     GPL-3.0+
27
 *
28
 * LICENSE:
29
 *
30
 * This program is free software: you can redistribute it and/or modify
31
 * it under the terms of the GNU Affero General Public License as
32
 * published by the Free Software Foundation, either version 3 of the
33
 * License, or (at your option) any later version.
34
 *
35
 * This program is distributed in the hope that it will be useful,
36
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
37
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
38
 * GNU Affero General Public License for more details.
39
 *
40
 * You should have received a copy of the GNU Affero General Public License
41
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
42
 */
43
44
class Dispatcher {
45
46
    use TimestampTrait;
47
48
    private $configuration;
49
50
    private $request;
51
52
    private $router;
53
54
    private $table;
55
56
    private $response;
57
58
    private $extra;
59
60
    private $logger;
61
62
    private $cache;
63
64
    private $events;
65
66
    public function __construct(
67
        $configuration = array(),
68
        Emitter $emitter = null,
69
        CacheManager $cache = null,
70
        Logger $logger = null
71
    ) {
72
73
        ob_start();
74
75
        $this->setTimestamp();
76
77
        $this->extra = new Extra($this->logger);
0 ignored issues
show
Unused Code introduced by
The call to Model::__construct() has too many arguments starting with $this->logger.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
78
79
        $this->configuration = new Configuration($this->getDefaultConfiguration());
80
81
        $this->configuration->merge($configuration);
82
83
        $this->events = is_null($emitter) ? new Emitter() : $emitter;
84
85
        $this->logger = is_null($logger) ? DispatcherLogger::create($this->configuration) : $logger;
86
87
        $this->cache = is_null($cache) ? DispatcherCache::create($this->configuration, $this->logger) : $cache;
88
89
        $this->request = new Request($this->configuration, $this->logger);
90
91
        $this->table = new RoutingTable();
92
93
        $this->router = new RouteCollector($this->table, $this->configuration, $this->logger, $this->cache, $this->extra);
94
95
        $this->response = new Response($this->configuration, $this->logger);
96
97
    }
98
99
    public function configuration() {
100
101
        return $this->configuration;
102
103
    }
104
105
    public function events() {
106
107
        return $this->events;
108
109
    }
110
111
    public function cache() {
112
113
        return $this->cache;
114
115
    }
116
117
    public function request() {
118
119
        return $this->request;
120
121
    }
122
123
    public function table() {
124
125
        return $this->table;
126
127
    }
128
129
    public function router() {
130
131
        return $this->router;
132
133
    }
134
135
    public function response() {
136
137
        return $this->response;
138
139
    }
140
141
    public function extra() {
142
143
        return $this->extra;
144
145
    }
146
147
    public function dispatch() {
148
149
        $this->events->emit( new DispatcherEvent($this) );
150
151
        if ( $this->configuration()->get('dispatcher-enabled') === false ) {
152
153
            $status = $this->configuration()->get('dispatcher-disabled-status');
154
155
            $content = $this->configuration()->get('dispatcher-disabled-message');
156
157
            $this->response()->status()->set($status);
158
159
            $this->response()->content()->set($content);
160
161
            return $this->shutdown();
162
163
        }
164
165
        $this->events->emit( $this->emitServiceSpecializedEvents('dispatcher.request') );
166
167
        $this->events->emit( $this->emitServiceSpecializedEvents('dispatcher.request.'.$this->request->method()->get()) );
168
169
        $this->events->emit( $this->emitServiceSpecializedEvents('dispatcher.request.#') );
170
171
        try {
172
173
            $this->router->route($this->request);
174
175
        } catch (DispatcherException $de) {
176
177
            $this->response()->status()->set( $de->getStatus() );
0 ignored issues
show
Bug introduced by
The method getStatus() does not seem to exist on object<Comodojo\Exception\DispatcherException>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
178
179
            $this->response()->content()->set( $de->getMessage() );
180
181
            return $this->shutdown();
182
183
        }
184
185
        $this->events->emit( $this->emitServiceSpecializedEvents('dispatcher.route') );
186
187
        $this->events->emit( $this->emitServiceSpecializedEvents('dispatcher.route.'.$this->router->getType()) );
188
189
        $this->events->emit( $this->emitServiceSpecializedEvents('dispatcher.route.'.$this->router->getService()) );
190
191
        $this->events->emit( $this->emitServiceSpecializedEvents('dispatcher.route.#') );
192
193
        // translate route to service
194
195
        try {
196
197
            $this->router->compose($this->response);
198
199
        } catch (DispatcherException $de) {
200
201
            $this->response()->status()->set( $de->getStatus() );
0 ignored issues
show
Bug introduced by
The method getStatus() does not seem to exist on object<Comodojo\Exception\DispatcherException>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
202
203
            $this->response()->content()->set( $de->getMessage() );
204
205
        }
206
207
        return $this->shutdown();
208
209
    }
210
211
    private function emitServiceSpecializedEvents($name) {
212
213
        return new ServiceEvent(
214
            $name,
215
            $this->logger,
216
            $this->request,
217
            $this->router,
218
            $this->response,
219
            $this->extra
220
        );
221
222
    }
223
224
    private function shutdown() {
225
226
        $this->events->emit( $this->emitServiceSpecializedEvents('dispatcher.response') );
227
228
        $this->events->emit( $this->emitServiceSpecializedEvents('dispatcher.response.'.$this->response->status()->get()) );
229
230
        $this->events->emit( $this->emitServiceSpecializedEvents('dispatcher.response.#') );
231
232
        $return = Processor::parse($this->configuration, $this->logger, $this->response);
233
234
        ob_end_clean();
235
236
        return $return;
237
238
    }
239
240
    private function getDefaultConfiguration() {
241
242
        return array(
243
            'dispatcher-enabled' => true,
244
            'dispatcher-disabled-status' => 503,
245
            'dispatcher-disabled-message' => 'Dispatcher offline',
246
            'dispatcher-log-name' => 'dispatcher',
247
            'dispatcher-log-enabled' => false,
248
            'dispatcher-log-level' => 'INFO',
249
            'dispatcher-log-target' => '%dispatcher-log-folder%/dispatcher.log',
250
            'dispatcher-log-folder' => '/log',
251
            'dispatcher-supported-methods' => array('GET','PUT','POST','DELETE','OPTIONS','HEAD'),
252
            'dispatcher-default-encoding' => 'UTF-8',
253
            'dispatcher-cache-enabled' => true,
254
            'dispatcher-cache-ttl' => 3600,
255
            'dispatcher-cache-folder' => '/cache',
256
            'dispatcher-cache-algorithm'  => 'PICK_FIRST',
257
            // should we implement this?
258
            //'dispatcher-autoroute' => false,
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
259
            'dispatcher-base-url' => self::urlGetAbsolute(),
260
            'dispatcher-real-path' => self::pathGetAbsolute()
261
        );
262
263
    }
264
265
    private static function urlGetAbsolute() {
0 ignored issues
show
Coding Style introduced by
urlGetAbsolute uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
266
267
        $http = 'http' . ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 's' : '') . '://';
268
269
        $uri = preg_replace("/\/index.php(.*?)$/i", "", $_SERVER['PHP_SELF']);
270
271
        return ( $http . $_SERVER['HTTP_HOST'] . $uri . "/" );
272
273
    }
274
275
    private static function pathGetAbsolute() {
276
277
        return realpath(dirname(__FILE__)."/../../../../")."/";
278
279
    }
280
281
}
282