/** * @param string $folderName * @param string $parentFolderId */ public function __construct($folderName, $parentFolderId) { $postBody = new PostBody(); $postBody->setField('name', $folderName); $postBody->setField('parent', ['id' => $parentFolderId]); $this->request = new PostRequest('folders'); $this->request->setRawJsonBody((array) $postBody->getFields()); }
/** * @param string $fileName * @param int $fileSize * @param string $parentFolderId */ public function __construct($fileName, $fileSize, $parentFolderId) { $postBody = new PostBody(); $postBody->setField('name', $fileName); $postBody->setField('size', $fileSize); $postBody->setField('parent', ['id' => $parentFolderId]); $this->request = new OptionsRequest('files/content'); $this->request->setRawJsonBody((array) $postBody->getFields()); }
public function testPOST() { $body = new PostBody(); $body->setField('foo', 'bar'); $body->setField('hello', 'world'); $request = new Request('POST', 'example.local', [], $body); $curl = $this->curlFormatter->format($request); $this->assertContains("-d 'foo=bar&hello=world'", $curl); $this->assertNotContains(" -G ", $curl); }
/** * @param string $documentId * @param string $name */ public function __construct($documentId, $name) { $postBody = new PostBody(); $postBody->setField('name', $name); $this->request = new PutRequest("documents/{$documentId}"); $this->request->setRawJsonBody($postBody->getFields()); }
/** * @param string $fileId * @param int $fileSize */ public function __construct($fileId, $fileSize) { $postBody = new PostBody(); $postBody->setField('size', $fileSize); $this->request = new OptionsRequest("files/{$fileId}/content"); $this->request->setRawJsonBody((array) $postBody->getFields()); }
/** * @param string $fileId * @param string $folderId */ public function __construct($fileId, $folderId) { $postBody = new PostBody(); $postBody->setField('parent', ['id' => $folderId]); $this->request = new PostRequest("files/{$fileId}/copy"); $this->request->setRawJsonBody((array) $postBody->getFields()); }
/** * @param string $fileName * @param string $parentFolderId * @param string $content */ public function __construct($fileName, $parentFolderId, $content) { $postBody = new PostBody(); $postBody->setField('parent_id', $parentFolderId); $postBody->addFile(new PostFile('filename', $content, $fileName)); $this->request = new PostRequest('files/content'); $this->request->setBody($postBody); }
public static function arrayToPostBody(\ArrayAccess $data, PostBody $postBody = null) { if (!$postBody) { $postBody = new PostBody(); } foreach ($data as $key => $value) { $postBody->setField($key, $value); } return $postBody; }
public function send($text = null, $icon = null, $attachments = []) { $self = $this; $this->httpclient->request($this->url, 'POST', function (Event $event) use($self, $text, $icon, $attachments) { $request = $event->message; /** @var \GuzzleHttp\Message\Request $request */ $body = new PostBody(); $body->setField('payload', Json::encode($self->getPayload($text, $icon, $attachments))); $request->setBody($body); }); }
/** * @param string $url * @param ExtendedRequest $extendedRequest */ public function __construct($url, ExtendedRequest $extendedRequest = null) { $postBody = new PostBody(); $postBody->setField('url', $url); $postFields = $postBody->getFields(); if (!is_null($extendedRequest)) { $postFields = array_merge($postFields, $extendedRequest->getPostBodyFields()); } $this->request = new PostRequest('documents'); $this->request->setRawJsonBody($postFields); }
public function testMultipartWithAmpersandInValue() { $b = new PostBody(); $b->setField('a', 'b&c=d'); $b->forceMultipartUpload(true); $this->assertEquals(['a' => 'b&c=d'], $b->getFields()); $m = new Request('POST', '/'); $b->applyRequestHeaders($m); $this->assertContains('multipart/form-data', $m->getHeader('Content-Type')); $this->assertTrue($m->hasHeader('Content-Length')); $contents = $b->getContents(); $this->assertContains('name="a"', $contents); $this->assertContains('b&c=d', $contents); }
/** * Get the deployment status from the server. * @return mixed|void * @throws ServerException */ public function status() { $url = $this->config->get('remote.endpoint') . '?cmd=status'; $config = $this->getRequestConfig(); try { $body = new PostBody(); $body->setField('config', json_encode($config)); $request = $this->getClient()->createRequest('POST', $url, ['headers' => $this->getHeaders(), 'body' => $body]); $response = $this->getClient()->send($request); return json_decode($response->getBody()->getContents(), true); } catch (ClientException $e) { throw new ServerException("Status error: " . $this->parseClientError($e), 0, $e); } }
public function testDoesNotOverwriteExistingHeaderForUrlencoded() { $m = new Request('POST', 'http://foo.com', ['content-type' => 'application/x-www-form-urlencoded; charset=utf-8']); $b = new PostBody(); $b->setField('foo', 'bar'); $b->applyRequestHeaders($m); $this->assertEquals('application/x-www-form-urlencoded; charset=utf-8', $m->getHeader('Content-Type')); }
public function rename($fileUri, $newFileUri) { $body = new PostBody(); $body->setField('apiKey', $this->apiKey); $body->setField('projectId', $this->projectId); $body->setField('fileUri', $fileUri); $body->setField('newFileUri', $newFileUri); $request = $this->client->createRequest('POST', 'file/rename'); $request->setBody($body); return $this->queueRequest($request); }
public function testMultipartWithBase64Fields() { $b = new PostBody(); $b->setField('foo64', '/xA2JhWEqPcgyLRDdir9WSRi/khpb2Lh3ooqv+5VYoc='); $b->forceMultipartUpload(true); $this->assertEquals(['foo64' => '/xA2JhWEqPcgyLRDdir9WSRi/khpb2Lh3ooqv+5VYoc='], $b->getFields()); $m = new Request('POST', '/'); $b->applyRequestHeaders($m); $this->assertContains('multipart/form-data', (string) $m->getHeader('Content-Type')); $this->assertTrue($m->hasHeader('Content-Length')); $contents = $b->getContents(); $this->assertContains('name="foo64"', $contents); $this->assertContains('/xA2JhWEqPcgyLRDdir9WSRi/khpb2Lh3ooqv+5VYoc=', $contents); }
/** * Makes a cURL HTTP request to the API and returns the response * todo this needs to also handle PUT, POST, DELETE * * @param string $method * @param $path * @param RequestOptions $options * * @throws \Exception * @return string */ private function getHTTPResponse($method, $path, RequestOptions $options = null) { $client = new Client(); // Build body $body = new PostBody(); if ($options) { foreach ($options->getPostParams() as $name => $value) { $body->setField($name, $value); } } // Prepare the request $request = new Request($method, $this->url . $path, [], $body, []); // Get response $response = $client->send($request); $body = json_decode($response->getBody()); if (isset($body->data)) { return $body->data; } else { throw new \Exception('Error calling ' . $method . ' to: ' . $path); } }
/** * Makes a cURL HTTP request to the API and returns the response * * @param string $method * @param string $path * @param array|null $params * @param string|null $apiKey * * @throws \UpliftSocial\SDK\Exceptions\BadRequestException * @throws \UpliftSocial\SDK\Exceptions\UnauthorizedException * @throws \UpliftSocial\SDK\Exceptions\InternalServerException * @throws \UpliftSocial\SDK\Exceptions\UpliftSocialException * @throws \Exception * * @return mixed */ private static function getResponse($method, $path, $params = [], $apiKey = null) { if ($params && !is_array($params)) { throw new BadRequestException('Invalid parameters provided'); } $params = $params ?: []; if (!$apiKey) { if (!isset(self::$apiKey)) { throw new BadRequestException('Please provide an access token with your request'); } $apiKey = self::$apiKey; } $client = new GuzzleClient(['base_url' => self::$apiBase, 'defaults' => ['headers' => self::getAuthHeader($apiKey)]]); $request = $client->createRequest($method, $path); if (self::methodHasBody($method)) { $body = new PostBody(); foreach ($params as $field => $value) { $body->setField($field, $value); } $request->setBody($body); } else { $request->setQuery($params); } // Get response try { $response = $client->send($request); $body = json_decode($response->getBody()); if (isset($body->data)) { if ($body->messages == 'error') { self::handleResponseError($body); } return $body->data; } } catch (BadResponseException $e) { $message = sprintf("Uplift API: %s\nPath: %s\nMethod: %s\nResponse:\n%s\nRequest:\n%s", $e->getResponse()->getStatusCode(), $path, $method, $e->getResponse()->getBody(), $params ? 'Body: ' . json_encode($params, JSON_PRETTY_PRINT) . '. ' : 'null'); throw new InternalServerException($message); } throw new \Exception('Error calling ' . $method . ' to: ' . $path); }
/** * @param string $name * @param array|string $value * * @return $this */ public function setPostBodyField($name, $value) { $this->postBody->setField($name, $value); return $this; }
/** * Apply POST fields and files to a request to attempt to give an accurate * representation. * * @param RequestInterface $request Request to update * @param array $body Body to apply */ protected function addPostData(RequestInterface $request, array $body) { static $fields = ['string' => true, 'array' => true, 'NULL' => true, 'boolean' => true, 'double' => true, 'integer' => true]; $post = new PostBody(); foreach ($body as $key => $value) { if (isset($fields[gettype($value)])) { $post->setField($key, $value); } elseif ($value instanceof PostFileInterface) { $post->addFile($value); } else { $post->addFile(new PostFile($key, $value)); } } if ($request->getHeader('Content-Type') == 'multipart/form-data') { $post->forceMultipartUpload(true); } $request->setBody($post); }
/** * Apply POST fields and files to a request to attempt to give an accurate * representation. * * @param RequestInterface $request Request to update * @param array $body Body to apply */ protected function addPostData(RequestInterface $request, array $body) { static $fields = ['string' => true, 'array' => true, 'NULL' => true, 'boolean' => true, 'double' => true, 'integer' => true]; $post = new PostBody(); foreach ($body as $key => $value) { if (isset($fields[gettype($value)])) { $post->setField($key, $value); } elseif ($value instanceof PostFileInterface) { $post->addFile($value); } else { $post->addFile(new PostFile($key, $value)); } } $request->setBody($post); }
/** * Upload a file to the Library. Must be one of PNG, JPG, JPEG, GIF, or PDF. * The server scans files for viruses, so this returns an ID for a FileUploadStatus. * @param string $accessToken - Constant Contact Oauth2 Access Token * @param string $fileName - Name of the file * @param string $fileLocation - Path to the location of the file on the server * @throws IllegalArgumentException if file type is not one listed in the description * @param string $description - Description of the file * @param string $source - Source * @param string $folderId - Folder ID to upload file to. Set as 0 for no folder. * @return string File upload status ID * @throws CtctException */ public function uploadFile($accessToken, $fileName, $fileLocation, $description, $source, $folderId) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime = finfo_file($finfo, $fileLocation); finfo_close($finfo); if ($mime == "image/png") { $fileType = "PNG"; } elseif ($mime = "image/jpeg") { $fileType = "JPG"; } elseif ($mime = "image/gif") { $fileType = "GIF"; } elseif ($mime = "application/pdf") { $fileType = "PDF"; } else { throw new IllegalArgumentException(sprintf(Config::get('errors.file_extension'), "PNG, JPG, JPEG, GIF, PDF was " . $mime)); } $baseUrl = Config::get('endpoints.base_url') . Config::get('endpoints.library_files'); $request = parent::createBaseRequest($accessToken, "POST", $baseUrl); $request->setHeader("Content-Type", "multipart/form-data"); $body = new PostBody(); $body->setField("folderId", $folderId); $body->setField("file_name", $fileName); $body->setField("file_type", $fileType); $body->setField("description", $description); $body->setField("source", $source); $body->addFile(new PostFile("data", fopen($fileLocation, 'r'), $fileName)); $request->setBody($body); try { $response = parent::getClient()->send($request); } catch (ClientException $e) { throw parent::convertException($e); } return $response->getHeader("Id"); }
/** * Create a Remove Contacts Activity from a file. Valid file types are txt, csv, xls, xlsx * @param string $accessToken - Constant Contact OAuth2 access token * @param string $fileName - The name of the file (ie: contacts.csv) * @param string $fileLocation - The location of the file on the server, this method uses fopen() * @param string $lists - Comma separated list of ContactList id's to add the contacts to * @return Activity * @throws CtctException */ public function addRemoveContactsFromListsActivityFromFile($accessToken, $fileName, $fileLocation, $lists) { $baseUrl = Config::get('endpoints.base_url') . Config::get('endpoints.remove_from_lists_activity'); $request = parent::createBaseRequest($accessToken, "POST", $baseUrl); $request->setHeader("Content-Type", "multipart/form-data"); $body = new PostBody(); $body->setField("lists", $lists); $body->setField("file_name", $fileName); $body->addFile(new PostFile("data", fopen($fileLocation, 'r'), $fileName)); $request->setBody($body); try { $response = parent::getClient()->send($request); } catch (ClientException $e) { throw parent::convertException($e); } return Activity::create($response->json()); }
/** * Get the "body" payload field for the Guzzle request. * * @param Swift_Mime_Message $message * @return PostBody */ protected function getBody(Swift_Mime_Message $message) { $body = new PostBody(); $body->setField('from', $this->getFrom($message)); $body->setField('to', $this->getTo($message)); $body->setField('subject', $message->getSubject()); $messageHtml = $message->getBody(); if ($message->getChildren()) { foreach ($message->getChildren() as $child) { if (str_contains($messageHtml, $child->getId())) { $messageHtml = str_replace($child->getId(), $child->getFilename(), $messageHtml); $body->addFile(new PostFile('inlineattachment', $child->getBody(), $child->getFilename(), ['Content-Type' => $child->getContentType()])); } else { switch (get_class($child)) { case 'Swift_Attachment': case 'Swift_Image': $body->addFile(new PostFile('attachment', $child->getBody(), $child->getFilename(), ['Content-Type' => $child->getContentType()])); break; case 'Swift_MimePart': switch ($child->getContentType()) { case 'text/plain': $body->setField('text', $child->getBody()); break; } break; } } } } $body->setField('html', $messageHtml); return $body; }
/** * Send a new request. * * @return $this */ protected function sendRequest() { // Setup the basi settings. $httpClient = new Client(['timeout' => $this->config->getConnectionTimeout()]); $requestType = 'GET'; $request = null; $options = array('headers' => array('User-Agent' => "\n Mozilla/5.0\n (compatible; CtoCommunication RequestExtended on Contao " . VERSION . "." . BUILD . ";\n rv:1.0);\n CtoCommunication RPC (ctoComV" . $GLOBALS["CTOCOM_VERSION"] . ")", 'Accept-Language' => vsprintf("%s, en;q=0.8", array($GLOBALS['TL_LANGUAGE'])), 'Accept' => 'text/plain; q=0.5, text/html')); // Add the user auth if set. if ($this->client->hasHttpAuth()) { $options['auth'] = [$this->client->getHttpUser(), $this->client->getHttpPassword()]; } if ($this->isGetRequest) { // Only get. // Build the array with the query params. $query = array(); foreach ($this->data as $key => $value) { $query[$value["name"]] = $value["value"]; } // Add to the options. $options = array_merge_recursive($options, array('query' => $query)); } else { // Create a new post body and add all form fields. $postBody = new PostBody(); foreach ($this->data as $key => $value) { if (isset($value["filename"]) == true && strlen($value["filename"]) != 0) { $postBody->addFile(new PostFile($value["name"], fopen($value["filepath"], 'r'), basename($value["filepath"]), array('contentType' => $value["mime"], 'encoding' => 'binary'))); } else { $postBody->setField($value["name"], $this->objIOEngine->OutputPost($value["value"], $this->objCodifyengine)); } } // Create a new request for post. $requestType = 'POST'; $options = array_merge_recursive($options, array('body' => $postBody)); } // create a new request. $request = $httpClient->createRequest($requestType, $this->client->getUrl() . $this->getQueryString(), $options); // Send the request. $this->request = $httpClient->send($request); return $this; }
protected function getRequest() { $body = new PostBody(); $body->setField('e', 'f'); return new Request('POST', 'http://www.test.com/path?a=b&c=d', [], $body); }
public function testCreatesMultipartUploadWithMultiFields() { $b = new PostBody(); $b->setField('testing', ['baz', 'bar']); $b->addFile(new PostFile('foo', fopen(__FILE__, 'r'))); $s = (string) $b; $this->assertContains(file_get_contents(__FILE__), $s); $this->assertContains('testing=bar', $s); }