PathPackage.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Asset;
  11. use Symfony\Component\Asset\Context\ContextInterface;
  12. use Symfony\Component\Asset\VersionStrategy\VersionStrategyInterface;
  13. /**
  14. * Package that adds a base path to asset URLs in addition to a version.
  15. *
  16. * In addition to the provided base path, this package also automatically
  17. * prepends the current request base path if a Context is available to
  18. * allow a website to be hosted easily under any given path under the Web
  19. * Server root directory.
  20. *
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. */
  23. class PathPackage extends Package
  24. {
  25. private $basePath;
  26. /**
  27. * @param string $basePath The base path to be prepended to relative paths
  28. */
  29. public function __construct(string $basePath, VersionStrategyInterface $versionStrategy, ContextInterface $context = null)
  30. {
  31. parent::__construct($versionStrategy, $context);
  32. if (!$basePath) {
  33. $this->basePath = '/';
  34. } else {
  35. if ('/' != $basePath[0]) {
  36. $basePath = '/'.$basePath;
  37. }
  38. $this->basePath = rtrim($basePath, '/').'/';
  39. }
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. public function getUrl(string $path)
  45. {
  46. $versionedPath = parent::getUrl($path);
  47. // if absolute or begins with /, we're done
  48. if ($this->isAbsoluteUrl($versionedPath) || ($versionedPath && '/' === $versionedPath[0])) {
  49. return $versionedPath;
  50. }
  51. return $this->getBasePath().ltrim($versionedPath, '/');
  52. }
  53. /**
  54. * Returns the base path.
  55. *
  56. * @return string The base path
  57. */
  58. public function getBasePath()
  59. {
  60. return $this->getContext()->getBasePath().$this->basePath;
  61. }
  62. }