UrlPackage.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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\Templating\Asset;
  11. /**
  12. * The URL packages adds a version and a base URL to asset URLs.
  13. *
  14. * @author Kris Wallsmith <kris@symfony.com>
  15. */
  16. class UrlPackage extends Package
  17. {
  18. private $baseUrls;
  19. /**
  20. * Constructor.
  21. *
  22. * @param string|array $baseUrls Base asset URLs
  23. * @param string $version The package version
  24. * @param string $format The format used to apply the version
  25. */
  26. public function __construct($baseUrls = array(), $version = null, $format = null)
  27. {
  28. parent::__construct($version, $format);
  29. if (!is_array($baseUrls)) {
  30. $baseUrls = (array) $baseUrls;
  31. }
  32. $this->baseUrls = array();
  33. foreach ($baseUrls as $baseUrl) {
  34. $this->baseUrls[] = rtrim($baseUrl, '/');
  35. }
  36. }
  37. public function getUrl($path)
  38. {
  39. if (false !== strpos($path, '://') || 0 === strpos($path, '//')) {
  40. return $path;
  41. }
  42. $url = $this->applyVersion($path);
  43. if ($url && '/' != $url[0]) {
  44. $url = '/'.$url;
  45. }
  46. return $this->getBaseUrl($path).$url;
  47. }
  48. /**
  49. * Returns the base URL for a path.
  50. *
  51. * @param string $path
  52. *
  53. * @return string The base URL
  54. */
  55. public function getBaseUrl($path)
  56. {
  57. switch ($count = count($this->baseUrls)) {
  58. case 0:
  59. return '';
  60. case 1:
  61. return $this->baseUrls[0];
  62. default:
  63. return $this->baseUrls[fmod(hexdec(substr(md5($path), 0, 10)), $count)];
  64. }
  65. }
  66. }