Completed
Push — master ( aa4365...e3f2b5 )
by
unknown
08:31
created

Application::init()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 9
nc 1
nop 1
1
<?php
2
namespace samsoncms\cms;
3
4
use samson\core\CompressableExternalModule;
5
use samson\core\SamsonLocale;
6
use samsonframework\container\definition\analyzer\annotation\annotation\Service;
7
use samsonphp\compressor\Compressor;
8
use samsonphp\event\Event;
9
use samsonphp\resource\Router;
10
use samsonphp\router\Module;
11
12
/**
13
 * SamsonCMS external compressible application for integrating
14
 * @author Vitaly Iegorov <[email protected]>
15
 * @Service("cms")
16
 */
17
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...
18
{
19
    const EVENT_IS_CMS = 'samsonsms.is.cms';
20
21
    /** @var string Module identifier */
22
    public $id = 'cms';
23
24
    public $baseUrl = 'cms';
25
26
    /** @var array Collection of SamsonCMS related modules */
27
    protected $cmsModuleList = [];
28
29
    protected $projectModuleList = [];
30
31
    /** @var bool Flag that currently we are woring in SamsonCMS */
32
    protected $isCMS = false;
33
34
    protected $template = '';
35
36
    //[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...
37
38
    protected function prepareModuleList()
39
    {
40
        $this->cmsModuleList = $this->system->getContainer()->getServices('module');
0 ignored issues
show
Unused Code introduced by
The call to ContainerInterface::getServices() has too many arguments starting with 'module'.

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...
41
42
        // Gather all project specific modules that do not dependent to SamsonCMS
43
        $parentDependencies = [];
44
        foreach ($this->cmsModuleList as $id => $module) {
45
            // Module dependency at project level composer.json and is not this module
46
            if (array_key_exists('projectRequireDev', $module->composerParameters) && $module->composerParameters['projectRequireDev'] === true && $id !== $this->id()) {
47
                $parentDependencies = array_merge($module->composerParameters['required'], [$module->composerParameters['composerName']], $parentDependencies);
48
            }
49
        }
50
        // Remove duplicates
51
        $parentDependencies = array_unique($parentDependencies);
52
53
        // Gather project-only related modules
54
        $this->projectModuleList = [];
55
        foreach ($this->cmsModuleList as $id => $module) {
56
            if (!array_key_exists('composerName', $module->composerParameters)) {
57
                $this->projectModuleList[$id] = $module;
58
            } elseif (array_key_exists('composerName', $module->composerParameters) && in_array($module->composerParameters['composerName'], $parentDependencies)) {
59
                $this->projectModuleList[$id] = $module;
60
            }
61
            if (!$this->isModuleDependent($module) && $id !== 'core' && !$this->ifModuleRelated($module)) {
62
                unset($this->cmsModuleList[$id]);
63
            }
64
        }
65
    }
66
67
    /**
68
     * Remove unnecessary modules list for SamsonCMS from loaded modules
69
     * and return left modules.
70
     *
71
     * @param array $otherModuleList List of SamsonCMS unneeded modules
72
     */
73
    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...
74
    {
75
        $this->prepareModuleList();
76
77
        $otherModuleList = $this->projectModuleList;
78
79
        /**
80
         * Change modules list between main web-application and SamsonCMS
81
         */
82
        // TODO: As this is processed before routing than we just check URL
83
        if ($this->isCMS() || strpos($_SERVER['REQUEST_URI'], '/'.$this->id.'/') !== false) {
84
            // Switch module list to SamsonCMS module list
85
            $otherModuleList = $this->cmsModuleList;
86
        }
87
    }
88
89
90
    /** SamsonCMS preparation stage handler */
91
    public function prepare()
92
    {
93
        /**
94
         * Subscribe for router resource initialization to remove SamsonCMS modules as we will generate
95
         * SamsonCMS resources manually
96
         */
97
        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...
98
    }
99
100
    /**
101
     * If module is dependent from current module through composer.json.
102
     *
103
     * @param $module Module for checking
104
     * @return bool True if module dependent
105
     */
106
    protected function isModuleDependent($module)
107
    {
108
        return isset($module->composerParameters['composerName']) && in_array($module->composerParameters['composerName'], $this->composerParameters['required']);
109
    }
110
111
    public function getModuleList(& $moduleListArray)
112
    {
113
        $this->prepareModuleList();
114
        $moduleListArray[Router::I_MAIN_PROJECT_TEMPLATE] = $this->projectModuleList;
115
        $moduleListArray[$this->template] = $this->cmsModuleList;
116
    }
117
118
    //[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...
119
120
121
    /**
122
     * Check if passed module is related to SamsonCMS.
123
     * Also method stores data to flag variable.
124
     *
125
     * @param $module
126
     *
127
     * @return bool True if module related to SamsonCMS
128
     */
129
    public function ifModuleRelated($module)
130
    {
131
        // Analyze if module class or one of its parents has samsoncms\ namespace pattern
132
        return count(preg_grep('/samsoncms\\\\/i', array_merge(array(get_class($module)), class_parents($module))));
133
    }
134
135
    /**
136
     * SamsonCMS initialization stage handler
137
     *
138
     * @param array $params Initialization parameters
139
     *
140
     * @return bool Initialization stage result
141
     */
142
    public function init(array $params = array())
143
    {
144
        // Old applications main page rendering
145
        Event::subscribe('template.main.rendered', array($this, 'oldMainRenderer'));
146
147
        // Old applications menu rendering
148
        Event::subscribe('template.menu.rendered', array($this, 'oldMenuRenderer'));
149
150
        Event::subscribe('samson.url.build', array($this, 'buildUrl'));
151
152
        Event::subscribe('samson.url.args.created', array($this, 'parseUrl'));
153
154
        Event::subscribe(Module::EVENT_ROUTE_FOUND, array($this, 'activeModuleHandler'));
155
156
        Event::subscribe('samsonphp.router.create.module.routes', array($this, 'updateCMSPrefix'));
157
158
        Event::subscribe(Compressor::E_CREATE_MODULE_LIST, array($this, 'getModuleList'));
159
160
        //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...
161
        $this->template = $this->path() . 'app/view/index.php';
162
163
        // Generate resources for new module
164
        //[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...
165
        //$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...
166
        //[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...
167
    }
168
169
    public function isCMS()
170
    {
171
        return $this->isCMS;
172
    }
173
174
    public function activeModuleHandler($module)
175
    {
176
        // Define if routed module is related to SamsonCMS
177
        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...
178
            // TODO: This should be removed - Reparse url
179
180
            url()->parse();
181
182
            // Switch template to SamsonCMS
183
            $this->system->template($this->template, true);
184
185
            Event::fire(self::EVENT_IS_CMS, array(&$this));
186
        }
187
    }
188
189
    /**
190
     * Callback for adding SamsonCMS related modules prefix to routes.
191
     *
192
     * @param $module
193
     * @param $prefix
194
     */
195
    public function updateCMSPrefix($module, &$prefix)
196
    {
197
        if (($module->id != $this->id) && $this->ifModuleRelated($module)) {
198
            $prefix = '/' . $this->baseUrl . $prefix;
199
        }
200
    }
201
202
    public function buildUrl(&$urlObj, &$httpHost, &$urlParams)
203
    {
204
        if ($this->isCMS) {
205
            if (in_array($urlParams[0], SamsonLocale::get(), true)) {
206
                array_splice($urlParams, 1, 0, array($this->baseUrl));
207
                $urlParams = array_values($urlParams);
208
            } else {
209
                array_unshift($urlParams, $this->baseUrl);
210
            }
211
        }
212
    }
213
214
    public function parseUrl(&$urlObj, &$urlArgs)
215
    {
216
        if ($this->isCMS) {
217
            if (in_array($urlArgs[0], SamsonLocale::get(), true)) {
218
                unset($urlArgs[1]);
219
                $urlArgs = array_values($urlArgs);
220
            } else {
221
                array_shift($urlArgs);
222
            }
223
        }
224
    }
225
226
    public function __base()
227
    {
228
        $templateModule = $this->system->module('template');
229
230
        // Switch system to SamsonCMS template module
231
        $this->system->active($templateModule);
232
233
        // Call template handler
234
        $templateModule->__handler();
235
    }
236
237
    public function oldMainRenderer(&$html)
238
    {
239
        // Render application main page block
240
        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...
241
            // Show only visible apps
242
            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...
243
                $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...
244
            }
245
        }
246
    }
247
248
    /**
249
     * @deprecated All application should draw menu block via events
250
     */
251
    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...
252
    {
253
        // Iterate loaded samson\cms\application
254
        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...
255
            // Show only visible apps
256
            if ($app->hide == false) {
257
                // Render application menu item
258
                $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...
259
                    ->view('menu/item')
260
                    ->active(url()->module == $app->id() ? 'active' : '')
261
                    ->app($app)
262
                    ->icon($app->icon)
263
                    ->name(isset($app->name{0}) ? $app->name : '')
264
                    ->output();
265
            }
266
        }
267
        $subMenu = '';
268
        // Find current SamsonCMS application
269
        if (\samsoncms\Application::find(url()->module, $app/*@var $app App*/)) {
270
            // If module has sub_menu view - render it
271
            if ($app->findView('sub_menu')) {
272
                // Explode url by symbols '/'
273
                $url = explode('/', $_SERVER['REQUEST_URI']);
274
                // If isset url with params search and param page equal 0
275
                if (isset($url[4]) && $url[3] != 'form') {
276
                    // Default value for search field
277
                    $paramSearch = urldecode($url[4]);
278
                    // Set params search
279
                    $app->set($paramSearch, 'search');
280
                }
281
				
282
                $subMenu .= $app->view('sub_menu')->set(t($app->name, true), 'appName')->output();
283
            }
284
        }
285
    }
286
287
    /**
288
     * @deprecated
289
     * @return string Page title
290
     */
291
    public function oldGetTitle()
292
    {
293
        $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...
294
        $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...
295
296
        return isset($current['title']) ? $current['title'] :
297
            (isset($local['title']) ? $local['title'] : '');
298
    }
299
}
300