Skip to content

Commit

Permalink
PhpStan warnings have been resolved
Browse files Browse the repository at this point in the history
  • Loading branch information
batumibiz committed Dec 2, 2024
1 parent beb191f commit ae61728
Show file tree
Hide file tree
Showing 6 changed files with 64 additions and 36 deletions.
1 change: 0 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@
"check": [
"@cs-check",
"@static-analysis",
"@taint-analysis",
"@test"
],
"cs-check": "phpcs",
Expand Down
14 changes: 12 additions & 2 deletions src/SessionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,15 @@ final class SessionHandler implements SessionInterface
private int $lifeTime = 10800;

private string $sessionId = '';

/**
* @var array<array-key, mixed>
*/
private array $data = [];

/**
* @param array<array-key, mixed> $options
*/
public function __construct(PDO $pdo, CookieManagerInterface $cookieManager, array $options = [])
{
$this->pdo = $pdo;
Expand All @@ -36,13 +43,13 @@ public function startSession(ServerRequestInterface $request): void
{
$id = trim((string) ($request->getCookieParams()[$this->cookieName] ?? ''));

if (! empty($id) && strlen($id) == 32) {
if ($id !== '' && strlen($id) === 32) {
$this->sessionId = $id;

$stmt = $this->pdo->prepare('SELECT * FROM `system__session` WHERE `session_id` = :id');
$stmt->bindValue(':id', $id);
$stmt->execute();
/** @var array|false $result */
/** @var array<array-key, mixed>|false $result */
$result = $stmt->fetch();

if ($result !== false && $result['modified'] > time() - $this->lifeTime) {
Expand Down Expand Up @@ -128,6 +135,9 @@ private function sendCookies(string $id, ResponseInterface $response): ResponseI
return $response->withHeader('Pragma', 'no-cache');
}

/**
* @param array<array-key, mixed> $options
*/
private function resolveOptions(array $options): void
{
if (isset($options['cookie_name'])) {
Expand Down
3 changes: 3 additions & 0 deletions src/SessionMiddlewareFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ public function __invoke(ContainerInterface $container): SessionMiddleware
return new SessionMiddleware($session);
}

/**
* @param array<array-key, mixed> $config
*/
public function checkGc(array $config): bool
{
$file = (string) ($config['gc_timestamp_file'] ?? '');
Expand Down
43 changes: 24 additions & 19 deletions tests/unit/SessionHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ class SessionHandlerTest extends MysqlTestCase
{
private SessionHandler $session;
private ServerRequestInterface $request;

/**
* @var array<array-key, mixed>
*/
private array $options = [
'cookie_name' => 'TESTSESSION',
'cookie_domain' => 'localhost',
Expand All @@ -31,7 +35,7 @@ public function setUp(): void
$loader->loadFile('install/sql/tables.sql');

if ($loader->hasErrors()) {
$this->fail(implode("\n", $loader->getErrors()));
self::fail(implode("\n", $loader->getErrors()));
}

$this->session = new SessionHandler(
Expand All @@ -47,70 +51,71 @@ public function setUp(): void

public function testImplementsSessionInterface(): void
{
$this->assertInstanceOf(SessionInterface::class, $this->session);
/** @phpstan-ignore staticMethod.alreadyNarrowedType */
self::assertInstanceOf(SessionInterface::class, $this->session);
}

public function testHasMethodWithExistingKey(): void
{
$this->initializeSessionWithData();
$this->assertTrue($this->session->has('foo'));
self::assertTrue($this->session->has('foo'));
}

public function testHasMethodWithNonExistentKey(): void
{
$this->initializeSessionWithData();
$this->assertFalse($this->session->has('bar'));
self::assertFalse($this->session->has('bar'));
}

public function testGetMethodWithExistingKey(): void
{
$this->initializeSessionWithData();
$this->assertSame('test-session', $this->session->get('foo'));
self::assertSame('test-session', $this->session->get('foo'));
}

public function testGetMethodWithNonExistentKeyReturnNull(): void
{
$this->initializeSessionWithData();
$this->assertNull($this->session->get('bar'));
self::assertNull($this->session->get('bar'));
}

public function testGetMethodWithNonExistentKeyReturnDefaultValue(): void
{
$this->initializeSessionWithData();
$this->assertSame('mydata', $this->session->get('bar', 'mydata'));
self::assertSame('mydata', $this->session->get('bar', 'mydata'));
}

public function testUnsetMethod(): void
{
$this->initializeSessionWithData();
$this->assertTrue($this->session->has('foo'));
self::assertTrue($this->session->has('foo'));
$this->session->unset('foo');
$this->session->unset('bar');
$this->assertFalse($this->session->has('foo'));
self::assertFalse($this->session->has('foo'));
}

public function testSetMethod(): void
{
$this->initializeSessionWithData();
$this->session->set('foo', 'newdata');
$this->session->set('baz', 'bat');
$this->assertSame('newdata', $this->session->get('foo'));
$this->assertSame('bat', $this->session->get('baz'));
self::assertSame('newdata', $this->session->get('foo'));
self::assertSame('bat', $this->session->get('baz'));
}

public function testClearMethod(): void
{
$this->initializeSessionWithData();
$this->session->set('baz', 'bat');
$this->session->clear();
$this->assertFalse($this->session->has('foo'));
$this->assertFalse($this->session->has('baz'));
self::assertFalse($this->session->has('foo'));
self::assertFalse($this->session->has('baz'));
}

public function testWithExpiredData(): void
{
$this->initializeSessionWithData(30000);
$this->assertFalse($this->session->has('foo'));
self::initializeSessionWithData(30000);
self::assertFalse($this->session->has('foo'));
}

public function testGarbageCollector(): void
Expand All @@ -120,7 +125,7 @@ public function testGarbageCollector(): void
$query = self::getPdo()->query(
"SELECT * FROM `system__session` WHERE `session_id` = 'ssssssssssssssssssssssssssssssss'"
);
$this->assertEquals(0, $query->rowCount());
self::assertEquals(0, $query->rowCount());
}

public function testPersistenceWithExistingSessionId(): void
Expand All @@ -135,7 +140,7 @@ public function testPersistenceWithExistingSessionId(): void
$this->options
);
$session2->startSession($this->request);
$this->assertEquals('bat', $session2->get('baz'));
self::assertEquals('bat', $session2->get('baz'));
}

public function testPeresistenceGenerateNewsessionId(): void
Expand All @@ -156,15 +161,15 @@ public function testPeresistenceGenerateNewsessionId(): void
$this->options
);
$newSession->startSession($request);
$this->assertEquals('bat', $newSession->get('baz'));
self::assertEquals('bat', $newSession->get('baz'));
}

public function testPersistenceIfNoIdAndNoData(): void
{
$this->session->startSession($this->createMock(ServerRequestInterface::class));
$this->session->persistSession(new Response());
$query = self::getPdo()->query('SELECT * FROM `system__session`');
$this->assertEquals(0, $query->rowCount());
self::assertEquals(0, $query->rowCount());
}

private function initializeSessionWithData(int $modified = 0): void
Expand Down
21 changes: 14 additions & 7 deletions tests/unit/SessionMiddlewareFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Mobicms\Testutils\MysqlTestCase;
use Mobicms\Testutils\SqlDumpLoader;
use PDO;
use PHPUnit\Framework\MockObject\Exception;
use Psr\Container\ContainerInterface;

use function is_file;
Expand Down Expand Up @@ -51,7 +52,7 @@ public function testExceptionIfTimestampFileIsNotWritable(): void
public function testNeedGarbageCollection(): void
{
touch($this->file, time() - 10000);
$this->assertTrue(
self::assertTrue(
$this->factory->checkGc(
[
'gc_timestamp_file' => $this->file,
Expand All @@ -64,7 +65,7 @@ public function testNeedGarbageCollection(): void
public function testNotNeedGarbageCollection(): void
{
touch($this->file);
$this->assertFalse(
self::assertFalse(
$this->factory->checkGc(
[
'gc_timestamp_file' => $this->file,
Expand All @@ -81,23 +82,28 @@ public function testCreateTimestampFile(): void
}

$this->factory->checkGc(['gc_timestamp_file' => $this->file]);
$this->assertTrue(is_file($this->file));
self::assertTrue(is_file($this->file));
}

public function testFactoryReturnsSessionMiddlewareInstance()
public function testFactoryReturnsSessionMiddlewareInstance(): void
{
$loader = new SqlDumpLoader(self::getPdo());
$loader->loadFile('install/sql/tables.sql');

if ($loader->hasErrors()) {
$this->fail(implode("\n", $loader->getErrors()));
self::fail(implode("\n", $loader->getErrors()));
}

touch($this->file, time() - 10000);
$result = (new SessionMiddlewareFactory())($this->getContainer(['gc_timestamp_file' => $this->file]));
$this->assertInstanceOf(SessionMiddleware::class, $result);
/** @phpstan-ignore staticMethod.alreadyNarrowedType */
self::assertInstanceOf(SessionMiddleware::class, $result);
}

/**
* @param array<array-key, string> $options
* @throws Exception
*/
private function getContainer(array $options): ContainerInterface
{
$config = $this->createMock(ConfigInterface::class);
Expand All @@ -117,7 +123,8 @@ private function getContainer(array $options): ContainerInterface
fn($val) => match ($val) {
ConfigInterface::class => $config,
PDO::class => self::getPdo(),
CookieManagerInterface::class => $this->createMock(CookieManagerInterface::class)
CookieManagerInterface::class => $this->createMock(CookieManagerInterface::class),
default => null,
}
);

Expand Down
18 changes: 11 additions & 7 deletions tests/unit/SessionMiddlewareTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@
use Mobicms\Testutils\MysqlTestCase;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class SessionMiddlewareTest extends MysqlTestCase
{
private SessionMiddleware $middleware;

/**
* @throws \PHPUnit\Framework\MockObject\Exception
*/
public function setUp(): void
{
$this->middleware = new SessionMiddleware(
Expand All @@ -27,21 +29,20 @@ public function setUp(): void
);
}

public function testImplementsMiddlewareInterface(): void
{
$this->assertInstanceOf(MiddlewareInterface::class, $this->middleware);
}

public function testProcess(): void
{
$result = $this->middleware->process(
$this->mockRequest(),
$this->mockRequestHandler()
);

$this->assertInstanceOf(ResponseInterface::class, $result);
/** @phpstan-ignore staticMethod.alreadyNarrowedType */
self::assertInstanceOf(ResponseInterface::class, $result);
}

/**
* @throws \PHPUnit\Framework\MockObject\Exception
*/
private function mockRequest(): ServerRequestInterface
{
$request = $this->createMock(ServerRequestInterface::class);
Expand All @@ -52,6 +53,9 @@ private function mockRequest(): ServerRequestInterface
return $request;
}

/**
* @throws \PHPUnit\Framework\MockObject\Exception
*/
private function mockRequestHandler(): RequestHandlerInterface
{
$handler = $this->createMock(RequestHandlerInterface::class);
Expand Down

0 comments on commit ae61728

Please sign in to comment.