diff --git a/app/Helper/LinkAce.php b/app/Helper/LinkAce.php index e87846a0..fb75ce98 100644 --- a/app/Helper/LinkAce.php +++ b/app/Helper/LinkAce.php @@ -2,6 +2,8 @@ namespace App\Helper; +use Illuminate\Support\Facades\Http; + /** * Class LinkAce * @@ -23,9 +25,15 @@ class LinkAce ]; // Try to get the HTML content of that URL - try { - $html = file_get_contents($url); - } catch (\Exception $e) { + $response = Http::get($url); + + if (!$response->successful()) { + return $fallback; + } + + $html = $response->body(); + + if (empty($html)) { return $fallback; } @@ -36,10 +44,6 @@ class LinkAce return $fallback; } - if (empty($html)) { - return $fallback; - } - // Parse the HTML for the title $res = preg_match("/(.*)<\/title>/siU", $html, $title_matches); diff --git a/tests/Unit/Helper/LinkaceHelperTest.php b/tests/Unit/Helper/LinkaceHelperTest.php index e7a96938..5d1c30bb 100644 --- a/tests/Unit/Helper/LinkaceHelperTest.php +++ b/tests/Unit/Helper/LinkaceHelperTest.php @@ -3,6 +3,7 @@ namespace Tests\Unit; use App\Helper\LinkAce; +use Illuminate\Support\Facades\Http; use Tests\TestCase; /** @@ -20,6 +21,12 @@ class LinkaceHelperTest extends TestCase */ public function testTitleFromValidURL(): void { + $testHtml = '<!DOCTYPE html><head><title>Google'; + + Http::fake([ + '*' => Http::response($testHtml, 200), + ]); + $url = 'https://google.com/'; $result = LinkAce::getMetaFromURL($url); @@ -36,11 +43,15 @@ class LinkaceHelperTest extends TestCase */ public function testTitleFromInvalidURL(): void { - $url = 'https://a-google-url-that-does-not-exist.comcom/'; + $url = 'https://googlegoogle.comcom/'; + + Http::fake([ + '*' => Http::response(null, 404), + ]); $result = LinkAce::getMetaFromURL($url); $this->assertArrayHasKey('title', $result); - $this->assertEquals('a-google-url-that-does-not-exist.comcom', $result['title']); + $this->assertEquals('googlegoogle.comcom', $result['title']); } } diff --git a/tests/Unit/Models/LinkCreateTest.php b/tests/Unit/Models/LinkCreateTest.php index ae09fff9..428c5979 100644 --- a/tests/Unit/Models/LinkCreateTest.php +++ b/tests/Unit/Models/LinkCreateTest.php @@ -8,6 +8,7 @@ use App\Models\User; use App\Repositories\LinkRepository; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; +use Illuminate\Support\Facades\Http; use Tests\TestCase; class LinkCreateTest extends TestCase @@ -22,6 +23,12 @@ class LinkCreateTest extends TestCase { parent::setUp(); + $testHtml = 'Google'; + + Http::fake([ + '*' => Http::response($testHtml, 200), + ]); + $this->user = factory(User::class)->create(); }