tin is a code highlighter for PHP.

2.0.0 2024-03-14 19:45 UTC

This package is auto-updated.

Last update: 2024-11-15 11:50:32 UTC


README

tin is a code highlighter for PHP (Terminal, HTML, etc.).

Tests Formats Version Total Downloads License

Installation

Requires PHP 8.3+

You can install the package via composer:

composer require felixdorn/tin

Screenshots

A piece of code highlighted using tin

Another piece of code highlighted using tin

Yes, this comes from a terminal.

Usage

<?php

use Felix\Tin\Themes\JetbrainsDark;
use Felix\Tin\Tin;

echo Tin::from(JetbrainsDark::class, $ansi = true)->highlight("<?php\n\necho 'Hello world';\n");

Customizing the output

You have complete control over the highlighting process. Implement the Felix\Tin\Contracts\OutputInterface interface or implement a custom theme if you are just looking to change the colors.

Outputs

$tin = new \Felix\Tin\Tin(
    new \Felix\Tin\Outputs\AnsiOutput()
)
$tin = new \Felix\Tin\Tin(
    new \Felix\Tin\Outputs\HtmlOutput()
)

Callable output is best used in combination with the ANSI or HTML output, you can think of it as a sort of decorator when you need change a small thing without creating a class.

$tin = new \Felix\Tin\Tin(
    new \Felix\Tin\Outputs\CallableOutput(
        new \Felix\Tin\Themes\OneDark(),
        fn (\Felix\Tin\Line $line) => $line->number % 2 ? 
            (new \Felix\Tin\Outputs\AnsiOutput())->transformLine($line) :
             null
    )
)

Themes

Themes define the colors used by outputs. The format is r;g;b, to match the default ANSI format.

Creating a theme

You need to extend Felix\Tin\Themes\Theme and set the colors to whatever you want.

The color are RGB values separated by a ;.

use Felix\Tin\Contracts\ThemeInterface;
use Felix\Tin\Enums\TokenType;

class OneDark extends ThemeInterface
{
    /** {@inheritDoc} */
    public function color(TokenType $type): string
    {
        return match ($type) {
            TokenType::Keyword  => '199;120;221',
            TokenType::Variable => '224;107;116',
            TokenType::Comment  => '91;98;110',
            TokenType::String   => '152;195;121',
            TokenType::Function, TokenType::NamedParameter, TokenType::Attribute => '98;174;239',
            TokenType::Number, TokenType::Html => '229;192;122',
            default => '171;178;191',
        };
    }
}

Testing

composer test

tin was created by Félix Dorn under the MIT license.