Signature.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Theme\Model\Url\Plugin;
  7. /**
  8. * Plugin that activates signing of static file URLs with corresponding deployment version
  9. */
  10. class Signature
  11. {
  12. /**
  13. * XPath for configuration setting of signing static files
  14. */
  15. const XML_PATH_STATIC_FILE_SIGNATURE = 'dev/static/sign';
  16. /**
  17. * Template of signature component of URL, parametrized with the deployment version of static files
  18. */
  19. const SIGNATURE_TEMPLATE = 'version%s';
  20. /**
  21. * @var \Magento\Framework\View\Url\ConfigInterface
  22. */
  23. private $config;
  24. /**
  25. * @var \Magento\Framework\App\View\Deployment\Version
  26. */
  27. private $deploymentVersion;
  28. /**
  29. * @param \Magento\Framework\View\Url\ConfigInterface $config
  30. * @param \Magento\Framework\App\View\Deployment\Version $deploymentVersion
  31. */
  32. public function __construct(
  33. \Magento\Framework\View\Url\ConfigInterface $config,
  34. \Magento\Framework\App\View\Deployment\Version $deploymentVersion
  35. ) {
  36. $this->config = $config;
  37. $this->deploymentVersion = $deploymentVersion;
  38. }
  39. /**
  40. * Append signature to rendered base URL for static view files
  41. *
  42. * @param \Magento\Framework\Url\ScopeInterface $subject
  43. * @param string $baseUrl
  44. * @param string $type
  45. * @param null $secure
  46. * @return string
  47. * @see \Magento\Framework\Url\ScopeInterface::getBaseUrl()
  48. *
  49. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  50. */
  51. public function afterGetBaseUrl(
  52. \Magento\Framework\Url\ScopeInterface $subject,
  53. $baseUrl,
  54. $type = \Magento\Framework\UrlInterface::URL_TYPE_LINK,
  55. $secure = null
  56. ) {
  57. if ($type == \Magento\Framework\UrlInterface::URL_TYPE_STATIC && $this->isUrlSignatureEnabled()) {
  58. $baseUrl .= $this->renderUrlSignature() . '/';
  59. }
  60. return $baseUrl;
  61. }
  62. /**
  63. * Whether signing of URLs is enabled or not
  64. *
  65. * @return bool
  66. */
  67. protected function isUrlSignatureEnabled()
  68. {
  69. return (bool)$this->config->getValue(self::XML_PATH_STATIC_FILE_SIGNATURE);
  70. }
  71. /**
  72. * Render URL signature from the template
  73. *
  74. * @return string
  75. */
  76. protected function renderUrlSignature()
  77. {
  78. return sprintf(self::SIGNATURE_TEMPLATE, $this->deploymentVersion->getValue());
  79. }
  80. }