Passed
Push — master ( 5e9e3d...710625 )
by Maciej
04:36 queued 11s
created

AbstractHandler::sendRequest()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 25
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 18
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 25
ccs 0
cts 19
cp 0
crap 6
rs 9.6666
1
<?php
2
/**
3
 * File: AbstractHandler.php
4
 *
5
 * @author      Maciej Sławik <[email protected]>
6
 * Github:      https://github.com/maciejslawik
7
 */
8
9
namespace MSlwk\FreshMail\Handler;
10
11
use MSlwk\FreshMail\Error\ErrorHandlerInterface;
12
use MSlwk\FreshMail\Exception\Connection\FreshMailConnectionException;
13
14
/**
15
 * Class AbstractHandler
16
 *
17
 * @package MSlwk\FreshMail\Handler
18
 */
19
abstract class AbstractHandler
20
{
21
    const API_URL = 'https://api.freshmail.com';
22
23
    /**
24
     * @var ErrorHandlerInterface
25
     */
26
    protected $errorHandler;
27
28
    /**
29
     * @var string
30
     */
31
    protected $apiKey;
32
33
    /**
34
     * @var string
35
     */
36
    protected $apiSecret;
37
38
    /**
39
     * AbstractHandler constructor.
40
     *
41
     * @param ErrorHandlerInterface $errorHandler
42
     * @param string $apiKey
43
     * @param string $apiSecret ]
44
     */
45 973
    public function __construct(ErrorHandlerInterface $errorHandler, string $apiKey, string $apiSecret)
46
    {
47 973
        $this->errorHandler = $errorHandler;
48 973
        $this->apiKey = $apiKey;
49 973
        $this->apiSecret = $apiSecret;
50 973
    }
51
52
    /**
53
     * @param string $getData
54
     * @param string $jsonData
55
     * @return string
56
     */
57 7
    protected function getAuthorizationHash(string $getData, string $jsonData): string
58
    {
59 7
        return sha1($this->apiKey . $getData . $jsonData . $this->apiSecret);
60
    }
61
62
    /**
63
     * @param array $getRequestParams
64
     * @param array $postRequestParams
65
     * @return \stdClass
66
     */
67 812
    protected function processRequest(array $getRequestParams = [], array $postRequestParams = []): \stdClass
68
    {
69 812
        $apiResponse = $this->sendRequest(
70 812
            $this->generateGetParamsString($getRequestParams),
71 812
            $this->generatePostParamsString($postRequestParams)
72
        );
73
74 812
        $responseObject = json_decode($apiResponse);
75 812
        $this->validate($responseObject);
76 126
        return $responseObject;
77
    }
78
79
    /**
80
     * @param string $getRequestParamsString
81
     * @param string $postRequestParamsString
82
     * @return string
83
     * @throws FreshMailConnectionException
84
     */
85
    protected function sendRequest(string $getRequestParamsString, string $postRequestParamsString): string
86
    {
87
        $headers = [
88
            'Content-Type: application/json',
89
            'X-Rest-ApiKey: ' . $this->apiKey,
90
            'X-Rest-ApiSign: ' . $this->getAuthorizationHash(
91
                $this->getApiEndpoint() . $getRequestParamsString,
92
                $postRequestParamsString
93
            )
94
        ];
95
        $curl = curl_init(self::API_URL . $this->getApiEndpoint() . $getRequestParamsString);
96
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
97
        curl_setopt($curl, CURLOPT_HEADER, true);
98
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
99
        if ($postRequestParamsString) {
100
            curl_setopt($curl, CURLOPT_POSTFIELDS, $postRequestParamsString);
101
            curl_setopt($curl, CURLOPT_POST, true);
102
        }
103
        $rawResponse = curl_exec($curl);
104
105
        $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
106
        $response = substr($rawResponse, $headerSize);
0 ignored issues
show
Bug introduced by
It seems like $rawResponse can also be of type true; however, parameter $string of substr() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

106
        $response = substr(/** @scrutinizer ignore-type */ $rawResponse, $headerSize);
Loading history...
107
        curl_close($curl);
108
109
        return $response;
110
    }
111
112
    /**
113
     * @param $response
114
     * @throws FreshMailConnectionException
115
     */
116 812
    protected function validate($response)
117
    {
118 812
        if (!$response instanceof \stdClass) {
119 7
            throw new FreshMailConnectionException();
120
        }
121 805
        if ($response->status !== 'OK') {
122 679
            $this->errorHandler->raiseException($response->errors[0]);
123
        }
124 126
    }
125
126
    /**
127
     * @param array $getParams
128
     * @return string
129
     */
130 826
    private function generateGetParamsString(array $getParams): string
131
    {
132 826
        $requstParamsString = '';
133 826
        foreach ($getParams as $param) {
134 28
            $requstParamsString .= '/' . $param;
135
        }
136 826
        return $requstParamsString;
137
    }
138
139
    /**
140
     * @param array $postParams
141
     * @return string
142
     */
143 826
    private function generatePostParamsString(array $postParams): string
144
    {
145 826
        if (empty($postParams)) {
146 84
            $requestParamsString = '';
147
        } else {
148 742
            $requestParamsString = json_encode($postParams);
149
        }
150 826
        return $requestParamsString;
151
    }
152
153
    /**
154
     * @return string
155
     */
156
    abstract protected function getApiEndpoint(): string;
157
}
158