Completed
Push — master ( af8828...3a4530 )
by Vladimir
02:46
created

Attachment::toArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
ccs 0
cts 3
cp 0
rs 9.4285
cc 1
eloc 4
nc 1
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace FondBot\Contracts\Drivers\Message;
6
7
use FondBot\Bot;
8
use FondBot\Contracts\Core\Arrayable;
9
use FondBot\Contracts\Filesystem\File;
10
use GuzzleHttp\Client;
11
12
class Attachment implements Arrayable
13
{
14
    public const TYPE_FILE = 'file';
15
    public const TYPE_IMAGE = 'image';
16
    public const TYPE_AUDIO = 'audio';
17
    public const TYPE_VIDEO = 'video';
18
19
    protected $type;
20
    protected $path;
21
    protected $contents;
22
    protected $guzzle;
23
24 8
    public function __construct(string $type, string $path, Client $guzzle = null)
25
    {
26 8
        $this->type = $type;
27 8
        $this->path = $path;
28 8
        $this->guzzle = $guzzle ?? Bot::getInstance()->get(Client::class);
29 8
    }
30
31
    /**
32
     * Get attachment type.
33
     *
34
     * @return string
35
     */
36 8
    public function getType(): string
37
    {
38 8
        return $this->type;
39
    }
40
41
    /**
42
     * Get path to the attachment.
43
     *
44
     * @return string
45
     */
46
    public function getPath(): string
47
    {
48
        return $this->path;
49
    }
50
51
    /**
52
     * Get attachment contents.
53
     *
54
     * @return string
55
     */
56
    public function getContents(): string
57
    {
58
        if ($this->contents === null) {
59
            $this->contents = $this->guzzle->get($this->path)->getBody()->getContents();
60
        }
61
62
        return $this->contents;
63
    }
64
65
    /**
66
     * Get attachment as a file.
67
     *
68
     * @return File
69
     */
70
    public function getFile(): File
71
    {
72
        // Create temporary file
73
        $path = sys_get_temp_dir().'/'.uniqid('attachment', true);
74
        file_put_contents($path, $this->getContents());
75
76
        return new File($path);
77
    }
78
79
    /**
80
     * Get all types.
81
     *
82
     * @return array
83
     */
84 4
    public static function possibleTypes(): array
85
    {
86
        return [
87 4
            static::TYPE_FILE,
88 4
            static::TYPE_IMAGE,
89 4
            static::TYPE_AUDIO,
90 4
            static::TYPE_VIDEO,
91
        ];
92
    }
93
94
    /**
95
     * Get the instance as an array.
96
     *
97
     * @return array
98
     */
99
    public function toArray(): array
100
    {
101
        return [
102
            'type' => $this->type,
103
            'path' => $this->path,
104
        ];
105
    }
106
}
107