Skip to content

Commit cb741b2

Browse files
committed
Strip Whitespace if setting is activated
1 parent 1a1f044 commit cb741b2

File tree

2 files changed

+57
-1
lines changed

2 files changed

+57
-1
lines changed

src/Compiler.php

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,14 @@ class Compiler
2929

3030
/** @var string[] */
3131
protected $banner;
32+
3233
/**
3334
* @var TwigBuilder
3435
*/
3536
protected $builder;
3637

38+
protected $stripWhitespace = true;
39+
3740
public function __construct(DOMDocument $document, LoggerInterface $logger)
3841
{
3942
$this->builder = new TwigBuilder();
@@ -75,6 +78,10 @@ public function convert(): string
7578

7679
$html = $this->replacePlaceholders($html);
7780

81+
if($this->stripWhitespace) {
82+
$html = $this->stripWhitespace($html);
83+
}
84+
7885
if (!empty($this->banner)) {
7986
$html = $this->addBanner($html);
8087
}
@@ -420,7 +427,7 @@ protected function addBanner(string $html)
420427

421428
$bannerLines[] = ' #}';
422429

423-
$html = implode("\n", $bannerLines)."\n".$html;
430+
$html = implode(PHP_EOL, $bannerLines).PHP_EOL.$html;
424431

425432
return $html;
426433
}
@@ -438,4 +445,33 @@ public function refactorTemplateString($value)
438445

439446
return $value;
440447
}
448+
449+
public function stripWhitespace($html)
450+
{
451+
$html = preg_replace('/(\s)+/s', '\\1', $html);
452+
$html = str_replace("\n", '', $html);
453+
454+
// Trim node text
455+
$html = preg_replace('/\>[^\S ]+/s', ">", $html);
456+
$html = preg_replace('/[^\S ]+\</s', "<", $html);
457+
458+
$html = preg_replace('/> </s', '><', $html);
459+
$html = preg_replace('/} </s', '}<', $html);
460+
$html = preg_replace('/> {/s', '>{', $html);
461+
$html = preg_replace('/} {/s', '}{', $html);
462+
463+
return $html;
464+
}
465+
466+
/**
467+
* @param bool $stripWhitespace
468+
*
469+
* @return Compiler
470+
*/
471+
public function setStripWhitespace(bool $stripWhitespace): Compiler
472+
{
473+
$this->stripWhitespace = $stripWhitespace;
474+
475+
return $this;
476+
}
441477
}

tests/CompilerTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,26 @@ public function leavesMustacheVariablesIntact()
1616
$this->assertEqualHtml($expected, $actual);
1717
}
1818

19+
/** @test */
20+
public function stripsOutWhitespaceBetweenTags()
21+
{
22+
$html = '
23+
<template>
24+
25+
<div>
26+
{{ someVariable }}
27+
</div>
28+
29+
</template>';
30+
31+
$expected = '<div>{{ someVariable }}</div>';
32+
33+
$compiler = $this->createCompiler($html);
34+
$actual = $compiler->convert();
35+
36+
$this->assertEquals($expected, $actual);
37+
}
38+
1939
/** @test */
2040
public function setBannerWithSingleLineAddsBannerCommentToTheTopOfTheTwigFile()
2141
{

0 commit comments

Comments
 (0)