Completed
Push — master ( 4c1222...393226 )
by Romain
10s
created

Code::request()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 3
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Kerox\Messenger\Api;
6
7
use Kerox\Messenger\Request\CodeRequest;
8
use Kerox\Messenger\Response\CodeResponse;
9
10
class Code extends AbstractApi
11
{
12
    private const CODE_TYPE_STANDARD = 'standard';
13
14
    /**
15
     * @param int         $imageSize
16
     * @param string      $codeType
17
     * @param string|null $ref
18
     *
19
     * @throws \InvalidArgumentException
20
     *
21
     * @return \Kerox\Messenger\Response\CodeResponse
22
     */
23
    public function request(int $imageSize = 1000, string $codeType = self::CODE_TYPE_STANDARD, ?string $ref = null): CodeResponse
24 6
    {
25
        $this->isValidCodeImageSize($imageSize);
26 6
        $this->isValidCodeType($codeType);
27 6
28
        if ($ref !== null) {
29
            $this->isValidRef($ref);
30
        }
31
32
        $request = new CodeRequest($this->pageToken, $imageSize, $codeType, $ref);
33
        $response = $this->client->post('me/messenger_codes', $request->build());
34
35 1
        return new CodeResponse($response);
36
    }
37 1
38 1
    /**
39
     * @param int $imageSize
40
     *
41 1
     * @throws \InvalidArgumentException
42
     */
43
    private function isValidCodeImageSize(int $imageSize): void
44
    {
45
        if ($imageSize < 100 || $imageSize > 2000) {
46
            throw new \InvalidArgumentException('$imageSize must be between 100 and 2000');
47
        }
48
    }
49
50
    /**
51 5
     * @param string $codeType
52
     *
53 5
     * @throws \InvalidArgumentException
54 3
     */
55
    private function isValidCodeType(string $codeType): void
56 2
    {
57 2
        $allowedCodeType = $this->getAllowedCodeType();
58
        if (!\in_array($codeType, $allowedCodeType, true)) {
59
            throw new \InvalidArgumentException('$codeType must be either ' . implode(', ', $allowedCodeType));
60 1
        }
61 1
    }
62
63 1
    /**
64
     * @param string $ref
65
     *
66
     * @throws \InvalidArgumentException
67
     */
68
    private function isValidRef(string $ref): void
69
    {
70
        if (!preg_match('/^[a-zA-Z0-9\+\/=\-.:_ ]{1,250}$/', $ref)) {
71 5
            throw new \InvalidArgumentException('$ref must be a string of max 250 characters. Valid characters are a-z A-Z 0-9 +/=-.:_');
72
        }
73 5
    }
74 2
75
    /**
76 3
     * @return array
77
     */
78
    private function getAllowedCodeType(): array
79
    {
80
        return [
81
            self::CODE_TYPE_STANDARD,
82
        ];
83 3
    }
84
}
85