unify generating webpack asset url

This commit is contained in:
Pig Fang 2020-03-26 10:15:48 +08:00
parent 04dfdfb6c2
commit 530ed88bd1
2 changed files with 13 additions and 6 deletions

View File

@ -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");
}
}
}

View File

@ -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')