/**
  * Connects to remote server.
  *
  * @throws \InvalidArgumentException|\RuntimeException
  */
 protected function connect()
 {
     $host = $this->gitEnvironment->getHost();
     $username = $this->gitEnvironment->getUsername();
     $port = $this->gitEnvironment->getPort();
     $password = $this->gitEnvironment->getPassword();
     $privateKey = $this->gitEnvironment->getPrivateKey();
     $privateKeyPassword = $this->gitEnvironment->getPrivateKeyPassword();
     $this->sftp = new SFTP($host, 22);
     if (!$this->sftp) {
         throw new SshLoginException(sprintf('SSH connection failed on "%s:%s"', $host, $port));
     }
     if (isset($username) && $privateKey != null) {
         $key = new RSA();
         //Set Private Key Password
         if ($privateKeyPassword) {
             $key->setPassword($privateKeyPassword);
         }
         $key->loadKey($privateKey);
         //Login using private key
         if (!$this->sftp->login($username, $key)) {
             throw new SshLoginException(sprintf('SFTP authentication failed for user "%s" using private key', $username));
         }
     } else {
         if (!$this->sftp->login($username, $password)) {
             throw new SshLoginException(sprintf('SFTP authentication failed for user "%s" using password', $username));
         }
     }
 }