forked from MarcusSchwarz/lesserphp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLessc.php
More file actions
1748 lines (1502 loc) · 52.3 KB
/
Copy pathLessc.php
File metadata and controls
1748 lines (1502 loc) · 52.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* http://leafo.net/lessphp
*
* LESS CSS compiler, adapted from http://lesscss.org
*
* Copyright 2013, Leaf Corcoran <leafot@gmail.com>
* Copyright 2016, Marcus Schwarz <github@maswaba.de>
* Licensed under MIT or GPLv3, see LICENSE
*/
namespace LesserPHP;
use Exception;
use LesserPHP\Functions\AbstractFunctionCollection;
use LesserPHP\Utils\Color;
use LesserPHP\Utils\Util;
use stdClass;
/**
* The LESS compiler and parser.
*
* Converting LESS to CSS is a three stage process. The incoming file is parsed
* by `Parser` into a syntax tree, then it is compiled into another tree
* representing the CSS structure by `Lessc`. The CSS tree is fed into a
* formatter, which then outputs CSS as a string.
*
* During the first compile, all values are *reduced*, which means that their
* types are brought to the lowest form before being dumped as strings. This
* handles math equations, variable dereferences, and the like.
*
* The `compile` function of `Lessc` is the entry point.
*
* In summary:
*
* The `Lessc` class creates an instance of the parser, feeds it LESS code,
* then transforms the resulting tree to a CSS tree. This class also holds the
* evaluation context, such as all available mixins and variables at any given
* time.
*
* The `Parser` class is only concerned with parsing its input.
*
* The `Formatter` takes a CSS tree, and dumps it to a formatted string,
* handling things like indentation.
*/
class Lessc
{
/** @var string A list of directories used to search for imported files */
protected $importDir = [];
/** @var bool Should imports be disabled? */
protected bool $importDisabled = false;
/** @var null|int Round numbers to this precision FIXME currently not settable */
protected ?int $numberPrecision = null;
/** @var bool Should comments be preserved in the output? */
protected bool $preserveComments = false;
/** @var array List of all functions registered to be available in LESS */
protected array $libFunctions = [];
/** @var array List of all registered variables */
protected array $registeredVars = [];
/** @var FormatterClassic|null The formatter for the output */
protected ?FormatterClassic $formatter = null;
/** @var stdClass|null Environment FIXME should probably be its own proper class */
protected ?stdClass $env = null;
/** @var stdClass|null The currently parsed block FIXME should probably be its own proper class */
protected ?stdClass $scope = null;
/** @var array [file => mtime] list of all files that have been parsed, to avoid circular imports */
protected array $allParsedFiles = [];
/** @var Parser|null The currently used Parser instance. Used when creating error messages */
protected ?Parser $sourceParser = null;
/** @var int The position in the current parsing step (in $sourceParser) */
protected int $sourceLoc = -1;
/** @var int counter to uniquely identify imports */
protected static int $nextImportId = 0;
// region public API
/**
* Initialize the LESS Parser
*/
public function __construct()
{
$this->registerLibraryFunctions();
}
/**
* Compile the given LESS string into CSS
*
* @param string $string LESS code
* @param string|null $name optional filename to show in errors
* @throws Exception
* @throws ParserException
*/
public function compile(string $string, ?string $name = null): string
{
$locale = setlocale(LC_NUMERIC, 0);
setlocale(LC_NUMERIC, 'C');
$parser = $this->makeParser($name);
$root = $parser->parse($string);
$this->env = null;
$this->scope = null;
$this->allParsedFiles = [];
if ($this->formatter === null) $this->setFormatter();
if (!empty($this->registeredVars)) {
$this->injectVariables($this->registeredVars);
}
$this->sourceParser = $parser; // used for error messages
try {
$this->compileBlock($root);
} catch (Exception $e) {
setlocale(LC_NUMERIC, $locale);
$position = $this->sourceLoc !== -1 ? $this->sourceLoc : $root->count;
$this->sourceParser->throwError($e->getMessage(), $position, $e);
}
ob_start();
$this->formatter->block($this->scope);
$out = ob_get_clean();
setlocale(LC_NUMERIC, $locale);
return $out;
}
/**
* Parse the given File and return the compiled CSS.
*
* If an output file is specified, the compiled CSS will be written to that file.
*
* @param string $fname LESS file
* @param string|null $outFname optional output file
* @return int|string number of bytes written to file, or CSS if no output file
* @throws Exception
* @throws ParserException
*/
public function compileFile(string $fname, ?string $outFname = null)
{
if (!is_readable($fname)) {
throw new Exception('load error: failed to find ' . $fname);
}
$pi = pathinfo($fname);
$oldImport = $this->importDir;
$this->importDir = (array)$this->importDir;
$this->importDir[] = $pi['dirname'] . '/';
$this->addParsedFile($fname);
$out = $this->compile(file_get_contents($fname), $fname);
$this->importDir = $oldImport;
if ($outFname !== null) {
return file_put_contents($outFname, $out);
}
return $out;
}
// endregion
// region configuration API
/**
* Should comments be preserved in the output?
*
* Default is false
*
* @param bool $preserve
*/
public function setPreserveComments(bool $preserve): void
{
$this->preserveComments = $preserve;
}
/**
* Register a custom function to be available in LESS
*
* @param string $name name of function
* @param callable $func callback
*/
public function registerFunction(string $name, callable $func): void
{
$this->libFunctions[$name] = $func;
}
/**
* Remove a function from being available in LESS
*
* @param string $name The name of the function to unregister
*/
public function unregisterFunction(string $name): void
{
if (isset($this->libFunctions[$name])) {
unset($this->libFunctions[$name]);
}
}
/**
* Add additional variables to the parser
*
* Given variables are merged with any already set variables
*
* @param array $variables [name => value, ...]
*/
public function setVariables($variables): void
{
$this->registeredVars = array_merge($this->registeredVars, $variables);
}
/**
* Get the currently set variables
*
* @return array [name => value, ...]
*/
public function getVariables(): array
{
return $this->registeredVars;
}
/**
* Remove a currently set variable
*
* @param string $name
*/
public function unsetVariable(string $name): void
{
if (isset($this->registeredVars[$name])) {
unset($this->registeredVars[$name]);
}
}
/**
* Set the directories to search for imports
*
* Overwrites any previously set directories
*
* @param string|string[] $dirs
*/
public function setImportDir($dirs): void
{
$this->importDir = (array)$dirs;
}
/**
* Add an additional directory to search for imports
*/
public function addImportDir(string $dir): void
{
$this->importDir = (array)$this->importDir;
$this->importDir[] = $dir;
}
/**
* Enable or disable import statements
*
* There is usually no need to disable imports
*
* @param bool $enable
* @return void
*/
public function enableImports(bool $enable): void
{
$this->importDisabled = !$enable;
}
/**
* Set the formatter to use for output
*
* @param FormatterClassic|null $formatter Null for the default LessJs formatter
* @return void
*/
public function setFormatter(?FormatterClassic $formatter = null)
{
if ($formatter === null) {
$formatter = new FormatterLessJs();
}
$this->formatter = $formatter;
}
// endregion
/**
* Register all the default functions
*/
protected function registerLibraryFunctions()
{
$files = glob(__DIR__ . '/Functions/*.php');
foreach ($files as $file) {
$name = basename($file, '.php');
if (substr($name, 0, 8) == 'Abstract') continue;
$class = '\\LesserPHP\\Functions\\' . $name;
$funcObj = new $class($this);
if ($funcObj instanceof AbstractFunctionCollection) {
foreach ($funcObj->getFunctions() as $name => $callback) {
$this->registerFunction($name, $callback);
}
}
}
}
/**
* attempts to find the path of an import url, returns null for css files
*
* @internal parser internal method
*/
public function findImport(string $url): ?string
{
foreach ((array)$this->importDir as $dir) {
$full = $dir . (substr($dir, -1) != '/' ? '/' : '') . $url;
if ($this->fileExists($file = $full . '.less') || $this->fileExists($file = $full)) {
return $file;
}
}
return null;
}
/**
* Check if a given file exists and is actually a file
*
* @param string $name file path
* @return bool
*/
protected function fileExists(string $name): bool
{
return is_file($name);
}
/**
* @internal parser internal method
*/
public static function compressList($items, $delim)
{
if (!isset($items[1]) && isset($items[0])) return $items[0];
else return ['list', $delim, $items];
}
/**
* @throws Exception
*/
protected function tryImport($importPath, $parentBlock, $out)
{
if ($importPath[0] == 'function' && $importPath[1] == 'url') {
$importPath = $this->flattenList($importPath[2]);
}
$str = $this->coerceString($importPath);
if ($str === null) return false;
$url = $this->compileValue($this->unwrap($str));
// don't import if it ends in css
if (substr_compare($url, '.css', -4, 4) === 0) return false;
$realPath = $this->findImport($url);
if ($realPath === null) return false;
if ($this->importDisabled) {
return [false, '/* import disabled */'];
}
if (isset($this->allParsedFiles[realpath($realPath)])) {
return [false, null];
}
$this->addParsedFile($realPath);
$parser = $this->makeParser($realPath);
$root = $parser->parse(file_get_contents($realPath));
// set the parents of all the block props
foreach ($root->props as $prop) {
if ($prop[0] == 'block') {
$prop[1]->parent = $parentBlock;
}
}
// copy mixins into scope, set their parents
// bring blocks from import into current block
// TODO: need to mark the source parser these came from this file
foreach ($root->children as $childName => $child) {
if (isset($parentBlock->children[$childName])) {
$parentBlock->children[$childName] = array_merge(
$parentBlock->children[$childName],
$child
);
} else {
$parentBlock->children[$childName] = $child;
}
}
$pi = pathinfo($realPath);
$dir = $pi['dirname'];
[$top, $bottom] = $this->sortProps($root->props, true);
$this->compileImportedProps($top, $parentBlock, $out, $parser, $dir);
return [true, $bottom, $parser, $dir];
}
/**
* @throws Exception
*/
protected function compileImportedProps($props, $block, $out, $sourceParser, $importDir)
{
$oldSourceParser = $this->sourceParser;
$oldImport = $this->importDir;
// TODO: this is because the importDir api is stupid
$this->importDir = (array)$this->importDir;
array_unshift($this->importDir, $importDir);
foreach ($props as $prop) {
$this->compileProp($prop, $block, $out);
}
$this->importDir = $oldImport;
$this->sourceParser = $oldSourceParser;
}
/**
* Recursively compiles a block.
*
* A block is analogous to a CSS block in most cases. A single LESS document
* is encapsulated in a block when parsed, but it does not have parent tags
* so all of it's children appear on the root level when compiled.
*
* Blocks are made up of props and children.
*
* Props are property instructions, array tuples which describe an action
* to be taken, eg. write a property, set a variable, mixin a block.
*
* The children of a block are just all the blocks that are defined within.
* This is used to look up mixins when performing a mixin.
*
* Compiling the block involves pushing a fresh environment on the stack,
* and iterating through the props, compiling each one.
*
* @throws Exception
* @see compileProp()
*/
protected function compileBlock($block)
{
switch ($block->type) {
case 'root':
$this->compileRoot($block);
break;
case null:
$this->compileCSSBlock($block);
break;
case 'media':
$this->compileMedia($block);
break;
case 'directive':
$name = '@' . $block->name;
if (!empty($block->value)) {
$name .= ' ' . $this->compileValue($this->reduce($block->value));
}
$this->compileNestedBlock($block, [$name]);
break;
default:
throw new Exception("unknown block type: $block->type\n");
}
}
/**
* @throws Exception
*/
protected function compileCSSBlock($block)
{
$env = $this->pushEnv();
$selectors = $this->compileSelectors($block->tags);
$env->selectors = $this->multiplySelectors($selectors);
$out = $this->makeOutputBlock(null, $env->selectors);
$this->scope->children[] = $out;
$this->compileProps($block, $out);
$block->scope = $env; // mixins carry scope with them!
$this->popEnv();
}
/**
* @throws Exception
*/
protected function compileMedia($media)
{
$env = $this->pushEnv($media);
$parentScope = $this->mediaParent($this->scope);
$query = $this->compileMediaQuery($this->multiplyMedia($env));
$this->scope = $this->makeOutputBlock($media->type, [$query]);
$parentScope->children[] = $this->scope;
$this->compileProps($media, $this->scope);
if (count($this->scope->lines) > 0) {
$orphanSelelectors = $this->findClosestSelectors();
if (!is_null($orphanSelelectors)) {
$orphan = $this->makeOutputBlock(null, $orphanSelelectors);
$orphan->lines = $this->scope->lines;
array_unshift($this->scope->children, $orphan);
$this->scope->lines = [];
}
}
$this->scope = $this->scope->parent;
$this->popEnv();
}
protected function mediaParent($scope)
{
while (!empty($scope->parent)) {
if (!empty($scope->type) && $scope->type != 'media') {
break;
}
$scope = $scope->parent;
}
return $scope;
}
/**
* @throws Exception
*/
protected function compileNestedBlock($block, $selectors)
{
$this->pushEnv($block);
$this->scope = $this->makeOutputBlock($block->type, $selectors);
$this->scope->parent->children[] = $this->scope;
$this->compileProps($block, $this->scope);
$this->scope = $this->scope->parent;
$this->popEnv();
}
/**
* @throws Exception
*/
protected function compileRoot($root)
{
$this->pushEnv();
$this->scope = $this->makeOutputBlock($root->type);
$this->compileProps($root, $this->scope);
$this->popEnv();
}
/**
* @throws Exception
*/
protected function compileProps($block, $out)
{
foreach ($this->sortProps($block->props) as $prop) {
$this->compileProp($prop, $block, $out);
}
$out->lines = $this->deduplicate($out->lines);
}
/**
* Deduplicate lines in a block. Comments are not deduplicated. If a
* duplicate rule is detected, the comments immediately preceding each
* occurrence are consolidated.
*/
protected function deduplicate($lines)
{
$unique = [];
$comments = [];
foreach ($lines as $line) {
if (strpos($line, '/*') === 0) {
$comments[] = $line;
continue;
}
if (!in_array($line, $unique)) {
$unique[] = $line;
}
array_splice($unique, array_search($line, $unique), 0, $comments);
$comments = [];
}
return array_merge($unique, $comments);
}
protected function sortProps($props, $split = false)
{
$vars = [];
$imports = [];
$other = [];
$stack = [];
foreach ($props as $prop) {
switch ($prop[0]) {
case 'comment':
$stack[] = $prop;
break;
case 'assign':
$stack[] = $prop;
if (isset($prop[1][0]) && $prop[1][0] == Constants::VPREFIX) {
$vars = array_merge($vars, $stack);
} else {
$other = array_merge($other, $stack);
}
$stack = [];
break;
case 'import':
$id = self::$nextImportId++;
$prop[] = $id;
$stack[] = $prop;
$imports = array_merge($imports, $stack);
$other[] = ['import_mixin', $id];
$stack = [];
break;
default:
$stack[] = $prop;
$other = array_merge($other, $stack);
$stack = [];
break;
}
}
$other = array_merge($other, $stack);
if ($split) {
return [array_merge($vars, $imports, $vars), $other];
} else {
return array_merge($vars, $imports, $vars, $other);
}
}
/**
* @throws Exception
*/
protected function compileMediaQuery($queries)
{
$compiledQueries = [];
foreach ($queries as $query) {
$parts = [];
foreach ($query as $q) {
switch ($q[0]) {
case 'mediaType':
$parts[] = implode(' ', array_slice($q, 1));
break;
case 'mediaExp':
if (isset($q[2])) {
$parts[] = "($q[1]: " .
$this->compileValue($this->reduce($q[2])) . ')';
} else {
$parts[] = "($q[1])";
}
break;
case 'variable':
$parts[] = $this->compileValue($this->reduce($q));
break;
}
}
if (count($parts) > 0) {
$compiledQueries[] = implode(' and ', $parts);
}
}
$out = '@media';
if (!empty($parts)) {
$out .= ' ' .
implode($this->formatter->selectorSeparator, $compiledQueries);
}
return $out;
}
protected function multiplyMedia($env, $childQueries = null)
{
if (is_null($env) ||
!empty($env->block->type) && $env->block->type != 'media') {
return $childQueries;
}
// plain old block, skip
if (empty($env->block->type)) {
return $this->multiplyMedia($env->parent, $childQueries);
}
$out = [];
$queries = $env->block->queries;
if (is_null($childQueries)) {
$out = $queries;
} else {
foreach ($queries as $parent) {
foreach ($childQueries as $child) {
$out[] = array_merge($parent, $child);
}
}
}
return $this->multiplyMedia($env->parent, $out);
}
protected function expandParentSelectors(&$tag, $replace): int
{
$parts = explode("$&$", $tag);
$count = 0;
foreach ($parts as &$part) {
$part = str_replace(Constants::PARENT_SELECTOR, $replace, $part, $c);
$count += $c;
}
$tag = implode(Constants::PARENT_SELECTOR, $parts);
return $count;
}
protected function findClosestSelectors()
{
$env = $this->env;
$selectors = null;
while ($env !== null) {
if (isset($env->selectors)) {
$selectors = $env->selectors;
break;
}
$env = $env->parent;
}
return $selectors;
}
// multiply $selectors against the nearest selectors in env
protected function multiplySelectors($selectors)
{
// find parent selectors
$parentSelectors = $this->findClosestSelectors();
if (is_null($parentSelectors)) {
// kill parent reference in top level selector
foreach ($selectors as &$s) {
$this->expandParentSelectors($s, '');
}
return $selectors;
}
$out = [];
foreach ($parentSelectors as $parent) {
foreach ($selectors as $child) {
$count = $this->expandParentSelectors($child, $parent);
// don't prepend the parent tag if & was used
if ($count > 0) {
$out[] = trim($child);
} else {
$out[] = trim($parent . ' ' . $child);
}
}
}
return $out;
}
/**
* reduces selector expressions
* @throws Exception
*/
protected function compileSelectors($selectors)
{
$out = [];
foreach ($selectors as $s) {
if (is_array($s)) {
[, $value] = $s;
$out[] = trim($this->compileValue($this->reduce($value)));
} else {
$out[] = $s;
}
}
return $out;
}
protected function eq($left, $right)
{
return $left == $right;
}
/**
* @return bool
* @throws Exception
*/
protected function patternMatch($block, $orderedArgs, $keywordArgs)
{
// match the guards if it has them
// any one of the groups must have all its guards pass for a match
if (!empty($block->guards)) {
$groupPassed = false;
foreach ($block->guards as $guardGroup) {
foreach ($guardGroup as $guard) {
$this->pushEnv();
$this->zipSetArgs($block->args, $orderedArgs, $keywordArgs);
$negate = false;
if ($guard[0] == 'negate') {
$guard = $guard[1];
$negate = true;
}
$passed = $this->reduce($guard) == Constants::TRUE;
if ($negate) $passed = !$passed;
$this->popEnv();
if ($passed) {
$groupPassed = true;
} else {
$groupPassed = false;
break;
}
}
if ($groupPassed) break;
}
if (!$groupPassed) {
return false;
}
}
if (empty($block->args)) {
return $block->isVararg || empty($orderedArgs) && empty($keywordArgs);
}
$remainingArgs = $block->args;
if ($keywordArgs) {
$remainingArgs = [];
foreach ($block->args as $arg) {
if ($arg[0] == 'arg' && isset($keywordArgs[$arg[1]])) {
continue;
}
$remainingArgs[] = $arg;
}
}
$i = -1; // no args
// try to match by arity or by argument literal
foreach ($remainingArgs as $i => $arg) {
switch ($arg[0]) {
case 'lit':
if (empty($orderedArgs[$i]) || !$this->eq($arg[1], $orderedArgs[$i])) {
return false;
}
break;
case 'arg':
// no arg and no default value
if (!isset($orderedArgs[$i]) && !isset($arg[2])) {
return false;
}
break;
case 'rest':
$i--; // rest can be empty
break 2;
}
}
if ($block->isVararg) {
return true; // not having enough is handled above
} else {
$numMatched = $i + 1;
// greater than because default values always match
return $numMatched >= count($orderedArgs);
}
}
/**
* @throws Exception
*/
protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs, $skip = [])
{
$matches = null;
foreach ($blocks as $block) {
// skip seen blocks that don't have arguments
if (isset($skip[$block->id]) && !isset($block->args)) {
continue;
}
if ($this->patternMatch($block, $orderedArgs, $keywordArgs)) {
$matches[] = $block;
}
}
return $matches;
}
/**
* attempt to find blocks matched by path and args
* @throws Exception
*/
protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen = [])
{
if ($searchIn == null) return null;
if (isset($seen[$searchIn->id])) return null;
$seen[$searchIn->id] = true;
$name = $path[0];
if (isset($searchIn->children[$name])) {
$blocks = $searchIn->children[$name];
if (count($path) == 1) {
$matches = $this->patternMatchAll($blocks, $orderedArgs, $keywordArgs, $seen);
if (!empty($matches)) {
// This will return all blocks that match in the closest
// scope that has any matching block, like lessjs
return $matches;
}
} else {
$matches = [];
foreach ($blocks as $subBlock) {
$subMatches = $this->findBlocks(
$subBlock,
array_slice($path, 1),
$orderedArgs,
$keywordArgs,
$seen
);
if (!is_null($subMatches)) {
foreach ($subMatches as $sm) {
$matches[] = $sm;
}
}
}
return count($matches) > 0 ? $matches : null;
}
}
if ($searchIn->parent === $searchIn) return null;
return $this->findBlocks($searchIn->parent, $path, $orderedArgs, $keywordArgs, $seen);
}
/**
* sets all argument names in $args to either the default value
* or the one passed in through $values
*
* @throws Exception
*/
protected function zipSetArgs($args, $orderedValues, $keywordValues)
{
$assignedValues = [];
$i = 0;
foreach ($args as $a) {
if ($a[0] == 'arg') {
if (isset($keywordValues[$a[1]])) {
// has keyword arg
$value = $keywordValues[$a[1]];
} elseif (isset($orderedValues[$i])) {
// has ordered arg
$value = $orderedValues[$i];
$i++;
} elseif (isset($a[2])) {
// has default value
$value = $a[2];
} else {
throw new Exception('Failed to assign arg ' . $a[1]);
}
$value = $this->reduce($value);
$this->set($a[1], $value);
$assignedValues[] = $value;
} else {
// a lit
$i++;
}
}
// check for a rest
$last = end($args);
if ($last !== false && $last[0] === 'rest') {
$rest = array_slice($orderedValues, count($args) - 1);
$this->set($last[1], $this->reduce(['list', ' ', $rest]));