From 530ed88bd1e6c26ad8175d37fad53f0206675f55 Mon Sep 17 00:00:00 2001 From: Pig Fang Date: Thu, 26 Mar 2020 10:15:48 +0800 Subject: [PATCH] unify generating webpack asset url --- app/Services/Webpack.php | 17 ++++++++++++----- tests/ServicesTest/WebpackTest.php | 2 +- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/app/Services/Webpack.php b/app/Services/Webpack.php index bfa9df37..4998ca03 100644 --- a/app/Services/Webpack.php +++ b/app/Services/Webpack.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Services; use Illuminate\Filesystem\Filesystem; +use Illuminate\Routing\UrlGenerator; use Illuminate\Support\Arr; use Illuminate\Support\Str; @@ -15,14 +16,20 @@ class Webpack /** @var Option */ protected $options; - public function __construct(Filesystem $filesystem, Option $options) - { + protected $urlGenerator; + + public function __construct( + Filesystem $filesystem, + Option $options, + UrlGenerator $urlGenerator + ) { $path = public_path('app/manifest.json'); if ($filesystem->exists($path)) { $this->manifest = json_decode($filesystem->get($path), true); } $this->options = $options; + $this->urlGenerator = $urlGenerator; } public function __get(string $path) @@ -33,14 +40,14 @@ class Webpack public function url(string $path): string { if (Str::startsWith(config('app.asset.env'), 'dev')) { - $base = config('app.asset.url'); + $root = config('app.asset.url').':8080'; - return "$base:8080/$path"; + return $this->urlGenerator->assetFrom($root, $path); } else { $path = $this->$path; $cdn = $this->options->get('cdn_address'); - return $cdn ? "$cdn/app/$path" : url("/app/$path"); + return $this->urlGenerator->assetFrom($cdn, "/app/$path"); } } } diff --git a/tests/ServicesTest/WebpackTest.php b/tests/ServicesTest/WebpackTest.php index 9e0a53af..fe96b5f3 100644 --- a/tests/ServicesTest/WebpackTest.php +++ b/tests/ServicesTest/WebpackTest.php @@ -43,7 +43,7 @@ class WebpackTest extends TestCase $this->app->forgetInstance(Webpack::class); $webpack = $this->app->make(Webpack::class); - $this->assertEquals('http://localhost/app/b', $webpack->url('a')); + $this->assertEquals('/app/b', $webpack->url('a')); $this->mock(\App\Services\Option::class, function ($mock) { $mock->shouldReceive('get')