Passed
Push — develop ( 06fb87...d66898 )
by Nikolay
23:43
created

RouterProvider   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 168
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 12
eloc 72
dl 0
loc 168
rs 10
c 1
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getRoutes() 0 46 1
A getMiddleware() 0 6 1
A register() 0 11 1
A attachRoutes() 0 21 2
A hookModulesMethodGetPBXCoreRESTAdditionalRoutes() 0 22 5
A attachMiddleware() 0 10 2
1
<?php
2
/*
3
 * MikoPBX - free phone system for small business
4
 * Copyright (C) 2017-2020 Alexey Portnov and Nikolay Beketov
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with this program.
17
 * If not, see <https://www.gnu.org/licenses/>.
18
 */
19
20
declare(strict_types=1);
21
22
23
namespace MikoPBX\PBXCoreREST\Providers;
24
25
use MikoPBX\PBXCoreREST\Controllers\{Cdr\GetController as CdrGetController,
26
    Iax\GetController as IaxGetController,
27
    Modules\ModulesControllerBase,
28
    Sip\GetController as SipGetController,
29
    Sip\PostController as SipPostController,
30
    Storage\GetController as StorageGetController,
31
    Storage\PostController as StoragePostController,
32
    Syslog\GetController as SyslogGetController,
33
    Syslog\PostController as SyslogPostController,
34
    Sysinfo\GetController as SysinfoGetController,
35
    Sysinfo\PostController as SysinfoPostController,
36
    System\GetController as SystemGetController,
37
    System\PostController as SystemPostController,
38
    Files\GetController as FilesGetController,
39
    Files\PostController as FilesPostController,
40
    Advices\GetController as AdvicesGetController,
41
    License\GetController as LicenseGetController,
42
    License\PostController as LicensePostController
43
};
44
use MikoPBX\Common\Providers\PBXConfModulesProvider;
45
use MikoPBX\Core\System\Util;
46
use MikoPBX\Modules\Config\ConfigClass;
47
use MikoPBX\PBXCoreREST\Middleware\AuthenticationMiddleware;
48
use MikoPBX\PBXCoreREST\Middleware\NotFoundMiddleware;
49
use MikoPBX\PBXCoreREST\Middleware\ResponseMiddleware;
50
use Phalcon\Di\DiInterface;
51
use Phalcon\Di\ServiceProviderInterface;
52
use Phalcon\Events\Manager;
53
use Phalcon\Mvc\Micro;
54
use Phalcon\Mvc\Micro\Collection;
55
use Throwable;
56
57
58
/**
59
 * Register Router service
60
 */
61
class RouterProvider implements ServiceProviderInterface
62
{
63
    public const SERVICE_NAME = '';
64
65
    /**
66
     * Register response service provider
67
     *
68
     * @param \Phalcon\Di\DiInterface $di
69
     */
70
    public function register(DiInterface $di): void
71
    {
72
        /** @var Micro $application */
73
        $application = $di->getShared('application');
74
        /** @var Manager $eventsManager */
75
        $eventsManager = $di->getShared('eventsManager');
76
77
        $this->attachRoutes($application, $di);
78
        $this->attachMiddleware($application, $eventsManager);
79
80
        $application->setEventsManager($eventsManager);
81
    }
82
83
    /**
84
     * Attaches the routes to the application; lazy loaded
85
     *
86
     * @param Micro                   $application
87
     * @param \Phalcon\Di\DiInterface $di
88
     */
89
    private function attachRoutes(Micro $application, DiInterface $di): void
90
    {
91
        // Add hard coded routes
92
        $routes = $this->getRoutes();
93
94
        // Add additional modules routes
95
        $additionalRoutes  = $this->hookModulesMethodGetPBXCoreRESTAdditionalRoutes($di);
96
        $routes = array_merge($routes, ...$additionalRoutes);
97
98
        // Class, Method, Route, Handler, ParamsRegex
99
        foreach ($routes as $route) {
100
            $collection = new Collection();
101
            $collection
102
                ->setHandler($route[0], true)
103
                ->setPrefix($route[2])
104
                ->{$route[3]}(
105
                    $route[4],
106
                    $route[1]
107
                );
108
109
            $application->mount($collection);
110
        }
111
    }
112
113
    /**
114
     * Calls extensions modules for additional routes list
115
     *
116
     * @param \Phalcon\Di\DiInterface $di
117
     *
118
     * @return array
119
     */
120
    private function hookModulesMethodGetPBXCoreRESTAdditionalRoutes(DiInterface $di): array
121
    {
122
        $arrAdditionalRoutes = [];
123
        $additionalModules = $di->getShared(PBXConfModulesProvider::SERVICE_NAME);
124
        $method = ConfigClass::GET_PBXCORE_REST_ADDITIONAL_ROUTES;
125
        foreach ($additionalModules as $configClassObj) {
126
            if ( ! method_exists($configClassObj, $method)) {
127
                continue;
128
            }
129
            try {
130
                $additionalRoutes = call_user_func_array([$configClassObj, $method], []);
131
            } catch (Throwable $e) {
132
                global $errorLogger;
133
                $errorLogger->captureException($e);
134
                Util::sysLogMsg(__METHOD__, $e->getMessage(), LOG_ERR);
135
                continue;
136
            }
137
            if ( ! empty($additionalRoutes)) {
138
                $arrAdditionalRoutes[] = $additionalRoutes;
139
            }
140
        }
141
        return $arrAdditionalRoutes;
142
    }
143
144
    /**
145
     * Returns the array for the routes
146
     *
147
     * @return array
148
     */
149
    private function getRoutes(): array
150
    {
151
        return [
152
            // Class, Method, Route, Handler, ParamsRegex
153
154
            [SipGetController::class, 'callAction', '/pbxcore/api/sip/{actionName}', 'get', '/'],
155
            [SipPostController::class, 'callAction', '/pbxcore/api/sip/{actionName}', 'post', '/'],
156
157
            [IaxGetController::class, 'callAction', '/pbxcore/api/iax/{actionName}', 'get', '/'],
158
159
            [CdrGetController::class, 'callAction', '/pbxcore/api/cdr/{actionName}', 'get', '/'],
160
            [CdrGetController::class, 'playbackAction', '/pbxcore/api/cdr/playback', 'get', '/'],
161
162
            [StorageGetController::class, 'callAction', '/pbxcore/api/storage/{actionName}', 'get', '/'],
163
            [StoragePostController::class, 'callAction', '/pbxcore/api/storage/{actionName}', 'post', '/'],
164
165
            [SystemGetController::class, 'callAction', '/pbxcore/api/system/{actionName}', 'get', '/'],
166
            [SystemPostController::class, 'callAction', '/pbxcore/api/system/{actionName}', 'post', '/'],
167
168
            [SyslogGetController::class, 'callAction', '/pbxcore/api/syslog/{actionName}', 'get', '/'],
169
            [SyslogPostController::class, 'callAction', '/pbxcore/api/syslog/{actionName}', 'post', '/'],
170
171
            [SysinfoGetController::class, 'callAction', '/pbxcore/api/sysinfo/{actionName}', 'get', '/'],
172
            [SysinfoPostController::class, 'callAction', '/pbxcore/api/sysinfo/{actionName}', 'post', '/'],
173
174
            [FilesGetController::class, 'callAction', '/pbxcore/api/files/{actionName}', 'get', '/'],
175
            [FilesPostController::class, 'callAction', '/pbxcore/api/files/{actionName}', 'post', '/'],
176
177
            [AdvicesGetController::class, 'callAction', '/pbxcore/api/advices/{actionName}', 'get', '/'],
178
179
            [LicenseGetController::class, 'callAction', '/pbxcore/api/license/{actionName}', 'get', '/'],
180
            [LicensePostController::class, 'callAction', '/pbxcore/api/license/{actionName}', 'post', '/'],
181
182
            [
183
                ModulesControllerBase::class,
184
                'callActionForModule',
185
                '/pbxcore/api/modules/{moduleName}/{actionName}',
186
                'get',
187
                '/',
188
            ],
189
            [
190
                ModulesControllerBase::class,
191
                'callActionForModule',
192
                '/pbxcore/api/modules/{moduleName}/{actionName}',
193
                'post',
194
                '/',
195
            ],
196
        ];
197
    }
198
199
    /**
200
     * Attaches the middleware to the application
201
     *
202
     * @param Micro   $application
203
     * @param Manager $eventsManager
204
     */
205
    private function attachMiddleware(Micro $application, Manager $eventsManager): void
206
    {
207
        $middleware = $this->getMiddleware();
208
209
        /**
210
         * Get the events manager and attach the middleware to it
211
         */
212
        foreach ($middleware as $class => $function) {
213
            $eventsManager->attach('micro', new $class());
214
            $application->{$function}(new $class());
215
        }
216
    }
217
218
    /**
219
     * Returns the array for the middleware with the action to attach
220
     *
221
     * @return array
222
     */
223
    private function getMiddleware(): array
224
    {
225
        return [
226
            NotFoundMiddleware::class       => 'before',
227
            AuthenticationMiddleware::class => 'before',
228
            ResponseMiddleware::class       => 'after',
229
        ];
230
    }
231
232
}