Skip to content

Commit

Permalink
Refactor TwitterShortcode to use Guzzle for HTTP requests.
Browse files Browse the repository at this point in the history
  • Loading branch information
murdercode committed Dec 16, 2024
1 parent e96c249 commit 832836e
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 8 deletions.
4 changes: 3 additions & 1 deletion src/LaravelShortcodePlus.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@

final class LaravelShortcodePlus
{
public function __construct(protected string $content = '') {}
public function __construct(protected string $content = '')
{
}

public static function source(string $source): LaravelShortcodePlus
{
Expand Down
4 changes: 3 additions & 1 deletion src/LaravelShortcodePlusServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ public function configurePackage(Package $package): void
->hasMigration('create_laravel-shortcode-plus_table');
}

public function packageRegistered() {}
public function packageRegistered()
{
}

public function packageBooted(): void
{
Expand Down
42 changes: 36 additions & 6 deletions src/Shortcodes/TwitterShortcode.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

namespace Murdercode\LaravelShortcodePlus\Shortcodes;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;

class TwitterShortcode
{
public function register($shortcode): string
Expand All @@ -25,15 +29,41 @@ public function register($shortcode): string
return view('shortcode-plus::twitter', compact('html'))->render();
}

/**
* Get oEmbed data from Twitter
* Note: Twitter sometimes returns 404 for valid URLs, so we retry a few times
*
* @throws GuzzleException
*/
private static function getOembed(string $url): ?string
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://publish.twitter.com/oembed?url='.urlencode($url).'&omit_script=1');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
$maxAttempts = 3;
$attempt = 0;
$response = null;

while ($attempt < $maxAttempts && $response === null) {
try {
$client = new Client;
$res = $client->request('GET', 'https://publish.twitter.com/oembed', [
'query' => [
'url' => $url,
'omit_script' => 1,
],
]);

if ($res->getStatusCode() == 200) {
$response = $res->getBody()->getContents();
} else {
usleep(100000);
$attempt++;
}
} catch (RequestException $e) {
usleep(100000);
$attempt++;
}
}

if ($response === false) {
if ($response === null) {
return null;
}

Expand Down

0 comments on commit 832836e

Please sign in to comment.