3 declare(strict_types
=1);
5 namespace Shaarli\Front
;
7 use PHPUnit\Framework\TestCase
;
8 use Shaarli\Config\ConfigManager
;
9 use Shaarli\Container\ShaarliContainer
;
10 use Shaarli\Security\LoginManager
;
11 use Shaarli\Updater\Updater
;
12 use Slim\Http\Request
;
13 use Slim\Http\Response
;
16 class ShaarliAdminMiddlewareTest
extends TestCase
18 protected const TMP_MOCK_FILE
= '.tmp';
20 /** @var ShaarliContainer */
23 /** @var ShaarliMiddleware */
24 protected $middleware;
26 public function setUp(): void
28 $this->container
= $this->createMock(ShaarliContainer
::class);
30 touch(static::TMP_MOCK_FILE
);
32 $this->container
->conf
= $this->createMock(ConfigManager
::class);
33 $this->container
->conf
->method('getConfigFileExt')->willReturn(static::TMP_MOCK_FILE
);
35 $this->container
->loginManager
= $this->createMock(LoginManager
::class);
36 $this->container
->updater
= $this->createMock(Updater
::class);
38 $this->container
->environment
= ['REQUEST_URI' => 'http://shaarli/subfolder/path'];
40 $this->middleware
= new ShaarliAdminMiddleware($this->container
);
43 public function tearDown(): void
45 unlink(static::TMP_MOCK_FILE
);
49 * Try to access an admin controller while logged out -> redirected to login page.
51 public function testMiddlewareWhileLoggedOut(): void
53 $this->container
->loginManager
->expects(static::once())->method('isLoggedIn')->willReturn(false);
55 $request = $this->createMock(Request
::class);
56 $request->method('getUri')->willReturnCallback(function (): Uri
{
57 $uri = $this->createMock(Uri
::class);
58 $uri->method('getBasePath')->willReturn('/subfolder');
63 $response = new Response();
65 /** @var Response $result */
66 $result = $this->middleware
->__invoke($request, $response, function () {});
68 static::assertSame(302, $result->getStatusCode());
70 '/subfolder/login?returnurl=' . urlencode('http://shaarli/subfolder/path'),
71 $result->getHeader('location')[0]
76 * Process controller while logged in.
78 public function testMiddlewareWhileLoggedIn(): void
80 $this->container
->loginManager
->method('isLoggedIn')->willReturn(true);
82 $request = $this->createMock(Request
::class);
83 $request->method('getUri')->willReturnCallback(function (): Uri
{
84 $uri = $this->createMock(Uri
::class);
85 $uri->method('getBasePath')->willReturn('/subfolder');
90 $response = new Response();
91 $controller = function (Request
$request, Response
$response): Response
{
92 return $response->withStatus(418); // I'm a tea pot
95 /** @var Response $result */
96 $result = $this->middleware
->__invoke($request, $response, $controller);
98 static::assertSame(418, $result->getStatusCode());