Send request and return response.

Protected for phpUnit mocking.

@param string $url    URL
@param array  $params `GET` or `POST` parameters.
@param string $method `GET` or `POST` method.

@return string
517613
protected function sendRequest($url, array $params, $method)
    {
        $method = strtolower($method);
        $options = [
            CURLOPT_RETURNTRANSFER => true,
        ];

        if (self::REQUEST_METHOD_GET === $method) {
            $url .= '?' . http_build_query($params);
        } else {
            $options[CURLOPT_POST] = true;
            $options[CURLOPT_POSTFIELDS] = http_build_query($params);
        }

        $ch = curl_init($url);
        curl_setopt_array($ch, $options);
        $response = curl_exec($ch);

        if (!$response) {
            throw new \RuntimeException('cURL: ' . curl_error($ch), curl_errno($ch));
        }
        curl_close($ch);

        return $response;
    }
375417
public function sendRequest($url, $params, $method)
    {
        try{
            if (!empty($params['html'])){
                $commandName = 'GenerateFromHTML';
            }
            else if (!empty($params['url'])){
                $commandName = 'GenerateFromURL';
            }
            else if (!empty($params['file'])&& $url=='pdf'){
                $commandName = 'GenerateFromFile';
            }
            else {
                $operations = $this->getDescription()->getOperations();
                foreach ($operations as $operation)
                {
                    if ($operation->getUri()==$url && $operation->getHttpMethod() == $method)
                    {
                        $commandName = $operation->getName();
                    }
                }
            }
            $command = $this->getCommand($commandName, $params);
            $ret = $this->execute($command);

            if ( $commandName == 'GetAssetList' || $commandName == 'UploadAsset' )
            {
                return json_encode($ret);
            }
            return $ret->getBody(true);

        }catch(ClientErrorResponseException $exception){
            throw new \Exception($exception->getResponse()->getBody(true), $exception->getResponse()->getStatusCode());
        }
    }
1030587
protected static function quickRequest(string $url, string $method, array $params = null, array $headers = null): Response
    {
        /** @var Request $self */
        $self = new static();
        $self->setUrl($url)->setMethod($method);

        if ($params != null) {
            $self->setParams($params);
        }

        if ($headers != null) {
            $self->setHeaders($headers);
        }

        $self->setOption(CURLOPT_FOLLOWLOCATION, true);
        $self->setOption(CURLOPT_MAXREDIRS, 10);

        return $self->exec();
    }
1331121
public function post($url, $params = null) {
    $this->params = $params;
    $this->method = 'POST';
    $this->url = $url;

    return $this->request();
  }
1354016
public static function request($url, $method = 'GET', array $parameter = [], array $option = [])
    {
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_HEADER => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_AUTOREFERER => true,
            CURLOPT_FOLLOWLOCATION => true,
        ]);

        if (isset($option[CURLOPT_CONNECTTIMEOUT])) {
            curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $option[CURLOPT_CONNECTTIMEOUT]);
        }

        if (isset($option[CURLOPT_TIMEOUT])) {
            curl_setopt($curl, CURLOPT_TIMEOUT, $option[CURLOPT_TIMEOUT]);
        }

        $query = empty($parameter) ? '' : http_build_query($parameter, '', '&');

        switch ($method) {
            case 'GET':
                if ($query) {
                    $url .= '?' . $query;
                }

                curl_setopt($curl, CURLOPT_HTTPGET, true);

                break;
            case 'POST':
                if ($query) {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $query);
                }

                if (isset($option[CURLOPT_HTTPHEADER]) && is_array($option[CURLOPT_HTTPHEADER])) {
                    $option[CURLOPT_HTTPHEADER] = array_merge($option[CURLOPT_HTTPHEADER], [
                        'content-type: application/x-www-form-urlencoded',
                    ]);
                } else {
                    $option[CURLOPT_HTTPHEADER] = [
                        'content-type: application/x-www-form-urlencoded',
                    ];
                }

                curl_setopt($curl, CURLOPT_POST, true);

                break;
            default:
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);

                break;
        }

        if (!empty($option)) {
            curl_setopt_array($curl, $option);
        }

        curl_setopt($curl, CURLOPT_URL, $url);

        $body = curl_exec($curl);

        if (false === $body) {
            $error = curl_error($curl);
            $code = curl_errno($curl);

            curl_close($curl);
        }

        $header = (object) curl_getinfo($curl);

        curl_close($curl);

        if (mb_strpos($header->content_type, 'application/json') !== false) {
            $body = mb_substr($body, $header->header_size);
            $body = json_decode($body);
        }

        return (object) [
            'header' => $header,
            'body' => $body,
        ];
    }
1119603
public function request($method, $url, $params = array(), $xml = "", $format = "")
	{
		if ( !$format) $format = $this->format;

		$response = $this->api->request($method, $url, $params, $xml, $format);
		return $this->parseResponse($response);
	}
260865
public function request(string $method, ...$params) : ResponseInterface
    {
        try {
            $response = $this->client
                ->post($this->path, $this->makeJson($method, $params));

            if ($response->hasError()) {
                // throw exception on error
                throw new BadRemoteCallException($response);
            }

            return $response;
        } catch (Throwable $exception) {
            throw exception()->handle($exception);
        }
    }
693365
protected function sendRequest($method, $url, array $params = [], array $headers = [])
    {
        $response = $request = $this->getHttpClient()->createRequest()
            ->setUrl($url)
            ->setMethod($method)
            ->setHeaders($headers)
            ->setData($params)
            ->send();
        if (!$response->isOk && $this->debug) {
            throw new Exception ('Http request failed.');
        }
        return $response;
    }
884780
public function send($method, $url)
    {
        $this->request = $this->requestFactory->createRequest($method, $this->prepareUrl($url), $this->headers);

        $this->sendRequest();
    }
12976
private function _request($method, $url, array $options) {
		try {
			$response = $this->httpClient->{$method}($url, $options);
		} catch(ClientException $e) {
			$response = $e->getResponse();
		} catch(ConnectException $e) {
			$this->_throwServerError($e);
		} catch (RequestException $e) {
			$this->_throwServerError($e);
		}

		return $response;
	}
236431
public function makeRequest($url, $params)
    {
        $http = new HttpClient('https://api.github.com');
        $res = $http->get($url, $params);

        return $res['body'];
    }
404944
public function request($url, $method = 'GET', $options = []): ResponseInterface
    {
        $method = strtoupper($method);

        $options = array_merge(self::$defaults, $options, ['handler' => $this->getHandlerStack()]);

        $options = $this->fixJsonIssue($options);

        if (property_exists($this, 'baseUri') && !is_null($this->baseUri)) {
            $options['base_uri'] = $this->baseUri;
        }

        $response = $this->getHttpClient()->request($method, $url, $options);
        $response->getBody()->rewind();

        return $response;
    }
133843
protected function query($method, $url, array $parameters = null)
    {
        return $this->httpClient->query($method, $url, $parameters);
    }
105960
public static function fromRequest(
		$method = null,
		$url = null,
		array $params = null
	) {
		$scheme = ( !isset( $_SERVER['HTTPS'] ) || $_SERVER['HTTPS'] != 'on' ) ?
			'http' : 'https';
		$url = ( $url ?: $scheme ) .
			'://' . $_SERVER['SERVER_NAME'] .
			':' .
			$_SERVER['SERVER_PORT'] .
			$_SERVER['REQUEST_URI'];
		$method = $method ?: $_SERVER['REQUEST_METHOD'];

		// We weren't handed any params, so let's find the ones relevant
		// to this request. If you run XML-RPC or similar you should use this
		// to provide your own parsed parameter-list
		if ( !$params ) {
			// Find request headers
			$headers = Util::getHeaders();

			// Parse the query-string to find GET params
			$params = Util::parseParameters( $_SERVER['QUERY_STRING'] );

			// It's a POST request of the proper content-type, so parse POST
			// params and add those overriding any duplicates from GET
			if ( $method === 'POST' &&
				isset( $headers['Content-Type'] ) &&
				strstr( $headers['Content-Type'],
					'application/x-www-form-urlencoded'
				)
			) {
				$post_data = Util::parseParameters(
					file_get_contents( self::$POST_INPUT )
				);
				$params = array_merge( $params, $post_data );
			}

			// We have a Authorization-header with OAuth data. Parse the header
			// and add those overriding any duplicates from GET or POST
			if ( isset( $headers['Authorization'] ) &&
				substr( $headers['Authorization'], 0, 6 ) === 'OAuth '
			) {
				$header_params = Util::splitHeader( $headers['Authorization'] );
				$params = array_merge( $params, $header_params );
			}
		}

		return new Request( $method, $url, $params );
	}
1010379
protected function request($url, $method, $data = null)
    {
        $this->testLogin();
        try {
            $response = $this->transport->send(
                $url, $method, $data, array(
                'Content-Type: ' . $this->mapper->getContentType(),
                )
            );
        } catch (HttpStatusException $e) {
            $message = $e->getMessage();
            if ($e->getCode() == 403 || $e->getCode() == 422) {
                $this->errors = $this->mapper->mapFromStorage($this->transport->getLastResponse());
                if ($this->errors instanceof ErrorArray && count($this->errors) > 0) {
                    $message .= PHP_EOL . 'Errors:' . PHP_EOL . $this->errors;
                }
            }

            if (self::$debug) {
                printf(
                    'Url: %s' . PHP_EOL . 'Method: %s' . PHP_EOL . 'Data: %s', $url, $method, $data
                );
            }

            switch ($e->getCode()) {
                case 401:
                    throw new NotLoggedInException($message, 0, $e);
                    break;
                case 403:
                    throw new ForbiddenException($message, 0, $e);
                    break;
                case 404:
                    throw new NotFoundException($message, 0, $e);
                    break;
                case 406:
                case 422:
                    throw new NotValidException($message, 0, $e);
                    break;
                default:
                    $message = 'Unknown error; check https://github.com/bluetools/moneybird_php_api/wiki/Common-errors';
                // no break
                case 500:
                case 501:
                    throw new ServerErrorException($message, 0, $e);
                    break;
            }
        }

        return $response;
    }
384926
public function _fetch ($url, $method, $params) {
		if (! extension_loaded ('curl')) {
			$this->error = 'cURL extension not loaded.';
			return false;
		}

		$ch = curl_init ();
		curl_setopt ($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_MAXREDIRS, 3);
		curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($ch, CURLOPT_VERBOSE, 0);
		curl_setopt ($ch, CURLOPT_HEADER, 1);
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 10);
		curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);

		/* HTTP Basic Authentication */
		if ($this->user && $this->password) {
			curl_setopt ($ch, CURLOPT_USERPWD, $this->user . ":" . $this->password);	
		}

		if ($this->request_format == 'xml') {
			$this->request_headers = array_merge ($this->request_headers, array ("Expect:", "Content-Type: text/xml", "Length: " . strlen ($params)));
		}
		switch ($method) {
			case 'POST':
				curl_setopt ($ch, CURLOPT_POST, 1);
				curl_setopt ($ch, CURLOPT_POSTFIELDS, $params);
				break;
			case 'DELETE':
				curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
				break;
			case 'PUT':
				curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
				curl_setopt ($ch, CURLOPT_POSTFIELDS, $params);
				break;
			case 'GET':
			default:
				break;
		}

		if (count ($this->request_headers)) {
			curl_setopt ($ch, CURLOPT_HTTPHEADER, $this->request_headers);
		}

		$res = curl_exec ($ch);

		$http_code = curl_getinfo ($ch, CURLINFO_HTTP_CODE);

		// Check HTTP status code for denied access
		if ($http_code == 401) {
			$this->errno = $http_code;
			$this->error = "HTTP Basic: Access denied.";
			curl_close ($ch);
			return false;
		}

		// Check HTTP status code for rate limit
		if ($http_code == 429) {
			if (preg_match ('/Retry-After: ([0-9]+)/', $res, $retry_after)) {
			  sleep(intval($retry_after[1]));
			  return $this->_fetch ($url, $method, $params);
			}
			$this->errno = $http_code;
			$this->error = "Too Many Requests";
			curl_close ($ch);
			return false;
		}

		if (! $res) {
			$this->errno = curl_errno ($ch);
			$this->error = curl_error ($ch);
			curl_close ($ch);
			return false;
		}

		curl_close ($ch);
		return $res;
	}
486403
protected function request($parameters, $method = 'GET')
    {
        $formParams = $this->getFormParams($parameters);

        if (!isset($formParams['api_key'])) {
            return null;
        }

        if ($method === 'POST') {
            // split params
            $response = $this->httpClient->request($method, Api::PATH_TO_API_SCRIPT, array(
                'query' => $this->getQueryParams($parameters),
                'form_params' => $formParams
            ));
        } else {
            // all params as query GET params
            $response = $this->httpClient->request($method, Api::PATH_TO_API_SCRIPT, array(
                'query' => array_merge($this->getQueryParams($parameters), $formParams),
            ));
        }

        return $response;
    }