File tree 1 file changed +36
-6
lines changed
1 file changed +36
-6
lines changed Original file line number Diff line number Diff line change 2
2
3
3
namespace Murdercode \LaravelShortcodePlus \Shortcodes ;
4
4
5
+ use GuzzleHttp \Client ;
6
+ use GuzzleHttp \Exception \GuzzleException ;
7
+ use GuzzleHttp \Exception \RequestException ;
8
+
5
9
class TwitterShortcode
6
10
{
7
11
public function register ($ shortcode ): string
@@ -25,15 +29,41 @@ public function register($shortcode): string
25
29
return view ('shortcode-plus::twitter ' , compact ('html ' ))->render ();
26
30
}
27
31
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
+ */
28
38
private static function getOembed (string $ url ): ?string
29
39
{
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
+ }
35
65
36
- if ($ response === false ) {
66
+ if ($ response === null ) {
37
67
return null ;
38
68
}
39
69
You can’t perform that action at this time.
0 commit comments