g2-8.x-1.x-dev/tests/src/Unit/MatcherTest.php
tests/src/Unit/MatcherTest.php
<?php
declare(strict_types=1);
namespace Drupal\Tests\g2\Unit;
use AhoCorasick\MultiStringMatcher;
use Drupal\g2\Matcher;
use Drupal\Tests\UnitTestCase;
/**
* Class MatcherTest provides unit test for the match and replace logic.
*
* @group G2
*/
class MatcherTest extends UnitTestCase {
/**
* Data provider for testHandleSource.
*
* @return array<string,array{string[],string,string}>
* Test data.
*/
public static function providerHandle(): array {
$res = [
"terminal match" => [
['foo'],
"Don't say foo",
"Don't say <dfn>foo</dfn>",
],
"multiple matches" => [
['foo', 'bar'],
'<p>foo: In the foo, the <a href="/foo/bar">foo bar</a> is the bar',
// Notice how the '<p>' is closed because we normalize the string.
'<p><dfn>foo</dfn>: In the <dfn>foo</dfn>, the <a href="/foo/bar">foo bar</a> is the <dfn>bar</dfn></p>',
],
"other multiple matches #3376460" => [
["foo", "bar"],
'A foo is a bar.',
'A <dfn>foo</dfn> is a <dfn>bar</dfn>.',
],
"embedded matches #3376460" => [
['foo', 'bar', 'foobar'],
'foo: the foobarbaz is a foobar',
'<dfn>foo</dfn>: the foobarbaz is a <dfn>foobar</dfn>',
],
"second match is within an element #3376460" => [
['foo', 'foobar'],
"Is foo also a <em>foobar</em>?",
"Is <dfn>foo</dfn> also a <em><dfn>foobar</dfn></em>?",
],
"empty input" => [["foo"], "", ""],
"whitespace input" => [["foo"], " ", " "],
"missing closing element" => [["foo"], "<p> ", "<p> </p>"],
"forbidden script" => [
["foo"],
'<script>the foo bar</script>',
'<script>the foo bar</script>',
],
"forbidden style" => [
["foo"],
'<style>the foo bar</style>',
'<style>the foo bar</style>',
],
"forbidden a" => [
["foo"],
'<a href="zog">the foo bar</a>',
'<a href="zog">the foo bar</a>',
],
"existing dfn" => [
["foo"],
'some <dfn>foo</dfn> is not a foo.',
'some <dfn>foo</dfn> is not a <dfn>foo</dfn>.',
],
"allowed em wrapper" => [
["foo"],
'the <em>foo</em> bar',
'the <em><dfn>foo</dfn></em> bar',
],
"no match" => [
['baz'],
'<p>no match: In the foo, the <a href="/foo/bar">foo bar</a> is the bar',
'<p>no match: In the foo, the <a href="/foo/bar">foo bar</a> is the bar</p>',
],
"match in stop list" => [
["no"],
'This is no match',
'This is no match',
],
];
return $res;
}
/**
* Test handleSource().
*
* @param string[] $patterns
* The patterns to look for in the input.
* @param string $input
* The input in which to look for the patterns.
* @param string $expected
* The expected matching results.
*
* @dataProvider providerHandle
*/
public function testHandleSource(array $patterns, string $input, string $expected): void {
$msm = new MultiStringMatcher($patterns);
$stopList = ['no'];
$actual = Matcher::handleSource($input, $msm, $stopList);
$this->assertEquals($expected, $actual);
}
}
