protected function ensureDirectoryExists($directory, $create = false)
    {
        $url = $this->sftp->getUrl($directory);

        $resource = @opendir($url);
        if (false === $resource && (!$create || !$this->createDirectory($directory))) {
            throw new \RuntimeException(sprintf('The directory \'%s\' does not exist and could not be created.', $directory));
        }

        // make sure we don't leak the resource
        if (is_resource($resource)) {
            closedir($resource);
        }
    }