From 26bbd9c9459da95f04afb4c58141469748843ba3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E9=93=AD=E6=98=95?= Date: Wed, 28 Oct 2020 12:06:37 +0800 Subject: [PATCH] Fixed `Paginator::resolveCurrentPath` deos not works. (#2723) * Fixed `Paginator::resolveCurrentPath` deos not works. * Update --- src/Listener/PageResolverListener.php | 19 +++++++++++++++++++ tests/PageResolverListenerTest.php | 7 +++++++ 2 files changed, 26 insertions(+) diff --git a/src/Listener/PageResolverListener.php b/src/Listener/PageResolverListener.php index f3b4fa9..2141f16 100644 --- a/src/Listener/PageResolverListener.php +++ b/src/Listener/PageResolverListener.php @@ -54,5 +54,24 @@ public function process(object $event) return 1; }); + + Paginator::currentPathResolver(function () { + $default = '/'; + if (! ApplicationContext::hasContainer() || + ! interface_exists(RequestInterface::class) || + ! Context::has(ServerRequestInterface::class) + ) { + return $default; + } + + $container = ApplicationContext::getContainer(); + $url = $container->get(RequestInterface::class)->url(); + + if (filter_var($url, FILTER_VALIDATE_URL) !== false) { + return $url; + } + + return $url; + }); } } diff --git a/tests/PageResolverListenerTest.php b/tests/PageResolverListenerTest.php index 78f19a8..6bbdce1 100644 --- a/tests/PageResolverListenerTest.php +++ b/tests/PageResolverListenerTest.php @@ -17,6 +17,7 @@ use Hyperf\HttpServer\Request; use Hyperf\Paginator\LengthAwarePaginator; use Hyperf\Paginator\Listener\PageResolverListener; +use Hyperf\Paginator\Paginator; use Hyperf\Utils\ApplicationContext; use Hyperf\Utils\Context; use Mockery; @@ -33,6 +34,9 @@ protected function setUp() { Context::set(PsrServerRequestInterface::class, null); Context::set('http.request.parsedData', null); + Paginator::currentPathResolver(function () { + return '/'; + }); } protected function tearDown() @@ -47,12 +51,14 @@ public function testPageResolve() $this->getContainer(); $paginator = new LengthAwarePaginator([1, 2], 10, 2, null); $this->assertSame('/?page=2', $paginator->nextPageUrl()); + $this->assertSame('/', Paginator::resolveCurrentPath()); $listener = new PageResolverListener(); $listener->process(new BootApplication()); $paginator = new LengthAwarePaginator([1, 2], 10, 2, null); $this->assertSame('/?page=2', $paginator->nextPageUrl()); + $this->assertSame('/', Paginator::resolveCurrentPath()); Context::set(PsrServerRequestInterface::class, value(function () { $request = new \Hyperf\HttpMessage\Server\Request('GET', '/index'); @@ -60,6 +66,7 @@ public function testPageResolve() })); $paginator = new LengthAwarePaginator([1, 2], 10, 2, null); $this->assertSame('/?page=3', $paginator->nextPageUrl()); + $this->assertSame('/index', Paginator::resolveCurrentPath()); } protected function getContainer()