Add unit tests for Smilies::isEmojiPost

- Current implementation is failing tests with emojis including the zero-width-joiner character, encoded on 3 bytes only.
This commit is contained in:
Hypolite Petovan 2023-08-29 22:16:09 -04:00
parent 6ed440718d
commit 059a111282
2 changed files with 73 additions and 1 deletions

View File

@ -289,11 +289,12 @@ class Smilies
/** /**
* Checks if the body only contains 4 byte unicode characters. * Checks if the body only contains 4 byte unicode characters.
* *
* @param string $body * @param string $body Possibly-HTML post body
* @return boolean * @return boolean
*/ */
public static function isEmojiPost(string $body): bool public static function isEmojiPost(string $body): bool
{ {
// Strips all whitespace
$conv = preg_replace('#\s#u', '', html_entity_decode($body)); $conv = preg_replace('#\s#u', '', html_entity_decode($body));
// Emojis are always 4 byte Unicode characters // Emojis are always 4 byte Unicode characters
return (!empty($conv) && (strlen($conv) / mb_strlen($conv) == 4)); return (!empty($conv) && (strlen($conv) / mb_strlen($conv) == 4));

View File

@ -72,4 +72,75 @@ class SmiliesTest extends FixtureTest
$output = Smilies::replaceFromArray($text, $smilies); $output = Smilies::replaceFromArray($text, $smilies);
self::assertEquals($expected, $output); self::assertEquals($expected, $output);
} }
public function dataIsEmojiPost(): array
{
return [
'emoji' => [
'expected' => true,
'body' => '👀',
],
'emojis' => [
'expected' => true,
'body' => '👀🤷',
],
'emoji+whitespace' => [
'expected' => true,
'body' => ' 👀 ',
],
'empty' => [
'expected' => false,
'body' => '',
],
'whitespace' => [
'expected' => false,
'body' => '
',
],
'emoji+ASCII' => [
'expected' => false,
'body' => '🤷a',
],
'HTML entity whitespace' => [
'expected' => false,
'body' => ' ',
],
'HTML entity else' => [
'expected' => false,
'body' => '°',
],
'emojis+HTML whitespace' => [
'expected' => true,
'body' => '👀 🤷',
],
'emojis+HTML else' => [
'expected' => false,
'body' => '👀<🤷',
],
'zwj' => [
'expected' => true,
'body' => '👨‍👨‍👧‍',
],
'zwj+whitespace' => [
'expected' => true,
'body' => ' 👨‍👨‍👧‍ ',
],
'zwj+HTML whitespace' => [
'expected' => true,
'body' => ' 👨‍👨‍👧‍ ',
],
];
}
/**
* @dataProvider dataIsEmojiPost
*
* @param bool $expected
* @param string $body
* @return void
*/
public function testIsEmojiPost(bool $expected, string $body)
{
$this->assertEquals($expected, Smilies::isEmojiPost($body));
}
} }