JsonManifestVersionStrategy.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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\VersionStrategy;
  11. /**
  12. * Reads the versioned path of an asset from a JSON manifest file.
  13. *
  14. * For example, the manifest file might look like this:
  15. * {
  16. * "main.js": "main.abc123.js",
  17. * "css/styles.css": "css/styles.555abc.css"
  18. * }
  19. *
  20. * You could then ask for the version of "main.js" or "css/styles.css".
  21. */
  22. class JsonManifestVersionStrategy implements VersionStrategyInterface
  23. {
  24. private $manifestPath;
  25. private $manifestData;
  26. /**
  27. * @param string $manifestPath Absolute path to the manifest file
  28. */
  29. public function __construct(string $manifestPath)
  30. {
  31. $this->manifestPath = $manifestPath;
  32. }
  33. /**
  34. * With a manifest, we don't really know or care about what
  35. * the version is. Instead, this returns the path to the
  36. * versioned file.
  37. */
  38. public function getVersion(string $path)
  39. {
  40. return $this->applyVersion($path);
  41. }
  42. public function applyVersion(string $path)
  43. {
  44. return $this->getManifestPath($path) ?: $path;
  45. }
  46. private function getManifestPath(string $path): ?string
  47. {
  48. if (null === $this->manifestData) {
  49. if (!is_file($this->manifestPath)) {
  50. throw new \RuntimeException(sprintf('Asset manifest file "%s" does not exist.', $this->manifestPath));
  51. }
  52. $this->manifestData = json_decode(file_get_contents($this->manifestPath), true);
  53. if (0 < json_last_error()) {
  54. throw new \RuntimeException(sprintf('Error parsing JSON from asset manifest file "%s": ', $this->manifestPath).json_last_error_msg());
  55. }
  56. }
  57. return $this->manifestData[$path] ?? null;
  58. }
  59. }