Passed
Push — master ( 6215ec...1255dc )
by Darío
01:47
created

Application::getRouter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
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
     * Base path for the application
24
     *
25
     * @var string
26
     */
27
    protected $basePath;
28
29
    /**
30
     * Module path
31
     *
32
     * The path where all modules are located.
33
     *
34
     * @var string
35
     */
36
    protected $modulePath;
37
38
    /**
39
     * List of modules available
40
     *
41
     * Each module in this list must be a folder inside $modulePath
42
     *
43
     * @var array
44
     */
45
    private $modules;
46
47
    /**
48
     * The router instance
49
     *
50
     * @var Router
51
     */
52
    private $router;
53
54
    /**
55
     * Development or production mode
56
     *
57
     * @var boolean
58
     */
59
    private $devMode;
60
61
    /**
62
     * Returns the modulePath attribute
63
     *
64
     * @return string
65
     */
66
    public function getModulePath()
67
    {
68
        return $this->modulePath;
69
    }
70
71
    /**
72
     * Returns the modules available
73
     *
74
     * @return array
75
     */
76
    public function getModules()
77
    {
78
        return $this->modules;
79
    }
80
81
    /**
82
     * Returns the router instance
83
     *
84
     * @return Router
85
     */
86
    public function getRouter()
87
    {
88
        return $this->router;
89
    }
90
91
    /**
92
     * Constructor
93
     *
94
     * @param array $config
95
     *
96
     * @throws \InvalidArgumentException
97
     * @throws \RuntimeException
98
     */
99
    public function __construct(Array $config)
100
    {
101
        # start sessions
102
        if (!isset($_SESSION))
103
            session_start();
104
105
        if (!array_key_exists('environment', $config))
106
            throw new \InvalidArgumentException("The 'environment' key was not defined");
107
108
        if (!array_key_exists('dev_mode', $config['environment']))
109
            throw new \InvalidArgumentException("The 'dev_mode' key was not defined");
110
111
        $this->devMode = $config["environment"]["dev_mode"];
112
113
        if (!array_key_exists('modules', $config))
114
            throw new \InvalidArgumentException("The 'modules' key was not defined");
115
116
        $this->modules = $config["modules"];
117
118
        # setting module path
119
        $this->modulePath = (!array_key_exists('module_path', $config['environment']))
120
            ? 'module'
121
            : $config['environment']['module_path'];
122
123
        #  setting development or production environment
124
        if ($this->devMode)
125
        {
126
            ini_set('display_errors', 1);
127
            error_reporting(-1);
128
        }
129
        else
130
        {
131
            ini_set('display_errors', 0);
132
            error_reporting(0);
133
        }
134
135
        if (!array_key_exists('router', $config))
136
            throw new \InvalidArgumentException("The 'router' key was not defined");
137
138
        if (!array_key_exists('routes', $config["router"]))
139
            throw new \InvalidArgumentException("The 'routes' key was not defined");
140
141
        $this->router = new Router($config["router"]["routes"]);
142
143
        if (!array_key_exists('base_path', $config['environment']))
144
            throw new \InvalidArgumentException("The 'base_path' key was not defined");
145
146
        $this->basePath = $config["environment"]["base_path"];
147
148
        # load routes from config
149
        foreach ($config["router"]["routes"] as $name => $route)
150
        {
151
            if ($route instanceof \Zend\Router\Http\RouteInterface)
152
                $this->router->addZendRoute($name, $route);
153
            else
154
                $this->router->addRoute($route);
155
        }
156
157
        # register autoloading functions for each module
158
        foreach ($this->modules as $module)
159
        {
160
            \Drone\Loader\ClassMap::$path = $this->basePath .
161
                DIRECTORY_SEPARATOR . $this->modulePath .
162
                DIRECTORY_SEPARATOR . $module .
163
                DIRECTORY_SEPARATOR . 'source';
164
165
            spl_autoload_register("Drone\Loader\ClassMap::autoload");
166
        }
167
168
        # load routes from each module
169
        foreach ($this->modules as $module)
170
        {
171
            if (file_exists($this->modulePath . "/$module/config/module.config.php"))
172
            {
173
                $module_config_file = require($this->modulePath . "/$module/config/module.config.php");
174
175
                if (!array_key_exists('router', $module_config_file))
176
                    throw new \RuntimeException("The 'router' key was not defined in the config file for module '$module'");
177
178
                if (!array_key_exists('routes', $module_config_file["router"]))
179
                    throw new \RuntimeException("The 'routes' key was not defined in the config file for module '$module'");
180
181
                $this->getRouter()->addRoute($module_config_file["router"]["routes"]);
182
            }
183
        }
184
    }
185
186
    /**
187
     * Runs the application
188
     *
189
     * @return null
190
     */
191
    public function run()
192
    {
193
        $module     = isset($_GET["module"])     ? $_GET["module"]     : null;
194
        $controller = isset($_GET["controller"]) ? $_GET["controller"] : null;
195
        $view       = isset($_GET["view"])       ? $_GET["view"]       : null;
196
197
        $request = new  \Zend\Http\Request();
198
199
        # build URI
200
        $uri = '';
201
        $uri .= !empty($module)     ? '/' . $module : "";
202
        $uri .= !empty($controller) ? '/' . $controller : "";
203
        $uri .= !empty($view)       ? '/' . $view : "";
204
205
        if (empty($uri))
206
            $uri = "/";
207
208
        $request->setUri($uri);
209
210
        $match = $this->router->getZendRouter()->match($request);
211
212
        if (!is_null($match))
213
        {
214
            $params = $match->getParams();
215
            $parts  = explode("\\", $params["controller"]);
216
217
            $module     = $parts[0];
218
            $controller = $parts[2];
219
            $view       = $params["action"];
220
221
            $this->router->setIdentifiers($module, $controller, $view);
222
        }
223
        else
224
            $this->router->setIdentifiers($module, $controller, $view);
225
226
        $this->router->match();
227
228
        $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...
229
            "config"  => $this->basePath .
230
                DIRECTORY_SEPARATOR . $this->modulePath .
231
                DIRECTORY_SEPARATOR . $module .
232
                DIRECTORY_SEPARATOR . 'config/module.config.php'
233
        ]));
234
235
        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

235
        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...
236
        {
237
            $result = $this->router->run();
238
239
            if ($result instanceof View)
240
            {
241
                $result->setPath($this->basePath . DIRECTORY_SEPARATOR . $this->modulePath . DIRECTORY_SEPARATOR . 'source/view');
242
243
                if (is_null($result->getName()))
0 ignored issues
show
introduced by
The condition is_null($result->getName()) is always false.
Loading history...
244
                    $result->setView($router->getController()->getMethod());
245
246
                $result->render();
247
            }
248
        }
249
    }
250
}