Completed
Push — master ( f27221...aa4365 )
by Nikita
03:05
created

Application::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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