ResourceLoaderLessVarFileModule.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * Subclass with context specific LESS variables
  4. */
  5. class ResourceLoaderLessVarFileModule extends ResourceLoaderFileModule {
  6. protected $lessVariables = [];
  7. /**
  8. * @inheritDoc
  9. */
  10. public function __construct(
  11. $options = [],
  12. $localBasePath = null,
  13. $remoteBasePath = null
  14. ) {
  15. if ( isset( $options['lessMessages'] ) ) {
  16. $this->lessVariables = $options['lessMessages'];
  17. }
  18. parent::__construct( $options, $localBasePath, $remoteBasePath );
  19. }
  20. /**
  21. * @inheritDoc
  22. */
  23. public function getMessages() {
  24. // Overload so MessageBlobStore can detect updates to messages and purge as needed.
  25. return array_merge( $this->messages, $this->lessVariables );
  26. }
  27. /**
  28. * Exclude a set of messages from a JSON string representation
  29. *
  30. * @param string $blob
  31. * @param array $exclusions
  32. * @return array $blob
  33. */
  34. protected function excludeMessagesFromBlob( $blob, $exclusions ) {
  35. $data = json_decode( $blob, true );
  36. // unset the LESS variables so that they are not forwarded to JavaScript
  37. foreach ( $exclusions as $key ) {
  38. unset( $data[$key] );
  39. }
  40. return (object)$data;
  41. }
  42. /**
  43. * @inheritDoc
  44. */
  45. protected function getMessageBlob( ResourceLoaderContext $context ) {
  46. $blob = parent::getMessageBlob( $context );
  47. return json_encode( $this->excludeMessagesFromBlob( $blob, $this->lessVariables ) );
  48. }
  49. /**
  50. * Takes a message and wraps it in quotes for compatibility with LESS parser
  51. * (ModifyVars) method so that the variable can be loaded and made available to stylesheets.
  52. * Note this does not take care of CSS escaping. That will be taken care of as part
  53. * of CSS Janus.
  54. *
  55. * @param string $msg
  56. * @return string wrapped LESS variable definition
  57. */
  58. private static function wrapAndEscapeMessage( $msg ) {
  59. return str_replace( "'", "\'", CSSMin::serializeStringValue( $msg ) );
  60. }
  61. /**
  62. * Get language-specific LESS variables for this module.
  63. *
  64. * @param ResourceLoaderContext $context
  65. * @return array LESS variables
  66. */
  67. protected function getLessVars( ResourceLoaderContext $context ) {
  68. $blob = parent::getMessageBlob( $context );
  69. $lessMessages = $this->excludeMessagesFromBlob( $blob, $this->messages );
  70. $vars = parent::getLessVars( $context );
  71. foreach ( $lessMessages as $msgKey => $value ) {
  72. $vars['msg-' . $msgKey] = self::wrapAndEscapeMessage( $value );
  73. }
  74. return $vars;
  75. }
  76. }