diff --git a/composer.json b/composer.json index 287bee0..2176b1d 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "codeinc/assets-middleware", - "version": "2.0.2", + "version": "2.0.3", "description": "A PSR-15 middleware to server static assets (CSS, JS, images, etc.)", "homepage": "https://github.com/CodeIncHQ/AssetsMiddleware", "type": "library", diff --git a/src/AssetsMiddleware.php b/src/AssetsMiddleware.php index 875cfc9..b356053 100644 --- a/src/AssetsMiddleware.php +++ b/src/AssetsMiddleware.php @@ -243,8 +243,27 @@ public function getAssetUri(string $assetPath):?string } foreach ($this->getAssetsDirectories() as $directoryKey => $directoryPath) { if (substr($assetPath, 0, strlen($directoryPath)) == $directoryPath) { - return $this->assetsUriPrefix.urlencode($directoryKey) - .str_replace('\\', '/', substr($assetPath, strlen($directoryPath))); + return $this->assetsUriPrefix.urlencode($directoryKey).'/' + .str_replace('\\', '/', substr($assetPath, strlen($directoryPath) + 1)); + } + } + return null; + } + + /** + * Returns the URI of an assets directory. + * + * @param string $dirPath + * @return null|string + */ + public function getAssetsDirectoryUri(string $dirPath):?string + { + if (($realDirPath = realpath($dirPath)) === false) { + throw new InvalidAssetPathException($dirPath); + } + foreach ($this->getAssetsDirectories() as $directoryKey => $directoryPath) { + if ($realDirPath = $directoryPath) { + return $this->assetsUriPrefix.urlencode($directoryKey).'/'; } } return null; diff --git a/src/Exceptions/InvalidAssetDirectoryPathException.php b/src/Exceptions/InvalidAssetDirectoryPathException.php new file mode 100644 index 0000000..8ba0ed1 --- /dev/null +++ b/src/Exceptions/InvalidAssetDirectoryPathException.php @@ -0,0 +1,63 @@ + +// Date: 28/09/2018 +// Project: AssetsMiddleware +// +declare(strict_types=1); +namespace CodeInc\AssetsMiddleware\Exceptions; +use Throwable; + + +/** + * Class InvalidAssetDirectoryPathException + * + * @package CodeInc\AssetsMiddleware\Exceptions + * @author Joan Fabrégat + */ +class InvalidAssetDirectoryPathException extends \RuntimeException implements AssetsMiddlewareException +{ + /** + * @var string + */ + private $dirPath; + + /** + * InvalidAssetDirectoryPathException constructor. + * + * @param string $dirPath + * @param int $code + * @param Throwable|null $previous + */ + public function __construct(string $dirPath, int $code = 0, Throwable $previous = null) + { + $this->dirPath = $dirPath; + parent::__construct( + sprintf("The assets directory path '%s' is not valid.", $dirPath), + $code, + $previous + ); + } + + /** + * @return string + */ + public function getDirPath():string + { + return $this->dirPath; + } +} \ No newline at end of file