/** * @param array $data * * @return array|string|null * * @throws \Exception */ public function send($data = null) { $request = new FormRequest($this->method, $this->resource, $this->host); if ($data) { $request->addFields($data); } try { $this->logger->addDebug('Request: ' . $request->getUrl()); /** @var Buzz\Message\Response $response */ $response = $this->client->send($request); $this->logger->addDebug('Response: ' . $response->getStatusCode() . ' ' . substr($response->getContent(), 0, 300) . PHP_EOL . var_export($this->client->getClient()->getInfo(), true)); } catch (\Exception $e) { switch ($e->getCode()) { case 28: $code = 504; break; default: $code = $e->getCode() >= 100 ? $e->getCode() : 500; } $this->logger->addCritical(PHP_EOL . __METHOD__ . sprintf('[%s/%s] %s', $e->getCode(), $code, $e->getMessage())); throw new WebGateException($e->getMessage(), $code, $e); } if ($response->getStatusCode() != 200) { throw new WebGateException(json_decode($response->getContent(), true), $response->getStatusCode()); } return json_decode($response->getContent(), true); }
private function doRealRequest($url, array $options) { $request = new FormRequest(Request::METHOD_POST); $request->fromUrl($url); $request->setFields($options); $response = new Response(); $client = new FileGetContents(); $client->send($request, $response); return $response->getContent(); }
/** * @param $method * @param null $params * @param $route * @param null $headers * @return mixed */ private function makeRequest($method, $params = null, $route, $headers = null) { $request = new FormRequest($method, $route, $this->apiSettings['api_endpoint']); if ($params) { $request->setFields($params); } if ($headers) { $request->setHeaders($headers); } return $this->sendRequest($request); }
/** * Create a request object * * @param string $method The HTTP method for the request * @param string $host The api host for the request * @param string $endpoint The api endpoint for the request * @param array $postVars A list of post variables * * @return RequestInterface The request */ protected function createRequest($method, $host, $endpoint, array $postVars = null) { if (empty($postVars)) { $request = new Request($method, $endpoint, $host); } else { $request = new FormRequest($method, $endpoint, $host); foreach ($postVars as $key => $value) { $request->setField($key, $value); } } return $request; }
/** * @param UserInterface $user * @param NamedNumberInterface[] $recipient * @param string $coverPage * @param string $coverPageText * @param string $resolution * @param \DateTime $sendTime * @param array $attachments * @return string */ public function sendFax(UserInterface $user, array $recipient, $coverPage, $coverPageText, $resolution, \DateTime $sendTime, array $attachments) { $form = new FormRequest(); $form->setResource(self::FAX_OUT_ENDPOINT); $recipients = array(); foreach ($recipient as $rec) { $recipients[] = $rec->getNumber() . ($rec->getName() ? '|' . $rec->getName() : ''); } $uploads = array(); foreach ($attachments as $attachment) { $uploads[] = new FormUpload($attachment); } $fields = array('Username' => $user->getUserNumber(), 'Password' => $user->getPassword(), 'Extension' => $user->getExtension(), 'Recipient' => $recipients, 'Coverpage' => $coverPage, 'Coverpagetext' => $coverPageText, 'Resolution' => $resolution, 'Sendtime' => $sendTime->format('d:m:y h:i'), 'Attachment' => $uploads); $form->addFields($fields); return $this->browser->post(self::FAX_OUT_ENDPOINT, $form->getHeaders(), $form->getContent()); }
/** * Executes a http request. * * @param Request $request The http request. * * @return Response The http response. */ public function execute(Request $request) { $method = $request->getMethod(); $endpoint = $request->getEndpoint(); $params = $request->getParams(); $headers = $request->getHeaders(); try { if ($method === 'GET') { $buzzResponse = $this->client->call($endpoint . '?' . http_build_query($params), $method, $headers, array()); } else { $buzzRequest = new FormRequest(); $buzzRequest->fromUrl($endpoint); $buzzRequest->setMethod($method); $buzzRequest->setHeaders($headers); foreach ($params as $key => $value) { if ($value instanceof Image) { $value = new FormUpload($value->getData()); } $buzzRequest->setField($key, $value); } $buzzResponse = new BuzzResponse(); $this->client->send($buzzRequest, $buzzResponse); } } catch (RequestException $e) { throw new Exception($e->getMessage()); } return static::convertResponse($request, $buzzResponse); }
/** * Fetch from the API * @param string $endpoint Fetch from the endpoint * @param array $params Any parameters * @return \stdClass|\stdClass[] */ public static function fetch($endpoint, array $params = []) { $client = self::getClient(); $browser = new Browser($client); $method = Request::METHOD_GET; foreach (self::$postEndpoints as $check) { if (preg_match("/^{$check}\$/", $endpoint)) { $method = Request::METHOD_POST; } } $request = new FormRequest($method, $endpoint, self::BASE_URL); $request->setFields($params); $response = new Response(); $listener = new JsonListener(); $browser->addListener($listener); $response = $browser->send($request, $response); return $response->getContent(); }
public function doSendRequest(array $options) { $request = new FormRequest(Request::METHOD_POST); $request->fromUrl(static::HTTP_AccessPoint_Send); $request->setFields(array('json' => json_encode($options))); $response = new Response(); $client = new FileGetContents(); $client->send($request, $response); $json = $response->getContent(); $status = json_decode($json, true); if (!isset($status[static::Error_Code])) { throw new InvalidResponseException('JSON response does not contain response code'); } $normalized_status = $status; $normalized_status[self::NORMALIZED_MESSAGE] = $status[self::Error_Message]; $normalized_status[self::NORMALIZED_CODE] = $status[self::Error_Code]; return $normalized_status; }
/** * @param FormUpload $image * @param int $expire * * @return FormRequest */ private function buildRequest($image, $expire) { $request = new FormRequest(); $request->fromUrl(self::REQUEST_URL); $request->setField('uploadedfile', $image); $request->setField('expire', $expire); $request->setField('upload', 1); return $request; }
/** * Authenticate on OAuth server with the specific authorization code. * * @param string $code The authorization code * * @return array The struct array('access_token' => string, 'expires_in' => integer) * * @throws Exception\AuthException * @throws Exception\NetworkException */ public function authenticate($code) { $request = new FormRequest(); $response = new Response(); $request->setHost(self::BASEURL); $request->setResource('/token'); $request->setField('grant_type', 'authorization_code'); $request->setField('code', $code); $request->setField('client_id', $this->appId); $request->setField('client_secret', $this->appSecret); try { $this->client->send($request, $response); } catch (ClientException $ex) { throw new Exception\NetworkException($ex, $request, $response); } if ($response->getStatusCode() === 200) { return json_decode($response->getContent(), true); } throw new Exception\AuthException('Could not authenticate. Reason: ' . $response->getContent(), $response->getStatusCode()); }
/** * Performs an "Had" action on facebook app * * <code> * curl * -F 'access_token=xxxxxxxxxxxxxxxx' * -F 'cocktail=http://just-had-a-cocktail.pagodabox.com/cocktail/yyyyyyy' * 'https://graph.facebook.com/me/lmammino-jhac:had' * </code> * * @param $cocktailUrl */ public function hadCocktail($cocktailUrl, $timestamp = NULL) { $request = new FormRequest(Request::METHOD_POST, 'me/lmammino-jhac:had', self::$GRAPH_HOST); $request->setField('access_token', $this->accessToken); $request->setField('cocktail', $cocktailUrl); if ($timestamp) { $date = date('c', $timestamp); $request->setField('start_time', $date); $request->setField('end_time', $date); } $response = new Response(); $this->buzz->send($request, $response); return json_decode($response->getContent()); }
public function testLoginWithExistingFrontendSession() { $loginFormResponse = $this->sendHttpRequest(new Request('GET', '/login', $this->getHttpHost())); $domDocument = $loginFormResponse->toDomDocument(); $xpath = new \DOMXPath($domDocument); $csrfDomElements = $xpath->query("//input[@name='_csrf_token']/@value"); self::assertGreaterThan(0, $csrfDomElements->length); $csrfTokenValue = $csrfDomElements->item(0)->nodeValue; $loginPostRequest = new FormRequest('POST', '/login', $this->getHttpHost()); $loginPostRequest->addFields(['_username' => $this->getLoginUsername(), '_password' => $this->getLoginPassword(), '_csrf_token' => $csrfTokenValue]); $loginResponse = $this->sendHttpRequest($loginPostRequest); if (!($sessionCookieHeader = $loginResponse->getHeader('set-cookie'))) { self::fail('No cookie in login response'); } list($sessionCookie) = explode(';', $sessionCookieHeader); $request = $this->createHttpRequest('POST', '/api/ezp/v2/user/sessions', 'SessionInput+json', 'Session+json'); $this->setSessionInput($request); $request->addHeader("Cookie: {$sessionCookie}"); $response = $this->sendHttpRequest($request); self::assertHttpResponseCodeEquals($response, 201); }
/** * @param array $notification * * @return string */ public function notifyValidate(array $notification) { $request = new FormRequest(); $request->setField('cmd', self::CMD_NOTIFY_VALIDATE); $request->addFields($notification); $request->setMethod('POST'); $request->fromUrl($this->getIpnEndpoint()); $response = new Response(); $this->client->send($request, $response); if (false == $response->isSuccessful()) { throw HttpException::factory($request, $response); } if (self::NOTIFY_VERIFIED === $response->getContent()) { return self::NOTIFY_VERIFIED; } return self::NOTIFY_INVALID; }
/** * Upload file- Not working!!!! - 408 error code... * * IMPROVE.... * * @param string $destFolderPath Target folder of the file * @param boolean $createParents Create parents folder if not exist * @param string $filePath Local file to upload * @param boolean $overwrite (Optionnal - Default null) null : Set error if file exists, true : overwrite file, false : skip upload if file exist * @param \DateTime $mtime (Optionnal) Set the modification time * @param \DateTime $crtime (Optionnal) Set the creation time * @param \DateTime $atime (Optionnal) Set the access time * * @return array Response of the request ("json_decoded") * * @throws PatbzhSynologyException In case synology api sends an error response * @throws \\InvalidArgumentException */ public function uploadFile($destFolderPath, $createParents, $filePath, $overwrite = null, $mtime = null, $crtime = null, $atime = null) { if (!is_string($destFolderPath)) { throw new \InvalidArgumentException('$destFolderPath should be a string'); } if (!is_string($filePath)) { throw new \InvalidArgumentException('$filePath should be a string'); } if (!is_bool($createParents)) { throw new \InvalidArgumentException('$createParents should be a boolean'); } if (!is_null($overwrite) && !is_bool($overwrite)) { throw new \InvalidArgumentException('$overwrite should be a boolean'); } if (!is_null($mtime) && !$mtime instanceof \DateTime) { throw new \InvalidArgumentException('$mtime should be a \\DateTime'); } if (!is_null($crtime) && !$crtime instanceof \DateTime) { throw new \InvalidArgumentException('$crtime should be a \\DateTime'); } if (!is_null($atime) && !$atime instanceof \DateTime) { throw new \InvalidArgumentException('$atime should be a \\DateTime'); } $additionalParams['dest_folder_path'] = $destFolderPath; if ($createParents) { $additionalParams['create_parents'] = 'true'; } if (!$createParents) { $additionalParams['create_parents'] = 'false'; } if (!is_null($overwrite) && $createParents) { $additionalParams['overwrite'] = 'true'; } if (!is_null($overwrite) && !$createParents) { $additionalParams['overwrite'] = 'false'; } if (!is_null($mtime)) { $additionalParams['mtime'] = $mtime->getTimestamp(); } if (!is_null($crtime)) { $additionalParams['crtime'] = $crtime->getTimestamp(); } if (!is_null($atime)) { $additionalParams['atime'] = $atime->getTimestamp(); } // $additionalParams['file'] = $file; $cgiPath = 'FileStation/api_upload.cgi'; $apiName = 'SYNO.FileStation.Upload'; $version = 1; // Check Available APIS if ($this->getIsQueriesValidated() && !in_array($apiName, array('SYNO.API.Auth', 'SYNO.API.Info')) && !isset($this->availableApis[$apiName])) { $this->retrieveAvailableApis($apiName); // Validate API information $calledApiInformation = $this->availableApis[$apiName]; if (is_null($calledApiInformation)) { throw new \RuntimeException('Unavailable API'); } if ($cgiPath != $calledApiInformation['ApiPath']) { throw new \RuntimeException('CGI Path problem [Requested: ' . $cgiPath . '][ServerVersion: ' . $calledApiInformation['ApiPath'] . ']'); } if ($calledApiInformation['MinVersion'] > $version) { throw new \RuntimeException('API Version issue [Requested: ' . $version . '][MinVersion: ' . $calledApiInformation['MinVersion'] . ']'); } if ($calledApiInformation['MaxVersion'] < $version) { throw new \RuntimeException('API Version issue [Requested: ' . $version . '][MaxVersion: ' . $calledApiInformation['MaxVersion'] . ']'); } } // Login if required if (!$this->isLoggedIn()) { $this->login(); } // Set "mandatory" parameters list $params = array('api' => $apiName, 'version' => $version, 'method' => 'upload'); if ($this->isLoggedIn()) { $params['_sid'] = $this->getSessionId(); } // Add additionnal parameters if ($additionalParams !== null) { $params = $params + $additionalParams; } // Set request $queryString = 'webapi/' . $cgiPath; $request = new FormRequest('POST', $queryString, $this->getBaseUrl()); $request->addFields($params); $uploadedFile = new FormUpload($filePath); $uploadedFile->setContentType('application/octet-stream'); $request->setField('file', $uploadedFile); $response = new Response(); // Handle request $this->httpClient->send($request, $response); // Check response $parsedResponse = json_decode($response->getContent(), true); // Throw exception in case of error if ($parsedResponse['success'] !== true) { throw new PatbzhSynologyException($this->getErrorMessage($parsedResponse['error']['code']) . ' (' . $parsedResponse['error']['code'] . ')', $parsedResponse['error']['code']); } // Return json_decoded response return $parsedResponse; }
/** * @param FormRequest $request */ protected function addOptions(FormRequest $request) { $request->setField('USER', $this->options['username']); $request->setField('PWD', $this->options['password']); $request->setField('PARTNER', $this->options['partner']); $request->setField('VENDOR', $this->options['vendor']); $request->setField('TENDER', $this->options['tender']); }
/** * @param $referenceFull * * @return Response * * @throws MediaStorageClientApiException */ public function getMedia($referenceFull) { if (empty($referenceFull)) { throw new MediaStorageClientApiException('Param referenceFull is empty'); } try { $request = new FormRequest(); $request->setMethod(FormRequest::METHOD_GET); $request->setHost($this->getApiUrlConfig('base_url')); $url = $this->getApiUrlConfig('get_media_by_reference_full_url') . '/' . ltrim($referenceFull, '/'); $request->setResource($url); $this->logger->debug('Send ' . $this->getApiUrlConfig('base_url') . $url); /** @var Response $response */ $response = $this->client->send($request, null); $this->logger->debug('Response: ' . $response->getStatusCode() . ' ' . substr($response->getContent(), 0, 300)); } catch (\Exception $e) { throw new MediaStorageClientApiException($e->getMessage()); } return $response; }
/** * @param FormRequest $request */ protected function addVersionField(FormRequest $request) { $request->setField('VERSION', self::VERSION); }
/** * @dataProvider provideClient */ public function testPlus($client) { $request = new FormRequest(); $request->fromUrl($_SERVER['TEST_SERVER']); $request->setField('math', '1+1=2'); $response = $this->send($client, $request); $data = json_decode($response->getContent(), true); parse_str($data['INPUT'], $fields); $this->assertEquals(array('math' => '1+1=2'), $fields); }
public function testGetRequest() { $request = new FormRequest(FormRequest::METHOD_GET, '/search'); $request->setField('q', 'cats'); $this->assertEquals('/search?q=cats', $request->getResource()); $this->assertEmpty($request->getContent()); }
/** * @param \Buzz\Message\Form\FormRequest $request * * @throws \Payum\Core\Exception\Http\HttpException * * @return \Payum\Core\Bridge\Buzz\JsonResponse */ protected function doRequest(FormRequest $request) { $request->setMethod('POST'); $request->fromUrl($this->getApiEndpoint()); $this->client->send($request, $response = new JsonResponse()); if (false == $response->isSuccessful()) { throw HttpException::factory($request, $response); } return $response; }
/** * @param User $user */ private function refreshToken($user) { $req = new FormRequest(Request::METHOD_POST, "/" . $this->tenant . "/oauth2/token", "https://login.windows.net"); $req->setFields(array("client_id" => $this->clientId, "client_secret" => $this->clientSecret, "grant_type" => "refresh_token", "refresh_token" => $user->getAzureRenewAccessToken(), "resource" => "https://graph.windows.net")); $res = new Response(); $client = new Curl(); $client->setTimeout(20000); $client->send($req, $res); if ($res->getStatusCode() == 200) { $data = json_decode($res->getContent()); $user->setAzureAccessToken($data->access_token); $user->setAzureRenewAccessToken($data->refresh_token); $this->users->updateUser($user); $this->accessToken = $data->access_token; } else { $this->token->getToken()->setAuthenticated(false); throw new AccountExpiredException("Link with Office 365 has expired"); } }
/** * Возвращает результаты запроса. * * @return mixed * @throws \Api\Exceptions\Exception */ public function getResult() { $log = ['time' => microtime(true), 'uri' => sprintf('%s?%s', $this->uri, http_build_query($this->queryParameters)), 'code' => 200]; $uri = sprintf('%s://%s/%s?%s', $this->api->getScheme(), $this->api->getDomain(), $this->uri, http_build_query(array_merge($this->queryParameters, ['appId' => $this->api->getAppId(), 'appKey' => $this->api->getAppKey()]))); $browser = new Browser(new Curl()); $request = new FormRequest($this->method, $uri); if ($this->method == RequestInterface::METHOD_POST && !empty($this->postParameters)) { foreach ($this->postParameters as $key => $value) { $request->setField($key, $value); } } /** @var \Buzz\Message\Response $result */ $result = $browser->send($request); $exception = null; if ($result->isClientError() || $result->isServerError()) { switch ($result->getStatusCode()) { case 404: $exception = new Http(sprintf('API returned 404 on request to «%s»: %s', $this->uri, $result->getContent()), 404); break; default: $exception = new Http(sprintf('API returned 500 on request to «%s»: %s', $this->uri, $result->getContent()), 500); break; } } if (null !== $exception) { $log['time'] = microtime(true) - $log['time']; $log['code'] = $exception->getCode(); $this->api->appendLog($log); throw $exception; } $json = json_decode($result->getContent(), true); $error = json_last_error(); if ($error !== JSON_ERROR_NONE) { throw new Json(sprintf('%s on %s', $this->jsonError($error), $this->uri)); } $log['time'] = microtime(true) - $log['time']; $this->api->appendLog($log); return $json; }