Completed
Pull Request — master (#127)
by Alexandr
05:03
created

ValidatorTrait::isValidDateTime()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 6
c 0
b 0
f 0
ccs 5
cts 5
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Kerox\Messenger\Helper;
6
7
use Kerox\Messenger\Exception\InvalidArrayException;
8
use Kerox\Messenger\Exception\InvalidClassException;
9
use Kerox\Messenger\Exception\InvalidColorException;
10
use Kerox\Messenger\Exception\InvalidCountryException;
11
use Kerox\Messenger\Exception\InvalidCurrencyException;
12
use Kerox\Messenger\Exception\InvalidDateTimeException;
13
use Kerox\Messenger\Exception\InvalidExtensionException;
14
use Kerox\Messenger\Exception\InvalidKeyException;
15
use Kerox\Messenger\Exception\InvalidLocaleException;
16
use Kerox\Messenger\Exception\InvalidStringException;
17
use Kerox\Messenger\Exception\InvalidTypeException;
18
use Kerox\Messenger\Exception\InvalidUrlException;
19
use Kerox\Messenger\Exception\MessengerException;
20
use Kerox\Messenger\Model\Common\Button\AbstractButton;
21
use Kerox\Messenger\Model\Message;
22
use Kerox\Messenger\Model\Message\Attachment;
23
use Kerox\Messenger\Model\Message\Attachment\Template\GenericTemplate;
24
use Kerox\Messenger\SendInterface;
25
26
trait ValidatorTrait
27
{
28
    /**
29
     * @param string $value
30
     *
31
     * @throws \Kerox\Messenger\Exception\InvalidColorException
32
     */
33 2
    protected function isValidColor(string $value): void
34
    {
35 2
        if (!preg_match('/^#[A-Fa-f0-9]{6}$/', $value)) {
36 1
            throw new InvalidColorException('The color must be expressed in #rrggbb format.');
37
        }
38 1
    }
39
40
    /**
41
     * @param string $value
42
     * @param int    $length
43
     *
44
     * @throws \Kerox\Messenger\Exception\InvalidStringException
45
     */
46 45
    protected function isValidString(string $value, int $length = 20): void
47
    {
48 45
        if (mb_strlen($value) > $length) {
49 1
            throw new InvalidStringException(sprintf('String should not exceed %s characters.', $length));
50
        }
51 44
    }
52
53
    /**
54
     * @param string $value
55
     *
56
     * @throws \Kerox\Messenger\Exception\InvalidUrlException
57
     */
58 36
    protected function isValidUrl(string $value): void
59
    {
60 36
        if (!preg_match(
61 36
            '/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&\/=]*)$/',
62 36
            $value
63
        )) {
64 1
            throw new InvalidUrlException(sprintf('%s is not a valid url.', $value));
65
        }
66 35
    }
67
68
    /**
69
     * @param string $value
70
     *
71
     * @throws \Kerox\Messenger\Exception\InvalidLocaleException
72
     */
73 8
    protected function isValidLocale(string $value): void
74
    {
75 8
        if (!preg_match('/^[a-z]{2}_[A-Z]{2}$/', $value)) {
76 1
            throw new InvalidLocaleException(sprintf(
77 1
                '%s is not valid. Locale must be in ISO-639-1 and ISO-3166-1 format like fr_FR.',
78 1
                $value
79
            ));
80
        }
81 7
    }
82
83
    /**
84
     * @param string $value
85
     *
86
     * @throws \Kerox\Messenger\Exception\InvalidCountryException
87
     */
88 2
    protected function isValidCountry(string $value): void
89
    {
90 2
        if (!preg_match('/^[A-Z]{2}$/', $value)) {
91 1
            throw new InvalidCountryException(sprintf(
92 1
                '%s is not valid. Country must be in ISO 3166 Alpha-2 format like FR.',
93 1
                $value
94
            ));
95
        }
96 1
    }
97
98
    /**
99
     * @param string $value
100
     *
101
     * @throws \Kerox\Messenger\Exception\InvalidDateTimeException
102
     */
103 11
    protected function isValidDateTime(string $value): void
104
    {
105 11
        if (!preg_match('/^(\d{4})-(0[1-9]|1[0-2])-([12]\d|0[1-9]|3[01])T(0\d|1\d|2[0-3]):([0-5]\d)$/', $value)) {
106 1
            throw new InvalidDateTimeException(sprintf(
107 1
                '%s is not valid. DateTime must be in ISO-8601 AAAA-MM-JJThh:mm format.',
108 1
                $value
109
            ));
110
        }
111 10
    }
112
113
    /**
114
     * @param array $array
115
     * @param int   $maxSize
116
     * @param int   $minSize
117
     *
118
     * @throws \Kerox\Messenger\Exception\InvalidArrayException
119
     */
120 28
    protected function isValidArray(array $array, int $maxSize, ?int $minSize = null): void
121
    {
122 28
        $countArray = \count($array);
123 28
        if ($minSize !== null && $countArray < $minSize) {
124 1
            throw new InvalidArrayException(sprintf('The minimum number of items for this array is %d.', $minSize));
125
        }
126 27
        if ($countArray > $maxSize) {
127 3
            throw new InvalidArrayException(sprintf('The maximum number of items for this array is %d.', $maxSize));
128
        }
129 26
    }
130
131
    /**
132
     * @param string $value
133
     *
134
     * @throws \Kerox\Messenger\Exception\InvalidCurrencyException
135
     */
136 8
    protected function isValidCurrency(string $value): void
137
    {
138 8
        $allowedCurrency = $this->getAllowedCurrency();
139
140 8
        $regex = '/^' . implode('|', $allowedCurrency) . '$/';
141 8
        if (!preg_match($regex, $value)) {
142 1
            throw new InvalidCurrencyException(sprintf(
143 1
                '%s is not a valid currency. Currency must be in ISO-4217-3 format.',
144 1
                $value
145
            ));
146
        }
147 7
    }
148
149
    /**
150
     * @param string $filename
151
     * @param array  $allowedExtension
152
     *
153
     * @throws \Kerox\Messenger\Exception\InvalidExtensionException
154
     */
155 4
    protected function isValidExtension(string $filename, array $allowedExtension): void
156
    {
157 4
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
158 4
        if (empty($ext) || !\in_array($ext, $allowedExtension, true)) {
159 1
            throw new InvalidExtensionException(sprintf(
160 1
                '%s does not have a valid extension. Allowed extensions are "%s".',
161 1
                $filename,
162 1
                implode(', ', $allowedExtension)
163
            ));
164
        }
165 3
    }
166
167
    /**
168
     * @param \Kerox\Messenger\Model\Common\Button\AbstractButton[] $buttons
169
     * @param array                                                 $allowedButtonsType
170
     *
171
     * @throws \Kerox\Messenger\Exception\InvalidClassException
172
     */
173 8
    protected function isValidButtons(array $buttons, array $allowedButtonsType): void
174
    {
175
        /** @var \Kerox\Messenger\Model\Common\Button\AbstractButton $button */
176 8
        foreach ($buttons as $button) {
177 8
            if (!$button instanceof AbstractButton) {
178 1
                throw new InvalidClassException(
179 1
                    sprintf('Array can only contain instance of %s.', AbstractButton::class)
180
                );
181
            }
182
183 7
            if (!\in_array($button->getType(), $allowedButtonsType, true)) {
184 3
                throw new InvalidClassException(sprintf(
185 3
                    'Buttons can only be an instance of %s.',
186 7
                    implode(', ', $allowedButtonsType)
187
                ));
188
            }
189
        }
190 5
    }
191
192
    /**
193
     * @param $message
194
     *
195
     * @throws \Kerox\Messenger\Exception\MessengerException
196
     *
197
     * @return \Kerox\Messenger\Model\Message
198
     */
199 12
    protected function isValidMessage($message): Message
200
    {
201 12
        if ($message instanceof Message) {
202
            return $message;
203
        }
204
205 12
        if (\is_string($message) || $message instanceof Attachment) {
206 11
            return Message::create($message);
207
        }
208
209 1
        throw new MessengerException(sprintf(
210 1
            'message must be a string or an instance of %s or %s.',
211 1
            Message::class,
212 1
            Attachment::class
213
        ));
214
    }
215
216
    /**
217
     * @param string $action
218
     *
219
     * @throws \Kerox\Messenger\Exception\InvalidKeyException
220
     */
221 2
    protected function isValidSenderAction(string $action): void
222
    {
223 2
        $allowedSenderAction = $this->getAllowedSenderAction();
224 2
        if (!\in_array($action, $allowedSenderAction, true)) {
225 1
            throw new InvalidKeyException(sprintf(
226 1
                'action must be either "%s".',
227 1
                implode(', ', $allowedSenderAction)
228
            ));
229
        }
230 1
    }
231
232
    /**
233
     * @param string $messagingType
234
     *
235
     * @throws InvalidTypeException
236
     */
237 2
    protected function isValidMessagingType(string $messagingType): void
238
    {
239 2
        $allowedMessagingType = $this->getAllowedMessagingType();
240 2
        if (!\in_array($messagingType, $allowedMessagingType, true)) {
241 1
            throw new InvalidTypeException(sprintf(
242 1
                'messagingType must be either "%s".',
243 1
                implode(', ', $allowedMessagingType)
244
            ));
245
        }
246 1
    }
247
248
    /**
249
     * @param string $notificationType
250
     *
251
     * @throws \Kerox\Messenger\Exception\InvalidTypeException
252
     */
253 5
    protected function isValidNotificationType(string $notificationType): void
254
    {
255 5
        $allowedNotificationType = $this->getAllowedNotificationType();
256 5
        if (!\in_array($notificationType, $allowedNotificationType, true)) {
257 1
            throw new InvalidTypeException(sprintf(
258 1
                'notificationType must be either "%s".',
259 1
                implode(', ', $allowedNotificationType)
260
            ));
261
        }
262 4
    }
263
264
    /**
265
     * @param string                         $tag
266
     * @param \Kerox\Messenger\Model\Message $message
267
     *
268
     * @throws \Kerox\Messenger\Exception\InvalidClassException
269
     * @throws \Kerox\Messenger\Exception\InvalidKeyException
270
     */
271 3
    protected function isValidTag(string $tag, Message $message = null): void
272
    {
273 3
        $allowedTag = $this->getAllowedTag();
274 3
        if (!\in_array($tag, $allowedTag, true)) {
275 1
            throw new InvalidKeyException(sprintf(
276 1
                'tag must be either "%s".',
277 1
                implode(', ', $allowedTag)
278
            ));
279
        }
280
281 2
        if ($tag === SendInterface::TAG_ISSUE_RESOLUTION && $message !== null && !$message instanceof GenericTemplate) {
282 1
            throw new InvalidClassException(sprintf(
283 1
                'message must be an instance of %s if tag is set to %s.',
284 1
                GenericTemplate::class,
285 1
                SendInterface::TAG_ISSUE_RESOLUTION
286
            ));
287
        }
288 1
    }
289
290
    /**
291
     * @return array
292
     */
293 2
    public function getAllowedSenderAction(): array
294
    {
295
        return [
296 2
            SendInterface::SENDER_ACTION_TYPING_ON,
297 2
            SendInterface::SENDER_ACTION_TYPING_OFF,
298 2
            SendInterface::SENDER_ACTION_MARK_SEEN,
299
        ];
300
    }
301
302
    /**
303
     * @return array
304
     */
305 2
    public function getAllowedMessagingType(): array
306
    {
307
        return [
308 2
            self::MESSAGING_TYPE_RESPONSE,
0 ignored issues
show
Bug introduced by
The constant Kerox\Messenger\Helper\V...MESSAGING_TYPE_RESPONSE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
309 2
            self::MESSAGING_TYPE_MESSAGE_TAG,
0 ignored issues
show
Bug introduced by
The constant Kerox\Messenger\Helper\V...SAGING_TYPE_MESSAGE_TAG was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
310 2
            self::MESSAGING_TYPE_NON_PROMOTIONAL_SUBSCRIPTION,
0 ignored issues
show
Bug introduced by
The constant Kerox\Messenger\Helper\V...ROMOTIONAL_SUBSCRIPTION was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
311 2
            self::MESSAGING_TYPE_UPDATE,
0 ignored issues
show
Bug introduced by
The constant Kerox\Messenger\Helper\V...::MESSAGING_TYPE_UPDATE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
312
        ];
313
    }
314
315
    /**
316
     * @return array
317
     */
318 5
    public function getAllowedNotificationType(): array
319
    {
320
        return [
321 5
            SendInterface::NOTIFICATION_TYPE_REGULAR,
322 5
            SendInterface::NOTIFICATION_TYPE_SILENT_PUSH,
323 5
            SendInterface::NOTIFICATION_TYPE_NO_PUSH,
324
        ];
325
    }
326
327
    /**
328
     * @return array
329
     */
330 3
    public function getAllowedTag(): array
331
    {
332
        return [
333 3
            SendInterface::TAG_BUSINESS_PRODUCTIVITY,
334 3
            SendInterface::TAG_COMMUNITY_ALERT,
335 3
            SendInterface::TAG_CONFIRMED_EVENT_REMINDER,
336 3
            SendInterface::TAG_NON_PROMOTIONAL_SUBSCRIPTION,
337 3
            SendInterface::TAG_PAIRING_UPDATE,
338 3
            SendInterface::TAG_APPLICATION_UPDATE,
339 3
            SendInterface::TAG_ACCOUNT_UPDATE,
340 3
            SendInterface::TAG_PAYMENT_UPDATE,
341 3
            SendInterface::TAG_PERSONAL_FINANCE_UPDATE,
342 3
            SendInterface::TAG_SHIPPING_UPDATE,
343 3
            SendInterface::TAG_RESERVATION_UPDATE,
344 3
            SendInterface::TAG_ISSUE_RESOLUTION,
345 3
            SendInterface::TAG_APPOINTMENT_UPDATE,
346 3
            SendInterface::TAG_GAME_EVENT,
347 3
            SendInterface::TAG_TRANSPORTATION_UPDATE,
348 3
            SendInterface::TAG_FEATURE_FUNCTIONALITY_UPDATE,
349 3
            SendInterface::TAG_TICKET_UPDATE,
350
        ];
351
    }
352
353
    /**
354
     * @return array
355
     */
356 8
    public function getAllowedCurrency(): array
357
    {
358
        return [
359 8
            'SGD',
360
            'RON',
361
            'EUR',
362
            'TRY',
363
            'SEK',
364
            'ZAR',
365
            'HKD',
366
            'CHF',
367
            'NIO',
368
            'JPY',
369
            'ISK',
370
            'TWD',
371
            'NZD',
372
            'CZK',
373
            'AUD',
374
            'THB',
375
            'BOB',
376
            'BRL',
377
            'MXN',
378
            'USD',
379
            'ILS',
380
            'HNL',
381
            'MOP',
382
            'COP',
383
            'UYU',
384
            'CRC',
385
            'DKK',
386
            'QAR',
387
            'PYG',
388
            'CAD',
389
            'INR',
390
            'KRW',
391
            'GTQ',
392
            'AED',
393
            'VEF',
394
            'SAR',
395
            'NOK',
396
            'CNY',
397
            'ARS',
398
            'PLN',
399
            'GBP',
400
            'PEN',
401
            'PHP',
402
            'VND',
403
            'RUB',
404
            'HUF',
405
            'MYR',
406
            'CLP',
407
            'IDR',
408
        ];
409
    }
410
}
411