Test Failed
Push — master ( d641b2...b856ab )
by Jan
03:23
created

Webhook::getIsTts()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 0
1
<?php
2
declare(strict_types=1);
3
4
namespace DiscordWebhook;
5
6
use DiscordWebhook\Generator\PayloadGenerator;
7
use Doctrine\Common\Collections\ArrayCollection;
8
use GuzzleHttp\Client;
9
use RuntimeException;
10
use SplFileInfo;
11
12
/**
13
 * Class Webhook
14
 *
15
 * @author Scrummer <[email protected]>
16
 * @package DiscordWebhook
17
 */
18
class Webhook
19
{
20
    /**
21
     * @var Client[]|ArrayCollection
22
     */
23
    private $clients;
24
25
    /**
26
     * @var null|string
27
     */
28
    private $username;
29
30
    /**
31
     * @var null|string
32
     */
33
    private $avatar;
34
35
    /**
36
     * @var null|string
37
     */
38
    private $message;
39
40
    /**
41
     * @var null|bool
42
     */
43
    private $isTts;
44
45
    /**
46
     * @var null|SplFileInfo
47
     */
48
    private $file;
49
50
    /**
51
     * @var Embed[]|ArrayCollection
52
     */
53
    private $embeds;
54
55
    /**
56
     * @var PayloadGenerator
57
     */
58
    private $payloadGenerator;
59
60
    /**
61
     * Constructor.
62
     *
63
     * @param array $url
64
     */
65
    public function __construct(array $url)
66
    {
67
        $this->embeds = new ArrayCollection();
68
        $this->clients = new ArrayCollection();
69
        $this->payloadGenerator = new PayloadGenerator();
70
71
        foreach ($url as $webhook) {
72
            $this->clients->add(new Client([
73
                'base_uri' => $webhook
74
            ]));
75
        }
76
    }
77
78
    /**
79
     * Send the Webhook
80
     *
81
     * @return bool
82
     */
83
    public function send(): bool
84
    {
85
        /** @var int[] $responseCodes */
86
        $responseCodes = [];
87
        $payload = $this->buildPayload();
88
89
        $this->clients->forAll(static function (int $key, Client $client) use ($payload) {
90
            $responseCodes[] = $client->request(
0 ignored issues
show
Comprehensibility Best Practice introduced by
$responseCodes was never initialized. Although not strictly required by PHP, it is generally a good practice to add $responseCodes = array(); before regardless.
Loading history...
91
                'POST',
92
                $client->getConfig('base_uri')->getPath(),
93
                $payload
94
            )->getStatusCode();
95
        });
96
97
        foreach ($responseCodes as $responseCode) {
98
            if (!in_array($responseCode, [200, 201, 202, 204], true)) {
99
                return false;
100
            }
101
        }
102
103
        return true;
104
    }
105
106
    private function buildPayload(): array
107
    {
108
        dump($this->payloadGenerator->generate($this));
109
110
        exit;
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return array. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
111
        // ==============================
112
        $fields = [
0 ignored issues
show
Unused Code introduced by
$fields = array('usernam..., 'embeds' => 'embeds') is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
113
            'username' => 'username',
114
            'avatar'   => 'avatar_url',
115
            'message'  => 'content',
116
            'tts'      => 'tts',
117
            'file'     => 'file',
118
            'embeds'   => 'embeds'
119
        ];
120
        $payload = [
121
            'multipart' => []
122
        ];
123
124
        foreach ($fields as $field => $payloadField) {
125
            if (!property_exists($this, $field) || null === $this->$field) {
126
                continue;
127
            }
128
129
            if (is_string($this->$field) || is_bool($this->$field)) { // add string and booloan values
130
                $payload['multipart'][] = [
131
                    'name'     => $payloadField,
132
                    'contents' => $this->$field
133
                ];
134
            } elseif ($this->$field instanceof SplFileInfo) { // add file
135
                /** @var SplFileInfo $file */
136
                $file = $this->$field;
137
138
                $payload['multipart'][] = [
139
                    'name'     => $payloadField,
140
                    'contents' => $file->openFile()->fread($file->getSize()),
141
                    'filename' => $file->getFilename()
142
                ];
143
            }
144
        }
145
146
        return $payload;
147
    }
148
149
    /**
150
     * @return string|null
151
     */
152
    public function getUsername(): ?string
153
    {
154
        return $this->username;
155
    }
156
157
    /**
158
     * @param string|null $username
159
     *
160
     * @return Webhook
161
     */
162
    public function setUsername(?string $username): Webhook
163
    {
164
        $this->username = $username;
165
166
        return $this;
167
    }
168
169
    /**
170
     * @return string|null
171
     */
172
    public function getAvatar(): ?string
173
    {
174
        return $this->avatar;
175
    }
176
177
    /**
178
     * @param string|null $avatar
179
     *
180
     * @return Webhook
181
     */
182
    public function setAvatar(?string $avatar): Webhook
183
    {
184
        $this->avatar = $avatar;
185
186
        return $this;
187
    }
188
189
    /**
190
     * @return string|null
191
     */
192
    public function getMessage(): ?string
193
    {
194
        return $this->message;
195
    }
196
197
    /**
198
     * @param string|null $message
199
     *
200
     * @return Webhook
201
     */
202
    public function setMessage(?string $message): Webhook
203
    {
204
        $this->message = $message;
205
206
        return $this;
207
    }
208
209
    /**
210
     * @return bool|null
211
     */
212
    public function getIsTts(): ?bool
213
    {
214
        return $this->isTts;
215
    }
216
217
    /**
218
     * @param bool|null $isTts
219
     *
220
     * @return Webhook
221
     */
222
    public function setIsTts(?bool $isTts): Webhook
223
    {
224
        $this->isTts = $isTts;
225
226
        return $this;
227
    }
228
229
    /**
230
     * @return SplFileInfo|null
231
     */
232
    public function getFile(): ?SplFileInfo
233
    {
234
        return $this->file;
235
    }
236
237
    /**
238
     * @param SplFileInfo|null $file
239
     *
240
     * @return Webhook
241
     */
242
    public function setFile(?SplFileInfo $file): Webhook
243
    {
244
        $this->file = $file;
245
246
        return $this;
247
    }
248
249
    /**
250
     * Add an embed to the message.
251
     *
252
     * @param Embed $embed
253
     *
254
     * @return int The index of the recently added embed
255
     */
256
    public function addEmbed(Embed $embed): int
257
    {
258
        if ($this->embeds->count() >= Embed::CONFIG_MAX_COUNT) {
259
            throw new RuntimeException(sprintf('Maximum amount of embeds reached for this message. Discord allows only %d embeds.', Embed::CONFIG_MAX_COUNT));
260
        }
261
262
        $this->embeds->add($embed);
263
264
        return (int)$this->embeds->indexOf($embed);
265
    }
266
267
    /**
268
     * @return array|null
269
     */
270
    public function getEmbeds(): ?array
271
    {
272
        return $this->embeds->isEmpty() ? null : $this->embeds->toArray();
273
    }
274
}
275