-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBaseModule.php
More file actions
661 lines (549 loc) · 19.4 KB
/
Copy pathBaseModule.php
File metadata and controls
661 lines (549 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
<?php
namespace wdmg\base;
/**
* Yii2 Base module
*
* @category Module
* @version 1.4.1
* @author Alexsander Vyshnyvetskyy <alex.vyshnyvetskyy@gmail.com>
* @link https://github.com/wdmg/yii2-base
* @copyright Copyright (c) 2019 - 2023 W.D.M.Group, Ukraine
* @license https://opensource.org/licenses/MIT Massachusetts Institute of Technology (MIT) License
*
*/
use wdmg\helpers\ArrayHelper;
use function GuzzleHttp\Psr7\str;
use yii\base\BootstrapInterface;
use Yii;
use yii\base\Module;
/**
* Base module definition class
*/
class BaseModule extends Module implements BootstrapInterface
{
/**
* @var string the prefix for routing of module
*/
public $routePrefix = "admin";
/**
* @var string, the name of module
*/
public $name = "Base module";
/**
* @var string, the description of module
*/
public $description = "Base module interface";
/**
* @var string, the current timezone
*/
public $timezone = 'Europe/Kiev';
/**
* @var string the vendor name of module
*/
private $vendor = "wdmg";
/**
* @var string the alias of module base path
*/
private $alias;
/**
* @var array the eta data of current module
*/
private $meta;
/**
* @var string the module version
*/
private $version = "1.4.1";
/**
* @var integer, priority of initialization
*/
private $priority = 10;
/**
* @var array of strings missing translations
*/
public $missingTranslation;
/**
* Private properties of child modules
* @var array
*/
private $privateProperties = [
'name', 'description', 'controllerNamespace', 'defaultRoute', 'routePrefix', 'vendor', 'controllerMap'
];
/**
* {@inheritdoc}
*/
public function init()
{
parent::init();
// Set controller namespace for console commands
if (Yii::$app instanceof \yii\console\Application) {
$this->controllerNamespace = 'wdmg\\' . $this->id . '\commands';
$this->defaultRoute = 'init';
}
// Set alias of module base path
$this->alias = '@'.$this->vendor.'/'.$this->id;
$this->setAliases([
$this->alias => $this->basePath
]);
// Set version of current module
$this->setVersion($this->version);
// Set priority of current module
$this->setPriority($this->priority);
// Register translations
$this->registerTranslations();
// Normalize route prefix
$this->routePrefixNormalize();
// Set meta data of current module
$this->setMetaData();
// Set default timezone if not exist
if ($this->timezone)
ini_set('date.timezone', $this->timezone);
else if (!ini_get('date.timezone'))
ini_set('date.timezone', 'Europe/London');
if (ini_get('date.timezone'))
date_default_timezone_set(ini_get('date.timezone'));
}
/**
* Get module vendor
* @return string of current module vendor
*/
public function getVendor() {
return $this->vendor;
}
/**
* Get module version
* @return string of current module version
*/
public function getVersion() {
$this->version = parent::getVersion();
return $this->version;
}
/**
* Set current module version
* @param $version string
*/
public function setVersion($version)
{
parent::setVersion($version);
$this->version = $version;
}
/**
* Get module priority
* @return integer of current module priority
*/
public function getPriority() {
return $this->priority;
}
/**
* Set current module priority
* @param $priority integer
*/
public function setPriority($priority) {
$this->priority = $priority;
}
/**
* Get alias
* @return string of current module alias
*/
public function getBaseAlias() {
return $this->alias;
}
/**
* Set meta data
* @return array of current module meta data
*/
public function setMetaData() {
$data = [];
$module = $this;
if (isset($module->id)) {
$data['id'] = $module->id;
$data['uniqueId'] = $module->getUniqueId();
$data['name'] = str_replace(Yii::getAlias('@vendor').'/',"", $module->getBasePath());
$data['label'] = (isset($module->name)) ? $module->name : null;
$data['version'] = $module->getVersion();
$data['vendor'] = (isset($module->vendor)) ? $module->vendor : null;
$data['alias'] = $module->getBaseAlias();
$data['paths']['basePath'] = $module->getBasePath();
$data['paths']['controllerPath'] = $module->getControllerPath();
$data['paths']['layoutPath'] = $module->getLayoutPath();
$data['paths']['viewPath'] = $module->getViewPath();
$data['components'] = $module->getComponents();
$data['parent']['id'] = (isset($module->module->id)) ? $module->module->id : null;
$data['parent']['uniqueId'] = $module->module->getUniqueId();
$data['parent']['version'] = $module->module->getVersion();
$data['parent']['paths']['basePath'] = $module->module->getBasePath();
$data['parent']['paths']['controllerPath'] = $module->module->getControllerPath();
$data['parent']['paths']['layoutPath'] = $module->module->getLayoutPath();
$data['parent']['paths']['viewPath'] = $module->module->getViewPath();
$data['extensions'] = Yii::$app->extensions;
}
$this->meta = $data;
}
/**
* Get meta data
* @return array of current module meta data
*/
public function getMetaData() {
return $this->meta;
}
/**
* Get option from DB, params or module public properties
* @return mixed of params or current module properties
*/
public function getOption($option) {
$value = null;
if (isset(Yii::$app->options)) {
if (!$value = Yii::$app->options->get($option)) {
if (preg_match('/\./', $option)) {
$split = explode('.', $option, 2);
if (count($split) > 1) {
if (!empty($split[0]) && !empty($split[1])) {
$option = $split[1];
}
}
}
if (isset(Yii::$app->params[$option]))
$value = Yii::$app->params[$option];
elseif (isset($this->$option))
$value = $this->$option;
}
} else {
if (preg_match('/\./', $option)) {
$split = explode('.', $option, 2);
if (count($split) > 1) {
if (!empty($split[0]) && !empty($split[1])) {
$section = $split[0];
$option = $split[1];
}
}
}
if (isset(Yii::$app->params[$option]))
$value = Yii::$app->params[$option];
elseif (isset($this->$option))
$value = $this->$option;
}
if (YII_ENV_DEV) {
if (isset(Yii::$app->options))
Yii::debug('Option from options`'.$option.'` is ' . gettype(Yii::$app->options->get('admin.checkForUpdates')) .' and value: '. var_export(Yii::$app->options->get('admin.checkForUpdates'), true));
if (isset(Yii::$app->params['admin.checkForUpdates']))
Yii::debug('Option from params`'.$option.'` is ' . gettype(Yii::$app->params['admin.checkForUpdates']) .' and value: '. var_export(Yii::$app->params['admin.checkForUpdates'], true));
Yii::debug('`'.$option.'` is ' . gettype($value) .' and value: '. var_export($value, true));
}
return $value;
}
/**
* {@inheritdoc}
*/
public function afterAction($action, $result)
{
// Log missing translations
if (is_array($this->missingTranslation) && YII_ENV == 'dev')
Yii::warning('Missing translations: ' . var_export($this->missingTranslation, true), 'i18n');
$result = parent::afterAction($action, $result);
return $result;
}
/**
* Registers translations for module
*/
public function registerTranslations()
{
$moduleId = 'base';
if (!is_null($this->id))
$moduleId = $this->id;
Yii::$app->i18n->translations['app/modules/' . $moduleId] = [
'class' => 'yii\i18n\PhpMessageSource',
'sourceLanguage' => 'en-US',
'basePath' => '@vendor/' . $this->vendor . '/yii2-' . $moduleId . '/messages',
'on missingTranslation' => function ($event) {
if (YII_ENV == 'dev')
$this->missingTranslation[] = $event->message;
}
];
// Name and description translation of module
$this->name = Yii::t('app/modules/' . $moduleId, $this->name);
$this->description = Yii::t('app/modules/' . $moduleId, $this->description);
}
/**
* Public translation function, Module::t('app/modules/admin', 'Dashboard');
* @return string of current message translation
*/
public static function t($category, $message, $params = [], $language = null)
{
return Yii::t('app/modules/' . self::id .'/'. $category, $message, $params, $language);
}
/**
* Normalize route
* @return string of current route
*/
public function normalizeRoute($route)
{
$route = ltrim($route, '/');
$route = rtrim($route, '/');
$route = '/'.$route;
$route = str_replace('//', '/', $route);
return $route;
}
/**
* Normalize route prefix
* @return string of current route prefix
*/
public function routePrefixNormalize()
{
if(!empty($this->routePrefix))
$this->routePrefix = self::normalizeRoute($this->routePrefix);
return $this->routePrefix;
}
/**
* Build dashboard navigation items for NavBar
* @param $options array, if you need to add a custom menu routes, like create, update, etc. item
* @return array of current module nav items
*/
public function dashboardNavItems($options = null)
{
$items = [
'label' => $this->name,
'url' => [$this->routePrefix . '/'. $this->id . ((isset($this->defaultRoute)) ? '/' . $this->defaultRoute : '')],
'active' => (\Yii::$app->controller->module->id == $this->id) ? true : false
];
if (is_array($options)) {
foreach ($options as $route => $option) {
if (is_string($route)) {
$items['items'] = [
[
'label' => (isset($option['label'])) ? $option['label'] : $route,
'icon' => (isset($option['icon'])) ? $option['icon'] : null,
'url' => [$this->routePrefix . '/' . $this->id . '/' . ltrim($route, '/')],
'active' => ((\Yii::$app->controller->module->id == $this->id) && (\Yii::$app->controller->action->id == ltrim($route, '/'))) ? true : false
],
];
}
}
}
if (!is_null($options)) {
if (isset($options['count'])) {
$items['label'] .= '<span class="badge badge-default float-right">' . $options['count'] . '</span>';
unset($options['count']);
}
if (is_array($options))
$items = ArrayHelper::merge($items, $options);
}
return $items;
}
/**
* Check if module exist
*
* @param $id
* @param bool $returnId
* @return string
*/
public function moduleExist($id, $returnId = false)
{
// If module configured without parent module, like `admin/...`
if (!(preg_match('/\/[^\s]+/', $id))) {
$parent = $this->module->id;
if ($parent)
$id = $parent . '/' . $id;
}
$isExist = (Yii::$app->hasModule($id));
if ($returnId && $isExist)
return $id;
return $isExist;
}
/**
* Check if module exist and return instance
*
* @param $id string, the module name (if the module name does not contain the parent module,
* it will be assigned from the launch module)
* @param $returnInstance boolean, the return instance of module
* @return boolean, null or intance
*/
public function moduleLoaded($id, $returnInstance = false, $autoLoad = false)
{
// If module configured without parent module, like `admin/...`
if (!(preg_match('/\/[^\s]+/', $id))) {
$parent = $this->module->id;
if ($parent)
$id = $parent . '/' . $id;
}
if ($id = $this->moduleExist($id, true)) {
if ($returnInstance)
return Yii::$app->getModule($id, $autoLoad);
else
return true;
} else {
return false;
}
return null;
}
/**
* Returns a value indicating whether the current request is made via command line (console).
*
* @return bool
*/
public function isConsole()
{
return Yii::$app->request->isConsoleRequest;
}
/**
* Returns a value indicating whether the current request made for admin dashboard.
*
* @return bool
* @throws \yii\base\InvalidConfigException
*/
public function isBackend($onlyAuth = true)
{
if ($this->isConsole())
return true;
$isBackend = false;
if (substr(Yii::$app->request->getUrl(), 0, 6) == '/admin')
return true;
if ($onlyAuth && Yii::$app->getUser()->getIsGuest())
return false;
return false;
}
public function isRestAPI()
{
if ($this->isConsole())
return false;
if (Yii::$app->controller instanceof \yii\rest\Controller)
return true;
return false;
}
/**
* Bootstrap interface, to be called during application loaded module.
* @param $app object, the application currently running
*/
public function bootstrap($app)
{
// Get URL path prefix if exist
if (isset($this->routePrefix))
$prefix = $this->routePrefix . '/';
else
$prefix = '';
// Add module URL rules
if ($urlManager = $app->getUrlManager()) {
$urlManager->addRules([
$prefix . '<module:' . $this->id . '>/<controller:\w+>/<action:\w+>/<id:\d+>' => '<module>/<controller>/<action>',
$prefix . '<module:' . $this->id . '>/<controller:\w+>/<action:\w+>' => '<module>/<controller>/<action>',
$prefix . '<module:' . $this->id . '>/<controller:\w+>' => '<module>/<controller>/index',
], true);
}
// Add short module alias, like `@sitemap` instead of long `@wdmg/sitemap`
if ($this->id !== 'base') {
Yii::setAlias('@' . $this->id, Yii::getAlias($this->getBaseAlias()));
}
// Get missing translations
$missingTranslation = $this->missingTranslation;
// Log missing translations
if (!($app instanceof \yii\console\Application) && $this->module) {
\yii\base\Event::on(\yii\base\Controller::class, \yii\base\Controller::EVENT_AFTER_ACTION, function ($event) use ($missingTranslation) {
// Log missing translations
if (is_array($missingTranslation) && YII_ENV == 'dev')
Yii::warning('Missing translations: ' . var_export($missingTranslation, true), 'i18n');
});
}
}
/**
* Register log activity of modules and user actions.
* Used in controllers.
*
* @param $message
* @param null $event
* @param null $type
* @param int $level
* @see \wdmg\activity\models\Activity
*/
public function logActivity($message, $event = null, $type = null, $level = 2) {
if (
(!empty($message) && !is_null($event)) &&
class_exists('\wdmg\activity\models\Activity') &&
$this->moduleLoaded('activity') &&
isset(Yii::$app->activity)
) {
Yii::$app->activity->set(
$message,
$event,
$type,
$level
);
}
}
/**
* Main method of installation module
* @see \wdmg\options\models\Options
*
* @return boolean, false if install failure
*/
public function install() {
if (!($options = Yii::$app->getModule('admin/options')))
$options = Yii::$app->getModule('options');
if (!is_null($options) && isset(Yii::$app->options)) {
$props = get_class_vars(get_class($this));
foreach ($props as $prop => $value) {
// Skip private properties of modules
if (in_array($prop, $this->privateProperties))
continue;
if (is_array($value))
Yii::$app->options->set($this->id .'.'. $prop, $value, 'array', null, true, false);
elseif (is_object($value))
Yii::$app->options->set($this->id .'.'. $prop, $value, 'object', null, true, false);
elseif (is_bool($value))
Yii::$app->options->set($this->id .'.'. $prop, ($value) ? 1 : 0, 'boolean', null, true, false);
else
Yii::$app->options->set($this->id .'.'. $prop, $value, null, null, true, false);
}
return true;
}
return false;
}
/**
* Main method of uninstallation module
* @return boolean, false if uninstall failure
*/
public function uninstall() {
return true;
}
/**
* Runs command in console (CLI) from web-request
*
* @param string $command, cli command, like `php yii hello/index`
* @param bool $await, flag if need wait the return execution output
* @param bool $cli, flag if need execute system comands
* @param bool $escape, flag if need to escape shell metacharacters
* @return null|array
*/
public function runConsole($command, $await = true, $cli = false, $escape = true)
{
ignore_user_abort(true);
set_time_limit(0);
$status = null;
$output = null;
$cmd = "";
if (!$cli) {
$script = Yii::getAlias('@app/yii');
$cmd = "php " . $script . " " . $command;
} else {
$cmd = $command;
}
if (!$await) {
header('Connection: close');
@ob_end_flush();
@ob_flush();
@flush();
if (session_id())
session_write_close();
}
if ($escape)
$cmd = escapeshellcmd($cmd);
if (mb_strtolower(mb_substr(php_uname(), 0, 7)) == "windows" || $cli) {
$status = popen($cmd . ' 2>&1', 'r');
$output = '';
while (!feof($status)) {
$output .= fgets($status);
}
return [pclose($status), trim($output)];
} else {
$output = exec($cmd . " > /dev/null 2>&1 &", $status);
return [$status, trim($output)];
}
}
}