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