RemoteJsonManifestVersionStrategy.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. use Symfony\Contracts\HttpClient\HttpClientInterface;
  12. /**
  13. * Reads the versioned path of an asset from a remote JSON manifest file.
  14. *
  15. * For example, the manifest file might look like this:
  16. * {
  17. * "main.js": "main.abc123.js",
  18. * "css/styles.css": "css/styles.555abc.css"
  19. * }
  20. *
  21. * You could then ask for the version of "main.js" or "css/styles.css".
  22. */
  23. class RemoteJsonManifestVersionStrategy implements VersionStrategyInterface
  24. {
  25. private $manifestData;
  26. private $manifestUrl;
  27. private $httpClient;
  28. /**
  29. * @param string $manifestUrl Absolute URL to the manifest file
  30. */
  31. public function __construct(string $manifestUrl, HttpClientInterface $httpClient)
  32. {
  33. $this->manifestUrl = $manifestUrl;
  34. $this->httpClient = $httpClient;
  35. }
  36. /**
  37. * With a manifest, we don't really know or care about what
  38. * the version is. Instead, this returns the path to the
  39. * versioned file.
  40. */
  41. public function getVersion(string $path)
  42. {
  43. return $this->applyVersion($path);
  44. }
  45. public function applyVersion(string $path)
  46. {
  47. if (null === $this->manifestData) {
  48. $this->manifestData = $this->httpClient->request('GET', $this->manifestUrl, [
  49. 'headers' => ['accept' => 'application/json'],
  50. ])->toArray();
  51. }
  52. return $this->manifestData[$path] ?? $path;
  53. }
  54. }