Skip to content

Commit 8157191

Browse files
Stephan Wentzpl-github
authored andcommitted
feat: Add session handling in request builder
1 parent 5ad0332 commit 8157191

File tree

5 files changed

+94
-39
lines changed

5 files changed

+94
-39
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
"phpstan/phpstan": "^1.2",
2727
"phpstan/phpstan-phpunit": "^1.0",
2828
"phpstan/phpstan-symfony": "^1.0",
29-
"phpunit/phpunit": "^10.0",
29+
"phpunit/phpunit": "^10.1",
3030
"riverline/multipart-parser": "^2.0",
3131
"slam/phpstan-extensions": "^6.0",
3232
"squizlabs/php_codesniffer": "^3.7.1",

phpunit.xml.dist

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
11
<?xml version="1.0" encoding="UTF-8"?>
22
<!-- https://phpunit.readthedocs.io/en/latest/configuration.html -->
3-
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.0/phpunit.xsd" backupGlobals="false" colors="true" bootstrap="vendor/autoload.php" extensionsDirectory="/usr/lib/tools/phpunit.d" cacheDirectory=".phpunit.cache">
4-
<coverage>
5-
<include>
6-
<directory suffix=".php">src</directory>
7-
</include>
8-
</coverage>
3+
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.1/phpunit.xsd" backupGlobals="false" colors="true" bootstrap="vendor/autoload.php" extensionsDirectory="/usr/lib/tools/phpunit.d" cacheDirectory=".phpunit.cache">
4+
<coverage/>
95
<php>
106
<ini name="error_reporting" value="-1"/>
117
</php>
@@ -14,4 +10,9 @@
1410
<directory>tests</directory>
1511
</testsuite>
1612
</testsuites>
13+
<source>
14+
<include>
15+
<directory suffix=".php">src</directory>
16+
</include>
17+
</source>
1718
</phpunit>

src/Request/RequestBuilder.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ final class RequestBuilder
3030
/** @var mixed[] */
3131
private array $files = [];
3232
/** @var mixed[] */
33+
private array $sessionValues = [];
34+
/** @var mixed[] */
3335
private array $server = [];
3436
private string|null $content = null;
3537
private bool $changeHistory = true;
@@ -317,4 +319,17 @@ public function getChangeHistory(): bool
317319
{
318320
return $this->changeHistory;
319321
}
322+
323+
/** @return array<string, mixed> */
324+
public function getSessionValues(): array
325+
{
326+
return $this->sessionValues;
327+
}
328+
329+
public function sessionValue(string $key, mixed $value): self
330+
{
331+
$this->sessionValues[$key] = $value;
332+
333+
return $this;
334+
}
320335
}

src/Request/RequestTrait.php

Lines changed: 48 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@
66

77
use PHPUnit\Framework\TestCase;
88
use Symfony\Component\BrowserKit\AbstractBrowser;
9-
use Symfony\Component\BrowserKit\Cookie;
9+
use Symfony\Component\HttpFoundation\Cookie;
1010
use Symfony\Component\HttpFoundation\Response;
11-
use Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage;
11+
use Symfony\Component\HttpFoundation\Session\SessionInterface;
1212

13+
use function assert;
1314
use function method_exists;
1415
use function Safe\sprintf;
1516

@@ -52,42 +53,14 @@ protected static function getRequestClient(): AbstractBrowser
5253
));
5354
}
5455

55-
final public function generateCsrfToken(string $tokenId): string
56+
final public function generateCsrfToken(): string
5657
{
5758
$client = self::getRequestClient();
5859

59-
$cookie = $client->getCookieJar()->get('MOCKSESSID');
60-
61-
// create a new session object
62-
$container = $client->getContainer();
63-
$session = $container->get('session.factory')->createSession();
64-
65-
if ($cookie) {
66-
// get the session id from the session cookie if it exists
67-
$session->setId($cookie->getValue());
68-
$session->start();
69-
} else {
70-
// or create a new session id and a session cookie
71-
$session->start();
72-
$session->save();
73-
74-
$sessionCookie = new Cookie(
75-
$session->getName(),
76-
$session->getId(),
77-
null,
78-
null,
79-
'localhost',
80-
);
81-
$client->getCookieJar()->set($sessionCookie);
82-
}
83-
8460
$container = $client->getContainer();
8561
$tokenGenerator = $container->get('security.csrf.token_generator');
86-
$csrfToken = $tokenGenerator->generateToken();
87-
$session->set(SessionTokenStorage::SESSION_NAMESPACE . '/' . $tokenId, $csrfToken);
88-
$session->save();
8962

90-
return $csrfToken;
63+
return $tokenGenerator->generateToken();
9164
}
9265

9366
final protected function build(string $method, string $uri): RequestBuilder
@@ -113,6 +86,10 @@ final protected function request(RequestBuilder $requestBuilder): Response
11386
{
11487
$client = self::getRequestClient();
11588

89+
if ($requestBuilder->getSessionValues()) {
90+
$this->applySessionValues($requestBuilder->getSessionValues());
91+
}
92+
11693
$client->request(
11794
$requestBuilder->getMethod(),
11895
$requestBuilder->getUri(),
@@ -125,4 +102,43 @@ final protected function request(RequestBuilder $requestBuilder): Response
125102

126103
return $client->getResponse();
127104
}
105+
106+
/** @param array<string, mixed> $sessionValues */
107+
private function applySessionValues(array $sessionValues): void
108+
{
109+
$client = self::getRequestClient();
110+
assert($client instanceof AbstractBrowser);
111+
112+
$cookie = $client->getCookieJar()->get('MOCKSESSID');
113+
114+
// create a new session object
115+
$container = $client->getContainer();
116+
$session = $container->get('session.factory')->createSession();
117+
assert($session instanceof SessionInterface);
118+
119+
if ($cookie) {
120+
// get the session id from the session cookie if it exists
121+
$session->setId($cookie->getValue());
122+
$session->start();
123+
} else {
124+
// or create a new session id and a session cookie
125+
$session->start();
126+
$session->save();
127+
128+
$sessionCookie = new Cookie(
129+
$session->getName(),
130+
$session->getId(),
131+
null,
132+
null,
133+
'localhost',
134+
);
135+
$client->getCookieJar()->set($sessionCookie);
136+
}
137+
138+
foreach ($sessionValues as $key => $value) {
139+
$session->set($key, $value);
140+
}
141+
142+
$session->save();
143+
}
128144
}

tests/Request/RequestBuilderTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,29 @@ public function testChangeHistoryIsReturned(): void
356356
$this->assertTrue($builder->getChangeHistory());
357357
}
358358

359+
public function testSessionValuesAreStored(): void
360+
{
361+
$builder = $this->createRequestBuilder('GET', '/users')
362+
->sessionValue('username', 'tester')
363+
->sessionValue('amount', 123)
364+
->sessionValue('price', 999.9)
365+
->sessionValue('complex', [1, 'abc', 3.5, [1, 2, 3], ['a', 'b', 'c']]);
366+
367+
$this->assertSame([
368+
'username' => 'tester',
369+
'amount' => 123,
370+
'price' => 999.9,
371+
'complex' => [1, 'abc', 3.5, [1, 2, 3], ['a', 'b', 'c']],
372+
], $builder->getSessionValues());
373+
}
374+
375+
public function testSessionValuesAreReturned(): void
376+
{
377+
$builder = $this->createRequestBuilder('GET', '/users');
378+
379+
$this->assertSame([], $builder->getSessionValues());
380+
}
381+
359382
private function createRequestBuilder(string $method = 'GET', string $uri = '/foo'): RequestBuilder
360383
{
361384
return RequestBuilder::create(

0 commit comments

Comments
 (0)