Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/sanderdlm/highlighter
Customizable PHP syntax highlighter using tokens
https://github.com/sanderdlm/highlighter
Last synced: 7 days ago
JSON representation
Customizable PHP syntax highlighter using tokens
- Host: GitHub
- URL: https://github.com/sanderdlm/highlighter
- Owner: sanderdlm
- Created: 2022-06-30T19:43:29.000Z (over 2 years ago)
- Default Branch: master
- Last Pushed: 2022-09-08T12:32:41.000Z (about 2 years ago)
- Last Synced: 2024-10-29T11:58:32.808Z (8 days ago)
- Language: PHP
- Size: 90.8 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Highlighter
A teeny-tiny PHP syntax highlighter. Uses `PhpToken` to convert PHP code into PHP language tokens, and then renders those tokens as HTML using either the default styles or custom ones you provide.
## Usage
Vegetable.php
```php
edible = $edible;
$this->color = $color;
}public function isEdible(): string
{
return $this->edible;
}public function getColor(): string
{
return $this->color;
}
}
```
Using the following code:
```php
$input = file_get_contents('Vegetable.php');
$html = new Highlighter()->render($input);
echo $html;
```
results in the following HTML:
```html<?php
// Great source of vitamins
class Vegetable
{
public readonly string $edible;
public readonly string $color;
public function __construct(string $edible, string $color = "green")
{
$this->edible = $edible;
$this->color = $color;
}
public function isEdible(): string
{
return $this->edible;
}
public function getColor(): string
{
return $this->color;
}
}
```
Each piece of the PHP code is rendered as an HTML `` tag with inline styles applied to it. Special characters like quotes are converted into HTML entities and line breaks are rendered as `
` tags.When rendered in a browser, the HTML will look like this:
![](vegetable.png)
## Custom styles
The highlighting is 100% customizable.Internally, the `Highlighter` class uses a token map and a style map. You can pass both to the constructor of the class and override the defaults. Your token map should contain PHP token codes (e.g. T_OPEN_TAG), grouped together using a keyword. Your style map should map CSS styles to the keywords you chose for your token map.
```php
// If you enter the following token map
$tokenMap = [
'foobar' => [
T_STRING, // identifiers, e.g. keywords like parent and self, function names, class names and more
T_CALLABLE, // any callable,
]
];// Your style map has to contain styles for that keyword
$styleMap = [
'foobar' => 'color: #3A97D4; font-weight: bold;',
];
```
See [the PHP docs](https://www.php.net/manual/en/tokens.php) for a list of all possible parser tokens.