Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions src/GlobalServerContext.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace BEAR\QueryRepository;

use Override;

use function is_string;

/**
* Server context implementation using $_SERVER superglobal
*
* This is the default implementation for traditional PHP-FPM environments
* where each request runs in isolation and $_SERVER is safe to use.
*
* For concurrent request processing (Swoole, RoadRunner), use a request-scoped
* implementation instead.
*/
final class GlobalServerContext implements ServerContextInterface
{
#[Override]
public function get(string $key): string|null
{
if (! isset($_SERVER[$key])) {
return null;
}

/** @var mixed $value */
$value = $_SERVER[$key];

return is_string($value) ? $value : null;
}

#[Override]
public function has(string $key): bool
{
return isset($_SERVER[$key]);
}
}
2 changes: 2 additions & 0 deletions src/QueryRepositoryModule.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ protected function configure(): void
$this->bind(RefreshAnnotatedCommand::class);
$this->bind(RefreshSameCommand::class);
$this->bind(ResourceStorageSaver::class);
// Server context for thread safety (Swoole, RoadRunner, etc.)
$this->bind(ServerContextInterface::class)->to(GlobalServerContext::class)->in(Scope::SINGLETON);
// #[Cacheable]
$this->install(new CacheableModule());
// #[CacheableResponse]
Expand Down
9 changes: 9 additions & 0 deletions src/RepositoryLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ public function log(string $operation, array $context = []): void
$this->logs[] = ['op' => $operation, ...$context];
}

/**
* {@inheritDoc}
*/
#[Override]
public function reset(): void
{
$this->logs = [];
}

#[Override]
public function __toString(): string
{
Expand Down
9 changes: 9 additions & 0 deletions src/RepositoryLoggerInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,14 @@ interface RepositoryLoggerInterface
/** @param array<string, mixed> $context */
public function log(string $operation, array $context = []): void;

/**
* Reset the logger state
*
* This method clears all accumulated logs. It should be called at the end of
* each request in long-running environments (Swoole, RoadRunner) to prevent
* log accumulation across requests.
*/
public function reset(): void;

public function __toString(): string;
}
27 changes: 19 additions & 8 deletions src/ResourceStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
use function explode;
use function implode;
use function is_array;
use function is_string;
use function sprintf;
use function strtoupper;
use function trim;

/**
* @psalm-type Props = array{
Expand All @@ -32,7 +32,8 @@
* uriTag: UriTag,
* saver: ResourceStorageSaver,
* roProvider:ProviderInterface<TagAwareAdapterInterface>,
* etagProvider: ProviderInterface<TagAwareAdapterInterface>
* etagProvider: ProviderInterface<TagAwareAdapterInterface>,
* serverContext: ServerContextInterface
* }
*/
final class ResourceStorage implements ResourceStorageInterface
Expand Down Expand Up @@ -64,6 +65,7 @@ public function __construct(
private PurgerInterface $purger,
private UriTagInterface $uriTag,
private ResourceStorageSaver $saver,
private ServerContextInterface $serverContext,
#[Set(TagAwareAdapterInterface::class, ResourceObjectPool::class)]
ProviderInterface $roPoolProvider,
#[Set(TagAwareAdapterInterface::class, EtagPool::class)]
Expand Down Expand Up @@ -239,19 +241,26 @@ private function evaluateBody(mixed $body): mixed

private function getUriKey(AbstractUri $uri, string $type): string
{
return $type . ($this->uriTag)($uri) . (isset($_SERVER['X_VARY']) ? $this->getVary() : '');
return $type . ($this->uriTag)($uri) . ($this->serverContext->has('X_VARY') ? $this->getVary() : '');
}

private function getVary(): string
{
$xvary = $_SERVER['X_VARY'];
/** @psalm-suppress RedundantCast */
$varys = explode(',', (string) $xvary); // @phpstan-ignore-line
$xvary = $this->serverContext->get('X_VARY');
assert($xvary !== null, 'getVary() is only called when X_VARY exists');

$varys = explode(',', $xvary);
$varyString = '';
foreach ($varys as $vary) {
$vary = trim($vary);
if ($vary === '') {
continue;
}

$phpVaryKey = sprintf('X_%s', strtoupper($vary));
if (isset($_SERVER[$phpVaryKey]) && is_string($_SERVER[$phpVaryKey])) {
$varyString .= $_SERVER[$phpVaryKey];
$value = $this->serverContext->get($phpVaryKey);
if ($value !== null) {
$varyString .= $value;
}
}

Expand Down Expand Up @@ -279,6 +288,7 @@ public function __serialize(): array
'saver' => $this->saver,
'roProvider' => $this->roPoolProvider,
'etagProvider' => $this->etagPoolProvider,
'serverContext' => $this->serverContext,
];
}

Expand All @@ -293,6 +303,7 @@ public function __unserialize(array $data): void
$this->purger = $data['purger'];
$this->uriTag = $data['uriTag'];
$this->saver = $data['saver'];
$this->serverContext = $data['serverContext'];
$this->initializePools($data['roProvider'], $data['etagProvider']);
}
}
33 changes: 33 additions & 0 deletions src/ServerContextInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace BEAR\QueryRepository;

/**
* Provides access to server context in a thread-safe manner
*
* This interface abstracts access to request context (like $_SERVER) to support
* concurrent request processing in environments like Swoole, RoadRunner, and ReactPHP.
*
* For traditional PHP-FPM: Use GlobalServerContext (default)
* For Swoole/RoadRunner: Implement with request-scoped context
*/
interface ServerContextInterface
{
/**
* Get a value from the server context
*
* @param string $key The key to retrieve (e.g., 'HTTP_USER_AGENT', 'X_VARY')
*
* @return string|null The value or null if not set
*/
public function get(string $key): string|null;

/**
* Check if a key exists in the server context
*
* @param string $key The key to check
*/
public function has(string $key): bool;
}
11 changes: 11 additions & 0 deletions tests/GetInterceptorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,15 @@ public function testHttpCacheVary(): void

unset($_SERVER['X_VARY'], $_SERVER['X_VAL1'], $_SERVER['X_VAL2']);
}

public function testHttpCacheVaryWithEmptySegment(): void
{
$_SERVER['X_VARY'] = 'val1, , val2';
$_SERVER['X_VAL1'] = '1';
$_SERVER['X_VAL2'] = '2';
$ro = $this->resource->get('app://self/etag');
$this->assertArrayNotHasKey('Age', $ro->headers);

unset($_SERVER['X_VARY'], $_SERVER['X_VAL1'], $_SERVER['X_VAL2']);
}
}
91 changes: 91 additions & 0 deletions tests/GlobalServerContextTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<?php

declare(strict_types=1);

namespace BEAR\QueryRepository;

use PHPUnit\Framework\TestCase;

use function array_key_exists;

class GlobalServerContextTest extends TestCase
{
private GlobalServerContext $context;

/** @var array<string, mixed> */
private array $originalServer = [];

protected function setUp(): void
{
parent::setUp();

// Save original values for keys we'll modify
foreach (['TEST_KEY', 'TEST_STRING', 'TEST_INT', 'HTTP_USER_AGENT', 'X_VARY'] as $key) {
if (array_key_exists($key, $_SERVER)) {
$this->originalServer[$key] = $_SERVER[$key];
}
}

$this->context = new GlobalServerContext();
}

protected function tearDown(): void
{
// Restore original values or unset if they didn't exist
foreach (['TEST_KEY', 'TEST_STRING', 'TEST_INT', 'HTTP_USER_AGENT', 'X_VARY'] as $key) {
if (array_key_exists($key, $this->originalServer)) {
$_SERVER[$key] = $this->originalServer[$key];
} else {
unset($_SERVER[$key]);
}
}

parent::tearDown();
}

public function testGetReturnsValue(): void
{
$_SERVER['TEST_KEY'] = 'test_value';

$this->assertSame('test_value', $this->context->get('TEST_KEY'));
}

public function testGetReturnsNullForNonExistentKey(): void
{
$this->assertNull($this->context->get('NON_EXISTENT_KEY'));
}

public function testGetReturnsNullForNonStringValue(): void
{
$_SERVER['TEST_INT'] = 123;

$this->assertNull($this->context->get('TEST_INT'));
}

public function testHasReturnsTrueForExistingKey(): void
{
$_SERVER['TEST_KEY'] = 'value';

$this->assertTrue($this->context->has('TEST_KEY'));
}

public function testHasReturnsFalseForNonExistentKey(): void
{
$this->assertFalse($this->context->has('NON_EXISTENT_KEY'));
}

public function testGetHttpUserAgent(): void
{
$userAgent = 'Mozilla/5.0 Test';
$_SERVER['HTTP_USER_AGENT'] = $userAgent;

$this->assertSame($userAgent, $this->context->get('HTTP_USER_AGENT'));
}

public function testGetXVary(): void
{
$_SERVER['X_VARY'] = 'val1,val2';

$this->assertSame('val1,val2', $this->context->get('X_VARY'));
}
}
21 changes: 21 additions & 0 deletions tests/RepositoryLoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,25 @@ public function testLogWithNullValue(): void
$logger->log('save-donut', ['uri' => 'app://self/page', 'sMaxAge' => null]);
$this->assertSame('{"op":"save-donut","uri":"app://self/page","sMaxAge":null}', (string) $logger);
}

public function testReset(): void
{
$logger = new RepositoryLogger();
$logger->log('operation1', ['id' => 1]);
$logger->log('operation2', ['id' => 2]);
$this->assertNotEmpty((string) $logger);

$logger->reset();
$this->assertSame('', (string) $logger);
}

public function testResetAllowsNewLogs(): void
{
$logger = new RepositoryLogger();
$logger->log('old-operation');
$logger->reset();
$logger->log('new-operation');

$this->assertSame('{"op":"new-operation"}', (string) $logger);
}
}
2 changes: 2 additions & 0 deletions tests/ResourceRepositoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public function get()
new NullPurger(),
new UriTag(),
new ResourceStorageSaver(),
new GlobalServerContext(),
$tagAwareAdapterProvider,
$tagAwareAdapterProvider,
),
Expand Down Expand Up @@ -106,6 +107,7 @@ public function get()
new NullPurger(),
new UriTag(),
new ResourceStorageSaver(),
new GlobalServerContext(),
$tagAwareAdapterProvider,
$tagAwareAdapterProvider,
),
Expand Down
1 change: 1 addition & 0 deletions tests/ResourceStorageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public function get()
new NullPurger(),
new UriTag(),
new ResourceStorageSaver(),
new GlobalServerContext(),
$tagAwareAdapterProvider,
$tagAwareAdapterProvider,
);
Expand Down
Loading