• 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

97.98
/src/Normalizers/SassNormalizer.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Bugo\SCSS\Normalizers;
6

7
use Bugo\SCSS\Syntax;
8

9
use function array_pop;
10
use function ctype_alnum;
11
use function ctype_digit;
12
use function end;
13
use function implode;
14
use function in_array;
15
use function intdiv;
16
use function ltrim;
17
use function rtrim;
18
use function sort;
19
use function str_contains;
20
use function str_ends_with;
21
use function str_repeat;
22
use function str_starts_with;
23
use function strlen;
24
use function strpos;
25
use function substr;
26
use function substr_count;
27
use function trim;
28

29
final readonly class SassNormalizer implements SourceNormalizer
30
{
31
    private const SINGLE_LINE_DIRECTIVES = [
32
        'import',
33
        'use',
34
        'forward',
35
        'charset',
36
        'extend',
37
        'return',
38
        'debug',
39
        'warn',
40
        'error',
41
    ];
42

43
    private const BLOCK_HEADER_DIRECTIVES = [
44
        'if',
45
        'else',
46
        'for',
47
        'each',
48
        'while',
49
        'media',
50
        'supports',
51
        'keyframes',
52
        'function',
53
        'mixin',
54
        'include',
55
    ];
56

57
    private const BLOCK_HEADER_CHARS = ['.', '#', '&', '%', '['];
58

59
    private const PSEUDO_CLASSES = [
60
        'hover',
61
        'active',
62
        'focus',
63
        'has',
64
        'first-child',
65
        'nth-child',
66
        'nth-of-type',
67
        'not',
68
    ];
69

70
    private const DIRECTIVE_HEADER_KEYWORDS = ['@for', '@each', '@while', '@if'];
71

72
    private const DIRECTIVE_CONTINUATION_KEYWORDS = ['from', 'to', 'through', 'in'];
73

74
    public function supports(Syntax $syntax): bool
75
    {
76
        return $syntax === Syntax::SASS;
21 ✔
77
    }
78

79
    public function normalize(string $source): string
80
    {
81
        $eol        = $this->detectLineEnding($source);
68 ✔
82
        $lines      = $this->splitByLineBreaks($source);
68 ✔
83
        $indentSize = $this->detectIndentSize($lines);
68 ✔
84

85
        /** @var list<string> $result */
86
        $result = [];
68 ✔
87

88
        /** @var list<array{level: int}> $stack */
89
        $stack = [];
68 ✔
90

91
        $pendingEmptyLines  = [];
68 ✔
92
        $inMultilineComment = false;
68 ✔
93

94
        $lineCount = count($lines);
68 ✔
95

96
        for ($index = 0; $index < $lineCount; $index++) {
68 ✔
97
            $rawLine = $lines[$index];
68 ✔
98
            $line    = rtrim($rawLine, "\r\n");
68 ✔
99
            $trimmed = ltrim($line);
68 ✔
100

101
            if ($trimmed === '') {
68 ✔
102
                $pendingEmptyLines[] = '';
43 ✔
103

104
                continue;
43 ✔
105
            }
106

107
            if ($inMultilineComment) {
65 ✔
108
                $result[] = $line;
3 ✔
109

110
                if (str_contains($trimmed, '*/')) {
3 ✔
111
                    $inMultilineComment = false;
3 ✔
112
                }
113

114
                continue;
3 ✔
115
            }
116

117
            if (str_starts_with($trimmed, '/*')) {
65 ✔
118
                $this->flushPendingEmptyLines($result, $pendingEmptyLines);
3 ✔
119

120
                $result[] = $line;
3 ✔
121

122
                if (! str_contains($trimmed, '*/')) {
3 ✔
123
                    $inMultilineComment = true;
3 ✔
124
                }
125

126
                continue;
3 ✔
127
            }
128

129
            if (str_starts_with($trimmed, '//')) {
65 ✔
130
                $this->flushPendingEmptyLines($result, $pendingEmptyLines);
4 ✔
131

132
                $result[] = $line;
4 ✔
133

134
                continue;
4 ✔
135
            }
136

137
            $leadingSpaces = strlen($line) - strlen($trimmed);
65 ✔
138
            $level         = intdiv($leadingSpaces, $indentSize);
65 ✔
139

140
            while (! empty($stack) && end($stack)['level'] >= $level) {
65 ✔
141
                /** @var array{level: int} $block */
142
                $block = array_pop($stack);
24 ✔
143

144
                $result[] = $this->indent($block['level'], $indentSize) . '}';
24 ✔
145
            }
146

147
            if ($level === 0) {
65 ✔
148
                $this->flushPendingEmptyLines($result, $pendingEmptyLines);
64 ✔
149
            }
150

151
            $pendingEmptyLines = [];
65 ✔
152

153
            [$trimmed, $index] = $this->mergeParenthesizedDeclaration($trimmed, $level, $index, $lines, $indentSize);
65 ✔
154
            [$trimmed, $index] = $this->mergeDirectiveHeader($trimmed, $level, $index, $lines, $indentSize);
65 ✔
155
            [$trimmed, $index] = $this->mergeSingleLineDirectiveParenthesizedCall(
65 ✔
156
                $trimmed,
65 ✔
157
                $level,
65 ✔
158
                $index,
65 ✔
159
                $lines,
65 ✔
160
                $indentSize
65 ✔
161
            );
65 ✔
162

163
            if (str_ends_with(rtrim($trimmed), ',')) {
65 ✔
164
                $result[] = $this->indent($level, $indentSize) . rtrim($trimmed);
1 ✔
165

166
                continue;
1 ✔
167
            }
168

169
            if (str_starts_with($trimmed, '=')) {
64 ✔
170
                $result[] = $this->indent($level, $indentSize) . '@mixin ' . substr($trimmed, 1) . ' {';
5 ✔
171

172
                $stack[] = ['level' => $level];
5 ✔
173
            } elseif (str_starts_with($trimmed, '+')) {
64 ✔
174
                $result[] = $this->indent($level, $indentSize) . '@include ' . substr($trimmed, 1) . ';';
4 ✔
175
            } elseif ($this->isSingleLineDirective($trimmed)) {
64 ✔
176
                $endsWithSemicolon = str_ends_with(rtrim($trimmed), ';');
12 ✔
177

178
                $result[] = $this->indent($level, $indentSize) . $trimmed . ($endsWithSemicolon ? '' : ';');
12 ✔
179
            } elseif ($this->startsWithAtKeyword($trimmed, ['media'])) {
61 ✔
180
                $result[] = $this->indent($level, $indentSize) . $this->ensureBlockHeaderHasOpeningBrace($trimmed);
3 ✔
181

182
                $stack[] = ['level' => $level];
3 ✔
183
            } elseif ($this->isBlockHeader($trimmed)) {
61 ✔
184
                $result[] = $this->indent($level, $indentSize) . $this->ensureBlockHeaderHasOpeningBrace($trimmed);
57 ✔
185

186
                $stack[] = ['level' => $level];
57 ✔
187
            } else {
188
                $result[] = $this->indent($level, $indentSize) . rtrim($trimmed, ';') . ';';
60 ✔
189
            }
190
        }
191

192
        while (! empty($stack)) {
68 ✔
193
            /** @var array{level: int} $block */
194
            $block = array_pop($stack);
58 ✔
195

196
            $result[] = $this->indent($block['level'], $indentSize) . '}';
58 ✔
197
        }
198

199
        return implode($eol, $result);
68 ✔
200
    }
201

202
    /**
203
     * @param list<string> $result
204
     * @param list<string> $pendingEmptyLines
205
     */
206
    private function flushPendingEmptyLines(array &$result, array &$pendingEmptyLines): void
207
    {
208
        foreach ($pendingEmptyLines as $empty) {
64 ✔
209
            $result[] = $empty;
24 ✔
210
        }
211

212
        $pendingEmptyLines = [];
64 ✔
213
    }
214

215
    private function indent(int $level, int $indentSize): string
216
    {
217
        return str_repeat(' ', $level * $indentSize);
65 ✔
218
    }
219

220
    /**
221
     * @param array<int, string> $lines
222
     * @return array{0: string, 1: int}
223
     */
224
    private function mergeParenthesizedDeclaration(
225
        string $trimmed,
226
        int $level,
227
        int $index,
228
        array $lines,
229
        int $indentSize
230
    ): array {
231
        $candidate = rtrim($trimmed);
65 ✔
232

233
        if (! str_contains($candidate, ':') || ! str_ends_with($candidate, '(')) {
65 ✔
234
            return [$trimmed, $index];
65 ✔
235
        }
236

237
        return $this->mergeParenthesizedContinuation($candidate, $level, $index, $lines, $indentSize);
1 ✔
238
    }
239

240
    /**
241
     * @param array<int, string> $lines
242
     * @return array{0: string, 1: int}
243
     */
244
    private function mergeDirectiveHeader(
245
        string $trimmed,
246
        int $level,
247
        int $index,
248
        array $lines,
249
        int $indentSize
250
    ): array {
251
        $header = rtrim($trimmed);
65 ✔
252

253
        if (! in_array($header, self::DIRECTIVE_HEADER_KEYWORDS, true)) {
65 ✔
254
            return [$trimmed, $index];
65 ✔
255
        }
256

257
        $max = count($lines);
1 ✔
258

259
        while ($index + 1 < $max) {
1 ✔
260
            $nextLine    = rtrim($lines[$index + 1], "\r\n");
1 ✔
261
            $nextTrimmed = ltrim($nextLine);
1 ✔
262

263
            if ($nextTrimmed === '') {
1 ✔
NEW
264
                break;
×
265
            }
266

267
            $leadingSpaces = strlen($nextLine) - strlen($nextTrimmed);
1 ✔
268
            $nextLevel     = intdiv($leadingSpaces, $indentSize);
1 ✔
269

270
            if ($nextLevel <= $level || ! $this->looksLikeDirectiveHeaderContinuation($nextTrimmed)) {
1 ✔
271
                break;
1 ✔
272
            }
273

274
            $header .= ' ' . $nextTrimmed;
1 ✔
275
            $index++;
1 ✔
276
        }
277

278
        return [$header, $index];
1 ✔
279
    }
280

281
    /**
282
     * @param array<int, string> $lines
283
     * @return array{0: string, 1: int}
284
     */
285
    private function mergeSingleLineDirectiveParenthesizedCall(
286
        string $trimmed,
287
        int $level,
288
        int $index,
289
        array $lines,
290
        int $indentSize
291
    ): array {
292
        $candidate = rtrim($trimmed);
65 ✔
293

294
        if (! $this->isSingleLineDirective($candidate) || $this->parenthesisBalance($candidate) <= 0) {
65 ✔
295
            return [$trimmed, $index];
65 ✔
296
        }
297

298
        return $this->mergeParenthesizedContinuation($candidate, $level, $index, $lines, $indentSize);
2 ✔
299
    }
300

301
    /**
302
     * @param array<int, string> $lines
303
     * @return array{0: string, 1: int}
304
     */
305
    private function mergeParenthesizedContinuation(
306
        string $merged,
307
        int $level,
308
        int $index,
309
        array $lines,
310
        int $indentSize
311
    ): array {
312
        $depth = $this->parenthesisBalance($merged);
3 ✔
313

314
        $max = count($lines);
3 ✔
315

316
        while ($depth > 0 && $index + 1 < $max) {
3 ✔
317
            $nextLine    = rtrim($lines[$index + 1], "\r\n");
3 ✔
318
            $nextTrimmed = ltrim($nextLine);
3 ✔
319

320
            if ($nextTrimmed === '') {
3 ✔
NEW
321
                break;
×
322
            }
323

324
            $leadingSpaces = strlen($nextLine) - strlen($nextTrimmed);
3 ✔
325
            $nextLevel     = intdiv($leadingSpaces, $indentSize);
3 ✔
326

327
            if ($nextLevel < $level) {
3 ✔
NEW
328
                break;
×
329
            }
330

331
            if ($nextLevel === $level && ! str_starts_with($nextTrimmed, ')')) {
3 ✔
NEW
332
                break;
×
333
            }
334

335
            $merged .= ' ' . $nextTrimmed;
3 ✔
336

337
            $depth += $this->parenthesisBalance($nextTrimmed);
3 ✔
338

339
            $index++;
3 ✔
340
        }
341

342
        return [$merged, $index];
3 ✔
343
    }
344

345
    private function looksLikeDirectiveHeaderContinuation(string $line): bool
346
    {
347
        if ($line === '') {
3 ✔
348
            return false;
1 ✔
349
        }
350

351
        if (str_starts_with($line, '$') || ctype_digit($line[0])) {
2 ✔
352
            return true;
1 ✔
353
        }
354

355
        foreach (self::DIRECTIVE_CONTINUATION_KEYWORDS as $keyword) {
2 ✔
356
            if ($line === $keyword || str_starts_with($line, $keyword . ' ')) {
2 ✔
357
                return true;
1 ✔
358
            }
359
        }
360

361
        return false;
1 ✔
362
    }
363

364
    private function parenthesisBalance(string $line): int
365
    {
366
        return substr_count($line, '(') - substr_count($line, ')');
13 ✔
367
    }
368

369
    private function detectLineEnding(string $source): string
370
    {
371
        $patterns = [
68 ✔
372
            "\r\n" => "\r\n",
68 ✔
373
            "\r"   => "\r",
68 ✔
374
        ];
68 ✔
375

376
        foreach ($patterns as $search => $replace) {
68 ✔
377
            if (str_contains($source, $search)) {
68 ✔
378
                return $replace;
4 ✔
379
            }
380
        }
381

382
        return "\n";
65 ✔
383
    }
384

385
    /**
386
     * @param array<int, string> $lines
387
     */
388
    private function detectIndentSize(array $lines): int
389
    {
390
        $sizes = [2];
68 ✔
391

392
        foreach ($lines as $line) {
68 ✔
393
            if (trim($line) === '') {
68 ✔
394
                continue;
43 ✔
395
            }
396

397
            $leadingSpaces = $this->leadingSpaceCount($line);
65 ✔
398

399
            if ($leadingSpaces > 0) {
65 ✔
400
                $sizes[] = $leadingSpaces;
60 ✔
401
            }
402
        }
403

404
        sort($sizes);
68 ✔
405

406
        return $sizes[0];
68 ✔
407
    }
408

409
    private function isSingleLineDirective(string $line): bool
410
    {
411
        return $this->startsWithAtKeyword($line, self::SINGLE_LINE_DIRECTIVES);
65 ✔
412
    }
413

414
    private function isBlockHeader(string $line): bool
415
    {
416
        if ($this->startsWithAtKeyword($line, self::BLOCK_HEADER_DIRECTIVES)) {
61 ✔
417
            return true;
9 ✔
418
        }
419

420
        if ($line !== '' && in_array($line[0], self::BLOCK_HEADER_CHARS, true)) {
61 ✔
421
            return true;
52 ✔
422
        }
423

424
        if (str_ends_with($line, ':')) {
60 ✔
425
            return true;
2 ✔
426
        }
427

428
        return ! str_contains($line, ':') || $this->containsPseudoClass($line);
60 ✔
429
    }
430

431
    private function ensureBlockHeaderHasOpeningBrace(string $line): string
432
    {
433
        return str_ends_with(rtrim($line), '{') ? rtrim($line) : $line . ' {';
57 ✔
434
    }
435

436
    /**
437
     * @return array<int, string>
438
     */
439
    private function splitByLineBreaks(string $source): array
440
    {
441
        $lines   = [];
68 ✔
442
        $current = '';
68 ✔
443
        $length  = strlen($source);
68 ✔
444

445
        for ($i = 0; $i < $length; $i++) {
68 ✔
446
            $char = $source[$i];
66 ✔
447

448
            if ($char === "\r") {
66 ✔
449
                $lines[] = $current;
4 ✔
450
                $current = '';
4 ✔
451

452
                if ($i + 1 < $length && $source[$i + 1] === "\n") {
4 ✔
453
                    $i++;
3 ✔
454
                }
455

456
                continue;
4 ✔
457
            }
458

459
            if ($char === "\n") {
66 ✔
460
                $lines[] = $current;
62 ✔
461
                $current = '';
62 ✔
462

463
                continue;
62 ✔
464
            }
465

466
            $current .= $char;
66 ✔
467
        }
468

469
        $lines[] = $current;
68 ✔
470

471
        return $lines;
68 ✔
472
    }
473

474
    private function leadingSpaceCount(string $line): int
475
    {
476
        $length = strlen($line);
65 ✔
477
        $count  = 0;
65 ✔
478

479
        while ($count < $length && ($line[$count] === ' ' || $line[$count] === "\t")) {
65 ✔
480
            $count++;
60 ✔
481
        }
482

483
        return $count;
65 ✔
484
    }
485

486
    /**
487
     * @param array<int, string> $keywords
488
     */
489
    private function startsWithAtKeyword(string $line, array $keywords): bool
490
    {
491
        if (! str_starts_with($line, '@')) {
65 ✔
492
            return false;
62 ✔
493
        }
494

495
        $rest = substr($line, 1);
24 ✔
496

497
        foreach ($keywords as $keyword) {
24 ✔
498
            if (! str_starts_with($rest, $keyword)) {
24 ✔
499
                continue;
23 ✔
500
            }
501

502
            $length = strlen($keyword);
22 ✔
503

504
            if (strlen($rest) === $length) {
22 ✔
505
                return true;
1 ✔
506
            }
507

508
            $next = $rest[$length];
22 ✔
509

510
            if (! ctype_alnum($next) && $next !== '_') {
22 ✔
511
                return true;
22 ✔
512
            }
513
        }
514

515
        return false;
14 ✔
516
    }
517

518
    private function containsPseudoClass(string $line): bool
519
    {
520
        foreach (self::PSEUDO_CLASSES as $pseudoClass) {
61 ✔
521
            $needle   = ':' . $pseudoClass;
61 ✔
522
            $position = 0;
61 ✔
523

524
            while (($position = strpos($line, $needle, $position)) !== false) {
61 ✔
525
                $nextIndex = $position + strlen($needle);
3 ✔
526

527
                if ($nextIndex >= strlen($line)) {
3 ✔
528
                    return true;
2 ✔
529
                }
530

531
                $next = $line[$nextIndex];
2 ✔
532

533
                if (! ctype_alnum($next) && $next !== '_' && $next !== '-') {
2 ✔
534
                    return true;
1 ✔
535
                }
536

537
                $position++;
1 ✔
538
            }
539
        }
540

541
        return false;
60 ✔
542
    }
543
}
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