[Html] add strip_tags function

This commit is contained in:
azjezz 2021-03-05 15:30:19 +01:00 committed by Saif Eddin Gmati
parent 347747f720
commit f32efe4597
5 changed files with 59 additions and 0 deletions

View File

@ -20,6 +20,8 @@ use const ENT_QUOTES;
*
* @throws Exception\InvariantViolationException If $encoding is invalid.
*
* @psalm-taint-escape html
*
* @psalm-pure
*/
function encode(string $html, bool $double_encoding = true, ?string $encoding = null): string

View File

@ -22,6 +22,8 @@ use const ENT_SUBSTITUTE;
*
* @throws Exception\InvariantViolationException If $encoding is invalid.
*
* @psalm-taint-escape html
*
* @psalm-pure
*/
function encode_special_characters(string $html, bool $double_encoding = true, ?string $encoding = null): string

View File

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Psl\Html;
use function strip_tags as php_strip_tags;
/**
* Strip HTML and PHP tags from a string.
*
* @param list<string> $allowed_tags tags which should not be stripped.
*
* @psalm-pure
*/
function strip_tags(string $html, array $allowed_tags = []): string
{
/**
* @psalm-suppress InvalidArgument
*
* @link https://github.com/vimeo/psalm/issues/5330
*/
return php_strip_tags($html, $allowed_tags);
}

View File

@ -464,6 +464,7 @@ final class Loader
'Psl\Html\encode_special_characters',
'Psl\Html\decode',
'Psl\Html\decode_special_characters',
'Psl\Html\strip_tags',
];
public const INTERFACES = [

View File

@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Psl\Tests\Html;
use PHPUnit\Framework\TestCase;
use Psl\Html;
final class StripTagsTest extends TestCase
{
/**
* @dataProvider provideData
*/
public function testEncode(string $expected, string $html, array $allowed_tags): void
{
static::assertSame($expected, Html\strip_tags($html, $allowed_tags));
}
public function provideData(): iterable
{
yield ['hello', 'hello', []];
yield ['hello', '<p>hello</p>', []];
yield ['<p>hello</p>', '<p>hello</p>', ['p']];
yield ['<p>hello</p>', '<p>hello</p>', ['p', 'span']];
yield ['hello, <span>world!</span>', '<p>hello, <span>world!</span></p>', ['span']];
yield ['<p>hello, world!</p>', '<p>hello, <span>world!</span></p>', ['p']];
yield ['hello, world!', '<p>hello, <span>world!</span></p>', []];
}
}