Skip to content

Commit

Permalink
Add redis database support
Browse files Browse the repository at this point in the history
A redis connection string can have a database number after the port, seperated by a slash.

Currently if you try and this in the redis server strings it is not passed in to the client so you can only use database 0.

This gets the path and removes the `/` and casts it to an int as all redis dbs are integers. If the path is not a valid numeric it will set it to 0 which is the current behaviour.
  • Loading branch information
Peter Gallagher committed Aug 23, 2024
1 parent 80979f1 commit 0816a7b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/Cache/RedisFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,9 @@ private function normalizeServer(string $server): array
$parsedServer = parse_url(trim($server));
if (! is_array($parsedServer)) {
throw new InvalidArgumentException(sprintf(
'Provided server "%s" is not a valid URL with format schema://[[username]:password@]host:port',
'Provided server "%s" is not a valid URL with format %s',
$server,
'schema://[[username]:password@]host:port/[database]',
));
}

Expand All @@ -73,6 +74,16 @@ private function normalizeServer(string $server): array
$parsedServer['password'] = urldecode($pass);
}

$database = $parsedServer['path'] ?? null;
unset($parsedServer['path']);

if ($database !== null) {
/**
* @todo Validate this is an integer and throw an exception if not for the next major version release
*/
$parsedServer['database'] = (int) trim($database, '/');
}

return $parsedServer;
}

Expand Down
25 changes: 25 additions & 0 deletions test/Cache/RedisFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,4 +157,29 @@ public static function provideServersWithCredentials(): iterable
'servers' => ['rediss://1.1.1.1:6379'],
], null, null, SSL::OPTIONS];
}

#[Test, DataProvider('provideServersWithDatabases')]
public function databaseConfigurationIsApplied(
array $redisConfig,
?int $expectedDatabase,
): void {
$this->container->expects($this->once())->method('get')->with('config')->willReturn([
'cache' => ['redis' => $redisConfig],
]);

$client = ($this->factory)($this->container);
$conn = $client->getConnection();

self::assertEquals($expectedDatabase, $conn->getParameters()->database); // @phpstan-ignore-line
}

public static function provideServersWithDatabases(): iterable
{
yield 'no database' => [[
'servers' => ['tcp://1.1.1.1:6379'],
], null];
yield 'database' => [[
'servers' => ['tcp://1.1.1.1:6379/5'],
], 5];
}
}

0 comments on commit 0816a7b

Please sign in to comment.