Passed
Push — develop ( 578d35...1edb03 )
by Nikolay
13:40 queued 12s
created

PBXCoreRESTClientProvider   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 39
c 1
b 0
f 0
dl 0
loc 74
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A restApiRequest() 0 47 5
A register() 0 6 1
1
<?php
2
/*
3
 * MikoPBX - free phone system for small business
4
 * Copyright © 2017-2023 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
namespace MikoPBX\Common\Providers;
23
24
use GuzzleHttp\Client;
25
use GuzzleHttp\Exception\ClientException;
26
use GuzzleHttp\Psr7\Message;
27
use MikoPBX\Common\Handlers\CriticalErrorsHandler;
28
use MikoPBX\Common\Models\PbxSettings;
29
use MikoPBX\Core\System\Util;
30
use MikoPBX\PBXCoreREST\Lib\PBXApiResult;
31
use Phalcon\Di\DiInterface;
32
use Phalcon\Di\ServiceProviderInterface;
33
34
/**
35
 * Represents a client for making REST API requests to PBX Core.
36
 *
37
 * @package MikoPBX\Common\Providers
38
 */
39
class PBXCoreRESTClientProvider implements ServiceProviderInterface
40
{
41
    public const SERVICE_NAME = 'restAPIClient';
42
    public const HTTP_METHOD_GET = 'GET';
43
    public const HTTP_METHOD_POST = 'POST';
44
45
    /**
46
     * Makes a REST API request.
47
     *
48
     * @param string $url - The API endpoint URL.
49
     * @param string $method - The HTTP method (default: 'GET').
50
     * @param array $data - Optional data to include in the request.
51
     * @return PBXApiResult - The response from the API as PBXApiResult class.
52
     */
53
    private static function restApiRequest(string $url, string $method = self::HTTP_METHOD_GET, array $data = [], array $headers = []): PBXApiResult
54
    {
55
        $res = new PBXApiResult();
56
57
        // Modify request data according to http method
58
        switch ($method){
59
            case self::HTTP_METHOD_GET:
60
                $requestData = ['query'=>$data];
61
                break;
62
            case self::HTTP_METHOD_POST:
63
                $requestData = ['form_params'=>$data];
64
                break;
65
            default:
66
                $requestData=$data;
67
        }
68
        $requestData['headers'] = $headers;
69
70
        // Get the web port from PbxSettings
71
        $webPort = PbxSettings::getValueByKey('WEBPort');
72
73
        // Create a new HTTP client instance
74
        $client = new Client([
75
            'base_uri' => 'http://localhost:' . $webPort,
76
            'timeout' => 30,
77
            'allow_redirects' => true
78
        ]);
79
80
        try {
81
            // Send the request and get the response
82
            $response = $client->request($method, $url, $requestData);
83
            $body = (string)$response->getBody();
84
            $result = json_decode($body, true);
85
            $res->data = $result['data'] ?? [];
86
            $res->messages = $result['messages'] ?? ['error' => 'Unable to parse response from core rest api'];
87
            $res->success = $result['result'] ?? false;
88
        } catch (ClientException $e) {
89
            // Handle client exception
90
            $message = "Rest API request error " . Message::toString($e->getResponse());
91
            Util::sysLogMsg(__METHOD__, $message, LOG_DEBUG);
92
            $res->messages['error'][] = $message;
93
        } catch (\Throwable $e) {
94
            // Handle other exceptions and log using CriticalErrorsHandler
95
            CriticalErrorsHandler::handleExceptionWithSyslog($e);
96
            $res->messages['error'][] = $e->getMessage();
97
        }
98
99
        return $res;
100
    }
101
102
    /**
103
     * Register the registry service provider.
104
     *
105
     * @param DiInterface $di The DI container.
106
     */
107
    public function register(DiInterface $di): void
108
    {
109
        $di->set(
110
            self::SERVICE_NAME,
111
            function (string $url, string $method = self::HTTP_METHOD_GET, array $data = []): PBXApiResult {
112
                return self::restApiRequest($url, $method, $data);
113
            }
114
        );
115
    }
116
}