From 43845f0bdd06f2b582d0b253a112eb152ea7d6f0 Mon Sep 17 00:00:00 2001 From: Simon Asika Date: Mon, 27 Jan 2025 16:36:06 +0800 Subject: [PATCH] Fix trailing dot. resolve #10 --- src/Autolink.php | 21 +++++++++++++++------ test/AutolinkTest.php | 26 ++++++++++++++++++++++++-- 2 files changed, 39 insertions(+), 8 deletions(-) diff --git a/src/Autolink.php b/src/Autolink.php index aea320f..460e444 100644 --- a/src/Autolink.php +++ b/src/Autolink.php @@ -99,23 +99,32 @@ public function convert(string $text, array $attribs = []): string return preg_replace_callback( $regex, function ($matches) use ($attribs, $linkNoScheme) { - preg_match('/[a-zA-Z]*\=\"(.*)/', $matches[0], $inElements); + $url = $matches[0]; + + preg_match('/[a-zA-Z]*\=\"(.*)/', $url, $inElements); if ($inElements) { - return $matches[0]; + return $url; } if ( $linkNoScheme && ( - str_starts_with($matches[0], '://') - || str_starts_with($matches[0], '@') + str_starts_with($url, '://') + || str_starts_with($url, '@') ) ) { - return $matches[0]; + return $url; + } + + $suffix = ''; + + if (str_ends_with($url, '.')) { + $suffix = '.'; + $url = substr($url, 0, -1); } - return $this->link($matches[0], $attribs); + return $this->link($url, $attribs) . $suffix; }, $text ); diff --git a/test/AutolinkTest.php b/test/AutolinkTest.php index 9171768..fdda256 100644 --- a/test/AutolinkTest.php +++ b/test/AutolinkTest.php @@ -6,6 +6,7 @@ use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Windwalker\Test\Traits\BaseAssertionTrait; +use function PHPUnit\Framework\assertEquals; /** * The AutolinkTest class. @@ -157,7 +158,7 @@ public function testTextLimit() ); $this->instance->textLimit(function ($url) { - return \Asika\Autolink\Autolink::shortenUrl($url); + return Autolink::shortenUrl($url); }); self::assertEquals( @@ -385,6 +386,27 @@ public function testGetAndSetLinkBuilder() self::assertInstanceOf('Closure', $this->instance->getLinkBuilder()); } + public function testIgnoreTrailingDot(): void + { + $txt = 'Link to https://google.com.'; + + $html = $this->instance->convert($txt); + + assertEquals( + 'Link to https://google.com.', + $html, + ); + + $txt = 'Link to https://google.com/search?foo=yoo.'; + + $html = $this->instance->convert($txt); + + assertEquals( + 'Link to https://google.com/search?foo=yoo.', + $html, + ); + } + /** * urlProvider * @@ -431,6 +453,6 @@ public static function urlProvider() #[DataProvider('urlProvider')] public function testShortenUrl($url, $expect, $limit, $dots) { - self::assertEquals($expect, \Asika\Autolink\Autolink::shortenUrl($url, $limit, $dots)); + self::assertEquals($expect, Autolink::shortenUrl($url, $limit, $dots)); } }