• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

dragomano / scss-php / 23594295754

26 Mar 2026 12:19PM UTC coverage: 84.536%. First build
23594295754

push

github

web-flow
Merge pull request #51 from dragomano/refactor

Rewrite compiler

10140 of 12016 new or added lines in 162 files covered. (84.39%)

10272 of 12151 relevant lines covered (84.54%)

83.37 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

74.7
/src/Builtins/SassMapModule.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Bugo\SCSS\Builtins;
6

7
use Bugo\SCSS\Exceptions\InvalidArgumentTypeException;
8
use Bugo\SCSS\Exceptions\MissingFunctionArgumentsException;
9
use Bugo\SCSS\Exceptions\UnknownSassFunctionException;
10
use Bugo\SCSS\Nodes\AstNode;
11
use Bugo\SCSS\Nodes\ListNode;
12
use Bugo\SCSS\Nodes\MapNode;
13
use Bugo\SCSS\Nodes\NamedArgumentNode;
14
use Bugo\SCSS\Nodes\NullNode;
15
use Bugo\SCSS\Runtime\BuiltinCallContext;
16
use Bugo\SCSS\Utils\AstValueComparator;
17

18
use function array_filter;
19
use function array_key_last;
20
use function array_map;
21
use function array_slice;
22
use function array_values;
23
use function count;
24
use function get_debug_type;
25
use function implode;
26
use function is_int;
27

28
/**
29
 * @phpstan-type MapPair array{key: AstNode, value: AstNode}
30
 * @psalm-type MapPair = array{key: AstNode, value: AstNode}
31
 */
32
final class SassMapModule extends AbstractModule
33
{
34
    private const FUNCTIONS = [
35
        'deep-merge',
36
        'deep-remove',
37
        'get',
38
        'has-key',
39
        'keys',
40
        'merge',
41
        'remove',
42
        'set',
43
        'values',
44
    ];
45

46
    private const GLOBAL_ALIASES = [
47
        'map-get'     => 'get',
48
        'map-has-key' => 'has-key',
49
        'map-keys'    => 'keys',
50
        'map-merge'   => 'merge',
51
        'map-remove'  => 'remove',
52
        'map-set'     => 'set',
53
        'map-values'  => 'values',
54
    ];
55

56
    public function getName(): string
57
    {
58
        return 'map';
147 ✔
59
    }
60

61
    public function getFunctions(): array
62
    {
63
        return self::FUNCTIONS;
16 ✔
64
    }
65

66
    public function getGlobalAliases(): array
67
    {
68
        return $this->globalAliases([], self::GLOBAL_ALIASES);
147 ✔
69
    }
70

71
    /**
72
     * @param array<int, AstNode> $positional
73
     * @param array<string, AstNode> $named
74
     */
75
    public function call(string $name, array $positional, array $named, ?BuiltinCallContext $context = null): AstNode
76
    {
77
        $previousDisplayName = $this->beginBuiltinCall($name, $context);
39 ✔
78

79
        try {
80
            return match ($name) {
39 ✔
81
                'deep-merge'  => $this->deepMerge($positional),
2 ✔
82
                'deep-remove' => $this->deepRemove($positional),
2 ✔
83
                'get'         => $this->get($positional, $context),
14 ✔
84
                'has-key'     => $this->hasKey($positional, $context),
7 ✔
85
                'keys'        => $this->keys($positional, $context),
5 ✔
86
                'merge'       => $this->merge($positional, $context),
5 ✔
87
                'remove'      => $this->remove($positional, $context),
5 ✔
88
                'set'         => $this->set($positional, $context),
5 ✔
89
                'values'      => $this->values($positional, $context),
4 ✔
90
                default       => throw new UnknownSassFunctionException('map', $name),
38 ✔
91
            };
39 ✔
92
        } finally {
93
            $this->endBuiltinCall($previousDisplayName);
39 ✔
94
        }
95
    }
96

97
    /**
98
     * @param array<int, AstNode> $positional
99
     */
100
    private function deepMerge(array $positional): AstNode
101
    {
102
        if (count($positional) < 2) {
2 ✔
NEW
103
            throw new MissingFunctionArgumentsException(
×
NEW
104
                $this->builtinErrorContext('map.deep-merge'),
×
NEW
105
                'two map arguments'
×
NEW
106
            );
×
107
        }
108

109
        return $this->deepMergeMaps(
2 ✔
110
            $this->asMap($positional[0], 'map.deep-merge'),
2 ✔
111
            $this->asMap($positional[1], 'map.deep-merge')
2 ✔
112
        );
2 ✔
113
    }
114

115
    /**
116
     * @param array<int, AstNode> $positional
117
     */
118
    private function deepRemove(array $positional): AstNode
119
    {
120
        if (count($positional) < 2) {
2 ✔
NEW
121
            throw new MissingFunctionArgumentsException(
×
NEW
122
                $this->builtinErrorContext('map.deep-remove'),
×
NEW
123
                'map and key path'
×
NEW
124
            );
×
125
        }
126

127
        return $this->removeNested(
2 ✔
128
            $this->asMap($positional[0], 'map.deep-remove'),
2 ✔
129
            array_slice($positional, 1)
2 ✔
130
        );
2 ✔
131
    }
132

133
    /**
134
     * @param array<int, AstNode> $positional
135
     */
136
    private function get(array $positional, ?BuiltinCallContext $context): AstNode
137
    {
138
        if (count($positional) < 2) {
18 ✔
139
            throw new MissingFunctionArgumentsException(
1 ✔
140
                $this->builtinErrorContext('map.get'),
1 ✔
141
                'map and key arguments'
1 ✔
142
            );
1 ✔
143
        }
144

145
        $this->warnAboutDeprecatedMapFunction($context, 'get', $positional);
17 ✔
146

147
        $current = $this->asMap($positional[0], 'map.get');
17 ✔
148
        $keys    = array_slice($positional, 1);
17 ✔
149

150
        foreach ($keys as $index => $key) {
17 ✔
151
            $value = $this->findByKey($current, $key);
17 ✔
152

153
            if ($value === null) {
17 ✔
154
                return $this->nullNode();
5 ✔
155
            }
156

157
            if ($index === count($keys) - 1) {
13 ✔
158
                return $value;
13 ✔
159
            }
160

161
            if (! ($value instanceof MapNode)) {
5 ✔
NEW
162
                return $this->nullNode();
×
163
            }
164

165
            $current = $value;
5 ✔
166
        }
167

NEW
168
        return $this->nullNode();
×
169
    }
170

171
    /**
172
     * @param array<int, AstNode> $positional
173
     */
174
    private function hasKey(array $positional, ?BuiltinCallContext $context): AstNode
175
    {
176
        if (count($positional) < 2) {
7 ✔
NEW
177
            throw new MissingFunctionArgumentsException(
×
NEW
178
                $this->builtinErrorContext('map.has-key'),
×
NEW
179
                'map and key arguments'
×
NEW
180
            );
×
181
        }
182

183
        $this->warnAboutDeprecatedMapFunction($context, 'has-key', $positional);
7 ✔
184

185
        $value = $this->get($positional, null);
7 ✔
186

187
        return $this->boolNode(! ($value instanceof NullNode));
7 ✔
188
    }
189

190
    /**
191
     * @param array<int, AstNode> $positional
192
     */
193
    private function keys(array $positional, ?BuiltinCallContext $context): AstNode
194
    {
195
        if (count($positional) < 1) {
5 ✔
NEW
196
            throw new MissingFunctionArgumentsException(
×
NEW
197
                $this->builtinErrorContext('map.keys'),
×
NEW
198
                'a map argument'
×
NEW
199
            );
×
200
        }
201

202
        $this->warnAboutDeprecatedMapFunction($context, 'keys', $positional);
5 ✔
203

204
        $map = $this->asMap($positional[0], 'map.keys');
5 ✔
205

206
        return new ListNode(array_map(
5 ✔
207
            /** @param MapPair $pair */
208
            fn(array $pair): AstNode => $pair['key'],
5 ✔
209
            $map->pairs
5 ✔
210
        ), 'comma');
5 ✔
211
    }
212

213
    /**
214
     * @param array<int, AstNode> $positional
215
     */
216
    private function merge(array $positional, ?BuiltinCallContext $context): AstNode
217
    {
218
        if (count($positional) < 2) {
5 ✔
NEW
219
            throw MissingFunctionArgumentsException::count(
×
NEW
220
                $this->builtinErrorContext('map.merge'),
×
NEW
221
                2,
×
NEW
222
                true
×
NEW
223
            );
×
224
        }
225

226
        $this->warnAboutDeprecatedMapFunction($context, 'merge', $positional);
5 ✔
227

228
        $map1 = $this->asMap($positional[0], 'map.merge');
5 ✔
229

230
        if (count($positional) === 2) {
5 ✔
231
            return $this->mergeTwo($map1, $this->asMap($positional[1], 'map.merge'));
4 ✔
232
        }
233

234
        $args = array_slice($positional, 1);
1 ✔
235

236
        if (count($args) === 1) {
1 ✔
NEW
237
            throw new MissingFunctionArgumentsException(
×
NEW
238
                $this->builtinErrorContext('map.merge'),
×
NEW
239
                'path keys and a map in variadic form'
×
NEW
240
            );
×
241
        }
242

243
        $lastIndex = array_key_last($args);
1 ✔
244

245
        if (! is_int($lastIndex)) {
1 ✔
NEW
246
            throw new MissingFunctionArgumentsException(
×
NEW
247
                $this->builtinErrorContext('map.merge'),
×
NEW
248
                'path keys and a map in variadic form'
×
NEW
249
            );
×
250
        }
251

252
        $map2 = $this->asMap($args[$lastIndex], 'map.merge');
1 ✔
253
        $path = array_slice($args, 0, -1);
1 ✔
254

255
        return $this->modifyNested($map1, $path, function (AstNode $existing) use ($map2): MapNode {
1 ✔
256
            if ($existing instanceof MapNode) {
1 ✔
257
                return $this->mergeTwo($existing, $map2);
1 ✔
258
            }
259

NEW
260
            return $map2;
×
261
        }, true);
1 ✔
262
    }
263

264
    /**
265
     * @param array<int, AstNode> $positional
266
     */
267
    private function remove(array $positional, ?BuiltinCallContext $context): AstNode
268
    {
269
        if (count($positional) < 1) {
5 ✔
NEW
270
            throw MissingFunctionArgumentsException::required(
×
NEW
271
                $this->builtinErrorContext('map.remove'),
×
NEW
272
                'map'
×
NEW
273
            );
×
274
        }
275

276
        $this->warnAboutDeprecatedMapFunction($context, 'remove', $positional);
5 ✔
277

278
        $map = $this->asMap($positional[0], 'map.remove');
5 ✔
279

280
        if (count($positional) === 1) {
5 ✔
281
            return $map;
1 ✔
282
        }
283

284
        $removeKeys = array_slice($positional, 1);
4 ✔
285

286
        $result = array_filter(
4 ✔
287
            $map->pairs,
4 ✔
288
            /** @param MapPair $pair */
289
            function (array $pair) use ($removeKeys): bool {
4 ✔
290
                foreach ($removeKeys as $removeKey) {
4 ✔
291
                    if (AstValueComparator::equals($pair['key'], $removeKey)) {
4 ✔
292
                        return false;
4 ✔
293
                    }
294
                }
295

296
                return true;
4 ✔
297
            }
4 ✔
298
        );
4 ✔
299

300
        return new MapNode(array_values($result));
4 ✔
301
    }
302

303
    /**
304
     * @param array<int, AstNode> $positional
305
     */
306
    private function set(array $positional, ?BuiltinCallContext $context): AstNode
307
    {
308
        if (count($positional) < 3) {
5 ✔
NEW
309
            throw new MissingFunctionArgumentsException(
×
NEW
310
                $this->builtinErrorContext('map.set'),
×
NEW
311
                'map, key path and value'
×
NEW
312
            );
×
313
        }
314

315
        $this->warnAboutDeprecatedMapFunction($context, 'set', $positional);
5 ✔
316

317
        $map   = $this->asMap($positional[0], 'map.set');
5 ✔
318
        $value = $positional[count($positional) - 1];
5 ✔
319
        $path  = array_slice($positional, 1, -1);
5 ✔
320

321
        return $this->modifyNested($map, $path, fn(AstNode $existing) => $value, true);
5 ✔
322
    }
323

324
    /**
325
     * @param array<int, AstNode> $positional
326
     */
327
    private function values(array $positional, ?BuiltinCallContext $context): AstNode
328
    {
329
        if (count($positional) < 1) {
4 ✔
NEW
330
            throw new MissingFunctionArgumentsException(
×
NEW
331
                $this->builtinErrorContext('map.values'),
×
NEW
332
                'a map argument'
×
NEW
333
            );
×
334
        }
335

336
        $this->warnAboutDeprecatedMapFunction($context, 'values', $positional);
4 ✔
337

338
        $map = $this->asMap($positional[0], 'map.values');
4 ✔
339

340
        return new ListNode(array_map(
4 ✔
341
            /** @param MapPair $pair */
342
            fn(array $pair): AstNode => $pair['value'],
4 ✔
343
            $map->pairs
4 ✔
344
        ), 'comma');
4 ✔
345
    }
346

347
    /**
348
     * @param array<int, AstNode> $positional
349
     */
350
    private function warnAboutDeprecatedMapFunction(
351
        ?BuiltinCallContext $context,
352
        string $name,
353
        array $positional
354
    ): void {
355
        if (! $this->isGlobalBuiltinCall()) {
35 ✔
356
            return;
13 ✔
357
        }
358

359
        $this->warnAboutDeprecatedBuiltinFunctionWithSingleSuggestion(
22 ✔
360
            $context,
22 ✔
361
            $this->deprecatedMapSuggestion($name, $positional),
22 ✔
362
            'map.' . $name
22 ✔
363
        );
22 ✔
364
    }
365

366
    /**
367
     * @param array<int, AstNode> $positional
368
     */
369
    private function deprecatedMapSuggestion(string $name, array $positional): string
370
    {
371
        $arguments = $positional;
22 ✔
372

373
        if ($this->rawArgumentsAvailable()) {
22 ✔
374
            $arguments = $this->rawPositionalArguments();
10 ✔
375
        }
376

377
        return 'map.' . $name . '(' . implode(', ', $this->describeBuiltinArguments($arguments)) . ')';
22 ✔
378
    }
379

380
    private function mergeTwo(MapNode $left, MapNode $right): MapNode
381
    {
382
        $result = [];
5 ✔
383

384
        foreach ($left->pairs as $pair) {
5 ✔
385
            $result[] = $pair;
5 ✔
386
        }
387

388
        foreach ($right->pairs as $rightPair) {
5 ✔
389
            $replaced = false;
5 ✔
390

391
            foreach ($result as $idx => $existing) {
5 ✔
392
                if (AstValueComparator::equals($existing['key'], $rightPair['key'])) {
5 ✔
393
                    $result[$idx] = $rightPair;
4 ✔
394
                    $replaced     = true;
4 ✔
395

396
                    break;
4 ✔
397
                }
398
            }
399

400
            if (! $replaced) {
5 ✔
401
                $result[] = $rightPair;
4 ✔
402
            }
403
        }
404

405
        return new MapNode($result);
5 ✔
406
    }
407

408
    private function deepMergeMaps(MapNode $left, MapNode $right): MapNode
409
    {
410
        $result = [];
2 ✔
411

412
        foreach ($left->pairs as $pair) {
2 ✔
413
            $result[] = $pair;
2 ✔
414
        }
415

416
        foreach ($right->pairs as $rightPair) {
2 ✔
417
            $matched = false;
2 ✔
418

419
            foreach ($result as $idx => $existing) {
2 ✔
420
                if (AstValueComparator::equals($existing['key'], $rightPair['key'])) {
2 ✔
421
                    if ($existing['value'] instanceof MapNode && $rightPair['value'] instanceof MapNode) {
2 ✔
422
                        $result[$idx] = [
2 ✔
423
                            'key'   => $existing['key'],
2 ✔
424
                            'value' => $this->deepMergeMaps($existing['value'], $rightPair['value']),
2 ✔
425
                        ];
2 ✔
426
                    } else {
427
                        $result[$idx] = $rightPair;
1 ✔
428
                    }
429

430
                    $matched = true;
2 ✔
431

432
                    break;
2 ✔
433
                }
434
            }
435

436
            if (! $matched) {
2 ✔
437
                $result[] = $rightPair;
2 ✔
438
            }
439
        }
440

441
        return new MapNode($result);
2 ✔
442
    }
443

444
    /**
445
     * @param array<int, AstNode> $path
446
     */
447
    private function removeNested(MapNode $map, array $path): MapNode
448
    {
449
        if ($path === []) {
2 ✔
NEW
450
            return $map;
×
451
        }
452

453
        $key   = $path[0];
2 ✔
454
        $tail  = array_slice($path, 1);
2 ✔
455
        $pairs = $map->pairs;
2 ✔
456

457
        foreach ($pairs as $idx => $pair) {
2 ✔
458
            if (! AstValueComparator::equals($pair['key'], $key)) {
2 ✔
459
                continue;
2 ✔
460
            }
461

462
            if ($tail === []) {
2 ✔
463
                unset($pairs[$idx]);
2 ✔
464

465
                return new MapNode(array_values($pairs));
2 ✔
466
            }
467

468
            if ($pair['value'] instanceof MapNode) {
2 ✔
469
                $pairs[$idx]['value'] = $this->removeNested($pair['value'], $tail);
2 ✔
470

471
                return new MapNode($pairs);
2 ✔
472
            }
473

NEW
474
            return $map;
×
475
        }
476

NEW
477
        return $map;
×
478
    }
479

480
    /**
481
     * @param array<int, AstNode> $path
482
     * @param callable(AstNode): AstNode $modify
483
     */
484
    private function modifyNested(MapNode $map, array $path, callable $modify, bool $addNesting): MapNode
485
    {
486
        if ($path === []) {
6 ✔
NEW
487
            $modified = $modify($map);
×
488

NEW
489
            return $modified instanceof MapNode ? $modified : $map;
×
490
        }
491

492
        $key   = $path[0];
6 ✔
493
        $tail  = array_slice($path, 1);
6 ✔
494
        $pairs = $map->pairs;
6 ✔
495

496
        foreach ($pairs as $idx => $pair) {
6 ✔
497
            if (AstValueComparator::equals($pair['key'], $key)) {
6 ✔
498
                if ($tail === []) {
6 ✔
499
                    $pairs[$idx]['value'] = $modify($pair['value']);
3 ✔
500

501
                    return new MapNode($pairs);
3 ✔
502
                }
503

504
                if ($pair['value'] instanceof MapNode) {
3 ✔
505
                    $pairs[$idx]['value'] = $this->modifyNested($pair['value'], $tail, $modify, $addNesting);
3 ✔
506

507
                    return new MapNode($pairs);
3 ✔
508
                }
509

NEW
510
                if (! $addNesting) {
×
NEW
511
                    return $map;
×
512
                }
513

NEW
514
                $pairs[$idx]['value'] = $this->modifyNested(new MapNode([]), $tail, $modify, true);
×
515

NEW
516
                return new MapNode($pairs);
×
517
            }
518
        }
519

520
        if (! $addNesting) {
3 ✔
NEW
521
            return $map;
×
522
        }
523

524
        if ($tail === []) {
3 ✔
525
            $pairs[] = ['key' => $key, 'value' => $modify(new MapNode([]))];
3 ✔
526

527
            return new MapNode($pairs);
3 ✔
528
        }
529

NEW
530
        $pairs[] = ['key' => $key, 'value' => $this->modifyNested(new MapNode([]), $tail, $modify, true)];
×
531

NEW
532
        return new MapNode($pairs);
×
533
    }
534

535
    private function findByKey(MapNode $map, AstNode $key): ?AstNode
536
    {
537
        foreach ($map->pairs as $pair) {
17 ✔
538
            if (AstValueComparator::equals($pair['key'], $key)) {
17 ✔
539
                return $pair['value'];
13 ✔
540
            }
541
        }
542

543
        return null;
5 ✔
544
    }
545

546
    /**
547
     * @return array<int, AstNode>
548
     */
549
    private function rawPositionalArguments(): array
550
    {
551
        $context = $this->activeBuiltinContext();
10 ✔
552

553
        if ($context === null || $context->rawArguments === null) {
10 ✔
NEW
554
            return [];
×
555
        }
556

557
        $arguments  = $context->rawArguments;
10 ✔
558
        $positional = [];
10 ✔
559

560
        foreach ($arguments as $argument) {
10 ✔
561
            if ($argument instanceof NamedArgumentNode) {
10 ✔
NEW
562
                continue;
×
563
            }
564

565
            $positional[] = $argument;
10 ✔
566
        }
567

568
        return $positional;
10 ✔
569
    }
570

571
    private function rawArgumentsAvailable(): bool
572
    {
573
        $context = $this->activeBuiltinContext();
22 ✔
574

575
        return $context !== null && $context->rawArguments !== null;
22 ✔
576
    }
577

578
    private function activeBuiltinContext(): ?BuiltinCallContext
579
    {
580
        return $this->activeBuiltinContext;
22 ✔
581
    }
582

583
    private function asMap(AstNode $value, string $context): MapNode
584
    {
585
        if (! ($value instanceof MapNode)) {
38 ✔
NEW
586
            throw new InvalidArgumentTypeException(
×
NEW
587
                $this->builtinErrorContext($context),
×
NEW
588
                'map',
×
NEW
589
                get_debug_type($value)
×
NEW
590
            );
×
591
        }
592

593
        return $value;
38 ✔
594
    }
595
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc