GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 1a23c2...5e10c9 )
by Judas
14:04
created

ClockworkSms::mergeMessageOptions()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 8.8571
c 0
b 0
f 0
cc 2
eloc 16
nc 2
nop 1
1
<?php
2
namespace DexBarrett\ClockworkSms;
3
4
use DexBarrett\ClockworkSms\Commands\CommandFactory;
5
use DexBarrett\ClockworkSms\Exception\ClockworkSmsException;
6
use GuzzleHttp\Client as GuzzleClient;
7
8
class ClockworkSms
9
{
10
    const MESSAGE_LIMIT = 500;
11
12
    private $apiKey;
13
    private $httpClient;
14
    private $commandFactory;
15
    private $format = 'xml';
16
17
    private $base = 'api.clockworksms.com';
18
19
    private $contentTypes = [
20
        'xml' => 'text/xml'
21
    ];
22
23
    private $options = [
24
        'ssl' => true,
25
        'from' => null,
26
        'long' => null,
27
        'truncate' => null,
28
        'invalidCharAction' => null,
29
    ];
30
31
    private $requiredParams = [
32
        'send' => ['to', 'message']
33
    ];
34
35
    private $validParams = [
36
        'send' => ['to', 'message', 'from', 'long', 'truncate', 'invalidCharAction']
37
    ];
38
39
    public function __construct(
40
        $apiKey = null,
41
        array $options = [],
42
        GuzzleClient $httpClient = null,
43
        CommandFactory $commandFactory = null
44
    ) {
45
        if ($apiKey === null) {
46
            throw new ClockworkSmsException('No API key provided');
47
        }
48
    
49
        $this->apiKey = $apiKey;
50
        $this->httpClient = $httpClient ?: new GuzzleClient;
51
        $this->commandFactory = $commandFactory ?: new CommandFactory;
52
        
53
        $this->parseOptions($options);
54
    }
55
56
    public function checkBalance()
57
    {
58
        return $this->sendRequest('balance');
59
    }
60
61
    public function send(array $messages)
62
    {
63
64
        $messages = ($this->containsMultipleMessages($messages))? $messages : [$messages];
65
66
        $this->validateMessages($messages);
67
68
        return $this->sendRequest('send', $this->mergeMessageOptions($messages));
69
    }
70
71
    public function getOptionValue($optionName)
72
    {
73
        $optionName = strtolower($optionName);
74
75
        if (! array_key_exists($optionName, $this->options)) {
76
            throw new ClockworkSmsException('Option does not exist');
77
        }
78
79
        return $this->options[$optionName];
80
    }
81
82
    protected function sendRequest($endpoint, $data = [])
83
    {
84
85
        $requestUrl = $this->buildApiEndpointUrl($endpoint);
86
87
        $command = $this->commandFactory->createCommand(
88
            $endpoint,
89
            $this->apiKey,
90
            $this->getFormat(),
91
            $data
92
        );
93
94
        $response = $this->httpClient->request('POST', $requestUrl, [
95
            'headers' => [
96
                'Content-Type' => $this->getContentType()
97
            ],
98
            'body' => $command->serialize()
99
        ]);
100
101
102
        return $command->deserialize((string)$response->getBody());
103
    }
104
105
106
    protected function parseOptions(array $options)
107
    {
108
        $normalizedOptions = array_change_key_case($options, CASE_LOWER);
109
110
        $this->options = array_merge(
111
            $this->options,
112
            array_intersect_key($normalizedOptions, $this->options)
113
        );
114
    }
115
116
    protected function getContentType()
117
    {
118
        return $this->contentTypes[$this->format];
119
    }
120
121
    protected function getFormat()
122
    {
123
        return $this->format;
124
    }
125
126
    private function containsMultipleMessages($messages)
127
    {
128
        return count(array_filter($messages, 'is_array')) > 0;
129
    }
130
131
    protected function buildApiEndpointUrl($endpoint)
132
    {
133
        return sprintf(
134
            '%s://%s/%s/%s',
135
            ($this->getOptionValue('ssl'))? 'https':'http',
136
            $this->base,
137
            $this->format,
138
            $endpoint
139
        );
140
    }
141
142
    protected function validateParameters($method, $parameters)
143
    {
144
        $missingParameters = array_diff(
145
            $this->requiredParams[$method],
146
            array_keys($parameters)
147
        );
148
149
        if (count($missingParameters)) {
150
            throw new ClockworkSmsException(
151
                "the following parameters are missing in call to method '{$method}': "
152
                . implode(', ', $missingParameters)
153
            );
154
        }
155
    }
156
157
    protected function validateMessages($messages)
158
    {
159
        if ($this->exceedsMessageLimit($messages)) {
160
            throw new ClockworkSmsException(sprintf(
161
                'Please call the send method with a maximum of %d messages',
162
                self::MESSAGE_LIMIT
163
            ));
164
        }
165
166
        foreach ($messages as $message) {
167
            $this->validateParameters('send', $message);
168
        }
169
    }
170
171
    protected function exceedsMessageLimit($messages)
172
    {
173
        return count($messages) > self::MESSAGE_LIMIT;
174
    }
175
176
    protected function mergeMessageOptions(array $messages)
177
    {
178
        $mergedMessages = [];
179
180
        $globalMessageOptions = array_filter(
181
            $this->options,
182
            function ($value, $key) {
183
                return $key != 'ssl';
184
            },
185
            ARRAY_FILTER_USE_BOTH
186
        );
187
188
        foreach ($messages as $message) {
189
            $validParams = array_intersect_key(
190
                $message,
191
                array_flip($this->validParams['send'])
192
            );
193
194
            $mergedMessages[] = array_filter(
195
                array_merge($globalMessageOptions, $validParams),
196
                function ($value) {
197
                    return $value !== null;
198
                }
199
            );
200
        }
201
202
        return $mergedMessages;
203
    }
204
}
205