Skip to content

Commit 0de5481

Browse files
committed
Add in PHP opening tag
1 parent c790bdd commit 0de5481

5 files changed

+31
-2
lines changed

README.md

+8
Original file line numberDiff line numberDiff line change
@@ -101,3 +101,11 @@ Every keyword inside each type will be coloured by that colour.
101101
* `(`
102102
* `)`
103103

104+
#### TYPE_CLASS
105+
106+
* `SyntaxHighlighterConfig`
107+
108+
#### TYPE_OPEN_TAG
109+
110+
* `<?php`
111+

src/SyntaxHighlightPrinter.php

+17
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,23 @@ public function __construct(
4646
$this->config = $config;
4747
}
4848

49+
/**
50+
* Pretty prints a file of statements (includes the opening <?php tag if it is required).
51+
*
52+
* @param Node[] $stmts Array of statements
53+
*
54+
* @return string Pretty printed statements
55+
*/
56+
public function prettyPrintFile(array $stmts) {
57+
$p = rtrim($this->prettyPrint($stmts));
58+
$p = preg_replace('/^\?>\n?/', '', $p, -1, $count);
59+
$p = preg_replace('/<\?php$/', '', $p);
60+
if (!$count) {
61+
$p = sprintf("%s\n\n%s", $this->color('<?php', SyntaxHighlighterConfig::TYPE_OPEN_TAG), $p);
62+
}
63+
return $p;
64+
}
65+
4966
/**
5067
* @param Stmt\Echo_ $node
5168
*

src/SyntaxHighlighter.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ class SyntaxHighlighter
1717
* @var \PhpParser\Parser
1818
*/
1919
private $parser;
20+
2021
/**
2122
* @var SyntaxHighlightPrinter
2223
*/
@@ -47,6 +48,6 @@ public function highlight($code)
4748
throw new \InvalidArgumentException('PHP could not be parsed');
4849
}
4950

50-
return $this->printer->prettyPrint($statements);
51+
return $this->printer->prettyPrintFile($statements);
5152
}
5253
}

src/SyntaxHighlighterConfig.php

+3
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ class SyntaxHighlighterConfig
1818
const TYPE_CALL_PARENTHESIS = 'call_parenthesis';
1919
const TYPE_LHS = 'lhs';
2020
const TYPE_CLASS = 'class';
21+
const TYPE_OPEN_TAG = 'open_tag';
2122

2223
/**
2324
* @var array
@@ -32,6 +33,7 @@ class SyntaxHighlighterConfig
3233
self::TYPE_CALL_PARENTHESIS,
3334
self::TYPE_LHS,
3435
self::TYPE_CLASS,
36+
self::TYPE_OPEN_TAG,
3537
];
3638

3739
/**
@@ -47,6 +49,7 @@ class SyntaxHighlighterConfig
4749
self::TYPE_CALL_PARENTHESIS => Colours::LIGHT_GRAY,
4850
self::TYPE_LHS => Colours::YELLOW,
4951
self::TYPE_CLASS => Colours::LIGHT_GRAY,
52+
self::TYPE_OPEN_TAG => Colours::CYAN,
5053
];
5154

5255
/**

test/SyntaxHighlighterTest.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ public function testSyntaxHighlighter()
4242
{
4343
$code = '<?php echo "hello world!";';
4444
$highlighter = $this->getHighlighter();
45-
$expected = "[33mecho[0m [32m'hello world!'[0m;";
45+
$expected = "[36m<?php[0m\n\n[33mecho[0m [32m'hello world!'[0m;";
4646
$this->assertEquals($expected, $highlighter->highlight($code));
4747
}
4848

0 commit comments

Comments
 (0)