Detects HTTP method to use for API call

@param string      $method The API method to call
@param array byref $params The parameters to send along

@return string The HTTP method that should be used
327382
protected function _detectMethod($method, &$params)
  {
    if (isset($params['httpmethod'])) {
      $httpmethod = $params['httpmethod'];
      unset($params['httpmethod']);
      return $httpmethod;
    }
    $apimethods = $this->getApiMethods();

    // multi-HTTP method API methods
    // parameter-based detection
    $httpmethods_by_param = [
      'POST' => [
        'campaign_id' => [
          'ads/accounts/:account_id/line_items',
          'ads/sandbox/accounts/:account_id/line_items'
        ],
        'media_id' => [
          'ads/accounts/:account_id/account_media',
          'ads/sandbox/accounts/:account_id/account_media'
        ],
        'name' => [
          'ads/accounts/:account_id/app_lists',
          'ads/accounts/:account_id/campaigns',
          'ads/accounts/:account_id/cards/app_download',
          'ads/accounts/:account_id/cards/image_app_download',
          'ads/accounts/:account_id/cards/image_conversation',
          'ads/accounts/:account_id/cards/lead_gen',
          'ads/accounts/:account_id/cards/video_app_download',
          'ads/accounts/:account_id/cards/video_conversation',
          'ads/accounts/:account_id/cards/website',
          'ads/accounts/:account_id/tailored_audiences',
          'ads/accounts/:account_id/web_event_tags',
          'ads/sandbox/accounts/:account_id/app_lists',
          'ads/sandbox/accounts/:account_id/campaigns',
          'ads/sandbox/accounts/:account_id/cards/app_download',
          'ads/sandbox/accounts/:account_id/cards/image_app_download',
          'ads/sandbox/accounts/:account_id/cards/image_conversation',
          'ads/sandbox/accounts/:account_id/cards/lead_gen',
          'ads/sandbox/accounts/:account_id/cards/video_app_download',
          'ads/sandbox/accounts/:account_id/cards/video_conversation',
          'ads/sandbox/accounts/:account_id/cards/website',
          'ads/sandbox/accounts/:account_id/tailored_audiences',
          'ads/sandbox/accounts/:account_id/web_event_tags'
        ],
        'permission_level' => [
          'ads/accounts/:account_id/tailored_audiences/:id/permissions',
          'ads/sandbox/accounts/:account_id/tailored_audiences/:id/permissions'
        ],
        'tailored_audience_id' => [
          'ads/accounts/:account_id/tailored_audience_changes',
          'ads/sandbox/accounts/:account_id/tailored_audience_changes'
        ],
        'targeting_value' => [
          'ads/accounts/:account_id/targeting_criteria',
          'ads/sandbox/accounts/:account_id/targeting_criteria'
        ],
        'tweet_ids' => [
          'ads/accounts/:account_id/promoted_tweets',
          'ads/sandbox/accounts/:account_id/promoted_tweets'
        ],
        'type' => [
          'ads/sandbox/accounts/:account_id/features',
          'ads/sandbox/accounts/:account_id/funding_instruments'
        ],
        'url' => [
          'account_activity/webhooks'
        ],
        'user_id' => [
          'ads/accounts/:account_id/promoted_accounts',
          'ads/sandbox/accounts/:account_id/promoted_accounts'
        ],
        'video_media_id' => [
          'ads/accounts/:account_id/videos',
          'ads/sandbox/accounts/:account_id/videos'
        ]
      ],
      'PUT' => [
        'name' => [
          'ads/accounts/:account_id/cards/image_conversation/:card_id',
          'ads/accounts/:account_id/cards/video_conversation/:card_id',
          'ads/accounts/:account_id/cards/website/:card_id',
          'ads/sandbox/accounts/:account_id/cards/image_conversation/:card_id',
          'ads/sandbox/accounts/:account_id/cards/video_conversation/:card_id',
          'ads/sandbox/accounts/:account_id/cards/website/:card_id'
        ]
      ]
    ];
    foreach ($httpmethods_by_param as $httpmethod => $methods_by_param) {
      foreach ($methods_by_param as $param => $methods) {
        if (in_array($method, $methods) && isset($params[$param])) {
          return $httpmethod;
        }
      }
    }

    // async media/upload calls may request a status by GET
    if ($method === 'media/upload'
      && isset($params['command'])
      && $params['command'] === 'STATUS'
    ) {
      return 'GET';
    }

    // prefer POST and PUT if parameters are set
    if (count($params) > 0) {
      if (in_array($method, $apimethods['POST'])) {
        return 'POST';
      }
      if (in_array($method, $apimethods['PUT'])) {
        return 'PUT';
      }
    }

    foreach ($apimethods as $httpmethod => $methods) {
      if (in_array($method, $methods)) {
        return $httpmethod;
      }
    }
    throw new \Exception('Can\'t find HTTP method to use for "' . $method . '".');
  }
1147721
public function methodName2URL($method)
    {
        if (! $this->restful)
            return parent::methodName2URL($method);

        $method = preg_replace('/Action$/i', '', $method);
        $method = preg_replace('/^(' . self::HTTP_METHOD_ANY . ')/i', '', $method);
        return trim(strtolower(preg_replace('/[A-Z]/', '-\0', $method)), '-');
    }
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);
        }
    }
466828
public function callAction($method, $parameters)
    {
        $response = call_user_func_array([$this, $method], $parameters);

        if (is_null($response) && ! is_null($this->layout)) {
            $response = $this->layout;
        }

        return $response;
    }
747324
private function getUrl($method)
    {
        return sprintf(
            $this::API_URL,
            $this->getDc(),
            $this->getApiVersion(),
            $method
        );
    }
307682
private function request($method, $url, $params = [])
    {
        $this->getLogger()->debug('Creating a new request with received parameters');
        $options = [
            'headers' => null, 'body' => null
        ];
        // Multipart
        if (array_key_exists('multipart', $params)) {
            // Build the multipart message
            $options['body'] = new MultipartStream($params['multipart']);
        } else if (array_key_exists('json', $params)) {
            // Build the JSON body and content type
            $options['body'] = json_encode($params['json']);
            $options['headers'] = ['content-type' => 'application/json'];
        } else if ($method == 'POST' || $method == 'PUT' || $method == 'DELETE') {
            $options['headers'] = ['content-type' => 'application/x-www-form-urlencoded'];
            if (count($params) > 0) {
                $options['body'] = http_build_query($params, null, '&');
            }
        }
        $this->logger->debug('Getting Authenticated Request');
        $request = $this->provider->getAuthenticatedRequest($method, $this->provider->getCmsApiUrl() . rtrim($url, '/'), $this->getAccessToken(), $options);
        $this->logger->debug('Getting parsed response from Abstract Provider');
        return $this->provider->getParsedResponse($request);
    }
154526
protected function doRequest($method, $endpoint, array $params = array(), $isVault = false)
    {
        if (empty($method) || !is_string($method)) {
            throw new InvalidArgumentException("HTTP METHOD must a string and a valid HTTP METHOD Value");
        }

        if (empty($endpoint) || !is_string($endpoint)) {
            throw new InvalidArgumentException("Endpoint must be a string and a valid api endpoint");
        }

        $credentials = $this->getConfiguration()->getApiUsername() . ':' . $this->getConfiguration()->getApiPassword();

        $url = $this->getConfiguration()->getApiEndpoint();

        if ($isVault) {
            $url = $this->getConfiguration()->getSecureVaultEndpoint();
        }

        $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'HiPayFullservice/1.0 (SDK PHP)';
        $finalUrl = $url . $endpoint;

        // set appropriate options
        $options = array(
            CURLOPT_URL => $finalUrl,
            CURLOPT_USERPWD => $credentials,
            CURLOPT_HTTPHEADER => array(
                'Accept: ' . $this->getConfiguration()->getApiHTTPHeaderAccept(),
                'User-Agent: ' . $userAgent
            ),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FAILONERROR => false,
            CURLOPT_HEADER => false,
        );

        // add post parameters
        if (strtolower($method) == 'post') {
            $options[CURLOPT_POST] = true;
            $options[CURLOPT_POSTFIELDS] = http_build_query($params);
        } else {
            $options[CURLOPT_POST] = false;
        }

        $proxyConfiguration = $this->getConfiguration()->getProxy();

        if (!empty($proxyConfiguration)) {
            $options[CURLOPT_PROXY] = $proxyConfiguration["host"];
            $options[CURLOPT_PROXYPORT] = $proxyConfiguration["port"];
            $options[CURLOPT_PROXYUSERPWD] = $proxyConfiguration["user"] . ":" . $proxyConfiguration["password"];
        }

        /**
         * Send a new request
         * $method can be any valid HTTP METHOD (GET, POST etc ...)
         * $uri The url/endpoint to request
         * $options Needed configuration
         */
        foreach ($options as $option => $value) {
            curl_setopt($this->_httpClient, $option, $value);
        }

        // execute the given cURL session
        if (false === ($result = curl_exec($this->_httpClient))) {
            throw new CurlException(curl_error($this->_httpClient), curl_errno($this->_httpClient));
        }

        $body = $result;

        $status = (int)curl_getinfo($this->_httpClient, CURLINFO_HTTP_CODE);
        $httpResponse = json_decode($body);

        if (floor($status / 100) != 2) {
            if (is_object($httpResponse) && isset($httpResponse->message, $httpResponse->code)) {
                $description = (isset($httpResponse->description)) ? $httpResponse->description : "";
                throw new ApiErrorException($httpResponse->message, $httpResponse->code, $description);
            } else {
                throw new HttpErrorException($body, $status);
            }
        }

        //Return a simple response object
        return new Response((string)$body, $status, array('Content-Type' => array('application/json; encoding=UTF-8')));
    }
248875
public function call($url, $method = 'GET', $params = [])
    {
        // Set call parameters
        $params = array_merge($this->params, is_array($params)? $params : []);

        // Setup parameters
        $content = '';
        $queryString = http_build_query($params);
        if ($method === 'GET') {
            $url = $url . '?' . $queryString;
        } else {
            $content = $queryString;
        }

        // Make call
        $result = @file_get_contents($url, false, stream_context_create([
            'http' => [
                'method'  => $method,
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $content
            ]
        ]));

        // Return result
        return $result;
    }
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;
    }
1068763
private function request($method, $resource, array $params)
    {
        $queryParams = ['api_key' => $this->apiKey];
        $queryParams += $params;

        $uri = $resource .'/?'. http_build_query($queryParams);

        try {
            $response = $this->client->request($method, $uri);
        } catch (ClientException $e) {
            $response = $e->getResponse();
            $msg = $response->getBody();
            $code = $response->getStatusCode();
            $previous = $e;
            throw new StreamFeedException($msg, $code, $previous);
        }

        $body = $response->getBody()->getContents();

        return json_decode($body, true);
    }
821745
private function checkParametersResolving($method, array $params = [])
    {
        if (!$this->resolveMethods) {
            return $params;
        }

        return app()->make(ServiceShortCuts::RESOLVER_SERVICE)->resolveMethodParameters($this, $method, $params);
    }
179281
protected function sendRequest(
        $method,
        $endpoint,
        array $params = []
    ) {
        $request = $this->request($method, $endpoint, $params);

        return $this->lastResponse = $this->client->sendRequest($request);
    }
548912
public function notify(string $method, $params): Promise
    {
        return $this->protocolWriter->write(
            new Message(
                new AdvancedJsonRpc\Notification($method, (object)$params)
            )
        );
    }
992461
protected function request($method, $url, $parameters = [])
    {
        $endpoint = 'https://api.b2bfamily.com' . $url;

        if (in_array($method, [self::METHOD_GET, self::METHOD_DELETE])) {
            $endpoint .= '?' . http_build_query($parameters, null, '&');
        }

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

        if (in_array($method, [self::METHOD_POST, self::METHOD_PUT])) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parameters));
        }

        $result = curl_exec($ch);
        $error = curl_error($ch);
        $errno = curl_errno($ch);

        curl_close($ch);

        if ($error) {
            throw new B2BFamilyException($error, $errno);
        }

        $result = json_decode($result, true);

        if (isset($result['error'])) {
            throw new B2BFamilyException($result['error']['message'], $result['error']['code']);
        }

        return $result;
    }
475623
public function request($method, $url, $params = array())
    {
        if (mb_substr($url, 0, 1, 'UTF-8') === '/') {
            $url = $this->api_endpoint . $url;
        }

        $remote_addr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1';
        $session_id  = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
        $user_agent  = sprintf("%s/%s PHP/%s %s",
            self::USER_AGENT,
            self::VERSION,
            phpversion(),
            $this->platform
        );

        $headers = [
            'Accept: application/json',
            'Session-Id: ' . $session_id,
            'Forwarded: ' . $remote_addr,
            'Authorization:  Bearer ' . $this->merchant_token,
            'Content-Type: application/json'
        ];

        curl_setopt_array($this->curl, [
            CURLOPT_USERAGENT     => $user_agent,
            CURLOPT_HTTPHEADER    => $headers,
            CURLOPT_URL           => $url,
            CURLOPT_CUSTOMREQUEST => $method
        ]);

        if (count($params) > 0) {
            $data      = json_encode($params, JSON_PRETTY_PRINT);
            $headers[] = 'Content-Length: ' . strlen($data);

            curl_setopt($this->curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($this->curl, CURLOPT_HTTPHEADER, $headers);
        }

        $body = curl_exec($this->curl);
        $info = curl_getinfo($this->curl);
        $code = (int)($info['http_code'] / 100);
        switch ($code) {
            case 0:
                $error = curl_error($this->curl);
                $errno = curl_errno($this->curl);
                throw new Exception(sprintf('Error: %s. Code: %s.', $error, $errno));
            case 1:
                throw new Exception(sprintf('Invalid HTTP Code: %s', $info['http_code']));
            case 2:
            case 3:
                return new Response($body);
            case 4:
            case 5:
                throw new Exception(sprintf('API Error: %s. HTTP Code: %s', $body, $info['http_code']));
            default:
                throw new Exception(sprintf('Invalid HTTP Code: %s', $info['http_code']));
        }
    }
1182007
protected function call($method, array $params = array())
    {
        $this->init();

        // Prepare headers
        $this->soapClient->__setSoapHeaders($this->getSessionHeader());

        $result = $this->logcall($method, $params);
        if (!isset($result->result)) {
            return array();
        }

        return $result->result;
    }
608262
public function api($endpoint, $method = null, $params = null)
    {
        $response = false;

        try {
            return $this->app[ 'facebook' ]->api($endpoint, $method, $params);
        } catch (\FacebookApiException $e) {
            // access token has expired
            $result = $e->getResult();
            $code = U::array_value($result, 'error.code');
            if ($code == 190) {
                // clear the access token of the user's profile
                if ($this->profile) {
                    $this->profile->grantAllPermissions();
                    $this->profile->set('access_token', '');
                    $this->profile->enforcePermissions();
                }
            } else {
                $this->app[ 'logger' ]->error($e);
            }

            return false;
        }
    }