Skip to content

Commit 8fb8ebb

Browse files
authored
Merge pull request #97 from murdercode/twitter-fix-2
Twitter fix 2
2 parents e96c249 + 26f312e commit 8fb8ebb

File tree

1 file changed

+36
-6
lines changed

1 file changed

+36
-6
lines changed

src/Shortcodes/TwitterShortcode.php

+36-6
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
namespace Murdercode\LaravelShortcodePlus\Shortcodes;
44

5+
use GuzzleHttp\Client;
6+
use GuzzleHttp\Exception\GuzzleException;
7+
use GuzzleHttp\Exception\RequestException;
8+
59
class TwitterShortcode
610
{
711
public function register($shortcode): string
@@ -25,15 +29,41 @@ public function register($shortcode): string
2529
return view('shortcode-plus::twitter', compact('html'))->render();
2630
}
2731

32+
/**
33+
* Get oEmbed data from Twitter
34+
* Note: Twitter sometimes returns 404 for valid URLs, so we retry a few times
35+
*
36+
* @throws GuzzleException
37+
*/
2838
private static function getOembed(string $url): ?string
2939
{
30-
$curl = curl_init();
31-
curl_setopt($curl, CURLOPT_URL, 'https://publish.twitter.com/oembed?url='.urlencode($url).'&omit_script=1');
32-
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
33-
$response = curl_exec($curl);
34-
curl_close($curl);
40+
$maxAttempts = 3;
41+
$attempt = 0;
42+
$response = null;
43+
44+
while ($attempt < $maxAttempts && $response === null) {
45+
try {
46+
$client = new Client;
47+
$res = $client->request('GET', 'https://publish.twitter.com/oembed', [
48+
'query' => [
49+
'url' => $url,
50+
'omit_script' => 1,
51+
],
52+
]);
53+
54+
if ($res->getStatusCode() == 200) {
55+
$response = $res->getBody()->getContents();
56+
} else {
57+
usleep(100000);
58+
$attempt++;
59+
}
60+
} catch (RequestException $e) {
61+
usleep(100000);
62+
$attempt++;
63+
}
64+
}
3565

36-
if ($response === false) {
66+
if ($response === null) {
3767
return null;
3868
}
3969

0 commit comments

Comments
 (0)