Passed
Pull Request — master (#83)
by Romain
03:05
created

File::jsonSerialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 0
dl 0
loc 12
ccs 5
cts 5
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A File::isAttachmentId() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Kerox\Messenger\Model\Message\Attachment;
6
7
use Kerox\Messenger\Model\Message\Attachment;
8
9
class File extends Attachment
10
{
11
    /**
12
     * @var null|string
13
     */
14
    protected $url;
15
16
    /**
17
     * @var null|bool
18
     */
19
    protected $reusable;
20
21
    /**
22
     * @var null|string
23
     */
24
    protected $attachmentId;
25
26
    /**
27
     * File constructor.
28
     *
29
     * @param string    $url
30
     * @param bool|null $reusable
31 6
     * @param string    $type
32
     *
33 6
     * @throws \InvalidArgumentException
34
     */
35 6
    public function __construct($url, ?bool $reusable = null, $type = Attachment::TYPE_FILE)
36 1
    {
37
        parent::__construct($type);
38 5
39 5
        if ($this->isAttachmentId($url)) {
40
            $this->attachmentId = $url;
41
        } else {
42 6
            $this->isValidUrl($url);
43 6
            $this->url = $url;
44
        }
45
46
        $this->reusable = $reusable;
47
    }
48
49
    /**
50 6
     * @param string    $url
51
     * @param bool|null $reusable
52 6
     *
53
     * @throws \InvalidArgumentException
54
     *
55
     * @return \Kerox\Messenger\Model\Message\Attachment\File
56
     */
57
    public static function create($url, ?bool $reusable = null): self
58 6
    {
59
        return new self($url, $reusable);
60 6
    }
61
62
    /**
63 6
     * @param $value
64 6
     *
65 6
     * @return bool
66
     */
67
    private function isAttachmentId($value): bool
68
    {
69 6
        return (bool) preg_match('/^[\d]+$/', $value);
70
    }
71
72
    /**
73
     * @return array
74
     */
75
    public function toArray(): array
76
    {
77
        $array = parent::toArray();
78
        $array += [
79
            'payload' => [
80
                'url'           => $this->url,
81
                'is_reusable'   => $this->reusable,
82
                'attachment_id' => $this->attachmentId,
83
            ],
84
        ];
85
86
        return $this->arrayFilter($array);
87
    }
88
}
89