Completed
Push — master ( f25d12...ece44a )
by Vitaly
11:51
created

Application::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 3 Features 2
Metric Value
c 7
b 3
f 2
dl 0
loc 21
rs 9.3142
cc 1
eloc 8
nc 1
nop 1
1
<?php
2
namespace samsoncms\cms;
3
4
use samson\core\CompressableExternalModule;
5
use samson\core\SamsonLocale;
6
use samsonphp\event\Event;
7
use samsonphp\resource\Router;
8
use samsonphp\router\Module;
9
10
/**
11
 * SamsonCMS external compressible application for integrating
12
 * @author Vitaly Iegorov <[email protected]>
13
 */
14
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...
15
{
16
    const EVENT_IS_CMS = 'samsonsms.is.cms';
17
18
    /** @var string Module identifier */
19
    public $id = 'cms';
20
21
    public $baseUrl = 'cms';
22
23
    /** @var array Collection of SamsonCMS related modules */
24
    protected $moduleList = [];
25
26
    /** @var bool Flag that currently we are woring in SamsonCMS */
27
    protected $isCMS = false;
28
29
    //[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...
30
    /**
31
     * Remove unnecessary modules list for SamsonCMS from loaded modules
32
     * and return left modules.
33
     *
34
     * @param array $otherModuleList List of SamsonCMS unneeded modules
35
     */
36
    public function filterModuleList(&$otherModuleList = [])
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
        $projectModules = [];
51
        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...
52
            if (!array_key_exists('composerName', $module->composerParameters)) {
53
                $projectModules[$id] = $module;
54
            } elseif (array_key_exists('composerName', $module->composerParameters) && in_array($module->composerParameters['composerName'], $parentDependencies)) {
55
                $projectModules[$id] = $module;
56
            }
57
        }
58
        $otherModuleList = $projectModules;
59
60
        // Gather SamsonCMS-only related modules
61
        $this->moduleList = $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...
62
        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...
63
            if (!$this->isModuleDependent($module) && $id !== 'core' && !$this->ifModuleRelated($module)) {
64
                unset($this->moduleList[$id]);
65
            }
66
        }
67
    }
68
69
    /**
70
     * Check if passed module is related to SamsonCMS.
71
     * Also method stores data to flag variable.
72
     *
73
     * @param $module
74
     *
75
     * @return bool True if module related to SamsonCMS
76
     */
77
    public function ifModuleRelated($module)
78
    {
79
        // Analyze if module class or one of its parents has samsoncms\ namespace pattern
80
        return count(preg_grep('/samsoncms\\\\/i', array_merge(array(get_class($module)), class_parents($module))));
81
    }
82
83
    /** SamsonCMS preparation stage handler */
84
    public function prepare()
85
    {
86
        /**
87
         * Subscribe for router resource initialization to remove SamsonCMS modules as we will generate
88
         * SamsonCMS resources manually
89
         */
90
        Event::subscribe(Router::EVENT_START_GENERATE_RESOURCES, [$this, 'filterModuleList']);
91
    }
92
93
    /**
94
     * If module is dependent from current module through composer.json.
95
     *
96
     * @param $module Module for checking
97
     * @return bool True if module dependent
98
     */
99
    protected function isModuleDependent($module)
100
    {
101
        return isset($module->composerParameters['composerName']) && in_array($module->composerParameters['composerName'], $this->composerParameters['required']);
102
    }
103
104
    //[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...
105
106
    /**
107
     * SamsonCMS initialization stage handler
108
     *
109
     * @param array $params Initialization parameters
110
     *
111
     * @return bool Initialization stage result
112
     */
113
    public function init(array $params = array())
114
    {
115
        // Old applications main page rendering
116
        Event::subscribe('template.main.rendered', array($this, 'oldMainRenderer'));
117
118
        // Old applications menu rendering
119
        Event::subscribe('template.menu.rendered', array($this, 'oldMenuRenderer'));
120
121
        Event::subscribe('samson.url.build', array($this, 'buildUrl'));
122
123
        Event::subscribe('samson.url.args.created', array($this, 'parseUrl'));
124
125
        Event::subscribe(Module::EVENT_ROUTE_FOUND, array($this, 'activeModuleHandler'));
126
127
        Event::subscribe('samsonphp.router.create.module.routes', array($this, 'updateCMSPrefix'));
128
129
        // Generate resources for new module
130
        //[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...
131
        $this->system->module('resourcer')->generateResources($this->moduleList, $this->path() . 'app/view/index.php');
132
        //[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...
133
    }
134
135
    public function isCMS()
136
    {
137
        return $this->isCMS;
138
    }
139
140
    public function activeModuleHandler($module)
141
    {
142
        // Define if routed module is related to SamsonCMS
143
        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...
144
            // TODO: This should be removed - Reparse url
145
            url()->parse();
146
147
            // Switch template to SamsonCMS
148
            $this->system->template($this->path() . 'app/view/index.php', true);
149
150
            Event::fire(self::EVENT_IS_CMS, array(&$this));
151
        }
152
    }
153
154
    /**
155
     * Callback for adding SamsonCMS related modules prefix to routes.
156
     *
157
     * @param $module
158
     * @param $prefix
159
     */
160
    public function updateCMSPrefix($module, &$prefix)
161
    {
162
        if (($module->id != $this->id) && $this->ifModuleRelated($module)) {
163
            $prefix = '/' . $this->baseUrl . $prefix;
164
        }
165
    }
166
167
    public function buildUrl(&$urlObj, &$httpHost, &$urlParams)
168
    {
169
        if ($this->isCMS) {
170
            if (in_array($urlParams[0], SamsonLocale::get(), true)) {
171
                array_splice($urlParams, 1, 0, array($this->baseUrl));
172
                $urlParams = array_values($urlParams);
173
            } else {
174
                array_unshift($urlParams, $this->baseUrl);
175
            }
176
        }
177
    }
178
179
    public function parseUrl(&$urlObj, &$urlArgs)
180
    {
181
        if ($this->isCMS) {
182
            if (in_array($urlArgs[0], SamsonLocale::get(), true)) {
183
                unset($urlArgs[1]);
184
                $urlArgs = array_values($urlArgs);
185
            } else {
186
                array_shift($urlArgs);
187
            }
188
        }
189
    }
190
191
    public function __base()
192
    {
193
        $templateModule = $this->system->module('template');
194
195
        // Switch system to SamsonCMS template module
196
        $this->system->active($templateModule);
197
198
        // Call template handler
199
        $templateModule->__handler();
200
    }
201
202
    public function oldMainRenderer(&$html)
203
    {
204
        // Render application main page block
205
        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...
206
            // Show only visible apps
207
            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...
208
                $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...
209
            }
210
        }
211
    }
212
213
    /**
214
     * @deprecated All application should draw menu block via events
215
     */
216
    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...
217
    {
218
        // Iterate loaded samson\cms\application
219
        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...
220
            // Show only visible apps
221
            if ($app->hide == false) {
222
                // Render application menu item
223
                $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...
224
                    ->view('menu/item')
225
                    ->active(url()->module == $app->id() ? 'active' : '')
226
                    ->app($app)
227
                    ->icon($app->icon)
228
                    ->name(isset($app->name{0}) ? $app->name : '')
229
                    ->output();
230
            }
231
        }
232
        $subMenu = '';
233
        // Find current SamsonCMS application
234
        if (\samsoncms\Application::find(url()->module, $app/*@var $app App*/)) {
235
            // If module has sub_menu view - render it
236
            if ($app->findView('sub_menu')) {
237
                // Explode url by symbols '/'
238
                $url = explode('/', $_SERVER['REQUEST_URI']);
239
                // If isset url with params search and param page equal 0
240
                if (isset($url[4]) && $url[3] != 'form') {
241
                    // Default value for search field
242
                    $paramSearch = urldecode($url[4]);
243
                    // Set params search
244
                    $app->set($paramSearch, 'search');
245
                }
246
				
247
                $subMenu .= $app->view('sub_menu')->set(t($app->name, true), 'appName')->output();
248
            }
249
        }
250
    }
251
252
    /**
253
     * @deprecated
254
     * @return string Page title
255
     */
256
    public function oldGetTitle()
257
    {
258
        $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...
259
        $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...
260
261
        return isset($current['title']) ? $current['title'] :
262
            (isset($local['title']) ? $local['title'] : '');
263
    }
264
}
265