Passed
Pull Request — master (#2)
by Luca
01:32
created

VimeoDownloader::getFormats()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
c 0
b 0
f 0
nc 3
nop 0
dl 0
loc 11
rs 10
1
<?php
2
3
namespace Jackal\Downloader\Ext\Vimeo\Downloader;
4
5
use Jackal\Downloader\Downloader\AbstractDownloader;
6
use Jackal\Downloader\Ext\Vimeo\Exception\VimeoDownloadException;
7
8
class VimeoDownloader extends AbstractDownloader
9
{
10
    const VIDEO_TYPE = 'vimeo';
11
12
    public function getURL(): string
13
    {
14
15
        $links = array_reduce($this->getVideoInfo(), function ($vimeoVideos, $currentVimeoVideo) {
16
            $quality = substr($currentVimeoVideo['quality'], 0, -1);
17
            $vimeoVideos[$quality] = $currentVimeoVideo['url'];
18
19
            return $vimeoVideos;
20
        }, []);
21
22
        ksort($links, SORT_NUMERIC);
23
24
        if ($links == []) {
25
            throw VimeoDownloadException::videoURLsNotFound();
26
        }
27
28
        $links = $this->filterByFormats($links);
29
30
        return array_values($links)[0];
31
    }
32
33
    private function getVideoInfo() : array
34
    {
35
        $requestUrl = $this->getRequestedUrl();
36
        $requestUrlContent = file_get_contents($requestUrl);
37
        $decode_to_arr = json_decode($requestUrlContent, true);
38
39
        $contentToReturn = @$decode_to_arr['request']['files']['progressive'];
40
        if (!$decode_to_arr or !is_array($contentToReturn)) {
41
            throw VimeoDownloadException::unableToParseContent($requestUrl, $requestUrlContent);
42
        }
43
44
        return $contentToReturn;
45
    }
46
47
    private function getRequestedUrl() : string
48
    {
49
        $originUrl = 'https://www.vimeo.com/' . $this->getVideoId();
50
        $data = file_get_contents($originUrl);
51
52
        $url = $this->executeRegex($data, '/"config_url"\:"(.*)"/U');
53
        $url = trim(str_replace('\\/', '/', $url));
54
55
        if (!$url or !filter_var($url, FILTER_VALIDATE_URL)) {
56
            throw VimeoDownloadException::unableToParseContent($originUrl, $url);
57
        }
58
59
        return $url;
60
    }
61
62
    protected function executeRegex($string, $regex, $group = 1) : ?string
63
    {
64
        preg_match($regex, $string, $matches);
65
        if (!array_key_exists($group, $matches)) {
66
            return null;
67
        }
68
69
        return $matches[$group];
70
    }
71
}
72