Completed
Push — master ( 405b00...f31961 )
by Vitaly
02:10
created

ExternalModule::__construct()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 18
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 18
rs 9.4286
cc 3
eloc 7
nc 2
nop 4
1
<?php
2
namespace samson\core;
3
use samsonframework\core\RequestInterface;
4
use samsonframework\core\ResourcesInterface;
5
use samsonframework\core\SystemInterface;
6
7
/**
8
 * SamsonPHP external module
9
 *
10
 * @author Vitaly Iegorov <[email protected]>
11
 * @version 0.1
12
 */
13
class ExternalModule extends Module implements iExternalModule
14
{
15
    /**
16
     * Pointer to parent module
17
     * @var \samson\core\Module
18
     * @see \samson\core\Module
19
     */
20
    public $parent = NULL;
21
22
    /** Коллекция связанных модулей с текущим */
23
    protected $requirements = array();
24
25
    /**
26
     * ExternalModule constructor.
27
     *
28
     * @param string $path Path to module
29
     * @param ResourceMap $resources
30
     * @param Core $system Framework instance
31
     * @param Url $request Request instance
32
     */
33
    public function  __construct($path, ResourcesInterface $resources, SystemInterface $system, RequestInterface $request)
34
    {
35
        // Inject generic module dependencies
36
        $this->system = $system;
0 ignored issues
show
Documentation Bug introduced by
$system is of type object<samsonframework\core\SystemInterface>, but the property $system was declared to be of type object<samson\core\Core>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
37
        $this->request = $request;
0 ignored issues
show
Documentation Bug introduced by
$request is of type object<samsonframework\core\RequestInterface>, but the property $request was declared to be of type object<samson\core\URL>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
38
39
        // Module identifier not specified - set it to NameSpace\Classname
40
        if (!isset($this->id{0}) && !isset($identifier)) {
0 ignored issues
show
Bug introduced by
The variable $identifier seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
41
            // Generate identifier from module class
42
            $this->id = AutoLoader::oldClassName(get_class($this));
43
        }
44
45
        // Subscribe to an config ready core event
46
        \samsonphp\event\Event::subscribe('core.started', array(&$this, 'init'));
47
48
        // Call parent constructor
49
        parent::__construct($this->id, $path, $resources);
50
    }
51
52
    /** @see \samson\core\iExternalModule::copy() */
53
    public function &copy()
54
    {
55
        // Get current class name
56
        $classname = get_class($this);
57
58
        // Generate unique virtual id for copy
59
        $id = $this->id;
60
61
        // Create copy instance
62
        $o = new $classname($this->path, $id, $this->resourceMap);
63
        $o->views = &$this->views;
64
        $o->parent = &$this->parent;
65
        $o->controllers = &$this->controllers;
66
        $o->path = $this->path;
67
68
        return $o;
69
    }
70
71
    /** Обработчик сериализации объекта */
72
    public function __sleep()
73
    {
74
        // Remove all unnecessary fields from serialization
75
        return array_diff(array_keys(get_object_vars($this)), array('view_path', 'view_html', 'view_data'));
76
    }
77
78
    /**
79
     * Перегружаем стандартное поведение выполнения действия контроллера
80
     * Если текущий модуль наследует другой <code>ModuleConnector</code>
81
     * то тогда сначала выполняется действие контроллера в данном модуле,
82
     * а потом в его родителе. Это дает возможность выполнять наследование
83
     * контроллеров модулей.
84
     *
85
     * @see iModule::action()
86
     */
87
    public function action($methodName = NULL)
88
    {
89
        // Выполним стандартное действие
90
        $result = parent::action($methodName);
91
92
        // Если мы не смогли выполнить действие для текущего модуля
93
        // и задан родительский модуль
94
        if ($result === A_FAILED && isset($this->parent)) {
95
            // Выполним действие для родительского модуля
96
            return $this->parent->action($methodName);
97
        }
98
99
        // Веренем результат выполнения действия
100
        return $result;
101
    }
102
103
    /** @see iModule::view() */
104
    public function view($viewPath)
105
    {
106
        //elapsed('['.$this->id.'] Setting view context: ['.$viewPath.']');
107
        // Find full path to view file
108
        $this->view_path = $this->findView($viewPath);
109
110
        // If we have not found view in current module but we have parent module
111
        if (isset($this->parent) && $this->view_path === false) {
112
            //elapsed('['.$this->id.'] Cannot set view['.$viewPath.'] - passing it to parent['.$this->parent->id.']');
113
114
            /*
115
             * Call parent module view setting and return PARENT module to chain
116
             * actually switching current module in chain
117
             */
118
            return $this->parent->view($viewPath);
119
        } else { // Call default module behaviour
120
            // Call default module behaviour
121
            parent::view($this->view_path);
122
123
            // If view has not been set at final stage - trigger error
124
            if ($this->view_path === false) {
125
                e('[##] Cannot find view "##"', E_SAMSON_FATAL_ERROR, array($this->id, $viewPath));
126
            }
127
128
            return $this;
129
        }
130
    }
131
132
    /**
133
     * Overloading default module rendering behaviour
134
     * as it is used in templates and views using m()->render()
135
     * without specifying concrete module or passing a variable.
136
     *
137
     * @see parent::render()
138
     */
139
    public function render($controller = null)
140
    {
141
        // If we have parent module connection and have no view set
142
        if (isset($this->parent) && $this->view_path == false) {
143
            // Merge current and parent module view data
144
            $this->parent->view_data = array_merge($this->parent->view_data, $this->view_data);
145
            // Set internal view context data pointer
146
            $this->parent->data = &$this->parent->view_data[$this->parent->view_context];
147
            // Call parent render
148
            return $this->parent->render($controller);
149
        } else { // Call default module behaviour
150
            return parent::render($controller);
151
        }
152
    }
153
154
    /**
155
     * Module preparation handler.
156
     * This function is triggered after module instance is being created.
157
     *
158
     * @return bool Preparation result
159
     */
160
    public function prepare()
161
    {
162
        return true;
163
    }
164
165
    /**
166
     * Module initialization.
167
     * This function is triggered when system has started. So here
168
     * we have all modules already prepared and loaded.
169
     *
170
     * @param array $params Collection of module initialization parameters
171
     * @return bool Initialization result
172
     */
173
    public function init(array $params = array())
174
    {
175
        $this->set($params);
0 ignored issues
show
Documentation introduced by
$params is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
176
177
        return true;
178
    }
179
}
180