Completed
Push — master ( 10bbaf...0fa0d2 )
by Андрей
8s
created

IntegrationModuleTrait::setModuleManager()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
/**
3
 * @link    https://github.com/nnx-framework/module
4
 * @author  Malofeykin Andrey  <[email protected]>
5
 */
6
namespace Nnx\Module;
7
8
use Nnx\Module\Event\IntegrationModuleEvent;
9
use Zend\ModuleManager\ModuleManagerInterface;
10
use Zend\EventManager\EventManagerInterface;
11
use Zend\ModuleManager\ModuleEvent;
12
use Nnx\Module\Event\IntegrationModuleEventInterface;
13
use ReflectionClass;
14
15
/**
16
 * Class IntegrationModuleTrait
17
 *
18
 * @package Nnx\Module\Options
19
 */
20
trait IntegrationModuleTrait
21
{
22
    /**
23
     * @see \Zend\EventManager\EventManagerAwareTrait::setEventManager
24
     *
25
     * @var array
26
     */
27
    protected $eventIdentifier = [
28
        IntegrationModuleInterface::class
29
    ];
30
31
    /**
32
     * Протип объекта, испольуземый для создания события бросаемого при инициализации интеграционного модуля
33
     *
34
     * @var IntegrationModuleEventInterface
35
     */
36
    protected $prototypeIntegrationModuleEvent;
37
38
    /**
39
     * Имя класса, который должен имплементировать \Nnx\Module\Event\IntegrationModuleEventInterface. Данный класс
40
     * используется для создания объекта прототипа события (@see \Nnx\Module\IntegrationModuleTrait::$prototypeIntegrationModuleEvent)
41
     *
42
     * @var string
43
     */
44
    protected $prototypeIntegrationModuleEventClassName = IntegrationModuleEvent::class;
45
46
    /**
47
     * Менеджер модулей
48
     *
49
     * @var ModuleManagerInterface
50
     */
51
    protected $moduleManager;
52
53
    /**
54
     * Приоритет обработчки отвечающего за проксирование события пост загрузки всех модулей. Для корректной работы
55
     * интеграционного модуля, это значение должно быть больше, по приоритету чем значение свойства 
56
     * @see \Nnx\Module\Listener\IntegrationModuleListener::$configuringServiceModulesHandlerPriority
57
     *
58
     *
59
     * при подписке на onLoadModulesPost в ServiceListener
60
     * (@see \Zend\ModuleManager\Listener\ServiceListener::attach) и меньше чем 
61
     *
62
     *
63
     *
64
     * @var int
65
     */
66
    protected $loadModulesPostProxyHandlerPriority = 100;
67
68
    /**
69
     * @return EventManagerInterface
70
     */
71
    abstract public function getEventManager();
72
73
    /**
74
     * Initialize workflow
75
     *
76
     * @param  ModuleManagerInterface $manager
77
     * @return void
78
     */
79
    public function init(ModuleManagerInterface $manager)
80
    {
81
        $this->initIntegrationModule($manager);
82
    }
83
84
    /**
85
     * Инициализация интеграционного модуля
86
     *
87
     * @param ModuleManagerInterface $manager
88
     */
89
    public function initIntegrationModule(ModuleManagerInterface $manager)
90
    {
91
        $this->setModuleManager($manager);
92
        $this->preInitIntegrationModule();
93
94
        $manager->getEventManager()->attach(
95
            ModuleEvent::EVENT_LOAD_MODULES_POST,
96
            [$this, 'onLoadModulesPostProxyHandler'],
97
            $this->loadModulesPostProxyHandlerPriority
98
        );
99
    }
100
101
    /**
102
     * Метод вызывается перед стандартным механизмом инициализаци. Используется для перегрузки в конкретном модуле.
103
     *
104
     * @return void
105
     */
106
    protected function preInitIntegrationModule()
107
    {
108
    }
109
110
    /**
111
     * Обработчик события возникающего после загрузки модулей
112
     *
113
     * @throws Exception\ErrorCreateIntegrationModuleEventException
114
     *
115
     * @throws Exception\InvalidModuleManagerException
116
     */
117
    public function onLoadModulesPostProxyHandler()
118
    {
119
        $event = clone $this->getPrototypeIntegrationModuleEvent();
120
        $event->setName(IntegrationModuleEventInterface::INIT_INTEGRATION_MODULE_EVENT);
121
        $event->setTarget($this);
122
123
        $moduleManager = $this->getModuleManager();
124
        $event->setModuleManager($moduleManager);
125
126
        $event->setModule($this);
127
128
        $this->getEventManager()->trigger($event);
129
    }
130
131
    /**
132
     * Возвращает протип объекта, испольуземый для создания события бросаемого при инициализации интеграционного модуля
133
     *
134
     * @return IntegrationModuleEventInterface
135
     *
136
     * @throws Exception\ErrorCreateIntegrationModuleEventException
137
     */
138
    public function getPrototypeIntegrationModuleEvent()
139
    {
140
        if ($this->prototypeIntegrationModuleEvent instanceof IntegrationModuleEventInterface) {
141
            return $this->prototypeIntegrationModuleEvent;
142
        }
143
144
        $eventClassName = $this->getPrototypeIntegrationModuleEventClassName();
145
146
        $r = new ReflectionClass($eventClassName);
147
        $event = $r->newInstance();
148
149
        if (!$event instanceof IntegrationModuleEventInterface) {
150
            $errMsg = sprintf('Integration module event not implement %s', IntegrationModuleEventInterface::class);
151
            throw new Exception\ErrorCreateIntegrationModuleEventException($errMsg);
152
        }
153
154
        $this->prototypeIntegrationModuleEvent = $event;
155
156
        return $this->prototypeIntegrationModuleEvent;
157
    }
158
159
    /**
160
     * Устанавливает протип объекта, испольуземый для создания события бросаемого при инициализации интеграционного модуля
161
     *
162
     * @param IntegrationModuleEventInterface $prototypeIntegrationModuleEvent
163
     *
164
     * @return $this
165
     */
166
    public function setPrototypeIntegrationModuleEvent(IntegrationModuleEventInterface $prototypeIntegrationModuleEvent)
167
    {
168
        $this->prototypeIntegrationModuleEvent = $prototypeIntegrationModuleEvent;
169
170
        return $this;
171
    }
172
173
    /**
174
     * Возвращает имя класса, который должен имплементировать \Nnx\Module\Event\IntegrationModuleEventInterface. Данный класс
175
     * используется для создания объекта прототипа события (@see \Nnx\Module\IntegrationModuleTrait::$prototypeIntegrationModuleEvent)
176
     *
177
     * @return string
178
     */
179
    public function getPrototypeIntegrationModuleEventClassName()
180
    {
181
        return $this->prototypeIntegrationModuleEventClassName;
182
    }
183
184
    /**
185
     * Устанавливает имя класса, который должен имплементировать \Nnx\Module\Event\IntegrationModuleEventInterface. Данный класс
186
     * используется для создания объекта прототипа события (@see \Nnx\Module\IntegrationModuleTrait::$prototypeIntegrationModuleEvent)
187
     *
188
     * @param string $prototypeIntegrationModuleEventClassName
189
     *
190
     * @return $this
191
     */
192
    public function setPrototypeIntegrationModuleEventClassName($prototypeIntegrationModuleEventClassName)
193
    {
194
        $this->prototypeIntegrationModuleEventClassName = $prototypeIntegrationModuleEventClassName;
195
196
        return $this;
197
    }
198
199
    /**
200
     * Возвращает менеджер модулей
201
     *
202
     * @return ModuleManagerInterface
203
     *
204
     * @throws Exception\InvalidModuleManagerException
205
     */
206
    public function getModuleManager()
207
    {
208
        if (!$this->moduleManager instanceof ModuleManagerInterface) {
209
            $errMsg = 'Module manager not installed';
210
            throw new Exception\InvalidModuleManagerException($errMsg);
211
        }
212
        return $this->moduleManager;
213
    }
214
215
    /**
216
     * Устанавливает менеджер модулей
217
     *
218
     * @param ModuleManagerInterface $moduleManager
219
     *
220
     * @return $this
221
     */
222
    public function setModuleManager(ModuleManagerInterface $moduleManager)
223
    {
224
        $this->moduleManager = $moduleManager;
225
226
        return $this;
227
    }
228
}
229