|
1
|
|
|
<?php |
|
2
|
|
|
namespace Cohensive\OEmbed; |
|
3
|
|
|
|
|
4
|
|
|
class RegexExtractor extends Extractor |
|
5
|
|
|
{ |
|
6
|
|
|
/** |
|
7
|
|
|
* Fetches data from provider. |
|
8
|
|
|
*/ |
|
9
|
|
|
public function fetch(array $parameters = []): ?Embed |
|
10
|
|
|
{ |
|
11
|
|
|
$data = $this->provider['data']; |
|
12
|
|
|
|
|
13
|
|
|
$matches = null; |
|
14
|
|
|
|
|
15
|
|
|
foreach ($this->provider['urls'] as $pattern) { |
|
16
|
|
|
if (preg_match($pattern, $this->url, $matches)) { |
|
17
|
|
|
break; |
|
18
|
|
|
} |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
if (!$matches) { |
|
22
|
|
|
return null; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
$protocol = $this->getProtocol(); |
|
26
|
|
|
|
|
27
|
|
|
$data = $this->hydrateProvider($data, $matches, $protocol); |
|
28
|
|
|
|
|
29
|
|
|
return new Embed(Embed::TYPE_REGEX, $this->url, $data); |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* Get protocol for current url and provider. |
|
34
|
|
|
*/ |
|
35
|
|
|
protected function getProtocol(): string |
|
36
|
|
|
{ |
|
37
|
|
|
if ($this->provider['ssl']) { |
|
38
|
|
|
return 'https'; |
|
39
|
|
|
} elseif (strpos($this->url, 'https://') === 0) { |
|
40
|
|
|
return 'https'; |
|
41
|
|
|
} else { |
|
42
|
|
|
return 'http'; |
|
43
|
|
|
} |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* Parse found provider and replace {x} parts with parsed code. |
|
48
|
|
|
*/ |
|
49
|
|
|
protected function hydrateProvider(array &$data, array $matches, string $protocol): array |
|
50
|
|
|
{ |
|
51
|
|
|
$matchCount = count($matches); |
|
52
|
|
|
|
|
53
|
|
|
// Check if we have an iframe creation array. |
|
54
|
|
|
foreach ($data as $key => $val) { |
|
55
|
|
|
if (is_array($val)) { |
|
56
|
|
|
$data[$key] = $this->hydrateProvider($val, $matches, $protocol); |
|
57
|
|
|
} else { |
|
58
|
|
|
$data[$key] = str_replace('{protocol}', $protocol, $data[$key]); |
|
59
|
|
|
for ($i = 1; $i < $matchCount; $i++) { |
|
60
|
|
|
$data[$key] = str_replace('{' . $i . '}', $matches[$i], $data[$key]); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
return $data; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|