MediaOnNetwork::toMedia()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 14
nc 4
nop 1
dl 0
loc 25
rs 9.7998
c 0
b 0
f 0
1
<?php
2
3
namespace ProtoneMedia\LaravelFFMpeg\Filesystem;
4
5
use ProtoneMedia\LaravelFFMpeg\FFMpeg\InteractsWithHttpHeaders;
6
7
class MediaOnNetwork
8
{
9
    use HasInputOptions;
10
    use InteractsWithHttpHeaders;
11
12
    /**
13
     * @var string
14
     */
15
    private $path;
16
17
    public function __construct(string $path, array $headers = [])
18
    {
19
        $this->path    = $path;
20
        $this->headers = $headers;
21
    }
22
23
    public static function make(string $path, array $headers = []): self
24
    {
25
        return new static($path, $headers);
26
    }
27
28
    public function getPath(): string
29
    {
30
        return $this->path;
31
    }
32
33
    public function getDisk(): Disk
34
    {
35
        return Disk::make(config('filesystems.default'));
36
    }
37
38
    public function getLocalPath(): string
39
    {
40
        return $this->path;
41
    }
42
43
    public function getFilenameWithoutExtension(): string
44
    {
45
        return pathinfo($this->getPath())['filename'];
46
    }
47
48
    public function getFilename(): string
49
    {
50
        return pathinfo($this->getPath())['basename'];
51
    }
52
53
    public function getCompiledInputOptions(): array
54
    {
55
        return array_merge($this->getInputOptions(), $this->getCompiledHeaders());
56
    }
57
58
    public function getCompiledHeaders(): array
59
    {
60
        return static::compileHeaders($this->getHeaders());
61
    }
62
63
    /**
64
     * Downloads the Media from the internet and stores it in
65
     * a temporary directory.
66
     *
67
     * @param callable $withCurl
68
     * @return \ProtoneMedia\LaravelFFMpeg\Filesystem\Media
69
     */
70
    public function toMedia(callable $withCurl = null): Media
71
    {
72
        $disk = Disk::makeTemporaryDisk();
73
74
        $curl = curl_init();
75
        curl_setopt($curl, CURLOPT_URL, $this->path);
76
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
77
78
        if (!empty($this->headers)) {
79
            curl_setopt($curl, CURLOPT_HTTPHEADER, $this->headers);
80
        }
81
82
        if ($withCurl) {
83
            $curl = $withCurl($curl) ?: $curl;
84
        }
85
86
        $contents = curl_exec($curl);
87
        curl_close($curl);
88
89
        $disk->getFilesystemAdapter()->put(
90
            $filename = $this->getFilename(),
91
            $contents
92
        );
93
94
        return new Media($disk, $filename);
95
    }
96
}
97