|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Jackal\Downloader\Ext\Youtube\Filter; |
|
4
|
|
|
|
|
5
|
|
|
use Jackal\Downloader\Ext\Youtube\Exception\YoutubeDownloaderException; |
|
6
|
|
|
use Jackal\Downloader\Ext\Youtube\Validator\ValidatorInterface; |
|
7
|
|
|
|
|
8
|
|
|
class VideoResultFilter |
|
9
|
|
|
{ |
|
10
|
|
|
protected $validator; |
|
11
|
|
|
|
|
12
|
|
|
public function setValidator(ValidatorInterface $validator) |
|
13
|
|
|
{ |
|
14
|
|
|
$this->validator = $validator; |
|
15
|
|
|
} |
|
16
|
|
|
|
|
17
|
|
|
protected function hasValidator() : bool |
|
18
|
|
|
{ |
|
19
|
|
|
return isset($this->validator); |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
protected function getValidator() : ?ValidatorInterface |
|
23
|
|
|
{ |
|
24
|
|
|
return $this->validator; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
public function filter(array $videos, array $selectedFormats = []) : array |
|
28
|
|
|
{ |
|
29
|
|
|
$outVideos = []; |
|
30
|
|
|
sort($selectedFormats, SORT_NUMERIC); |
|
31
|
|
|
|
|
32
|
|
|
foreach ($videos as $video) { |
|
33
|
|
|
if (isset($video['format'])) { |
|
34
|
|
|
$formatFound = $this->checkContainsAudioAndVideoFormat($video['format']); |
|
35
|
|
|
if (isset($formatFound)) { |
|
36
|
|
|
if (array_key_exists($formatFound, $outVideos)) { |
|
37
|
|
|
continue; |
|
38
|
|
|
} |
|
39
|
|
|
if ($this->hasValidator()) { |
|
40
|
|
|
if ($this->getValidator()->isValid($video['url'])) { |
|
41
|
|
|
$outVideos[$formatFound] = $video['url']; |
|
42
|
|
|
} |
|
43
|
|
|
} else { |
|
44
|
|
|
$outVideos[$formatFound] = $video['url']; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
if($selectedFormats != []) { |
|
48
|
|
|
foreach ($selectedFormats as $selectedFormat) { |
|
49
|
|
|
if (array_key_exists($selectedFormat, $outVideos)) { |
|
50
|
|
|
return [$selectedFormat => $outVideos[$selectedFormat]]; |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
if ($outVideos == []) { |
|
59
|
|
|
throw YoutubeDownloaderException::videoURLsNotFound(); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
ksort($outVideos, SORT_NUMERIC); |
|
63
|
|
|
|
|
64
|
|
|
return $outVideos; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
public function checkContainsAudioAndVideoFormat($string) : ?string |
|
68
|
|
|
{ |
|
69
|
|
|
foreach (['audio', 'video'] as $elem) { |
|
70
|
|
|
if (strpos($string, $elem) === false) { |
|
71
|
|
|
return null; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
preg_match('/([0-9]{2,4})p/', $string, $match); |
|
75
|
|
|
|
|
76
|
|
|
return $match[1] ?? null; |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|