Parse callback URL from request.

@param  array  $body
@param  array|string  $url

@return array
772252
final protected function parseRedirectAndCallbackUrlFromRequest(array $body, $url): array
    {
        if (\is_string($url)) {
            $body['callback_url'] = $url;
        } elseif (\is_array($url)) {
            $body['callback_url'] = $url['callback_url'] ?? null;
            $body['redirect_url'] = $url['redirect_url'] ?? null;
        }

        return $body;
    }
966211
public function url($body)
    {
        $re = '/window.location(\.assign|\.replace)\(["|\'](.+)["|\']/i';
        preg_match_all($re, $body, $matches);

        if (!empty($matches[2])) {
            return new Url($matches[2][0], true);
        }

        return false;
    }
823784
public static String get(String url, String body) {
        return request(HttpRequest.get(replaceLocalHost(url)), body).body();
    }
649995
protected function httpPostJson($uri, $body)
    {
        $this->log[] = [
                        'request' => [
                                    'method' => 'POST',
                                    'uri'    => $uri,
                                    'body'   => $body,
                                    ],
                        ];
        $response = \Httpful\Request::post($uri)
                                                ->addHeader('X-Auth-Email', $this->email)
                                                ->addHeader('X-Auth-Key', $this->apikey)
                                                ->sendsAndExpects(\Httpful\Mime::JSON)
                                                ->parseWith(function ($body) {
                                                    return \Metaclassing\Utility::decodeJson($body);
                                                })
                                                ->body($body)
                                                ->send()
                                                ->body;
        $this->log[count($this->log) - 1]['response'] = $response;
        if ($response['success'] != true) {
            throw new \Exception("post to {$uri} unsuccessful");
        }

        return $response['result'];
    }
728180
public function requestAsync($method, $url, $body = [], $query = [], $headers = [])
    {
        if (!empty($body)) {
            $body = encode($body);
            $headers['Content-Type'] = 'application/json';
        } else {
            $body = null;
        }

        $headers = array_merge($this->global_headers, $headers);

        return $this->client->requestAsync($method, $url, [
            'query'   => $query,
            'body'    => $body,
            'headers' => $headers,
        ]);
    }
144034
private function jsonCall($method, $uri, $body = null)
    {
        $jsonBody = null;

        if (null !== $body) {
            $jsonBody = json_encode($body);
        }

        $request = new Request($method, $uri, ['Content-Type' => 'application/json'], $jsonBody);
        $response = $this->guzzle->send($request);
        $this->lastResponse = $response;

        self::checkResponse($response);

        return json_decode($response->getBody());
    }
948894
public static function post($url, $headers = [], $body = null)
    {
        return Request::create('default')->post($url, $headers, $body);
    }
412533
public static function _parse_url_query($url)
    {
        $queryString = parse_url($url, PHP_URL_QUERY);

        $params = array();

        parse_str($queryString, $params);

        if (count($params) === 0) {
            return $params;
        }

        return array_filter($params);
    }
1036074
public function parse($url)
    {
        $this->_fixUrlForParsing($url);

        if (empty($url->path) && !isset($url->query['option'])) {
            $url->path = (get_viewer()->guest()) ? 'pages' : 'dashboard';
        }

        $segments = explode('/', trim($url->path, '/'));
        $segments = array_filter($segments);

        if (!empty($segments)) {
            $component = array_shift($segments);
            $url->query = array_merge(array('option' => 'com_'.$component), $url->query);
            $component = str_replace('com_', '', $url->query['option']);
            $query = $this->getComponentRouter($component)->parse($segments);
            $url->query = array_merge($url->query, array('option' => 'com_'.$component), $query);
        }

        return $url;
    }
842065
protected function perform($method, $url, $body = array(), $query = array(), $headers = array())
    {

        // response data placeholders
        $response = null;
        $responseHeaders = array();

        $logger = $this->getLogger();

        // determine allowed methods
        $methodName = strtoupper($method);

        // query string processing
        $processedUrl = $this->prepareUrl($url, $query);

        try {

            $logger->debug('NEW REQUEST: ' . $methodName . ' ' . $processedUrl);

            if (!in_array($methodName, array(
                'GET', 'POST', 'PUT', 'DELETE', 'HEAD'
            ))
            ) {
                throw new \Exception('Method not supported', HttpException::METHOD_NOT_SUPPORTED);
            }

            // prepare request headers and fields
            $contextParams = array(
                'http' => array(
                    'method' => $methodName,
                    'ignore_errors' => true   // we want to catch output although the error
                ));

            // skip SSL verification
            if($this->skipSsl){
                $contextParams['ssl'] = array(
                    'verify_peer'=>false,
                    'verify_peer_name'=>false
                );
            }

            // inject request parameters
            $this->applyHeaders($contextParams, $headers);
            $json = !empty($headers['Content-Type']) && $headers['Content-Type']=='application/json';
            $this->applyBody($contextParams, $methodName, $body, $json);

            // make request stream context
            $ctx = stream_context_create($contextParams);

            // initialize requests counter
            $counter = self::$retryLimit;

            $response = null;

            // perform request regarding counter limit and quotas
            while ($counter--) {
                try {
                    // pause upon limits exceeding
                    if (isset($responseHeaders['X-Shop-Api-Calls'])) {

                        $calls = $responseHeaders['X-Shop-Api-Calls'];
                        $limit = $responseHeaders['X-Shop-Api-Limit'];

                        if ($limit - $calls == 0) {
                            sleep(1);
                        }
                    }

                    $response = $this->doRequest($processedUrl, $ctx, $responseHeaders, $methodName);

                    break;
                } catch (\Exception $ex) {
                    // server pauses request for X seconds
                    if (!empty($responseHeaders['Retry-After'])) {
                        if ($counter <= 0) {
                            throw new \Exception('Retries count exceeded', HttpException::QUOTA_EXCEEDED);
                        }
                        sleep($responseHeaders['Retry-After']);
                    } else {
                        // other error
                        throw $ex;
                    }
                }
            }

            $parsedPayload = null;
            if ($methodName != 'HEAD') {
                // try to decode response
                if ($responseHeaders['Content-Type'] == 'application/json') {
                    $parsedPayload = @json_decode($response, true);

                    if (!$parsedPayload && !is_array($parsedPayload)) {
                        throw new \Exception('Result is not a valid JSON', HttpException::MALFORMED_RESULT);
                    }

                } else {
                    $parsedPayload = $response;
                }

                $logger->debug('Response body (decoded): ' . var_export($parsedPayload, true));
            }
        }catch(\Exception $ex){

            $message = $ex->getMessage();

            $logger->error(
                $ex->getMessage(), compact('method', 'url', 'query', 'headers', 'body', 'responseHeaders', 'response')
            );

            if($ex instanceof HttpException){
                $response = $ex->getResponse();
                $message = $ex->getMessage();
            }

            throw new HttpException(
                $message, $ex->getCode(), null, $method, $url, $headers, $query, $body, $response, $responseHeaders
            );
        }

        return array(
            'data' => $parsedPayload,
            'headers' => $responseHeaders
        );
    }
109561
protected function parseQueryParams($url)
    {
        $queries = [];

        $querySegment = \parse_url($url, PHP_URL_QUERY);
        \parse_str($querySegment, $queries);

        return $queries;
    }
37606
protected function httpPostJson($uri, $body)
    {
        $this->log[] = [
                        'request' => [
                                    'method' => 'POST',
                                    'uri'    => $uri,
                                    'body'   => $body,
                                    ],
                        ];
        $response = \Httpful\Request::post($uri)
                                                ->basicAuth($this->username, $this->password)
                                                ->sendsAndExpects(\Httpful\Mime::JSON)
                                                ->parseWith(function ($body) {
                                                   return $body;
                                                   //return \Metaclassing\Utility::decodeJson($body);
                                                })
                                                ->body($body)
                                                ->send()
                                                ->body;
        $this->log[count($this->log) - 1]['response'] = $response;
        //if ($response['success'] != true) {
        //    throw new \Exception("post to {$uri} unsuccessful");
        //}

        return $response;
    }
1125580
protected function parse($body)
    {
        $response = parent::parse($body);

        $data = simplexml_load_string($body);

        if ($data->CardTxn && $tds = $data->CardTxn->ThreeDSecure) {
            $response['acs_url'] = $tds->acs_url->__toString();
            $response['pareq_message'] = $tds->pareq_message->__toString();
            $response['pares_status'] = $tds->status->__toString();
            $response['aav'] = $tds->aav->__toString();
            $response['cardholder_registered'] = $tds->cardholder_registered->__toString();
            $response['cavvAlgorithm'] = $tds->cavvAlgorithm->__toString();
            $response['eci'] = $tds->eci->__toString();
            $response['xid'] = $tds->xid->__toString();
        }

        return $response;
    }
86211
protected static function parseUrl($url)
    {
        $components = @parse_url($url);
        if (! empty($components)) {
            return $components;
        }

        if (is_null(static::$is_parse_url_bugged)) {
            static::$is_parse_url_bugged = ! is_array(@parse_url("//example.org:80"));
        }

        //bugfix for https://bugs.php.net/bug.php?id=68917
        if (static::$is_parse_url_bugged &&
            strpos($url, '/') === 0 &&
            is_array($components = @parse_url('http:'.$url))
        ) {
            unset($components['scheme']);
            return $components;
        }
        throw new RuntimeException(sprintf("The given URL: `%s` could not be parse", $url));
    }
1353205
public function parse($body)
	{
		if (is_array($body)) {
			foreach ($body as $key => &$item) {
				if ($item instanceof AbstractFragment) {
					$parsedBody = $this->parse($item->getBody());

					// Add the parsed fragment to the parent.
					if ($item->mergeWithParent) {
						unset($body[$key]);
						$body = array_merge($body, $parsedBody);
					} // Replace its current position with the parsed fragment.
					else {
						$item = $parsedBody;
					}
				} // Further nesting to be parsed.
				elseif (is_array($item)) {
					$item = $this->parse($item);
				}
			}
			// Root level fragment, does not have a parent so it can not be merged with one.
		} elseif ($body instanceof AbstractFragment) {
			$body = $this->parse($body->getBody());
		}

		return $body;
	}
175904
public function get(
        string $url,
        string $method,
        array $query = [],
        array $body = [],
        array $server = []
    ): array {
        $method = strtolower($method);
        $requestParts = $this->buildRequestParts(
            $url,
            $query,
            $body,
            $server
        );

        return $this->tryRequest(function () use ($method, $requestParts) {
            return $this
                ->httpAdapter
                ->getByRequestParts(
                    $this->host,
                    $method,
                    $requestParts
                );
        }, $this
            ->retryMap
            ->getRetry(
                $url,
                $method
            )
        );
    }
1132224
private function parseUrl(string $url): array
    {
        $parts = parse_url($url);

        if ($parts === false || !isset($parts['host'])) {
            throw new \InvalidArgumentException(sprintf('Invalid connection URL given: "%s"', $url));
        }

        $params = [
            'login' => $parts['user'] ?? '',
            'password' => $parts['pass'] ?? '',
            'host' => $parts['host'],
            'port' => (int) ($parts['port'] ?? 5672),
            'vhost' => empty($parts['path']) || $parts['path'] === '/' ? '/' : substr($parts['path'], 1),
        ];

        parse_str($parts['query'] ?? '', $queryParams);

        return $params + $queryParams;
    }