Completed
Push — master ( d33e41...a89c3c )
by Nikita
02:12
created

Application::getModuleList()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
namespace samsoncms\cms;
3
4
use samson\core\CompressableExternalModule;
5
use samson\core\SamsonLocale;
6
use samsonphp\compressor\Compressor;
7
use samsonphp\event\Event;
8
use samsonphp\resource\Router;
9
use samsonphp\router\Module;
10
11
/**
12
 * SamsonCMS external compressible application for integrating
13
 * @author Vitaly Iegorov <[email protected]>
14
 */
15
class Application extends CompressableExternalModule
0 ignored issues
show
Deprecated Code introduced by
The class samson\core\CompressableExternalModule has been deprecated with message: Just implement samsonframework\core\CompressInterface

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
16
{
17
    const EVENT_IS_CMS = 'samsonsms.is.cms';
18
19
    /** @var string Module identifier */
20
    public $id = 'cms';
21
22
    public $baseUrl = 'cms';
23
24
    /** @var array Collection of SamsonCMS related modules */
25
    protected $cmsModuleList = [];
26
27
    protected $projectModuleList = [];
28
29
    /** @var bool Flag that currently we are woring in SamsonCMS */
30
    protected $isCMS = false;
31
32
    protected $template = '';
33
34
    //[PHPCOMPRESSOR(remove,start)]
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
35
36
    protected function prepareModuleList()
37
    {
38
        // Gather all project specific modules that do not dependent to SamsonCMS
39
        $parentDependencies = [];
40
        foreach ($this->system->module_stack as $id => $module) {
0 ignored issues
show
Bug introduced by
Accessing module_stack on the interface samsonframework\core\SystemInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
41
            // Module dependency at project level composer.json and is not this module
42
            if (array_key_exists('projectRequireDev', $module->composerParameters) && $module->composerParameters['projectRequireDev'] === true && $id !== $this->id()) {
43
                $parentDependencies = array_merge($module->composerParameters['required'], [$module->composerParameters['composerName']], $parentDependencies);
44
            }
45
        }
46
        // Remove duplicates
47
        $parentDependencies = array_unique($parentDependencies);
48
49
        // Gather project-only related modules
50
        $this->projectModuleList = [];
51
        $this->cmsModuleList = $this->system->module_stack;
0 ignored issues
show
Bug introduced by
Accessing module_stack on the interface samsonframework\core\SystemInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
52
        foreach ($this->system->module_stack as $id => $module) {
0 ignored issues
show
Bug introduced by
Accessing module_stack on the interface samsonframework\core\SystemInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
53
            if (!array_key_exists('composerName', $module->composerParameters)) {
54
                $this->projectModuleList[$id] = $module;
55
            } elseif (array_key_exists('composerName', $module->composerParameters) && in_array($module->composerParameters['composerName'], $parentDependencies)) {
56
                $this->projectModuleList[$id] = $module;
57
            }
58
            if (!$this->isModuleDependent($module) && $id !== 'core' && !$this->ifModuleRelated($module)) {
59
                unset($this->cmsModuleList[$id]);
60
            }
61
        }
62
    }
63
64
    /**
65
     * Remove unnecessary modules list for SamsonCMS from loaded modules
66
     * and return left modules.
67
     *
68
     * @param array $otherModuleList List of SamsonCMS unneeded modules
69
     */
70
    public function filterModuleList(&$otherModuleList = [])
0 ignored issues
show
Coding Style introduced by
filterModuleList 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...
71
    {
72
        $this->prepareModuleList();
73
74
        $otherModuleList = $this->projectModuleList;
75
76
        /**
77
         * Change modules list between main web-application and SamsonCMS
78
         */
79
        // TODO: As this is processed before routing than we just check URL
80
        if ($this->isCMS() || strpos($_SERVER['REQUEST_URI'], '/'.$this->id.'/') !== false) {
81
            // Switch module list to SamsonCMS module list
82
            $otherModuleList = $this->cmsModuleList;
83
        }
84
    }
85
86
87
    /** SamsonCMS preparation stage handler */
88
    public function prepare()
89
    {
90
        /**
91
         * Subscribe for router resource initialization to remove SamsonCMS modules as we will generate
92
         * SamsonCMS resources manually
93
         */
94
        Event::subscribe(Router::EVENT_START_GENERATE_RESOURCES, [$this, 'filterModuleList']);
0 ignored issues
show
Deprecated Code introduced by
The constant samsonphp\resource\Route...TART_GENERATE_RESOURCES has been deprecated with message: Use E_MODULES

This class constant has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the constant will be removed from the class and what other constant to use instead.

Loading history...
95
    }
96
97
    /**
98
     * If module is dependent from current module through composer.json.
99
     *
100
     * @param $module Module for checking
101
     * @return bool True if module dependent
102
     */
103
    protected function isModuleDependent($module)
104
    {
105
        return isset($module->composerParameters['composerName']) && in_array($module->composerParameters['composerName'], $this->composerParameters['required']);
106
    }
107
108
    public function getModuleList(& $moduleListArray)
109
    {
110
        $this->prepareModuleList();
111
        $moduleListArray[Router::I_MAIN_PROJECT_TEMPLATE] = $this->projectModuleList;
112
        $moduleListArray[$this->template] = $this->cmsModuleList;
113
    }
114
115
    //[PHPCOMPRESSOR(remove,end)]
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
116
117
118
    /**
119
     * Check if passed module is related to SamsonCMS.
120
     * Also method stores data to flag variable.
121
     *
122
     * @param $module
123
     *
124
     * @return bool True if module related to SamsonCMS
125
     */
126
    public function ifModuleRelated($module)
127
    {
128
        // Analyze if module class or one of its parents has samsoncms\ namespace pattern
129
        return count(preg_grep('/samsoncms\\\\/i', array_merge(array(get_class($module)), class_parents($module))));
130
    }
131
132
    /**
133
     * SamsonCMS initialization stage handler
134
     *
135
     * @param array $params Initialization parameters
136
     *
137
     * @return bool Initialization stage result
138
     */
139
    public function init(array $params = array())
140
    {
141
        // Old applications main page rendering
142
        Event::subscribe('template.main.rendered', array($this, 'oldMainRenderer'));
143
144
        // Old applications menu rendering
145
        Event::subscribe('template.menu.rendered', array($this, 'oldMenuRenderer'));
146
147
        Event::subscribe('samson.url.build', array($this, 'buildUrl'));
148
149
        Event::subscribe('samson.url.args.created', array($this, 'parseUrl'));
150
151
        Event::subscribe(Module::EVENT_ROUTE_FOUND, array($this, 'activeModuleHandler'));
152
153
        Event::subscribe('samsonphp.router.create.module.routes', array($this, 'updateCMSPrefix'));
154
155
        Event::subscribe(Compressor::E_CREATE_MODULE_LIST, array($this, 'getModuleList'));
156
157
        //url()->parse();
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
158
        $this->template = $this->path() . 'app/view/index.php';
159
160
        // Generate resources for new module
161
        //[PHPCOMPRESSOR(remove,start)]
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
162
        //$this->system->module('resourcer')->generateResources($this->cmsModuleList, $this->path() . 'app/view/index.php');
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
163
        //[PHPCOMPRESSOR(remove,end)]
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
164
    }
165
166
    public function isCMS()
167
    {
168
        return $this->isCMS;
169
    }
170
171
    public function activeModuleHandler($module)
172
    {
173
        // Define if routed module is related to SamsonCMS
174
        if($this->isCMS = $this->ifModuleRelated($module)){
0 ignored issues
show
Documentation Bug introduced by
The property $isCMS was declared of type boolean, but $this->ifModuleRelated($module) is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
175
            // TODO: This should be removed - Reparse url
176
177
            url()->parse();
178
179
            // Switch template to SamsonCMS
180
            $this->system->template($this->template, true);
181
182
            Event::fire(self::EVENT_IS_CMS, array(&$this));
183
        }
184
    }
185
186
    /**
187
     * Callback for adding SamsonCMS related modules prefix to routes.
188
     *
189
     * @param $module
190
     * @param $prefix
191
     */
192
    public function updateCMSPrefix($module, &$prefix)
193
    {
194
        if (($module->id != $this->id) && $this->ifModuleRelated($module)) {
195
            $prefix = '/' . $this->baseUrl . $prefix;
196
        }
197
    }
198
199
    public function buildUrl(&$urlObj, &$httpHost, &$urlParams)
200
    {
201
        if ($this->isCMS) {
202
            if (in_array($urlParams[0], SamsonLocale::get(), true)) {
203
                array_splice($urlParams, 1, 0, array($this->baseUrl));
204
                $urlParams = array_values($urlParams);
205
            } else {
206
                array_unshift($urlParams, $this->baseUrl);
207
            }
208
        }
209
    }
210
211
    public function parseUrl(&$urlObj, &$urlArgs)
212
    {
213
        if ($this->isCMS) {
214
            if (in_array($urlArgs[0], SamsonLocale::get(), true)) {
215
                unset($urlArgs[1]);
216
                $urlArgs = array_values($urlArgs);
217
            } else {
218
                array_shift($urlArgs);
219
            }
220
        }
221
    }
222
223
    public function __base()
224
    {
225
        $templateModule = $this->system->module('template');
226
227
        // Switch system to SamsonCMS template module
228
        $this->system->active($templateModule);
229
230
        // Call template handler
231
        $templateModule->__handler();
232
    }
233
234
    public function oldMainRenderer(&$html)
235
    {
236
        // Render application main page block
237
        foreach (\samsoncms\Application::loaded() as $app) {
0 ignored issues
show
Deprecated Code introduced by
The method samsoncms\Application::loaded() has been deprecated.

This method has been deprecated.

Loading history...
238
            // Show only visible apps
239
            if ($app->hide == false /*&& $app->findView('sub_menu')*/) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
240
                $html .= $app->main();
0 ignored issues
show
Deprecated Code introduced by
The method samsoncms\Application::main() has been deprecated with message: Subscribe to samsoncms/template event

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
241
            }
242
        }
243
    }
244
245
    /**
246
     * @deprecated All application should draw menu block via events
247
     */
248
    public function oldMenuRenderer(&$html, &$subMenu)
0 ignored issues
show
Coding Style introduced by
oldMenuRenderer 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...
249
    {
250
        // Iterate loaded samson\cms\application
251
        foreach (\samsoncms\Application::loaded() as $app) {
0 ignored issues
show
Deprecated Code introduced by
The method samsoncms\Application::loaded() has been deprecated.

This method has been deprecated.

Loading history...
252
            // Show only visible apps
253
            if ($app->hide == false) {
254
                // Render application menu item
255
                $html .= m('template')
0 ignored issues
show
Deprecated Code introduced by
The function m() has been deprecated with message: Use $this->system->module() in module context

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
256
                    ->view('menu/item')
257
                    ->active(url()->module == $app->id() ? 'active' : '')
258
                    ->app($app)
259
                    ->icon($app->icon)
260
                    ->name(isset($app->name{0}) ? $app->name : '')
261
                    ->output();
262
            }
263
        }
264
        $subMenu = '';
265
        // Find current SamsonCMS application
266
        if (\samsoncms\Application::find(url()->module, $app/*@var $app App*/)) {
267
            // If module has sub_menu view - render it
268
            if ($app->findView('sub_menu')) {
269
                // Explode url by symbols '/'
270
                $url = explode('/', $_SERVER['REQUEST_URI']);
271
                // If isset url with params search and param page equal 0
272
                if (isset($url[4]) && $url[3] != 'form') {
273
                    // Default value for search field
274
                    $paramSearch = urldecode($url[4]);
275
                    // Set params search
276
                    $app->set($paramSearch, 'search');
277
                }
278
				
279
                $subMenu .= $app->view('sub_menu')->set(t($app->name, true), 'appName')->output();
280
            }
281
        }
282
    }
283
284
    /**
285
     * @deprecated
286
     * @return string Page title
287
     */
288
    public function oldGetTitle()
289
    {
290
        $local   = m('local');
0 ignored issues
show
Deprecated Code introduced by
The function m() has been deprecated with message: Use $this->system->module() in module context

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
291
        $current = m();
0 ignored issues
show
Deprecated Code introduced by
The function m() has been deprecated with message: Use $this->system->module() in module context

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
292
293
        return isset($current['title']) ? $current['title'] :
294
            (isset($local['title']) ? $local['title'] : '');
295
    }
296
}
297