Example #1
0
 public static function connect(string $dsn, string $username, string $password, LoggerInterface $logger = NULL) : \Generator
 {
     if ('mysql:' !== substr($dsn, 0, 6)) {
         throw new \InvalidArgumentException(sprintf('Invalid MySQL DSN: "%s"', $dsn));
     }
     $settings = [];
     foreach (explode(';', substr($dsn, 6)) as $part) {
         list($k, $v) = array_map('trim', explode('=', $part));
         switch ($k) {
             case 'host':
             case 'dbname':
             case 'unix_socket':
                 $settings[$k] = $v;
                 break;
             case 'port':
                 $settings[$k] = (int) $v;
                 break;
             default:
                 throw new \InvalidArgumentException(sprintf('Unknown MySQL DSN param: "%s"', $k));
         }
     }
     if (empty($settings['host']) && empty($settings['unix_socket'])) {
         throw new \InvalidArgumentException('Neighter MySQL host nor Unix domain socket specified in MySQL DSN');
     }
     if (!empty($settings['unix_socket'])) {
         if (!Socket::isUnixSocketSupported()) {
             throw new \RuntimeException(sprintf('Cannot connect to MySQL socket "%s", PHP was not compiled with support for Unix domain sockets', $settings['unix_socket']));
         }
         $client = new Client(yield from SocketStream::fromUrl('unix://' . $settings['unix_socket']), $logger);
     } else {
         $client = new Client(yield from SocketStream::connect($settings['host'], $settings['port'] ?? 3306), $logger);
     }
     yield from $client->handleHandshake($username, $password);
     $conn = new static($client, (yield currentExecutor()), $logger);
     if (!empty($settings['dbname'])) {
         yield from $conn->changeDefaultSchema($settings['dbname']);
     }
     return $conn;
 }