1 | <?php |
||||
2 | namespace Cohensive\OEmbed; |
||||
3 | |||||
4 | use Cohensive\OEmbed\Exceptions\ExtractorException; |
||||
5 | |||||
6 | class OEmbedExtractor extends Extractor |
||||
7 | { |
||||
8 | public function __construct(string $provider, string $url, array $parameters = []) |
||||
9 | { |
||||
10 | $this->provider = $provider; |
||||
11 | $this->url = $url; |
||||
12 | $this->parameters = $parameters; |
||||
13 | } |
||||
14 | |||||
15 | /** |
||||
16 | * Fetches OEmbed data from provider. |
||||
17 | */ |
||||
18 | public function fetch(array $parameters = []): ?Embed |
||||
19 | { |
||||
20 | $requestUrl = $this->buildRequestUrl($parameters); |
||||
21 | $response = file_get_contents($requestUrl); |
||||
22 | |||||
23 | if (!$response) { |
||||
24 | return null; |
||||
25 | } |
||||
26 | |||||
27 | $oembedData = json_decode($response, true); |
||||
28 | |||||
29 | if (!$oembedData) { |
||||
30 | throw new ExtractorException('Invalid JSON response from OEmbed provider. Url: ' . $this->url); |
||||
31 | } |
||||
32 | |||||
33 | return new Embed(Embed::TYPE_OEMBED, $this->url, $oembedData); |
||||
34 | } |
||||
35 | |||||
36 | /** |
||||
37 | * Builds the complete request URL with all parameters. |
||||
38 | */ |
||||
39 | private function buildRequestUrl(array $parameters = []): string |
||||
40 | { |
||||
41 | $baseUrl = explode('?', $this->provider)[0]; |
||||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||||
42 | $existingParams = $this->extractExistingParams(); |
||||
43 | $finalParams = $this->mergeAllParameters($existingParams, $parameters); |
||||
44 | return $baseUrl . '?' . http_build_query($finalParams); |
||||
45 | } |
||||
46 | |||||
47 | /** |
||||
48 | * Extracts existing query parameters from the provider URL. |
||||
49 | */ |
||||
50 | private function extractExistingParams(): array |
||||
51 | { |
||||
52 | $queryString = parse_url($this->provider, PHP_URL_QUERY); |
||||
0 ignored issues
–
show
It seems like
$this->provider can also be of type array ; however, parameter $url of parse_url() does only seem to accept string , maybe add an additional type check?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
![]() |
|||||
53 | $existingParams = []; |
||||
54 | |||||
55 | if ($queryString) { |
||||
56 | parse_str($queryString, $existingParams); |
||||
57 | } |
||||
58 | |||||
59 | return $existingParams; |
||||
60 | } |
||||
61 | |||||
62 | /** |
||||
63 | * Merges all parameters in the correct priority order. |
||||
64 | */ |
||||
65 | private function mergeAllParameters(array $existingParams, array $parameters): array |
||||
66 | { |
||||
67 | $requestParams = $parameters ?: $this->parameters; |
||||
68 | $mandatoryParams = ['url' => $this->url]; |
||||
69 | |||||
70 | return array_merge($existingParams, $requestParams, $mandatoryParams); |
||||
71 | } |
||||
72 | } |
||||
73 |