-
Notifications
You must be signed in to change notification settings - Fork 23
/
Module.php
109 lines (93 loc) · 3.07 KB
/
Module.php
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
<?php
/**
* @link https://www.humhub.org/
* @copyright Copyright (c) 2018 HumHub GmbH & Co. KG
* @license https://www.humhub.com/licences
*/
namespace humhub\modules\rest;
use humhub\components\bootstrap\ModuleAutoLoader;
use humhub\components\Module as BaseModule;
use Yii;
use yii\helpers\Url;
class Module extends BaseModule
{
/**
* @event triggered before a request (inside event Application::EVENT_BEFORE_REQUEST of this Module)
*/
public const EVENT_REST_API_ADD_RULES = 'restApiAddRules';
/**
* @var string Prefix for REST API endpoint URLs
*/
public const API_URL_PREFIX = 'api/v1/';
/**
* @inheritdoc
*/
public $resourcesPath = 'resources';
/**
* @inheritdoc
*/
public function getConfigUrl()
{
return Url::to(['/rest/admin/index']);
}
/**
* Add REST API endpoint rules
*
* @param array $rules
* @param string $moduleId Provide module id if you want to make if disabled from settings of the module "REST API"
*/
public function addRules($rules, $moduleId = null)
{
if ($moduleId !== null && !$this->isActiveModule($moduleId)) {
return;
}
foreach ($rules as $r => $rule) {
if (isset($rule['pattern'])) {
$rules[$r]['pattern'] = self::API_URL_PREFIX . ltrim($rule['pattern'], '/');
}
}
Yii::$app->urlManager->addRules($rules);
}
/**
* Get enabled modules which have event to add REST API endpoints
*
* @return BaseModule[]
*/
public function getModulesWithRestApi()
{
$enabledModules = Yii::$app->moduleManager->getEnabledModules();
$restApiClass = Module::class;
$restApiEvent = Module::EVENT_REST_API_ADD_RULES;
$restApiModules = [];
foreach ($enabledModules as $enabledModule) {
/* @var BaseModule $enabledModule */
$moduleConfigFilePath = $enabledModule->getBasePath() . DIRECTORY_SEPARATOR . ModuleAutoLoader::CONFIGURATION_FILE;
if (!file_exists($moduleConfigFilePath)) {
continue;
}
$moduleConfig = require $moduleConfigFilePath;
if (empty($moduleConfig['events'])) {
continue;
}
foreach ($moduleConfig['events'] as $event) {
if ((isset($event['class'], $event['event']) && $event['class'] == $restApiClass && $event['event'] == $restApiEvent) ||
(isset($event[0], $event[1]) && $event[0] == $restApiClass && $event[1] == $restApiEvent)) {
$restApiModules[] = $enabledModule;
break;
}
}
}
return $restApiModules;
}
/**
* Check if the module is active for additional REST API endpoins
*
* @param string $moduleId
* @return bool
*/
public function isActiveModule($moduleId)
{
$apiModules = (array)$this->settings->getSerialized('apiModules');
return !isset($apiModules[$moduleId]) || $apiModules[$moduleId];
}
}