Upload costs

@param array $costs costs array

@throws \InvalidArgumentException
@throws \RetailCrm\Exception\CurlException
@throws \RetailCrm\Exception\InvalidJsonException

@return \RetailCrm\Response\ApiResponse
508937
public function costsUpload($costs)
    {
        if (!count($costs)) {
            throw new \InvalidArgumentException(
                'Parameter `costs` must contains a data'
            );
        }

        /* @noinspection PhpUndefinedMethodInspection */
        return $this->client->makeRequest(
            '/costs/upload',
            "POST",
            ['costs' => json_encode($costs)]
        );
    }
1203723
protected function uploadFile($options)
    {
        // If upload path not specified InvalidArgumentException will throw.
        if (!(isset($this->fileInfo['params']['destination'])
            && !empty($this->fileInfo['params']['destination']))
        ) {
            $this->error[] = 'Upload path required';

            return false;
        }

        if (isset($this->fileInfo['file']['name'])) {
            $this->setPathInfo();
        }

        if (isset($this->filePathInfo['extension'])) {

            // If invalid file uploaded return collect error.
            if (
            !in_array(
                strtolower($this->filePathInfo['extension']),
                array_map('strtolower', $this->fileInfo['ext'])
            )
            ) {
                $this->error[] = 'Invalid file format. Valid file format: '.implode(',', $this->fileInfo['ext']);

                return false;
            }
        }

        if (isset($this->fileInfo['file']['size']) &&
            $this->fileInfo['file']['size'] <= $this->getNumericfileSize($this->fileInfo['size'])
        ) {
            $path = str_replace(
                '/',
                DS,
                $this->getRootDir().DS.$this->fileInfo['params']['destination'].DS.$this->getFileName($options)
            );
            
            if (!is_writable($path)) {
                $this->error[] = "$path should exists and must be writable.";

                return false;
            }

            if (!is_writable($path)) {
                $this->error[] = "$path should exists and must be writable.";

                return false;
            }

            try {
                if (move_uploaded_file($this->fileInfo['file']['tmp_name'], $path) === true) {
                    return true;
                }
            } catch (\ErrorException $e) {
                // If file was not uploaded we will catch error.
                $this->error[] = $e->getMessage();

                return false;
            }
        } else {
            // If file size was too large  OutofRange exception will throw.
            $this->error[] =
                $this->fileInfo['file']['name'].' is too large.Exceeds upload limit '.$this->fileInfo['size'];

            return false;
        }
    }
175896
def get_shipping_costs(params)
      raise ArgumentError unless params[:ItemID]
      response = get_json_response(build_request_url('GetShippingCosts', params))
      return response
    end
548156
public function uploadContext(UploadContextParameters $params)
    {
        $requestData = $this->getDefaultRequestData('multipart', $params->exportToArray());

        return $this->sendRequest('contexts', $requestData, self::HTTP_METHOD_POST);
    }
1097087
public function sendRequests(array $requests)
    {
        $responses = $exceptions = [];

        foreach ($requests as $index => &$request) {
            if (is_string($request)) {
                $request = [$request];
            }

            if (is_array($request)) {
                $request = call_user_func_array(
                    [$this->getConfiguration()->getMessageFactory(), 'createInternalRequest'],
                    $request
                );
            }

            if (!$request instanceof RequestInterface) {
                $exceptions[] = HttpAdapterException::requestIsNotValid($request);
                unset($requests[$index]);
            } elseif (!$request instanceof InternalRequestInterface) {
                $request = $this->getConfiguration()->getMessageFactory()->createInternalRequest(
                    $request->getUri(),
                    $request->getMethod(),
                    $request->getProtocolVersion(),
                    $request->getHeaders(),
                    $request->getBody()
                );
            }
        }

        $success = function (ResponseInterface $response) use (&$responses) {
            $responses[] = $response;
        };

        $error = function (HttpAdapterException $exception) use (&$exceptions) {
            $exceptions[] = $exception;
        };

        $this->sendInternalRequests($requests, $success, $error);

        if (!empty($exceptions)) {
            throw new MultiHttpAdapterException($exceptions, $responses);
        }

        return $responses;
    }
582955
public static function build(array $array) {
        if (array_key_exists("type", $array) && in_array($array["type"], self::$availableTypes)) {
            switch ($array["type"]) {
                case Payment::TYPE_CREDIT:
                    return new CreditCard($array);
                    break;

                case Payment::TYPE_BOLETO:
                    return new Boleto($array);
                    break;

                case Payment::TYPE_DEBIT:
                case Payment::TYPE_TRANSFER:
                case Payment::TYPE_VOUCHER:
                    return new Payment($array);
                    break;

                default:  // Exception
            }
        }
        throw new \InvalidArgumentException("Array must contain a valid 'type' field");
    }
216232
public function handle($files)
    {
        if (is_array($files)) {
            return $this->handleMultipleFiles($files);
        }
        if (is_object($files)) {
            return $this->handleSingleFile($files);
        }
        throw new \Exception("Dados inválidos para upload");
    }
1356881
public function request($inputs)
    {
        $result = $this->restCall('PaymentRequest.json', $inputs);

        if ($result['Status'] == 100 || $result['Status'] == 101) {
            return ['Authority' => $result['Authority']];
        } else {
            return ['error' => $result['Status']];
        }
    }
1131870
public function createTransaction(array $params)
    {
        $this->sdk->Send = array_merge($this->sdk->Send, [
            'MerchantTradeNo' => '',
            'MerchantTradeDate' => date('Y/m/d H:i:s'),
            'LogisticsType' => '',
            'LogisticsSubType' => LogisticsSubType::UNIMART,
            'GoodsAmount' => 0,
            'CollectionAmount' => 0,
            'IsCollection' => IsCollection::NO,
            'GoodsName' => '',
            'SenderName' => '',
            'SenderPhone' => '',
            'SenderCellPhone' => '',
            'ReceiverName' => '',
            'ReceiverPhone' => '',
            'ReceiverCellPhone' => '',
            'ReceiverEmail' => '',
            'TradeDesc' => '',
            'ServerReplyURL' => '',
            'LogisticsC2CReplyURL' => '',
            'Remark' => '',
            'PlatformID' => '',
        ]);

        $this->sdk->SendExtend = [];

        $this->sdk->Send = array_replace(
            $this->sdk->Send,
            array_intersect_key($params, $this->sdk->Send)
        );

        $this->sdk->Send['GoodsAmount'] = (int) $this->sdk->Send['GoodsAmount'];
        $this->sdk->Send['CollectionAmount'] = (int) $this->sdk->Send['CollectionAmount'];

        if (empty($this->sdk->Send['LogisticsType']) === true) {
            $this->sdk->Send['LogisticsType'] = LogisticsType::CVS;
            switch ($this->sdk->Send['LogisticsSubType']) {
                case LogisticsSubType::TCAT:
                    $this->sdk->Send['LogisticsType'] = LogisticsType::HOME;
                    break;
            }
        }

        if ($this->sdk->Send['IsCollection'] === IsCollection::NO) {
            $this->sdk->Send['CollectionAmount'] = 0;
        } elseif (isset($this->sdk->Send['CollectionAmount']) === false) {
            $this->sdk->Send['CollectionAmount'] = (int) $this->sdk->Send['GoodsAmount'];
        }

        switch ($this->sdk->Send['LogisticsType']) {
            case LogisticsType::HOME:
                $this->sdk->SendExtend = array_merge($this->sdk->SendExtend, [
                    'SenderZipCode' => '',
                    'SenderAddress' => '',
                    'ReceiverZipCode' => '',
                    'ReceiverAddress' => '',
                    'Temperature' => '',
                    'Distance' => '',
                    'Specification' => '',
                    'ScheduledDeliveryTime' => '',
                ]);
                break;
            case LogisticsType::CVS:
                $this->sdk->SendExtend = array_merge($this->sdk->SendExtend, [
                    'ReceiverStoreID' => '',
                    'ReturnStoreID' => '',
                ]);
                break;
        }

        $this->sdk->SendExtend = array_replace(
            $this->sdk->SendExtend,
            array_intersect_key($params, $this->sdk->SendExtend)
        );

        return $this->sdk->BGCreateShippingOrder();
    }
153573
public function priceRule(array &$submitted, array $options = array())
    {
        $this->options = $options;
        $this->submitted = &$submitted;

        $this->validatePriceRule();
        $this->validateName();
        $this->validateWeight();
        $this->validateBool('status');
        $this->validateUsedPriceRule();
        $this->validateTriggerPriceRule();
        $this->validateCurrencyPriceRule();
        $this->validateValueTypePriceRule();
        $this->validateCodePriceRule();
        $this->validateValuePriceRule();

        $this->unsetSubmitted('update');

        return $this->getResult();
    }
61424
public function upload(array $options)
    {
        // Clean the path if it starts with /.
        if (substr($options['FileName'], 0, 1) === '/') {
            $options['FileName'] = ltrim($options['FileName'], '/');
        }

        if (!isset($options['BucketId']) && isset($options['BucketName'])) {
            $options['BucketId'] = $this->getBucketIdFromName($options['BucketName']);
        }

        // Retrieve the URL that we should be uploading to.
        $response = $this->client->request('POST', $this->apiUrl.'/b2_get_upload_url', [
            'headers' => [
                'Authorization' => $this->authToken
            ],
            'json' => [
                'bucketId' => $options['BucketId']
            ]
        ]);

        $uploadEndpoint = $response['uploadUrl'];
        $uploadAuthToken = $response['authorizationToken'];

        if (is_resource($options['Body'])) {
            // We need to calculate the file's hash incrementally from the stream.
            $context = hash_init('sha1');
            hash_update_stream($context, $options['Body']);
            $hash = hash_final($context);

            // Similarly, we have to use fstat to get the size of the stream.
            $size = fstat($options['Body'])['size'];
            
            // Rewind the stream before passing it to the HTTP client.
            rewind($options['Body']);
        } else {
            // We've been given a simple string body, it's super simple to calculate the hash and size.
            $hash = sha1($options['Body']);
            $size = mb_strlen($options['Body']);
        }

        if (!isset($options['FileLastModified'])) {
            $options['FileLastModified'] = round(microtime(true) * 1000);
        }

        if (!isset($options['FileContentType'])) {
            $options['FileContentType'] = 'b2/x-auto';
        }

        $response = $this->client->request('POST', $uploadEndpoint, [
            'headers' => [
                'Authorization' => $uploadAuthToken,
                'Content-Type' => $options['FileContentType'],
                'Content-Length' => $size,
                'X-Bz-File-Name' => $options['FileName'],
                'X-Bz-Content-Sha1' => $hash,
                'X-Bz-Info-src_last_modified_millis' => $options['FileLastModified']
            ],
            'body' => $options['Body']
        ]);

        return new File(
            $response['fileId'],
            $response['fileName'],
            $response['contentSha1'],
            $response['contentLength'],
            $response['contentType'],
            $response['fileInfo']
        );
    }
549423
public function post(array $guests): array
    {
        $options = ['json' => ['guests' => $guests]];

        /** @var JsonStream $stream */
        $stream = $this->client
            ->post(KintoneApi::generateUrl('guests.json'), $options)
            ->getBody();

        return $stream->jsonSerialize();
    }
1041069
public function createUploadedFilesFromArray(array $files)
    {
        $uploadedFiles = [];

        if (isset($files['tmp_name']) && ! is_array($files['tmp_name'])) {
            $uploadedFiles[] = $this->createUploadedFile(
                $files['tmp_name'],
                $files['size'],
                $files['error'],
                $files['name'],
                $files['type']
            );
        } elseif (isset($files['tmp_name']) && is_array($files['tmp_name'])) {
            foreach ($files['tmp_name'] as $key => $file) {
                $uploadedFiles[] = $this->createUploadedFile(
                    $file,
                    $files['size'][$key],
                    $files['error'][$key],
                    $files['name'][$key],
                    $files['type'][$key]
                );
            }
        } else {
            foreach ($files as $key => $value) {
                $uploadedFiles[$key] = $this->createUploadedFilesFromArray($value);
            }
        }

        return $uploadedFiles;
    }
514221
private static function normaliseUplaod(array $files)
    {
        $output = [];
        foreach ($files as $key => $value) {
            if ($value instanceof UploadedFileInterface) {
                $output[ $key ] = $value;
            } elseif (is_array($value) && isset($value[ 'tmp_name' ])) {
                $output[ $key ] = UploadedFile::create($value);
            } elseif (is_array($value)) {
                $output[ $key ] = self::normaliseUplaod($value);
            } else {
                throw new \InvalidArgumentException('The input parameter is not in the correct format.');
            }
        }

        return $output;
    }
1158164
public function upload()
        {
            $files = $this->getFiles();
            $response = [];
            $types = new ImageUploadTypes();
            foreach($files as $file){

                if(!$file instanceof ImageUpload)
                {
                    $file = new ImageUpload($file);
                    $file->setAllowedMimeTypes($types->getImageMimeTypes());
                    $file->setAllowedExt($types->getImageTypeExt(), ['.php']);
                }

                $response[] = $file->upload();
            }

            return $response;
        }
490661
public static function create(array $file)
    {
        if (!isset($file[ 'tmp_name' ])) {
            throw new \InvalidArgumentException('The tmp_name key is required.');
        }

        return new UploadedFile(
            $file[ 'tmp_name' ],
            isset($file[ 'name' ])
            ? $file[ 'name' ]
            : null,
            isset($file[ 'size' ])
            ? $file[ 'size' ]
            : null,
            isset($file[ 'type' ])
            ? $file[ 'type' ]
            : null,
            isset($file[ 'error' ])
            ? $file[ 'error' ]
            : UPLOAD_ERR_OK
        );
    }
1194648
public function upload()
    {
        $myConfig = \OxidEsales\Eshop\Core\Registry::getConfig();

        if ($myConfig->isDemoShop()) {
            $oEx = oxNew(\OxidEsales\Eshop\Core\Exception\ExceptionToDisplay::class);
            $oEx->setMessage('ARTICLE_EXTEND_UPLOADISDISABLED');
            \OxidEsales\Eshop\Core\Registry::getUtilsView()->addErrorToDisplay($oEx, false);

            return;
        }

        $soxId = $this->getEditObjectId();

        $aParams = \OxidEsales\Eshop\Core\Registry::getConfig()->getRequestParameter("newfile");
        $aParams = $this->_processOptions($aParams);
        $aNewFile = \OxidEsales\Eshop\Core\Registry::getConfig()->getUploadedFile("newArticleFile");

        //uploading and processing supplied file
        $oArticleFile = oxNew(\OxidEsales\Eshop\Application\Model\File::class);
        $oArticleFile->assign($aParams);

        if (!$aNewFile['name'] && !$oArticleFile->oxfiles__oxfilename->value) {
            return \OxidEsales\Eshop\Core\Registry::getUtilsView()->addErrorToDisplay('EXCEPTION_NOFILE');
        }

        if ($aNewFile['name']) {
            $oArticleFile->oxfiles__oxfilename = new \OxidEsales\Eshop\Core\Field($aNewFile['name'], \OxidEsales\Eshop\Core\Field::T_RAW);
            try {
                $oArticleFile->processFile('newArticleFile');
            } catch (Exception $e) {
                return \OxidEsales\Eshop\Core\Registry::getUtilsView()->addErrorToDisplay($e->getMessage());
            }
        }

        if (!$oArticleFile->isUnderDownloadFolder()) {
            return \OxidEsales\Eshop\Core\Registry::getUtilsView()->addErrorToDisplay('EXCEPTION_NOFILE');
        }

        //save media url
        $oArticleFile->oxfiles__oxartid = new \OxidEsales\Eshop\Core\Field($soxId, \OxidEsales\Eshop\Core\Field::T_RAW);
        $oArticleFile->save();
    }