Applies the array of request options to a request.
@param RequestInterface $request
@param array $options
@return RequestInterface
@throws InvalidBodySourceException
@throws InvalidBodyException
@throws InvalidQueryException
439478
private function applyOptions(RequestInterface $request, array &$options)
    {
        $modify = [];

        if (isset($options['form_params'])) {
            if (isset($options['multipart'])) {
                throw new InvalidBodySourceException();
            }
            $options['body'] = http_build_query($options['form_params'], null, '&');
            unset($options['form_params']);
            $options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded';
        }

        if (isset($options['multipart'])) {
            $elements = $options['multipart'];
            unset($options['multipart']);
            $options['body'] = new Psr7\MultipartStream($elements);
        }

        if (!empty($options['decode_content'])
            && $options['decode_content'] !== true
        ) {
            $modify['set_headers']['Accept-Encoding'] = $options['decode_content'];
        }

        if (isset($options['headers'])) {
            if (isset($modify['set_headers'])) {
                $modify['set_headers'] = $options['headers'] + $modify['set_headers'];
            } else {
                $modify['set_headers'] = $options['headers'];
            }
            unset($options['headers']);
        }

        if (isset($options['body'])) {
            if (is_array($options['body'])) {
                throw new InvalidBodyException();
            }
            $modify['body'] = Psr7\stream_for($options['body']);
            unset($options['body']);
        }

        if (!empty($options['auth'])) {
            $value = $options['auth'];
            $type = is_array($value)
                ? (isset($value[2]) ? strtolower($value[2]) : 'basic')
                : $value;
            $config['auth'] = $value;
            switch (strtolower($type)) {
                case 'basic':
                    $modify['set_headers']['Authorization'] = 'Basic '
                        . base64_encode("$value[0]:$value[1]");
                    break;
                case 'digest':
                    // @todo: Do not rely on curl
                    $options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST;
                    $options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]";
                    break;
            }
        }

        if (isset($options['query'])) {
            $value = $options['query'];
            if (is_array($value)) {
                $value = http_build_query($value, null, '&', PHP_QUERY_RFC3986);
            }
            if (!is_string($value)) {
                throw new InvalidQueryException();
            }
            $modify['query'] = $value;
            unset($options['query']);
        }

        if (isset($options['json'])) {
            $modify['body'] = Psr7\stream_for(json_encode($options['json']));
            $options['_conditional']['Content-Type'] = 'application/json';
            unset($options['json']);
        }

        $request = Psr7\modify_request($request, $modify);

        if ($request->getBody() instanceof Psr7\MultipartStream) {
            // Use a multipart/form-data POST if a Content-Type is not set.
            $options['_conditional']['Content-Type'] = 'multipart/form-data; boundary='
                . $request->getBody()->getBoundary();
        }

        // Merge in conditional headers if they are not present.
        if (isset($options['_conditional'])) {
            // Build up the changes so it's in a single clone of the message.
            $modify = [];
            foreach ($options['_conditional'] as $k => $v) {
                if (!$request->hasHeader($k)) {
                    $modify['set_headers'][$k] = $v;
                }
            }
            $request = Psr7\modify_request($request, $modify);
            // Don't pass this internal value along to middleware/handlers.
            unset($options['_conditional']);
        }

        return $request;
    }
520094
private function applyDefaultOptions(RequestableInterface $request)
    {
        // set custom password
        if ( isset($this->options['password']) )
        {
            $request->setPassword($this->options['password']);
        }
    }
1099874
protected function _sendRequest(Request $request, $options)
    {
        $responses = $this->_adapter->send($request, $options);
        $url = $request->getUri();
        foreach ($responses as $response) {
            $this->_cookies = $this->_cookies->addFromResponse($response, $request);
        }

        return array_pop($responses);
    }
11129
protected function addRequestBodyOptions(RequestInterface $request, array $options)
	{
		/*
		 * HTTP methods that cannot have payload:
		 * - GET   => cURL will automatically change method to PUT or POST if we
		 *            set CURLOPT_UPLOAD or CURLOPT_POSTFIELDS.
		 * - HEAD  => cURL treats HEAD as GET request with a same restrictions.
		 * - TRACE => According to RFC7231: a client MUST NOT send a message body
		 *            in a TRACE request.
		 */
		$http_methods = [
			'GET',
			'HEAD',
			'TRACE',
		];

		if (!in_array($request->getMethod(), $http_methods, true)) {
			$body      = $request->getBody();
			$body_size = $body->getSize();

			if ($body_size !== 0) {
				if ($body->isSeekable()) {
					$body->rewind();
				}

				if ($body_size === null || $body_size > self::$MAX_BODY_SIZE) {
					$options[CURLOPT_UPLOAD] = true;

					if ($body_size !== null) {
						$options[CURLOPT_INFILESIZE] = $body_size;
					}

					$options[CURLOPT_READFUNCTION] = function ($ch, $fd, $len) use ($body) {
						return $body->read($len);
					};
				}
				else {
					$options[CURLOPT_POSTFIELDS] = (string)$body;
				}
			}
		}

		if ($request->getMethod() === 'HEAD') {
			$options[CURLOPT_NOBODY] = true;
		}
		else if ($request->getMethod() !== 'GET') {
			$options[CURLOPT_CUSTOMREQUEST] = $request->getMethod();
		}

		return $options;
	}
106025
public function applyToRequest(RequestInterface $request)
    {
        $body = $this->streamFactory->createStream((string) $this->queryHelper);

        return $request
            ->withBody($body)
            ->withHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
1212619
protected function getUrl(ServerRequestInterface $request, array $options)
    {
        $url = $options['url'];
        if ($options['queryParam'] !== null && $request->getMethod() === 'GET') {
            $query = urlencode($options['queryParam']) . '=' . urlencode($request->getRequestTarget());
            if (strpos($url, '?') !== false) {
                $query = '&' . $query;
            } else {
                $query = '?' . $query;
            }

            $url .= $query;
        }

        return $url;
    }
1121914
protected function doRequest(RequestInterface $request)
    {
        // Create the stream context options array with the required method offset.
        $options = ['method' => $request->getMethod()];

        // Set HTTP Version
        $options['protocol_version'] = $request->getProtocolVersion();

        // If data exists let's encode it and make sure our Content-Type header is set.
        $data = (string) $request->getBody();

        if (isset($data)) {
            // If the data is a scalar value simply add it to the stream context options.
            if (is_scalar($data)) {
                $options['content'] = $data;
            } else // Otherwise we need to encode the value first.
            {
                $options['content'] = http_build_query($data);
            }

            if (!$request->getHeader('Content-Type')) {
                $request = $request->withHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
            }

            // Add the relevant headers.
            $request = $request->withHeader('Content-Length', (string) strlen($options['content']));
        }

        // Speed up stream get URL
        // @see http://stackoverflow.com/questions/3629504/php-file-get-contents-very-slow-when-using-full-url
        // @see http://stackoverflow.com/questions/13679976/how-to-speed-up-file-get-contents
        $request = $request->withHeader('Connection', 'Close');

        // Build the headers string for the request.
        if ($headers = $request->getHeaders()) {
            // Add the headers string into the stream context options array.
            $options['header'] = HeaderHelper::toHeaderLine($headers, true);
        }

        // If an explicit timeout is given user it.
        if ($this->getOption('timeout')) {
            $options['timeout'] = (int) $this->getOption('timeout');
        }

        // If an explicit user agent is given use it.
        if ($this->getOption('userAgent')) {
            $options['user_agent'] = $this->getOption('userAgent');
        }

        // Ignore HTTP errors so that we can capture them.
        $options['ignore_errors'] = 1;

        // Follow redirects.
        $options['follow_location'] = (int) $this->getOption('follow_location', 1);

        foreach ((array) $this->getOption('options') as $key => $value) {
            $options[$key] = $value;
        }

        // Create the stream context for the request.
        $context = stream_context_create(['http' => $options]);

        // Capture PHP errors
        $php_errormsg = '';
        $track_errors = ini_get('track_errors');
        ini_set('track_errors', '1');

        $connection = @fopen($request->getRequestTarget(), Stream::MODE_READ_ONLY_FROM_BEGIN, false, $context);

        if (!$connection) {
            if (!$php_errormsg) {
                // Error but nothing from php? Create our own
                $php_errormsg = sprintf('Could not connect to resource: %s', $request->getRequestTarget());
            }

            // Restore error tracking to give control to the exception handler
            ini_set('track_errors', $track_errors);

            throw new \RuntimeException($php_errormsg);
        }

        $stream = new Stream($connection);

        if ($dest = $this->getOption('target_file')) {
            $content = '';
            StreamHelper::copyTo($stream, $dest);
        } else {
            $content = $stream->getContents();
        }

        $metadata = $stream->getMetadata();

        $stream->close();

        if (isset($metadata['wrapper_data']['headers'])) {
            $headers = $metadata['wrapper_data']['headers'];
        } elseif (isset($metadata['wrapper_data'])) {
            $headers = $metadata['wrapper_data'];
        } else {
            $headers = [];
        }

        return $this->getResponse($headers, $content);
    }
711442
private function applyHandlerOptions(array $request, array &$options)
    {
        foreach ($request['client'] as $key => $value) {
            switch ($key) {
            // Violating PSR-4 to provide more room.
            case 'verify':

                if ($value === false) {
                    unset($options[CURLOPT_CAINFO]);
                    $options[CURLOPT_SSL_VERIFYHOST] = 0;
                    $options[CURLOPT_SSL_VERIFYPEER] = false;
                    continue 2;
                }

                $options[CURLOPT_SSL_VERIFYHOST] = 2;
                $options[CURLOPT_SSL_VERIFYPEER] = true;

                if (is_string($value)) {
                    $options[CURLOPT_CAINFO] = $value;
                    if (!file_exists($value)) {
                        throw new \InvalidArgumentException(
                            "SSL CA bundle not found: $value"
                        );
                    }
                }
                break;

            case 'decode_content':

                if ($value === false) {
                    continue 2;
                }

                $accept = Core::firstHeader($request, 'Accept-Encoding');
                if ($accept) {
                    $options[CURLOPT_ENCODING] = $accept;
                } else {
                    $options[CURLOPT_ENCODING] = '';
                    // Don't let curl send the header over the wire
                    $options[CURLOPT_HTTPHEADER][] = 'Accept-Encoding:';
                }
                break;

            case 'save_to':

                if (is_string($value)) {
                    if (!is_dir(dirname($value))) {
                        throw new \RuntimeException(sprintf(
                            'Directory %s does not exist for save_to value of %s',
                            dirname($value),
                            $value
                        ));
                    }
                    $value = new LazyOpenStream($value, 'w+');
                }

                if ($value instanceof StreamInterface) {
                    $options[CURLOPT_WRITEFUNCTION] =
                        function ($ch, $write) use ($value) {
                            return $value->write($write);
                        };
                } elseif (is_resource($value)) {
                    $options[CURLOPT_FILE] = $value;
                } else {
                    throw new \InvalidArgumentException('save_to must be a '
                        . 'GuzzleHttp\Stream\StreamInterface or resource');
                }
                break;

            case 'timeout':

                if (defined('CURLOPT_TIMEOUT_MS')) {
                    $options[CURLOPT_TIMEOUT_MS] = $value * 1000;
                } else {
                    $options[CURLOPT_TIMEOUT] = $value;
                }
                break;

            case 'connect_timeout':

                if (defined('CURLOPT_CONNECTTIMEOUT_MS')) {
                    $options[CURLOPT_CONNECTTIMEOUT_MS] = $value * 1000;
                } else {
                    $options[CURLOPT_CONNECTTIMEOUT] = $value;
                }
                break;

            case 'proxy':

                if (!is_array($value)) {
                    $options[CURLOPT_PROXY] = $value;
                } elseif (isset($request['scheme'])) {
                    $scheme = $request['scheme'];
                    if (isset($value[$scheme])) {
                        $options[CURLOPT_PROXY] = $value[$scheme];
                    }
                }
                break;

            case 'cert':

                if (is_array($value)) {
                    $options[CURLOPT_SSLCERTPASSWD] = $value[1];
                    $value = $value[0];
                }

                if (!file_exists($value)) {
                    throw new \InvalidArgumentException(
                        "SSL certificate not found: {$value}"
                    );
                }

                $options[CURLOPT_SSLCERT] = $value;
                break;

            case 'ssl_key':

                if (is_array($value)) {
                    $options[CURLOPT_SSLKEYPASSWD] = $value[1];
                    $value = $value[0];
                }

                if (!file_exists($value)) {
                    throw new \InvalidArgumentException(
                        "SSL private key not found: {$value}"
                    );
                }

                $options[CURLOPT_SSLKEY] = $value;
                break;

            case 'progress':

                if (!is_callable($value)) {
                    throw new \InvalidArgumentException(
                        'progress client option must be callable'
                    );
                }

                $options[CURLOPT_NOPROGRESS] = false;
                $options[CURLOPT_PROGRESSFUNCTION] =
                    function () use ($value) {
                        $args = func_get_args();
                        // PHP 5.5 pushed the handle onto the start of the args
                        if (is_resource($args[0])) {
                            array_shift($args);
                        }
                        call_user_func_array($value, $args);
                    };
                break;

            case 'debug':

                if ($value) {
                    $options[CURLOPT_STDERR] = Core::getDebugResource($value);
                    $options[CURLOPT_VERBOSE] = true;
                }
                break;
            }
        }
    }
1190909
public function execute(RequestInterface $request): RequestInterface
    {
        $body = $request->getBody()->getContents();

        $iv = random_bytes(self::INITIATION_VECTOR_LENGTH);
        $aesKey = random_bytes(self::AES_KEY_LENGTH);
        $encryptedAesKey = $this->publicKey->encrypt($aesKey);
        $bodyEncrypted = $this->determineBodyStringEncrypted($body, $aesKey, $iv);
        $hmac = $this->determineHmac($aesKey, $iv, $bodyEncrypted);
        $encryptedHeaders = [
            self::HEADER_CLIENT_ENCRYPTION_IV => [base64_encode($iv)],
            self::HEADER_CLIENT_ENCRYPTION_KEY => [base64_encode($encryptedAesKey)],
            self::HEADER_CLIENT_ENCRYPTION_HMAC => [base64_encode($hmac)],
        ];

        return new Request(
            $request->getMethod(),
            $request->getUri(),
            array_merge($request->getHeaders(), $encryptedHeaders),
            $bodyEncrypted
        );
    }
494828
public function create($options, $defaults = array())
    {
        if (is_array($options)) {
            $options += $defaults;
            $options = $this->format($options);
            $options = $this->normalize($options);

            $options = new RequestOptions($options);
        } elseif ($options instanceof RequestOptions) {
            $defaults = $this->create($defaults);
            $options->addDefaultHeaders($defaults->getHeaders());
            $options->addDefaultQueryParameters($defaults->getQueryParameters());
            $options->addDefaultBodyParameters($defaults->getBody());
        } else {
            throw new \InvalidArgumentException(
                'RequestOptions can only be created from array or from RequestOptions object'
            );
        }

        return $options->addDefaultHeaders($this->config->getDefaultHeaders());
    }
451091
public function doRequest($request, $options = null)
    {
        $request = array_merge($request, array(
            'Version'        => $this->_config->version,
            'ProcessorId'    => $this->_config->processorId,
            'MerchantId'     => $this->_config->merchantId,
            'TransactionPwd' => $this->_config->transactionPwd,
        ));

        $xml = new DOMDocument('1.0', 'utf-8');
        $envelope = $xml->createElement('CardinalMPI');
        foreach ($request as $k => $v) {
            $envelope->appendChild($xml->createElement($k, $v));
        }
        $xml->appendChild($envelope);

        $url = $this->_config->serviceUri();
        $xmlData = $xml->saveXML();
        $data = 'cmpi_msg=' . urlencode($xmlData);
        $header = array(
            'Content-type: application/x-www-form-urlencoded;charset="utf-8"',
            'Accept: text/xml',
            'Content-length: '.strlen($data),
        );
        // error_log($xmlData);

        return $this->submitRequest($url, $header, $data);
    }
174726
private function isOAuth2(RequestInterface $request, array $options)
    {
        // The 'auth' option must be set to 'oauth2'.
        if (!isset($options['auth']) || $options['auth'] !== 'oauth2') {
            return false;
        }

        // The request must be not for an access token endpoint.
        if ($this->provider->getBaseAccessTokenUrl([]) === $request->getUri()) {
            return false;
        }

        return true;
    }
1045179
public function handle(Request $request, $options = []): array
    {
        $this->fillOptions($options);

        try {
            foreach ($this->handlers as $handlerName) {
                /** @var BaseHandler $handler */
                $handler = new $handlerName();
                if (!$handler->handle($request, $this)) {
                    break;
                }
            }
        } catch (\Exception $e) {
            $answer = new \StdClass();
            $answer->jsonrpc = '2.0';
            $answer->error = JsonRpcHandler::handle($e);
            $this->response[] = $answer;
        }

        return \count($this->response) > 1 ? $this->response : (array)$this->response[0];
    }
1235110
public function getOptions(ServerRequestInterface $request): void
    {
        parent::getOptions($request);

        $this->search  = $request->get('search', '');
        $this->replace = $request->get('replace', '');
        $this->method  = $request->get('method', 'exact');
        $this->case    = $request->get('case', '');

        $this->error = '';
        switch ($this->method) {
            case 'exact':
                $this->regex = preg_quote($this->search, '/');
                break;
            case 'words':
                $this->regex = '\b' . preg_quote($this->search, '/') . '\b';
                break;
            case 'wildcards':
                $this->regex = '\b' . str_replace([
                        '\*',
                        '\?',
                    ], [
                        '.*',
                        '.',
                    ], preg_quote($this->search, '/')) . '\b';
                break;
            case 'regex':
                $this->regex = $this->search;
                // Check for invalid regular expressions.
                // A valid regex on an empty string returns zero.
                // An invalid regex on an empty string returns false and throws a warning.
                try {
                    preg_match('/' . $this->search . '/', '');
                } catch (Throwable $ex) {
                    /* I18N: http://en.wikipedia.org/wiki/Regular_expression */
                    $this->error = '<div class="alert alert-danger">' . I18N::translate('The regular expression appears to contain an error. It can’t be used.') . '</div>';
                }
                break;
        }
    }
642465
protected function handleRequest(RequestInterface $request): RequestInterface
    {
        if ($request instanceof JsonApiRequest) {
            $document = $request->getDocument();
            $stream   = $this->documentToStream($document);

            return $request->withBody($stream);
        }

        return $request;
    }
306862
public function add($request)
    {
        if (is_array($request)) {
            array_walk($request, [$this, __METHOD__]);

            return $this;
        }

        if (!$request instanceof Request) {
            throw new InvalidArgumentException('Argument for add() must be of type array or Request.');
        }

        $this->requests[] = $request;

        return $this;
    }
678489
public function render(Request $request, array $options = array())
    {
        return $this->doRender(
            $options + array(
                'app_id' => $this->appId,
                'width' => $this->defaultWidth,
                'num_posts' => $this->defaultNumPosts,
                'color_scheme' => $this->defaultColorScheme,
                'include_sdk' => $this->defaultIncludeSDK,
                'url' => $request->getSchemeAndHttpHost() . $request->attributes->get('semanticPathinfo', $request->getPathInfo()),
            )
        );
    }