PathPackage.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. * @param VersionStrategyInterface $versionStrategy The version strategy
  29. */
  30. public function __construct($basePath, VersionStrategyInterface $versionStrategy, ContextInterface $context = null)
  31. {
  32. parent::__construct($versionStrategy, $context);
  33. if (!$basePath) {
  34. $this->basePath = '/';
  35. } else {
  36. if ('/' != $basePath[0]) {
  37. $basePath = '/'.$basePath;
  38. }
  39. $this->basePath = rtrim($basePath, '/').'/';
  40. }
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function getUrl($path)
  46. {
  47. if ($this->isAbsoluteUrl($path)) {
  48. return $path;
  49. }
  50. return $this->getBasePath().ltrim($this->getVersionStrategy()->applyVersion($path), '/');
  51. }
  52. /**
  53. * Returns the base path.
  54. *
  55. * @return string The base path
  56. */
  57. public function getBasePath()
  58. {
  59. return $this->getContext()->getBasePath().$this->basePath;
  60. }
  61. }