1
0
mirror of https://github.com/Kovah/LinkAce.git synced 2025-04-20 23:11:56 +02:00

Migrate the HTML meta helper to the new HTTP facade

This commit is contained in:
Kovah 2020-03-04 15:26:31 +01:00
parent ac497fee0d
commit 9409d5a0a6
No known key found for this signature in database
GPG Key ID: AAAA031BA9830D7B
3 changed files with 31 additions and 9 deletions

View File

@ -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>(.*)<\/title>/siU", $html, $title_matches);

View File

@ -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</title></head></html>';
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']);
}
}

View File

@ -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 = '<!DOCTYPE html><head><title>Google</title></head></html>';
Http::fake([
'*' => Http::response($testHtml, 200),
]);
$this->user = factory(User::class)->create();
}