tempestphp / highlight

🎨 Fast, extensible, server-side code highlighting for web and terminal
https://tempest.stitcher.io/highlight/01-getting-started
MIT License
619 stars 36 forks source link

Fatal error when using emphasize tags around a string #148

Open nicwortel opened 2 weeks ago

nicwortel commented 2 weeks ago

Using tempest/highlight 2.10.2, the following piece of code results in a fatal error:

<?php

use Tempest\Highlight\Highlighter;

require_once __DIR__ . '/../vendor/autoload.php';

$highlighter = new Highlighter();

$code = '$foo = {_"SELECT * FROM users"_};';

$highlighter->parse($code, 'php');
PHP Fatal error:  Uncaught TypeError: str_replace(): Argument #3 ($subject) must be of type array|string, null given in /vendor/tempest/highlight/src/Languages/Base/Injections/AdditionInjection.php:21
Stack trace:
#0 /vendor/tempest/highlight/src/Languages/Base/Injections/AdditionInjection.php(21): str_replace()
#1 /vendor/tempest/highlight/src/Highlighter.php(146): Tempest\Highlight\Languages\Base\Injections\AdditionInjection->parse()
#2 /vendor/tempest/highlight/src/Highlighter.php(96): Tempest\Highlight\Highlighter->parseContent()
#3 reproduce.php(11): Tempest\Highlight\Highlighter->parse()
#4 {main}
  thrown in /vendor/tempest/highlight/src/Languages/Base/Injections/AdditionInjection.php on line 21

It looks like the preg_replace('/\R/u', PHP_EOL, $content) call in https://github.com/tempestphp/highlight/blob/2.10.2/src/Languages/Base/Injections/AdditionInjection.php#L19 is returning null.

Using Xdebug, if I evaluate preg_last_error_msg() right after this line I get the following error message:

Malformed UTF-8 characters, possibly incorrectly encoded

Note that I'm using the emphasis tags {_ _} around the string. Without those it works fine:

$code = '$foo = "SELECT * FROM users";';

$highlighter->parse($code, 'php');

Details of my PHP version:

PHP 8.3.10 (cli) (built: Aug  2 2024 15:31:39) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.3.10, Copyright (c) Zend Technologies
    with Zend OPcache v8.3.10, Copyright (c), by Zend Technologies
    with Xdebug v3.3.2, Copyright (c) 2002-2024, by Derick Rethans
nicwortel commented 2 weeks ago

Strangely enough I'm unable to reproduce the issue with preg_replace in isolation.

When I copy the value of $content and try to reproduce this on 3v4l.org it doesn't return null:

https://3v4l.org/FWi3n