| 1 |
<?php |
| 2 |
|
| 3 |
namespace ipl\Web\Less; |
| 4 |
|
| 5 |
use InvalidArgumentException; |
| 6 |
use Less_Exception_Parser; |
| 7 |
use Less_Parser; |
| 8 |
use Less_Tree; |
| 9 |
use Less_Tree_Declaration; |
| 10 |
use Less_Tree_DetachedRuleset; |
| 11 |
use Less_Tree_Element; |
| 12 |
use Less_Tree_Mixin_Call; |
| 13 |
use Less_Tree_Mixin_Definition; |
| 14 |
use Less_Tree_Ruleset; |
| 15 |
use RuntimeException; |
| 16 |
|
| 17 |
/** |
| 18 |
* Expand a named detached ruleset declaration into a Less template that calls it |
| 19 |
* |
| 20 |
* When a Less variable with the configured name is assigned a detached ruleset, this visitor |
| 21 |
* replaces that declaration with the result of parsing a provided Less template, using `{ruleset}` |
| 22 |
* as the placeholder for the detached ruleset call. The variable may appear in multiple Less files |
| 23 |
* or scopes; each occurrence is transformed independently into the configured template. |
| 24 |
* |
| 25 |
* See the following example Less and resolved CSS for a rough overview of the visitor features. |
| 26 |
* Note that at-signs used for Less variables and media rules are omitted because PHPStorm interprets them as |
| 27 |
* annotations. |
| 28 |
* |
| 29 |
* PHP — visitor is configured with a variable name and a Less template containing `{ruleset}`: |
| 30 |
* ``` |
| 31 |
* new DetachedRulesetCallVisitor('screen-only', 'media screen { {ruleset} }') |
| 32 |
* ``` |
| 33 |
* |
| 34 |
* Less — `screen-only` can be defined in multiple scopes; each is expanded independently: |
| 35 |
* ``` |
| 36 |
* screen-only: { |
| 37 |
* color: red; |
| 38 |
* } |
| 39 |
* ``` |
| 40 |
* |
| 41 |
* CSS: |
| 42 |
* ``` |
| 43 |
* media screen { |
| 44 |
* color: red; |
| 45 |
* } |
| 46 |
* ``` |
| 47 |
*/ |
| 48 |
class DetachedRulesetCallVisitor extends PreEvalVisitor |
| 49 |
{ |
| 50 |
/** |
| 51 |
* Parsed template mixin definition, prepended to each new tree's rules by {@see run()} |
| 52 |
* |
| 53 |
* The definition must remain in the AST after traversal so the Less compiler can resolve the |
| 54 |
* mixin calls that {@see visitDeclaration()} generates in place of matched declarations. |
| 55 |
* |
| 56 |
* @var Less_Tree_Mixin_Definition |
| 57 |
*/ |
| 58 |
private readonly Less_Tree_Mixin_Definition $mixinDef; |
| 59 |
|
| 60 |
/** |
| 61 |
* Create a new DetachedRulesetCallVisitor |
| 62 |
* |
| 63 |
* @param string $variableName The Less variable name (without `@`) whose value is the detached ruleset |
| 64 |
* @param string $template Less code to parse and inject, with `{ruleset}` as the placeholder for |
| 65 |
* the detached ruleset call — must be a developer-controlled constant, not user input |
| 66 |
* (the template is parsed as Less and could execute arbitrary Less if untrusted) |
| 67 |
* |
| 68 |
* @throws RuntimeException If a temporary file cannot be created or written to, or if the template cannot be parsed |
| 69 |
*/ |
| 70 |
public function __construct( |
| 71 |
protected readonly string $variableName, |
| 72 |
string $template, |
| 73 |
) { |
| 74 |
parent::__construct(); |
| 75 |
|
| 76 |
try { |
| 77 |
$this->mixinDef = $this->buildMixinDef($template); |
| 78 |
} catch (Less_Exception_Parser $e) { |
| 79 |
throw new RuntimeException( |
| 80 |
"Failed to parse template for detached ruleset: {$e->getMessage()}", |
| 81 |
$e->getCode(), |
| 82 |
$e, |
| 83 |
); |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
/** |
| 88 |
* Build the mixin definition from the template |
| 89 |
* |
| 90 |
* Parses the template into a {@see Less_Tree_Mixin_Definition} so that |
| 91 |
* {@see visitDeclaration()} can call it wherever the configured variable is |
| 92 |
* assigned a detached ruleset. The definition is injected at the root AST by {@see run()}. |
| 93 |
* |
| 94 |
* @return Less_Tree_Mixin_Definition The mixin definition built from the template |
| 95 |
* |
| 96 |
* @throws RuntimeException If a temporary file cannot be created or written to |
| 97 |
* @throws Less_Exception_Parser If the template cannot be parsed |
| 98 |
*/ |
| 99 |
protected function buildMixinDef(string $template): Less_Tree_Mixin_Definition |
| 100 |
{ |
| 101 |
$less = str_replace('{ruleset}', '@rules()', $template); |
| 102 |
// Less_Parser::parse() returns $this and does not expose the root ruleset. |
| 103 |
// parseFile(returnRoot: true) is the only public API that does, so we write |
| 104 |
// the content to a temp file and let the parser read it back. |
| 105 |
$t = tmpfile(); |
| 106 |
if ($t === false) { |
| 107 |
throw new RuntimeException('Failed to create a temporary file for Less compilation'); |
| 108 |
} |
| 109 |
|
| 110 |
try { |
| 111 |
if (fwrite($t, $less) === false) { |
| 112 |
throw new RuntimeException('Failed to write to temporary file for Less compilation'); |
| 113 |
} |
| 114 |
|
| 115 |
// Less_Tree::$parse holds the active Less_Parser instance set during compilation. |
| 116 |
// @link https://github.com/wikimedia/less.php/blob/v5.5.0/lib/Less/Tree.php |
| 117 |
// Using it here avoids constructing a new Less_Parser(), which would itself overwrite |
| 118 |
// Less_Tree::$parse, resetting the active parser's configuration (import paths, |
| 119 |
// variables, etc.) for the remainder of the current compilation. |
| 120 |
// Fallback: if called outside a compilation context (Less_Tree::$parse is null), |
| 121 |
// a bare parser is used and the template is parsed without inherited options. |
| 122 |
$root = (Less_Tree::$parse ?? new Less_Parser()) |
| 123 |
->parseFile(stream_get_meta_data($t)['uri'], returnRoot: true); |
| 124 |
} finally { |
| 125 |
fclose($t); |
| 126 |
} |
| 127 |
|
| 128 |
return new Less_Tree_Mixin_Definition( |
| 129 |
'.' . uniqid($this->variableName), |
| 130 |
[['name' => '@rules']], |
| 131 |
$root->rules, |
| 132 |
null, |
| 133 |
); |
| 134 |
} |
| 135 |
|
| 136 |
/** |
| 137 |
* Inject the template mixin definition at the root of the AST before traversal |
| 138 |
* |
| 139 |
* Unlike {@see PreEvalVisitor::run()}, this override intentionally modifies `$tree->rules`: |
| 140 |
* it prepends {@see $mixinDef} when the definition is not yet present in the tree, so the |
| 141 |
* Less compiler can resolve the mixin calls that {@see visitDeclaration()} generates in place |
| 142 |
* of matched declarations. Presence is checked by object identity, so the same tree can be |
| 143 |
* passed more than once without duplicate injection, and a fresh tree always receives the |
| 144 |
* definition regardless of how many other trees this visitor has already processed. |
| 145 |
* |
| 146 |
* @param Less_Tree $tree The root AST node to traverse |
| 147 |
* |
| 148 |
* @return void |
| 149 |
* |
| 150 |
* @throws InvalidArgumentException If the root node is not a {@see Less_Tree_Ruleset} |
| 151 |
*/ |
| 152 |
public function run(Less_Tree $tree): void |
| 153 |
{ |
| 154 |
if (! $tree instanceof Less_Tree_Ruleset) { |
| 155 |
throw new InvalidArgumentException(sprintf( |
| 156 |
'%s can only be run on %s instances', |
| 157 |
__METHOD__, |
| 158 |
Less_Tree_Ruleset::class, |
| 159 |
)); |
| 160 |
} |
| 161 |
|
| 162 |
$clone = clone $this; |
| 163 |
|
| 164 |
if (! in_array($this->mixinDef, $tree->rules, true)) { |
| 165 |
array_unshift($tree->rules, $this->mixinDef); |
| 166 |
} |
| 167 |
|
| 168 |
$clone->visitObj($tree); |
| 169 |
} |
| 170 |
|
| 171 |
/** |
| 172 |
* Handle a {@see Less_Tree_Declaration} node during AST traversal |
| 173 |
* |
| 174 |
* Leaves most declarations unchanged. When it encounters a variable declaration matching |
| 175 |
* {@see $variableName} whose value is a detached ruleset, it replaces that declaration with |
| 176 |
* a call to the template mixin, passing the detached ruleset directly as the argument. |
| 177 |
* The mixin definition itself is already in the root AST, injected by {@see run()}. |
| 178 |
* |
| 179 |
* @param Less_Tree_Declaration $d The declaration node being visited |
| 180 |
* |
| 181 |
* @return Less_Tree_Declaration|Less_Tree_Mixin_Call The original node, or the mixin call that replaces it |
| 182 |
*/ |
| 183 |
public function visitDeclaration(Less_Tree_Declaration $d): Less_Tree_Declaration|Less_Tree_Mixin_Call |
| 184 |
{ |
| 185 |
if ( |
| 186 |
$d->variable |
| 187 |
&& $d->name === "@{$this->variableName}" |
| 188 |
&& $d->value instanceof Less_Tree_DetachedRuleset |
| 189 |
) { |
| 190 |
return new Less_Tree_Mixin_Call( |
| 191 |
[new Less_Tree_Element(null, $this->mixinDef->name)], |
| 192 |
[['name' => null, 'value' => $d->value]], |
| 193 |
$d->index, |
| 194 |
$d->currentFileInfo, |
| 195 |
); |
| 196 |
} |
| 197 |
|
| 198 |
return $d; |
| 199 |
} |
| 200 |
} |