Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

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

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.