Automatically use local asset path when attempting to combine injected assets (#3802)

Credit to @cleverer. Fixes #3264.
This commit is contained in:
Nicolas Da Mutten 2018-09-24 22:17:00 +02:00 committed by Luke Towers
parent 51d79ffaba
commit aeb7616d06
2 changed files with 71 additions and 2 deletions

View File

@ -2,6 +2,7 @@
use Url;
use Html;
use File;
use System\Models\Parameter;
use System\Models\PluginVersion;
use System\Classes\CombineAssets;
@ -112,7 +113,7 @@ trait AssetMaker
public function addJs($name, $attributes = [])
{
if (is_array($name)) {
$name = $this->combineAssets($name);
$name = $this->combineAssets($name, $this->getLocalPath($this->assetPath));
}
$jsPath = $this->getAssetPath($name);
@ -142,7 +143,7 @@ trait AssetMaker
public function addCss($name, $attributes = [])
{
if (is_array($name)) {
$name = $this->combineAssets($name);
$name = $this->combineAssets($name, $this->getLocalPath($this->assetPath));
}
$cssPath = $this->getAssetPath($name);
@ -324,4 +325,13 @@ trait AssetMaker
}
}
protected function getLocalPath(string $relativePath)
{
$relativePath = File::symbolizePath($relativePath);
if (!starts_with($relativePath, [base_path()])) {
$relativePath = base_path($relativePath);
}
return $relativePath;
}
}

View File

@ -0,0 +1,59 @@
<?php
class AssetMakerStub
{
use System\Traits\AssetMaker;
use System\Traits\ViewMaker; // Needed for guessViewPath(), which is used to set default assetPath
}
class AssetMakerTest extends TestCase
{
private $stub;
public function setUp()
{
$this->createApplication();
$this->stub = new AssetMakerStub();
}
//
// Helpers
//
protected static function callProtectedMethod($object, $name, $params = [])
{
$className = get_class($object);
$class = new ReflectionClass($className);
$method = $class->getMethod($name);
$method->setAccessible(true);
return $method->invokeArgs($object, $params);
}
//
// Tests
//
public function testGetLocalPath()
{
$basePath = base_path();
// Default assetPath
$assetPath = $this->stub->guessViewPath('/assets', true);
$resolvedPath = $this->callProtectedMethod($this->stub, 'getLocalPath', [$assetPath]);
$this->assertEquals(realpath($basePath.$assetPath), realpath($resolvedPath));
// Paths with symbols
$resolvedPath = $this->callProtectedMethod($this->stub, 'getLocalPath', ['~/themes/demo/']);
$this->assertEquals(realpath($basePath.'/themes/demo/'), realpath($resolvedPath));
$resolvedPath = $this->callProtectedMethod($this->stub, 'getLocalPath', ['~/plugins/demo/']);
$this->assertEquals(realpath($basePath.'/plugins/demo/'), realpath($resolvedPath));
$resolvedPath = $this->callProtectedMethod($this->stub, 'getLocalPath', ['$/demo/']);
$this->assertEquals(realpath($basePath.'/plugins/demo/'), realpath($resolvedPath));
// Absolute Path
$resolvedPath = $this->callProtectedMethod($this->stub, 'getLocalPath', [$basePath.'/some/wild/absolute/path/']);
$this->assertEquals(realpath($basePath.'/some/wild/absolute/path/'), realpath($resolvedPath));
}
}