+ if (intval($res->getStatus() / 100) != 2) {
+ $this->displayErrorResponse($res);
+ }
+ return $res;
+ }
+
+ protected function displayErrorResponse($res)
+ {
+ Log::err(
+ 'Server returned an error status code ' . $res->getStatus()
+ );
+
+ $shown = false;
+ if ($res->getHeader('content-type') == 'application/json') {
+ $errData = json_decode($res->getBody());
+ if (!isset($errData->error)) {
+ Log::err('Error response does not contain "error" property');
+ } else if (isset($errData->error_description)) {
+ Log::err($errData->error . ': ' . $errData->error_description);
+ $shown = true;
+ } else {
+ Log::err($errData->error);
+ $shown = true;
+ }
+ }
+
+ if (!$shown) {
+ Log::err($res->getBody());
+ }
+ exit(11);
+ }
+
+ public function setAction($action)
+ {
+ $this->action = $action;
+ }
+
+ public function setType($type)
+ {
+ $this->type = $type;
+ }
+
+ public function setUrl($url)
+ {
+ $this->url = $url;
+ }
+
+ /**
+ * @param string $fieldName name of file-upload field
+ * @param array $fileNames list of local file paths
+ */
+ public function addUpload($fieldName, $fileNames)
+ {
+ if ($this->host->endpoints->media === null
+ || $this->directUpload
+ ) {
+ if ($this->sendAsJson) {
+ throw new \Exception(
+ 'No media endpoint available, which is required for JSON'
+ );
+ }
+ if (count($fileNames) == 1) {
+ $fileNames = reset($fileNames);
+ }
+ $this->uploadsInfo[$fieldName] = $fileNames;
+ return $this->req->addUpload($fieldName, $fileNames);
+ }
+
+ $urls = [];
+ foreach ($fileNames as $fileName) {
+ $urls[] = $this->uploadToMediaEndpoint($fileName);
+ }
+ if (count($urls) == 1) {
+ $urls = reset($urls);
+ }
+ $this->addProperty($fieldName, $urls);
+ }
+
+ /**
+ * @return string URL at media endpoint
+ */
+ public function uploadToMediaEndpoint($fileName)
+ {
+ $httpReq = $this->getHttpRequest(
+ $this->host->endpoints->media, $this->host->token
+ );
+ $httpReq->addUpload('file', $fileName);
+
+ if ($this->cfg->debug) {
+ $cp = new CurlPrinter();
+ $cp->show($httpReq, ['file' => $fileName]);
+ }
+ $res = $httpReq->send();