Completed
Push — master ( 817c3d...f287a4 )
by Vladimir
03:07
created

Attachment::getContents()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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