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
29 changes: 9 additions & 20 deletions src/Io/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,34 +165,23 @@ public function createConnection(
#[\SensitiveParameter]
$uri
) {
if (strpos($uri, '://') === false) {
$uri = 'mysql://' . $uri;
}

$parts = parse_url($uri);
$uri = preg_replace('#:[^:/]*@#', ':***@', $uri);
if (!isset($parts['scheme'], $parts['host']) || $parts['scheme'] !== 'mysql') {
return \React\Promise\reject(new \InvalidArgumentException(
'Invalid MySQL URI given (EINVAL)',
\defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : 22
));
}
assert(is_array($parts) && isset($parts['scheme'], $parts['host']));
assert($parts['scheme'] === 'mysql');

$args = [];
if (isset($parts['query'])) {
parse_str($parts['query'], $args);
}

try {
$authCommand = new AuthenticateCommand(
isset($parts['user']) ? rawurldecode($parts['user']) : 'root',
isset($parts['pass']) ? rawurldecode($parts['pass']) : '',
isset($parts['path']) ? rawurldecode(ltrim($parts['path'], '/')) : '',
isset($args['charset']) ? $args['charset'] : 'utf8mb4'
);
} catch (\InvalidArgumentException $e) {
return \React\Promise\reject($e);
}
/** @throws void already validated in MysqlClient ctor */
$authCommand = new AuthenticateCommand(
isset($parts['user']) ? rawurldecode($parts['user']) : 'root',
isset($parts['pass']) ? rawurldecode($parts['pass']) : '',
isset($parts['path']) ? rawurldecode(ltrim($parts['path'], '/')) : '',
isset($args['charset']) ? $args['charset'] : 'utf8mb4'
);

$connecting = $this->connector->connect(
$parts['host'] . ':' . (isset($parts['port']) ? $parts['port'] : 3306)
Expand Down
25 changes: 25 additions & 0 deletions src/MysqlClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Evenement\EventEmitter;
use React\EventLoop\LoopInterface;
use React\Mysql\Commands\AuthenticateCommand;
use React\Mysql\Io\Connection;
use React\Mysql\Io\Factory;
use React\Promise\Deferred;
Expand Down Expand Up @@ -80,13 +81,37 @@ class MysqlClient extends EventEmitter
* @param string $uri
* @param ?ConnectorInterface $connector
* @param ?LoopInterface $loop
* @throws \InvalidArgumentException if $uri is not a valid MySQL URI
*/
public function __construct(
#[\SensitiveParameter]
$uri,
$connector = null,
$loop = null
) {
if (strpos($uri, '://') === false) {
$uri = 'mysql://' . $uri;
}

$parts = parse_url($uri);
if ($parts === false || !isset($parts['scheme'], $parts['host']) || $parts['scheme'] !== 'mysql') {
$uri = preg_replace('#:[^:/]*@#', ':***@', $uri);
throw new \InvalidArgumentException(
'Invalid MySQL URI "' . $uri . '" (EINVAL)',
defined('SOCKET_EINVAL') ? SOCKET_EINVAL : 22
);
}

if (isset($parts['query'])) {
$query = [];
parse_str($parts['query'], $query);

// validate charset if given
if (isset($query['charset'])) {
new AuthenticateCommand('', '', '', $query['charset']);
}
}

if ($connector !== null && !$connector instanceof ConnectorInterface) { // manual type check to support legacy PHP < 7.1
throw new \InvalidArgumentException('Argument #2 ($connector) expected null|React\Socket\ConnectorInterface');
}
Expand Down
2 changes: 1 addition & 1 deletion tests/BaseTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ protected function getConnectionString($params = [])
{
$parts = $params + $this->getConnectionOptions();

return rawurlencode($parts['user']) . ':' . rawurlencode($parts['passwd']) . '@' . $parts['host'] . ':' . $parts['port'] . '/' . rawurlencode($parts['dbname']);
return 'mysql://' . rawurlencode($parts['user']) . ':' . rawurlencode($parts['passwd']) . '@' . $parts['host'] . ':' . $parts['port'] . '/' . rawurlencode($parts['dbname']);
}

/**
Expand Down
79 changes: 9 additions & 70 deletions tests/Io/FactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function testConnectWillUseHostAndDefaultPort()
$connector->expects($this->once())->method('connect')->with('127.0.0.1:3306')->willReturn($pending);

$factory = new Factory($loop, $connector);
$factory->createConnection('127.0.0.1');
$factory->createConnection('mysql://127.0.0.1');
}

public function testConnectWillUseGivenScheme()
Expand All @@ -44,28 +44,6 @@ public function testConnectWillUseGivenScheme()
$factory->createConnection('mysql://127.0.0.1');
}

public function testConnectWillRejectWhenGivenInvalidScheme()
{
$loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
$connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock();

$factory = new Factory($loop, $connector);

$promise = $factory->createConnection('foo://127.0.0.1');

$promise->then(null, $this->expectCallableOnceWith(
$this->logicalAnd(
$this->isInstanceOf('InvalidArgumentException'),
$this->callback(function (\InvalidArgumentException $e) {
return $e->getMessage() === 'Invalid MySQL URI given (EINVAL)';
}),
$this->callback(function (\InvalidArgumentException $e) {
return $e->getCode() === (defined('SOCKET_EINVAL') ? SOCKET_EINVAL : 22);
})
)
));
}

public function testConnectWillUseGivenHostAndGivenPort()
{
$loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
Expand All @@ -74,7 +52,7 @@ public function testConnectWillUseGivenHostAndGivenPort()
$connector->expects($this->once())->method('connect')->with('127.0.0.1:1234')->willReturn($pending);

$factory = new Factory($loop, $connector);
$factory->createConnection('127.0.0.1:1234');
$factory->createConnection('mysql://127.0.0.1:1234');
}

public function testConnectWillUseGivenUserInfoAsDatabaseCredentialsAfterUrldecoding()
Expand All @@ -87,7 +65,7 @@ public function testConnectWillUseGivenUserInfoAsDatabaseCredentialsAfterUrldeco
$connector->expects($this->once())->method('connect')->with('127.0.0.1:3306')->willReturn(\React\Promise\resolve($connection));

$factory = new Factory($loop, $connector);
$promise = $factory->createConnection('user%[email protected]');
$promise = $factory->createConnection('mysql://user%[email protected]');

$promise->then($this->expectCallableNever(), $this->expectCallableNever());

Expand All @@ -104,48 +82,13 @@ public function testConnectWillUseGivenPathAsDatabaseNameAfterUrldecoding()
$connector->expects($this->once())->method('connect')->with('127.0.0.1:3306')->willReturn(\React\Promise\resolve($connection));

$factory = new Factory($loop, $connector);
$promise = $factory->createConnection('127.0.0.1/test%20database');
$promise = $factory->createConnection('mysql://127.0.0.1/test%20database');

$promise->then($this->expectCallableNever(), $this->expectCallableNever());

$connection->emit('data', ["\x33\0\0\0" . "\x0a" . "mysql\0" . str_repeat("\0", 44)]);
}

public function testConnectWithInvalidUriWillRejectWithoutConnecting()
{
$loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
$connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock();
$connector->expects($this->never())->method('connect');

$factory = new Factory($loop, $connector);
$promise = $factory->createConnection('///');

$promise->then(null, $this->expectCallableOnceWith(
$this->logicalAnd(
$this->isInstanceOf('InvalidArgumentException'),
$this->callback(function (\InvalidArgumentException $e) {
return $e->getMessage() === 'Invalid MySQL URI given (EINVAL)';
}),
$this->callback(function (\InvalidArgumentException $e) {
return $e->getCode() === (defined('SOCKET_EINVAL') ? SOCKET_EINVAL : 22);
})
)
));
}

public function testConnectWithInvalidCharsetWillRejectWithoutConnecting()
{
$loop = $this->getMockBuilder('React\EventLoop\LoopInterface')->getMock();
$connector = $this->getMockBuilder('React\Socket\ConnectorInterface')->getMock();
$connector->expects($this->never())->method('connect');

$factory = new Factory($loop, $connector);
$promise = $factory->createConnection('localhost?charset=unknown');

$this->assertInstanceof('React\Promise\PromiseInterface', $promise);
$promise->then(null, $this->expectCallableOnce());
}

public function testConnectWithInvalidHostRejectsWithConnectionError()
{
$factory = new Factory();
Expand Down Expand Up @@ -204,7 +147,7 @@ public function testConnectWillRejectWhenServerClosesConnection()
$this->logicalAnd(
$this->isInstanceOf('RuntimeException'),
$this->callback(function (\RuntimeException $e) use ($uri) {
return $e->getMessage() === 'Connection to mysql://' . $uri . ' failed during authentication: Connection closed by peer (ECONNRESET)';
return $e->getMessage() === 'Connection to ' . $uri . ' failed during authentication: Connection closed by peer (ECONNRESET)';
}),
$this->callback(function (\RuntimeException $e) {
return $e->getCode() === (defined('SOCKET_ECONNRESET') ? SOCKET_ECONNRESET : 104);
Expand Down Expand Up @@ -244,7 +187,7 @@ public function testConnectWillRejectOnDefaultTimeoutFromIniDespiteValidAuth()
{
$factory = new Factory();

$uri = 'mysql://' . $this->getConnectionString();
$uri = $this->getConnectionString();

$old = ini_get('default_socket_timeout');
ini_set('default_socket_timeout', '0');
Expand Down Expand Up @@ -439,7 +382,7 @@ public function testlConnectWillRejectWhenUnderlyingConnectorRejects()
$connector->expects($this->once())->method('connect')->willReturn(\React\Promise\reject(new \RuntimeException('Failed', 123)));

$factory = new Factory($loop, $connector);
$promise = $factory->createConnection('user:[email protected]');
$promise = $factory->createConnection('mysql://user:[email protected]');

$promise->then(null, $this->expectCallableOnceWith(
$this->logicalAnd(
Expand All @@ -457,10 +400,6 @@ public function testlConnectWillRejectWhenUnderlyingConnectorRejects()
public function provideUris()
{
return [
[
'localhost',
'mysql://localhost'
],
[
'mysql://localhost',
'mysql://localhost'
Expand Down Expand Up @@ -520,7 +459,7 @@ public function testCancelConnectWillCancelPendingConnectionWithRuntimeException
$connector->expects($this->once())->method('connect')->willReturn($pending);

$factory = new Factory($loop, $connector);
$promise = $factory->createConnection('127.0.0.1');
$promise = $factory->createConnection('mysql://127.0.0.1');

$promise->cancel();

Expand All @@ -547,7 +486,7 @@ public function testCancelConnectDuringAuthenticationWillCloseConnection()
$connector->expects($this->once())->method('connect')->willReturn(\React\Promise\resolve($connection));

$factory = new Factory($loop, $connector);
$promise = $factory->createConnection('127.0.0.1');
$promise = $factory->createConnection('mysql://127.0.0.1');

$promise->cancel();

Expand Down
Loading