Completed
Push — master ( b2b558...421e0c )
by Nikita
12:38 queued 01:03
created

ExternalModule::setId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
namespace samson\core;
3
4
use samsonframework\core\RequestInterface;
5
use samsonframework\core\ResourcesInterface;
6
use samsonframework\core\SystemInterface;
7
use samsonphp\event\Event;
8
9
/**
10
 * SamsonPHP external module
11
 *
12
 * @author Vitaly Iegorov <[email protected]>
13
 * @version 0.1
14
 */
15
class ExternalModule extends Module implements iExternalModule
16
{
17
    /** @var Module Pointer to parent module */
18
    public $parent = null;
19
20
    /** Коллекция связанных модулей с текущим */
21
    protected $requirements = array();
22
23
    /**
24
     * ExternalModule constructor.
25
     *
26
     * @param string $path
27
     * @param ResourcesInterface $resources
28
     * @param SystemInterface $system
29
     */
30
    public function __construct($path, ResourcesInterface $resources, SystemInterface $system)
31
    {
32
        // Inject generic module dependencies
33
        $this->system = $system;
34
35
        // Module identifier not specified - set it to NameSpace\Classname
36
        if (!isset($this->id{0})) {
37
            // Generate identifier from module class
38
            $this->id = AutoLoader::oldClassName(get_class($this));
39
        }
40
41
        // Subscribe to an config ready core event
42
        Event::subscribe('core.started', array(& $this, 'init'));
43
44
        // Call parent constructor
45
        parent::__construct($this->id, $path, $resources);
46
    }
47
48
    public function setId($id)
49
    {
50
        $this->id = $id;
51
    }
52
    /** @see \samson\core\iExternalModule::copy() */
53
    public function &copy()
54
    {
55
        // Get current class name
56
        $classname = get_class($this);
57
58
        // Create copy instance
59
        $clone = new $classname($this->path, $this->resourceMap, $this->system);
60
        $clone->views = &$this->views;
61
        $clone->parent = &$this->parent;
62
        $clone->controllers = &$this->controllers;
63
        $clone->path = $this->path;
64
65
        return $clone;
66
    }
67
68
    /** Обработчик сериализации объекта */
69
    public function __sleep()
70
    {
71
        // Remove all unnecessary fields from serialization
72
        return array_diff(array_keys(get_object_vars($this)), array('view_path', 'view_html', 'view_data'));
73
    }
74
75
    /**
76
     * Перегружаем стандартное поведение выполнения действия контроллера
77
     * Если текущий модуль наследует другой <code>ModuleConnector</code>
78
     * то тогда сначала выполняется действие контроллера в данном модуле,
79
     * а потом в его родителе. Это дает возможность выполнять наследование
80
     * контроллеров модулей.
81
     *
82
     * @param string $methodName Controller action name
83
     * @return bool|mixed
84
     */
85
    public function action($methodName = null)
86
    {
87
        // Выполним стандартное действие
88
        $result = parent::action($methodName);
89
90
        // Если мы не смогли выполнить действие для текущего модуля
91
        // и задан родительский модуль
92
        if ($result === false && isset($this->parent)) {
93
            // Выполним действие для родительского модуля
94
            return $this->parent->action($methodName);
95
        }
96
97
        // Веренем результат выполнения действия
98
        return $result;
99
    }
100
101
    /**
102
     * Set current view for rendering.
103
     *
104
     * @param string $viewPath Path for view searching
105
     * @return self Chaining
106
     */
107
    public function view($viewPath)
108
    {
109
        //elapsed('['.$this->id.'] Setting view context: ['.$viewPath.']');
110
        // Find full path to view file
111
        $this->view_path = $this->findView($viewPath);
112
113
        // If we have not found view in current module but we have parent module
114
        if (isset($this->parent) && $this->view_path === false) {
115
            //elapsed('['.$this->id.'] Cannot set view['.$viewPath.'] - passing it to parent['.$this->parent->id.']');
116
117
            /*
118
             * Call parent module view setting and return PARENT module to chain
119
             * actually switching current module in chain
120
             */
121
            return $this->parent->view($viewPath);
122
        } else { // Call default module behaviour
123
            // Call default module behaviour
124
            parent::view($this->view_path);
125
126
            // If view has not been set at final stage - trigger error
127
            if ($this->view_path === false) {
128
                e('[##] Cannot find view "##"', E_SAMSON_FATAL_ERROR, array($this->id, $viewPath));
129
            }
130
131
            return $this;
132
        }
133
    }
134
135
    /**
136
     * Overloading default module rendering behaviour
137
     * as it is used in templates and views using m()->render()
138
     * without specifying concrete module or passing a variable.
139
     *
140
     * @param string $controller Controller action name
141
     */
142
    public function render($controller = null)
143
    {
144
        // If we have parent module connection and have no view set
145
        if (isset($this->parent) && $this->view_path == false) {
146
            // Merge current and parent module view data
147
            $this->parent->view_data = array_merge($this->parent->view_data, $this->view_data);
148
            // Set internal view context data pointer
149
            $this->parent->data = &$this->parent->view_data[$this->parent->view_context];
150
            // Call parent render
151
            $this->parent->render($controller);
152
        } else { // Call default module behaviour
153
            parent::render($controller);
154
        }
155
    }
156
157
    /**
158
     * Module preparation handler.
159
     * This function is triggered after module instance is being created.
160
     *
161
     * @return bool Preparation result
162
     */
163
    public function prepare()
164
    {
165
        return true;
166
    }
167
168
    /**
169
     * Module initialization.
170
     * This function is triggered when system has started. So here
171
     * we have all modules already prepared and loaded.
172
     *
173
     * @param array $params Collection of module initialization parameters
174
     * @return bool Initialization result
175
     */
176
    public function init(array $params = array())
177
    {
178
        $this->set($params);
179
180
        return true;
181
    }
182
}
183