Passed
Push — master ( 40eec0...6215ec )
by Darío
02:02
created

Application::run()   D

Complexity

Conditions 10
Paths 512

Size

Total Lines 46
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 29
nc 512
nop 0
dl 0
loc 46
rs 4.1777
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * DronePHP (http://www.dronephp.com)
4
 *
5
 * @link      http://github.com/Pleets/DronePHP
6
 * @copyright Copyright (c) 2016-2018 Pleets. (http://www.pleets.org)
7
 * @license   http://www.dronephp.com/license
8
 * @author    Darío Rivera <[email protected]>
9
 */
10
11
namespace Drone\Mvc;
12
13
use Drone\FileSystem\Shell;
14
15
/**
16
 * Application class
17
 *
18
 * This is the main class for mvc pattern
19
 */
20
class Application
21
{
22
    /**
23
     * Module path
24
     *
25
     * The path where all modules are located.
26
     *
27
     * @var string
28
     */
29
    protected $modulePath;
30
31
    /**
32
     * List of modules available
33
     *
34
     * Each module in this list must be a folder inside $modulePath
35
     *
36
     * @var array
37
     */
38
    private $modules;
39
40
    /**
41
     * The router instance
42
     *
43
     * @var Router
44
     */
45
    private $router;
46
47
    /**
48
     * Development or production mode
49
     *
50
     * @var boolean
51
     */
52
    private $devMode;
53
54
    /**
55
     * Returns the modulePath attribute
56
     *
57
     * @return string
58
     */
59
    public function getModulePath()
60
    {
61
        return $this->modulePath;
62
    }
63
64
    /**
65
     * Returns the modules available
66
     *
67
     * @return array
68
     */
69
    public function getModules()
70
    {
71
        return $this->modules;
72
    }
73
74
    /**
75
     * Returns the router instance
76
     *
77
     * @return Router
78
     */
79
    public function getRouter()
80
    {
81
        return $this->router;
82
    }
83
84
    /**
85
     * Constructor
86
     *
87
     * @param array $config
88
     *
89
     * @throws \InvalidArgumentException
90
     * @throws \RuntimeException
91
     */
92
    public function __construct(Array $config)
93
    {
94
        # start sessions
95
        if (!isset($_SESSION))
96
            session_start();
97
98
        if (!array_key_exists('environment', $config))
99
            throw new \InvalidArgumentException("The 'environment' key was not defined");
100
101
        if (!array_key_exists('dev_mode', $config['environment']))
102
            throw new \InvalidArgumentException("The 'dev_mode' key was not defined");
103
104
        $this->devMode = $config["environment"]["dev_mode"];
105
106
        if (!array_key_exists('modules', $config))
107
            throw new \InvalidArgumentException("The 'modules' key was not defined");
108
109
        $this->modules = $config["modules"];
110
111
        # setting module path
112
        $this->modulePath = (!array_key_exists('module_path', $config['environment']))
113
            ? 'module'
114
            : $config['environment']['module_path'];
115
116
        #  setting development or production environment
117
        if ($this->devMode)
118
        {
119
            ini_set('display_errors', 1);
120
            error_reporting(-1);
121
        }
122
        else
123
        {
124
            ini_set('display_errors', 0);
125
            error_reporting(0);
126
        }
127
128
        # register autoloading functions for each module
129
        $this->autoload($this->modules);
130
131
        if (!array_key_exists('router', $config))
132
            throw new \InvalidArgumentException("The 'router' key was not defined");
133
134
        if (!array_key_exists('routes', $config["router"]))
135
            throw new \InvalidArgumentException("The 'routes' key was not defined");
136
137
        $this->router = new Router($config["router"]["routes"]);
138
139
        if (!array_key_exists('base_path', $config['environment']))
140
            throw new \InvalidArgumentException("The 'base_path' key was not defined");
141
142
        $this->router->setBasePath($config["environment"]["base_path"]);
0 ignored issues
show
Bug introduced by
The method setBasePath() does not exist on Drone\Mvc\Router. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

142
        $this->router->/** @scrutinizer ignore-call */ 
143
                       setBasePath($config["environment"]["base_path"]);

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...
143
144
        # load routes from config
145
        foreach ($config["router"]["routes"] as $name => $route)
146
        {
147
            if ($route instanceof \Zend\Router\Http\RouteInterface)
148
                $this->getRouter()->addZendRoute($name, $route);
149
            else
150
                $this->getRouter()->addRoute($route);
151
        }
152
153
        # load routes from each module
154
        foreach ($this->modules as $module)
155
        {
156
            if (file_exists($this->modulePath . "/$module/config/module.config.php"))
157
            {
158
                $module_config_file = require($this->modulePath . "/$module/config/module.config.php");
159
160
                if (!array_key_exists('router', $module_config_file))
161
                    throw new \RuntimeException("The 'router' key was not defined in the config file for module '$module'");
162
163
                if (!array_key_exists('routes', $module_config_file["router"]))
164
                    throw new \RuntimeException("The 'routes' key was not defined in the config file for module '$module'");
165
166
                $this->getRouter()->addRoute($module_config_file["router"]["routes"]);
167
            }
168
        }
169
    }
170
171
    /**
172
     * Loads module classes and autoloading functions
173
     *
174
     * Each module must have a Module.php inside them. The goal of this file is register an autoloading function
175
     * to load all its controller and model classes.
176
     *
177
     * @param array $modules
178
     *
179
     * @throws RuntimeException
180
     *
181
     * @return null
182
     */
183
    private function autoload(Array $modules)
184
    {
185
        if (count($modules))
186
        {
187
            foreach ($modules as $module)
188
            {
189
                /*
190
                 *  This instruction includes each module declared.
191
                 *  Each module has an autoloader to load its classes (controllers and models)
192
                 */
193
                if (file_exists($this->modulePath ."/". $module."/Module.php"))
194
                    include($this->modulePath ."/". $module."/Module.php");
195
196
                spl_autoload_register($module . "\Module::loader");
197
            }
198
        }
199
        else
200
            throw new \RuntimeException("The application must have at least one module");
201
    }
202
203
    /**
204
     * Runs the application
205
     *
206
     * @return null
207
     */
208
    public function run()
209
    {
210
        $module     = isset($_GET["module"])     ? $_GET["module"] : null;
211
        $controller = isset($_GET["controller"]) ? $_GET["controller"] : null;
212
        $view       = isset($_GET["view"])       ? $_GET["view"] : null;
213
214
        $request = new  \Zend\Http\Request();
215
216
        # build URI
217
        $uri = '';
218
        $uri .= !empty($module)     ? '/' . $module : "";
219
        $uri .= !empty($controller) ? '/' . $controller : "";
220
        $uri .= !empty($view)       ? '/' . $view : "";
221
222
        if (empty($uri))
223
            $uri = "/";
224
225
        $request->setUri($uri);
226
227
        $match = $this->router->getZendRouter()->match($request);
228
229
        if (!is_null($match))
230
        {
231
            $params = $match->getParams();
232
            $parts  = explode("\\", $params["controller"]);
233
234
            $module     = $parts[0];
235
            $controller = $parts[2];
236
            $view       = $params["action"];
237
238
            $this->router->setIdentifiers($module, $controller, $view);
239
        }
240
        else
241
            $this->router->setIdentifiers($module, $controller, $view);
242
243
        $this->router->match();
244
245
        $this->controller->setModule(ModuleFactory::create($module, [
0 ignored issues
show
Bug introduced by
Are you sure the usage of Drone\Mvc\ModuleFactory:...ig/module.config.php')) targeting Drone\Mvc\ModuleFactory::create() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug Best Practice introduced by
The property controller does not exist on Drone\Mvc\Application. Did you maybe forget to declare it?
Loading history...
246
            "path"    => $this->modulePath,
247
            "classes" => 'source',
248
            "views"   => 'source/view',
249
            "config"  => 'config/module.config.php'
250
        ]));
251
252
        if ($this->getController()->getModule()->executionIsAllowed())
0 ignored issues
show
Bug introduced by
The method getController() does not exist on Drone\Mvc\Application. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

252
        if ($this->/** @scrutinizer ignore-call */ getController()->getModule()->executionIsAllowed())

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...
253
            $this->router->run();
254
    }
255
}