ViewFilter.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace Elgg\Amd;
  3. /**
  4. * WARNING: API IN FLUX. DO NOT USE DIRECTLY.
  5. *
  6. * This filter adds AMD names to anonymous AMD modules defined in views.
  7. *
  8. * @package Elgg.Core
  9. * @subpackage JavaScript
  10. * @since 1.9
  11. *
  12. * @access private
  13. */
  14. class ViewFilter {
  15. /**
  16. * Given the view name, returns the AMD name.
  17. *
  18. * @param string $name The name of the view (e.g., 'js/elgg/module.js')
  19. *
  20. * @return string The AMD name (e.g., 'elgg/module'), or blank for no AMD name.
  21. */
  22. private function getAmdName($name) {
  23. if (preg_match('~^(js/)?(.+)\\.js\\z~', $name, $m)) {
  24. // "js/foo/bar.js" or "foo/bar.js"
  25. return $m[2];
  26. }
  27. // must be in "js/" dir
  28. if (0 !== strpos($name, 'js/')) {
  29. return '';
  30. }
  31. $name = substr($name, 3);
  32. // Don't allow extension. We matched ".js" above
  33. if (pathinfo($name, PATHINFO_EXTENSION) !== null) {
  34. return '';
  35. }
  36. // "foo/bar"
  37. return $name;
  38. }
  39. /**
  40. * Inserts the AMD name into `$content` and returns the new value.
  41. *
  42. * @param string $viewName The name of the view.
  43. * @param string $content The output of the view to be filtered.
  44. *
  45. * @return string The new content with the AMD name inserted, if applicable.
  46. */
  47. public function filter($viewName, $content) {
  48. $amdName = $this->getAmdName($viewName);
  49. if (!empty($amdName)) {
  50. $content = preg_replace('/^(\s*)define\(([^\'"])/m', "\${1}define(\"$amdName\", \$2", $content, 1);
  51. }
  52. return $content;
  53. }
  54. }