_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q244500 | ShopOrderTrait.placeTransaction | validation | public function placeTransaction($gateway, $transactionId, $detail = null, $token = null)
{
return call_user_func(Config::get('shop.transaction') . '::create', [
'order_id' => $this->attributes['id'],
'gateway' => $gateway,
'transaction_id' => $transactionId,
'detail' => $detail,
'token' => $token,
]);
} | php | {
"resource": ""
} |
q244501 | CallbackController.process | validation | protected function process(Request $request)
{
$validator = Validator::make(
[
'order_id' => $request->get('order_id'),
'status' => $request->get('status'),
'shoptoken' => $request->get('shoptoken'),
],
[
'order_id' => 'required|exists:' . config('shop.order_table') . ',id',
'status' => 'required|in:success,fail',
'shoptoken' => 'required|exists:' . config('shop.transaction_table') . ',token,order_id,' . $request->get('order_id'),
]
);
if ($validator->fails()) {
abort(404);
}
$order = call_user_func(config('shop.order') . '::find', $request->get('order_id'));
$transaction = $order->transactions()->where('token', $request->get('shoptoken'))->first();
Shop::callback($order, $transaction, $request->get('status'), $request->all());
$transaction->token = null;
$transaction->save();
return redirect()->route(config('shop.callback_redirect_route'), ['orderId' => $order->id]);
} | php | {
"resource": ""
} |
q244502 | LaravelShop.placeOrder | validation | public static function placeOrder($cart = null)
{
try {
if (empty(static::$gatewayKey))
throw new ShopException('Payment gateway not selected.');
if (empty($cart)) $cart = Auth::user()->cart;
$order = $cart->placeOrder();
$statusCode = $order->statusCode;
\event(new OrderPlaced($order->id));
static::$gateway->setCallbacks($order);
if (static::$gateway->onCharge($order)) {
$order->statusCode = static::$gateway->getTransactionStatusCode();
$order->save();
// Create transaction
$order->placeTransaction(
static::$gatewayKey,
static::$gateway->getTransactionId(),
static::$gateway->getTransactionDetail(),
static::$gateway->getTransactionToken()
);
// Fire event
if ($order->isCompleted)
\event(new OrderCompleted($order->id));
} else {
$order->statusCode = 'failed';
$order->save();
}
} catch (ShopException $e) {
static::setException($e);
if (isset($order)) {
$order->statusCode = 'failed';
$order->save();
// Create failed transaction
$order->placeTransaction(
static::$gatewayKey,
uniqid(),
static::$exception->getMessage(),
$order->statusCode
);
}
} catch (GatewayException $e) {
static::$exception = $e;
if (isset($order)) {
$order->statusCode = 'failed';
$order->save();
// Create failed transaction
$order->placeTransaction(
static::$gatewayKey,
uniqid(),
static::$exception->getMessage(),
$order->statusCode
);
}
}
if ($order) {
static::checkStatusChange($order, $statusCode);
return $order;
} else {
return;
}
} | php | {
"resource": ""
} |
q244503 | LaravelShop.callback | validation | public static function callback($order, $transaction, $status, $data = null)
{
$statusCode = $order->statusCode;
try {
if (in_array($status, ['success', 'fail'])) {
static::$gatewayKey = $transaction->gateway;
static::$gateway = static::instanceGateway();
if ($status == 'success') {
static::$gateway->onCallbackSuccess($order, $data);
$order->statusCode = static::$gateway->getTransactionStatusCode();
// Create transaction
$order->placeTransaction(
static::$gatewayKey,
static::$gateway->getTransactionId(),
static::$gateway->getTransactionDetail(),
static::$gateway->getTransactionToken()
);
// Fire event
if ($order->isCompleted)
\event(new OrderCompleted($order->id));
} else if ($status == 'fail') {
static::$gateway->onCallbackFail($order, $data);
$order->statusCode = 'failed';
}
$order->save();
}
} catch (ShopException $e) {
static::setException($e);
$order->statusCode = 'failed';
$order->save();
} catch (GatewayException $e) {
static::setException($e);
$order->statusCode = 'failed';
$order->save();
}
static::checkStatusChange($order, $statusCode);
} | php | {
"resource": ""
} |
q244504 | LaravelShop.format | validation | public static function format($value)
{
return preg_replace(
[
'/:symbol/',
'/:price/',
'/:currency/'
],
[
Config::get('shop.currency_symbol'),
$value,
Config::get('shop.currency')
],
Config::get('shop.display_price_format')
);
} | php | {
"resource": ""
} |
q244505 | LaravelShop.checkStatusChange | validation | protected static function checkStatusChange($order, $prevStatusCode)
{
if (!empty($prevStatusCode) && $order->statusCode != $prevStatusCode)
\event(new OrderStatusChanged($order->id, $order->statusCode, $prevStatusCode));
} | php | {
"resource": ""
} |
q244506 | SerializeFormatter.preserveLines | validation | protected function preserveLines($data, bool $reverse)
{
$search = ["\n", "\r"];
$replace = ['\\n', '\\r'];
if ($reverse) {
$search = ['\\n', '\\r'];
$replace = ["\n", "\r"];
}
if (is_string($data)) {
$data = str_replace($search, $replace, $data);
} elseif (is_array($data)) {
foreach ($data as &$value) {
$value = $this->preserveLines($value, $reverse);
}
unset($value);
}
return $data;
} | php | {
"resource": ""
} |
q244507 | Database.getPath | validation | public function getPath(): string
{
return $this->config->getDir() . $this->getName() . $this->config->getExt();
} | php | {
"resource": ""
} |
q244508 | Database.openFile | validation | protected function openFile(int $mode): SplFileObject
{
$path = $this->getPath();
if (!is_file($path) && !@touch($path)) {
throw new Exception('Could not create file: ' . $path);
}
if (!is_readable($path) || !is_writable($path)) {
throw new Exception('File does not have permission for read and write: ' . $path);
}
if ($this->getConfig()->useGzip()) {
$path = 'compress.zlib://' . $path;
}
$res = $this->fileAccessMode[$mode];
$file = new SplFileObject($path, $res['mode']);
if ($mode === self::FILE_READ) {
$file->setFlags(SplFileObject::DROP_NEW_LINE | SplFileObject::SKIP_EMPTY | SplFileObject::READ_AHEAD);
}
if (!$this->getConfig()->useGzip() && !$file->flock($res['operation'])) {
$file = null;
throw new Exception('Could not lock file: ' . $path);
}
return $file;
} | php | {
"resource": ""
} |
q244509 | Database.closeFile | validation | protected function closeFile(SplFileObject &$file)
{
if (!$this->getConfig()->useGzip() && !$file->flock(LOCK_UN)) {
$file = null;
throw new Exception('Could not unlock file');
}
$file = null;
} | php | {
"resource": ""
} |
q244510 | Database.readFromFile | validation | public function readFromFile(): \Generator
{
$file = $this->openFile(static::FILE_READ);
try {
foreach ($file as $line) {
yield new Line($line);
}
} finally {
$this->closeFile($file);
}
} | php | {
"resource": ""
} |
q244511 | Database.appendToFile | validation | public function appendToFile(string $line)
{
$file = $this->openFile(static::FILE_APPEND);
$file->fwrite($line);
$this->closeFile($file);
} | php | {
"resource": ""
} |
q244512 | Database.writeTempToFile | validation | public function writeTempToFile(SplTempFileObject &$tmpFile)
{
$file = $this->openFile(static::FILE_WRITE);
foreach ($tmpFile as $line) {
$file->fwrite($line);
}
$this->closeFile($file);
$tmpFile = null;
} | php | {
"resource": ""
} |
q244513 | Flintstone.setConfig | validation | public function setConfig(Config $config)
{
$this->config = $config;
$this->getDatabase()->setConfig($config);
} | php | {
"resource": ""
} |
q244514 | Flintstone.get | validation | public function get(string $key)
{
Validation::validateKey($key);
// Fetch the key from cache
if ($cache = $this->getConfig()->getCache()) {
if ($cache->contains($key)) {
return $cache->get($key);
}
}
// Fetch the key from database
$file = $this->getDatabase()->readFromFile();
$data = false;
foreach ($file as $line) {
/** @var Line $line */
if ($line->getKey() == $key) {
$data = $this->decodeData($line->getData());
break;
}
}
// Save the data to cache
if ($cache && $data !== false) {
$cache->set($key, $data);
}
return $data;
} | php | {
"resource": ""
} |
q244515 | Flintstone.set | validation | public function set(string $key, $data)
{
Validation::validateKey($key);
// If the key already exists we need to replace it
if ($this->get($key) !== false) {
$this->replace($key, $data);
return;
}
// Write the key to the database
$this->getDatabase()->appendToFile($this->getLineString($key, $data));
// Delete the key from cache
if ($cache = $this->getConfig()->getCache()) {
$cache->delete($key);
}
} | php | {
"resource": ""
} |
q244516 | Flintstone.delete | validation | public function delete(string $key)
{
Validation::validateKey($key);
if ($this->get($key) !== false) {
$this->replace($key, false);
}
} | php | {
"resource": ""
} |
q244517 | Flintstone.flush | validation | public function flush()
{
$this->getDatabase()->flushFile();
// Flush the cache
if ($cache = $this->getConfig()->getCache()) {
$cache->flush();
}
} | php | {
"resource": ""
} |
q244518 | Flintstone.getKeys | validation | public function getKeys(): array
{
$keys = [];
$file = $this->getDatabase()->readFromFile();
foreach ($file as $line) {
/** @var Line $line */
$keys[] = $line->getKey();
}
return $keys;
} | php | {
"resource": ""
} |
q244519 | Flintstone.getAll | validation | public function getAll(): array
{
$data = [];
$file = $this->getDatabase()->readFromFile();
foreach ($file as $line) {
/** @var Line $line */
$data[$line->getKey()] = $this->decodeData($line->getData());
}
return $data;
} | php | {
"resource": ""
} |
q244520 | Flintstone.replace | validation | protected function replace(string $key, $data)
{
// Write a new database to a temporary file
$tmpFile = $this->getDatabase()->openTempFile();
$file = $this->getDatabase()->readFromFile();
foreach ($file as $line) {
/** @var Line $line */
if ($line->getKey() == $key) {
if ($data !== false) {
$tmpFile->fwrite($this->getLineString($key, $data));
}
} else {
$tmpFile->fwrite($line->getLine() . "\n");
}
}
$tmpFile->rewind();
// Overwrite the database with the temporary file
$this->getDatabase()->writeTempToFile($tmpFile);
// Delete the key from cache
if ($cache = $this->getConfig()->getCache()) {
$cache->delete($key);
}
} | php | {
"resource": ""
} |
q244521 | Config.normalizeConfig | validation | protected function normalizeConfig(array $config): array
{
$defaultConfig = [
'dir' => getcwd(),
'ext' => '.dat',
'gzip' => false,
'cache' => true,
'formatter' => null,
'swap_memory_limit' => 2097152, // 2MB
];
return array_replace($defaultConfig, $config);
} | php | {
"resource": ""
} |
q244522 | Config.setDir | validation | public function setDir(string $dir)
{
if (!is_dir($dir)) {
throw new Exception('Directory does not exist: ' . $dir);
}
$this->config['dir'] = rtrim($dir, '/\\') . DIRECTORY_SEPARATOR;
} | php | {
"resource": ""
} |
q244523 | Config.setExt | validation | public function setExt(string $ext)
{
if (substr($ext, 0, 1) !== '.') {
$ext = '.' . $ext;
}
$this->config['ext'] = $ext;
} | php | {
"resource": ""
} |
q244524 | Config.setCache | validation | public function setCache($cache)
{
if (!is_bool($cache) && !$cache instanceof CacheInterface) {
throw new Exception('Cache must be a boolean or an instance of Flintstone\Cache\CacheInterface');
}
if ($cache === true) {
$cache = new ArrayCache();
}
$this->config['cache'] = $cache;
} | php | {
"resource": ""
} |
q244525 | Config.setFormatter | validation | public function setFormatter($formatter)
{
if ($formatter === null) {
$formatter = new SerializeFormatter();
}
if (!$formatter instanceof FormatterInterface) {
throw new Exception('Formatter must be an instance of Flintstone\Formatter\FormatterInterface');
}
$this->config['formatter'] = $formatter;
} | php | {
"resource": ""
} |
q244526 | MapLoader.getSourceContext | validation | public function getSourceContext($name) : Source
{
if (!$this->exists($name)) {
throw new LoaderError(sprintf(
'Unable to find template "%s" from template map',
$name
));
}
if (!file_exists($this->map[$name])) {
throw new LoaderError(sprintf(
'Unable to open file "%s" from template map',
$this->map[$name]
));
}
$content = file_get_contents($this->map[$name]);
$source = new Source($content, $name, $this->map[$name]);
return $source;
} | php | {
"resource": ""
} |
q244527 | Module.onBootstrap | validation | public function onBootstrap(EventInterface $e)
{
$app = $e->getApplication();
$container = $app->getServiceManager();
/**
* @var Environment $env
*/
$config = $container->get('Configuration');
$env = $container->get(Environment::class);
$name = static::MODULE_NAME;
$options = $envOptions = empty($config[$name]) ? [] : $config[$name];
$extensions = empty($options['extensions']) ? [] : $options['extensions'];
$renderer = $container->get(TwigRenderer::class);
// Setup extensions
foreach ($extensions as $extension) {
// Allows modules to override/remove extensions.
if (empty($extension)) {
continue;
} elseif (is_string($extension)) {
if ($container->has($extension)) {
$extension = $container->get($extension);
} else {
$extension = new $extension($container, $renderer);
}
} elseif (!is_object($extension)) {
throw new InvalidArgumentException('Extensions should be a string or object.');
}
if (!$env->hasExtension(get_class($extension))) {
$env->addExtension($extension);
}
}
return;
} | php | {
"resource": ""
} |
q244528 | TwigRenderer.plugin | validation | public function plugin($name, array $options = null)
{
$helper = $this->getTwigHelpers()->setRenderer($this);
if ($helper->has($name)) {
return $helper->get($name, $options);
}
return $this->getHelperPluginManager()->get($name, $options);
} | php | {
"resource": ""
} |
q244529 | SocketConnector.readDataFromPendingClient | validation | private function readDataFromPendingClient($socket, int $length, PendingSocketClient $state)
{
$data = \fread($socket, $length);
if ($data === false || $data === '') {
return null;
}
$data = $state->receivedDataBuffer . $data;
if (\strlen($data) < $length) {
$state->receivedDataBuffer = $data;
return null;
}
$state->receivedDataBuffer = '';
Loop::cancel($state->readWatcher);
return $data;
} | php | {
"resource": ""
} |
q244530 | Process.start | validation | public function start(): Promise
{
if ($this->handle) {
throw new StatusError("Process has already been started.");
}
return call(function () {
$this->handle = $this->processRunner->start($this->command, $this->cwd, $this->env, $this->options);
return $this->pid = yield $this->handle->pidDeferred->promise();
});
} | php | {
"resource": ""
} |
q244531 | Process.join | validation | public function join(): Promise
{
if (!$this->handle) {
throw new StatusError("Process has not been started.");
}
return $this->processRunner->join($this->handle);
} | php | {
"resource": ""
} |
q244532 | Process.signal | validation | public function signal(int $signo)
{
if (!$this->isRunning()) {
throw new StatusError("Process is not running.");
}
$this->processRunner->signal($this->handle, $signo);
} | php | {
"resource": ""
} |
q244533 | Share.twitter | validation | public function twitter()
{
if (is_null($this->title)) {
$this->title = config('laravel-share.services.twitter.text');
}
$base = config('laravel-share.services.twitter.uri');
$url = $base . '?text=' . urlencode($this->title) . '&url=' . $this->url;
$this->buildLink('twitter', $url);
return $this;
} | php | {
"resource": ""
} |
q244534 | Share.linkedin | validation | public function linkedin($summary = '')
{
$base = config('laravel-share.services.linkedin.uri');
$mini = config('laravel-share.services.linkedin.extra.mini');
$url = $base . '?mini=' . $mini . '&url=' . $this->url . '&title=' . urlencode($this->title) . '&summary=' . urlencode($summary);
$this->buildLink('linkedin', $url);
return $this;
} | php | {
"resource": ""
} |
q244535 | Share.buildLink | validation | protected function buildLink($provider, $url)
{
$fontAwesomeVersion = config('laravel-share.fontAwesomeVersion', 4);
$this->html .= trans("laravel-share::laravel-share-fa$fontAwesomeVersion.$provider", [
'url' => $url,
'class' => key_exists('class', $this->options) ? $this->options['class'] : '',
'id' => key_exists('id', $this->options) ? $this->options['id'] : '',
]);
} | php | {
"resource": ""
} |
q244536 | TrustedFormIntegration.getFingers | validation | protected function getFingers(Lead $lead)
{
$fingers = [];
//Trusted form "should" convert these...
if ($lead->getEmail()) {
$fingers['email'] = strtolower($lead->getEmail());
}
if ($lead->getPhone()) {
$fingers['phone'] = preg_replace('/\D/', '', $lead->getPhone());
}
if ($lead->getMobile()) {
$fingers['mobile'] = preg_replace('/\D/', '', $lead->getMobile());
}
return $fingers;
} | php | {
"resource": ""
} |
q244537 | AbstractNeustarIntegration.domDocumentArray | validation | protected function domDocumentArray($root)
{
$result = [];
if ($root->hasAttributes()) {
foreach ($root->attributes as $attribute) {
$result['@attributes'][$attribute->name] = $attribute->value;
}
}
if ($root->hasChildNodes()) {
if (1 == $root->childNodes->length) {
$child = $root->childNodes->item(0);
if (in_array($child->nodeType, [XML_TEXT_NODE, XML_CDATA_SECTION_NODE]) && !empty($child->nodeValue)) {
$result['_value'] = $child->nodeValue;
return 1 == count($result)
? $result['_value']
: $result;
}
}
$groups = [];
foreach ($root->childNodes as $child) {
if (!isset($result[$child->nodeName])) {
$result[$child->nodeName] = $this->domDocumentArray($child);
} else {
if (!isset($groups[$child->nodeName])) {
$result[$child->nodeName] = [$result[$child->nodeName]];
$groups[$child->nodeName] = 1;
}
$result[$child->nodeName][] = $this->domDocumentArray($child);
}
}
}
return $result;
} | php | {
"resource": ""
} |
q244538 | LeadSubscriber.doAutoRunEnhancements | validation | public function doAutoRunEnhancements(LeadEvent $event)
{
$lead = $event->getLead();
if ($lead && (null !== $lead->getDateIdentified() || !$lead->isAnonymous())) {
// Ensure we do not duplicate this work within the same session.
$leadKey = strtolower(
implode(
'|',
[
$lead->getFirstname(),
($lead->getLastActive() ? $lead->getLastActive()->format('c') : ''),
$lead->getEmail(),
$lead->getPhone(),
$lead->getMobile(),
]
)
);
if (strlen($leadKey) > 3) {
if (isset($this->leadsEnhanced[$leadKey])) {
return;
} else {
$this->leadsEnhanced[$leadKey] = true;
}
}
/** @var \MauticPlugin\MauticEnhancerBundle\Integration\AbstractEnhancerIntegration */
$integrations = $this->enhancerHelper->getEnhancerIntegrations();
foreach ($integrations as $integration) {
$settings = $integration->getIntegrationSettings();
if ($settings->getIsPublished()) {
$features = $settings->getFeatureSettings();
if (isset($features['autorun_enabled']) && $features['autorun_enabled']) {
try {
$integration->doEnhancement($lead);
} catch (\Exception $exception) {
$e = new ApiErrorException(
'There was an issue using enhancer: '.$integration->getName(),
0,
$exception
);
if (!empty($lead)) {
$e->setContact($lead);
}
throw $e;
}
}
}
}
$this->logger->info('doAutoRunEnhancements complete');
}
} | php | {
"resource": ""
} |
q244539 | FileConverter.isImage | validation | public static function isImage($file)
{
try {
$level = error_reporting(E_ERROR | E_PARSE);
$isImage = self::isFile($file) && getimagesize($file) !== false;
error_reporting($level);
return $isImage;
} catch (Exception $e) {
return false;
}
} | php | {
"resource": ""
} |
q244540 | Http.setHeaders | validation | public function setHeaders(array $headers = [])
{
$originHeaders = empty($this->headers) ? [] : $this->headers;
$this->headers = array_merge($originHeaders, $headers);
return $this;
} | php | {
"resource": ""
} |
q244541 | Http.post | validation | public function post($url, $params = [])
{
$key = is_array($params) ? 'form_params' : 'body';
return $this->request('POST', $url, [$key => $params]);
} | php | {
"resource": ""
} |
q244542 | Http.request | validation | public function request($method, $url, $options = [])
{
$method = strtoupper($method);
$options = array_merge(self::$defaults, ['headers' => $this->headers], $options);
return $this->getClient()->request($method, $url, $options);
} | php | {
"resource": ""
} |
q244543 | Http.json | validation | public function json($url, $options = [], $encodeOption = JSON_UNESCAPED_UNICODE, $queries = [])
{
is_array($options) && $options = json_encode($options, $encodeOption);
return $this->setHeaders(['content-type' => 'application/json'])->request('POST', $url, [
'query' => $queries,
'body' => $options
]);
} | php | {
"resource": ""
} |
q244544 | Http.getClient | validation | public function getClient()
{
if (empty($this->client) || !($this->client instanceof HttpClient)) {
$this->client = new HttpClient();
}
return $this->client;
} | php | {
"resource": ""
} |
q244545 | Authorization.appendSignature | validation | public function appendSignature(array $params = [], $timestamp = '', $noncestr = '')
{
$params += [
'app_id' => $this->appId,
'time_stamp' => $timestamp ? : time(),
'nonce_str' => $noncestr ? : md5(uniqid())
];
if (isset($params['app_key'])) {
unset($params['app_key']);
}
ksort($params);
$params['sign'] = strtoupper(md5(http_build_query($params + ['app_key' => $this->appKey])));
return $params;
} | php | {
"resource": ""
} |
q244546 | OCRManager.getFixedFormat | validation | public function getFixedFormat($images, array $options = [])
{
//aliyun does not support batch operation
$images = is_array($images) ? $images[0] : $images;
if (FileConverter::isUrl($images)) {
throw new RuntimeException("Aliyun ocr not support online picture.");
}
if ($this->simpleRequestBody) {
return [
'image' => FileConverter::toBase64Encode($images),
'configure' => json_encode($options, JSON_UNESCAPED_UNICODE)
];
}
//aliyun cloud fixed request format
return [
'inputs' => [
[
'image' => [
'dataType' => 50,
'dataValue' => FileConverter::toBase64Encode($images)
],
'configure' => [
'dataType' => 50,
'dataValue' => json_encode($options, JSON_UNESCAPED_UNICODE)
]
]
]
];
} | php | {
"resource": ""
} |
q244547 | OCRManager.request | validation | protected function request($url, array $options = [])
{
$httpClient = new Http;
try {
$response = $httpClient->request('POST', $url, [
'form_params' => $options,
'query' => [$this->accessToken->getQueryName() => $this->accessToken->getAccessToken(true)]
]);
} catch (\GuzzleHttp\Exception\ClientException $e) {
if ($e->hasResponse()) {
$response = $e->getResponse();
} else {
throw $e;
}
}
return $httpClient->parseJson($response);
} | php | {
"resource": ""
} |
q244548 | OCRManager.buildRequestParam | validation | protected function buildRequestParam($images, $options = [])
{
//Baidu OCR不支持多个url或图片,只支持一次识别一张
if (is_array($images) && ! empty($images[0])) {
$images = $images[0];
}
// if (! $this->supportUrl && FileConverter::isUrl($images)) {
// throw new RuntimeException('current method not support online picture.');
// }
if ($this->supportUrl && FileConverter::isUrl($images)) {
$options['url'] = $images;
} else {
$options['image'] = FileConverter::toBase64Encode($images);
}
return $options;
} | php | {
"resource": ""
} |
q244549 | Authorization.signature | validation | protected function signature()
{
$signatureKey = $this->buildSignatureKey();
$sing = hash_hmac('SHA1', $signatureKey, $this->secretKey, true);
return base64_encode($sing . $signatureKey);
} | php | {
"resource": ""
} |
q244550 | Authorization.buildSignatureKey | validation | protected function buildSignatureKey()
{
$signatures = [
'a' => $this->appId,
'b' => $this->bucket,
'k' => $this->secretId,
'e' => time() + 2592000,
't' => time(),
'r' => rand(),
'u' => '0',
'f' => ''
];
return http_build_query($signatures);
} | php | {
"resource": ""
} |
q244551 | AccessToken.getAccessToken | validation | public function getAccessToken($forceRefresh = false)
{
$cacheKey = $this->getCacheKey();
$cached = $this->getCache()->fetch($cacheKey);
if (empty($cached) || $forceRefresh) {
$token = $this->getTokenFormApi();
$this->getCache()->save($cacheKey, $token[$this->tokenSucessKey], $token['expires_in']);
return $token[$this->tokenSucessKey];
}
return $cached;
} | php | {
"resource": ""
} |
q244552 | AccessToken.getTokenFormApi | validation | protected function getTokenFormApi()
{
$http = $this->getHttp();
$token = $http->parseJson($http->post(self::API_TOKEN_URI, [
'grant_type' => 'client_credentials',
'client_id' => $this->getAppKey(),
'client_secret' => $this->getSecretKey()
]));
if (empty($token[$this->tokenSucessKey])) {
throw new RuntimeException('Request AccessToken fail. response: '.json_encode($token, JSON_UNESCAPED_UNICODE));
}
return $token;
} | php | {
"resource": ""
} |
q244553 | AccessToken.getCacheKey | validation | public function getCacheKey()
{
if (is_null($this->cacheKey)) {
return $this->prefix.$this->appKey;
}
return $this->cacheKey;
} | php | {
"resource": ""
} |
q244554 | OCRManager.appendAppIdAndBucketIfEmpty | validation | protected function appendAppIdAndBucketIfEmpty(array $options = [])
{
$options['appid'] = empty($options['appid']) ? $this->authorization->getAppId() : $options['appid'];
$options['bucket'] = empty($options['bucket']) ? $this->authorization->getBucket() : $options['bucket'];
return $options;
} | php | {
"resource": ""
} |
q244555 | OCRManager.request | validation | protected function request($url, $images, array $options = [], $requestType = false)
{
$http = (new Http)->setHeaders([
'Authorization' => $this->authorization->getAuthorization()
]);
//腾讯 OCR 识别只支持单个图片
$image = is_array($images) ? $images[0] : $images;
//腾讯 OCR 识别时,部分接口的请求参数为 ret_image/url_list 部分又为 image/url --Fuck
$urlName = $requestType ? 'url_list' : 'url';
if (FileConverter::isUrl($image)) {
$isurl = true;
} else {
$isurl = false;
$multiparts['image'][] = $image;
}
$options = $this->appendAppIdAndBucketIfEmpty($options);
try {
if ($isurl) {
$response = $http->json($url, array_merge($options, [$urlName => $image]));
} else {
$response = $http->upload($url, $multiparts, $options);
}
} catch (\GuzzleHttp\Exception\ClientException $e) {
if ($e->hasResponse()) {
$response = $e->getResponse();
}
}
return $http->parseJson($response);
} | php | {
"resource": ""
} |
q244556 | Config.set | validation | public function set($key, $value)
{
Arr::set($this->configs, $key, $value);
return $this;
} | php | {
"resource": ""
} |
q244557 | Option.initFromSpecString | validation | protected function initFromSpecString($specString)
{
$pattern = '/
(
(?:[a-zA-Z0-9-]+)
(?:
\|
(?:[a-zA-Z0-9-]+)
)?
)
# option attribute operators
([:+?])?
# value types
(?:=(boolean|string|number|date|file|dir|url|email|ip|ipv6|ipv4))?
/x';
$ret = preg_match($pattern, $specString, $regs);
if ($ret === false || $ret === 0) {
throw new Exception('Incorrect spec string');
}
$orig = $regs[0];
$name = $regs[1];
$attributes = isset($regs[2]) ? $regs[2] : null;
$type = isset($regs[3]) ? $regs[3] : null;
$short = null;
$long = null;
// check long,short option name.
if (strpos($name, '|') !== false) {
list($short, $long) = explode('|', $name);
} else if (strlen($name) === 1) {
$short = $name;
} else if (strlen($name) > 1) {
$long = $name;
}
$this->short = $short;
$this->long = $long;
// option is required.
if (strpos($attributes, ':') !== false) {
$this->required();
} else if (strpos($attributes, '+') !== false) {
// option with multiple value
$this->multiple();
} else if (strpos($attributes, '?') !== false) {
// option is optional.(zero or one value)
$this->optional();
} else {
$this->flag();
}
if ($type) {
$this->isa($type);
}
} | php | {
"resource": ""
} |
q244558 | Option.pushValue | validation | public function pushValue($value)
{
$value = $this->_preprocessValue($value);
$this->value[] = $value;
$this->callTrigger();
} | php | {
"resource": ""
} |
q244559 | Option.renderReadableSpec | validation | public function renderReadableSpec($renderHint = true)
{
$c1 = '';
if ($this->short && $this->long) {
$c1 = sprintf('-%s, --%s', $this->short, $this->long);
} else if ($this->short) {
$c1 = sprintf('-%s', $this->short);
} else if ($this->long) {
$c1 = sprintf('--%s', $this->long);
}
if ($renderHint) {
return $c1.$this->renderValueHint();
}
return $c1;
} | php | {
"resource": ""
} |
q244560 | Option.isa | validation | public function isa($type, $option = null)
{
// "bool" was kept for backward compatibility
if ($type === 'bool') {
$type = 'boolean';
}
$this->isa = $type;
$this->isaOption = $option;
return $this;
} | php | {
"resource": ""
} |
q244561 | Option.getValidValues | validation | public function getValidValues()
{
if ($this->validValues) {
if (is_callable($this->validValues)) {
return call_user_func($this->validValues);
}
return $this->validValues;
}
return;
} | php | {
"resource": ""
} |
q244562 | Option.getSuggestions | validation | public function getSuggestions()
{
if ($this->suggestions) {
if (is_callable($this->suggestions)) {
return call_user_func($this->suggestions);
}
return $this->suggestions;
}
return;
} | php | {
"resource": ""
} |
q244563 | Argument.anyOfOptions | validation | public function anyOfOptions(OptionCollection $options)
{
$name = $this->getOptionName();
$keys = $options->keys();
return in_array($name, $keys);
} | php | {
"resource": ""
} |
q244564 | OptionParser.consumeOptionToken | validation | protected function consumeOptionToken(Option $spec, $arg, $next, & $success = false)
{
// Check options doesn't require next token before
// all options that require values.
if ($spec->isFlag()) {
if ($spec->isIncremental()) {
$spec->increaseValue();
} else {
$spec->setValue(true);
}
return 0;
} else if ($spec->isRequired()) {
if ($next && !$next->isEmpty() && !$next->anyOfOptions($this->specs)) {
$spec->setValue($next->arg);
return 1;
} else {
throw new RequireValueException("Option '{$arg->getOptionName()}' requires a value.");
}
} else if ($spec->isMultiple()) {
if ($next && !$next->isEmpty() && !$next->anyOfOptions($this->specs)) {
$this->pushOptionValue($spec, $arg, $next);
return 1;
}
} else if ($spec->isOptional() && $next && !$next->isEmpty() && !$next->anyOfOptions($this->specs)) {
$spec->setValue($next->arg);
return 1;
}
return 0;
} | php | {
"resource": ""
} |
q244565 | ContinuousOptionParser.advance | validation | public function advance()
{
if ($this->index >= $this->length) {
throw new LogicException("Argument index out of bounds.");
}
return $this->argv[$this->index++];
} | php | {
"resource": ""
} |
q244566 | ConsoleOptionPrinter.renderOption | validation | public function renderOption(Option $opt)
{
$c1 = '';
if ($opt->short && $opt->long) {
$c1 = sprintf('-%s, --%s', $opt->short, $opt->long);
} else if ($opt->short) {
$c1 = sprintf('-%s', $opt->short);
} else if ($opt->long) {
$c1 = sprintf('--%s', $opt->long);
}
$c1 .= $opt->renderValueHint();
return $c1;
} | php | {
"resource": ""
} |
q244567 | ConsoleOptionPrinter.render | validation | public function render(OptionCollection $options)
{
# echo "* Available options:\n";
$lines = array();
foreach ($options as $option) {
$c1 = $this->renderOption($option);
$lines[] = "\t".$c1;
$lines[] = wordwrap("\t\t".$option->desc, $this->screenWidth, "\n\t\t"); # wrap text
$lines[] = '';
}
return implode("\n", $lines);
} | php | {
"resource": ""
} |
q244568 | HandleVariationCommandHandler.correctProductAssignment | validation | private function correctProductAssignment($variationModel, $productIdentitiy)
{
if (null === $variationModel) {
return;
}
if ((int) $productIdentitiy->getAdapterIdentifier() === $variationModel->getArticle()->getId()) {
return;
}
$this->entityManager->getConnection()->update(
's_articles_details',
['articleID' => $productIdentitiy->getAdapterIdentifier()],
['id' => $variationModel->getId()]
);
$this->logger->notice('migrated variation from existing product to connector handeled product.', [
'variation' => $variationModel->getNumber(),
'old shopware product id' => $variationModel->getArticle()->getId(),
'new shopware product id' => $productIdentitiy->getAdapterIdentifier(),
]);
} | php | {
"resource": ""
} |
q244569 | PriceResponseParser.getPriceConfigurations | validation | private function getPriceConfigurations()
{
static $priceConfigurations;
if (null === $priceConfigurations) {
$priceConfigurations = $this->itemsSalesPricesApi->findAll();
$shopIdentities = $this->identityService->findBy([
'adapterName' => PlentymarketsAdapter::NAME,
'objectType' => Shop::TYPE,
]);
$shopIdentities = array_filter($shopIdentities, function (Identity $identity) {
$isMappedIdentity = $this->identityService->isMappedIdentity(
$identity->getObjectIdentifier(),
$identity->getObjectType(),
$identity->getAdapterName()
);
if (!$isMappedIdentity) {
return false;
}
return true;
});
if (empty($shopIdentities)) {
$priceConfigurations = [];
return $priceConfigurations;
}
$priceConfigurations = array_filter($priceConfigurations,
function ($priceConfiguration) use ($shopIdentities) {
foreach ($shopIdentities as $identity) {
foreach ((array) $priceConfiguration['clients'] as $client) {
if ($client['plentyId'] === -1 || $identity->getAdapterIdentifier() === (string) $client['plentyId']) {
return true;
}
}
}
return false;
});
if (empty($priceConfigurations)) {
$this->logger->notice('no valid price configuration found');
}
}
return $priceConfigurations;
} | php | {
"resource": ""
} |
q244570 | Uploader.status | validation | public function status($token)
{
$data = array(
'token' => $token,
);
$ch = $this->__initRequest('from_url/status', $data);
$this->__setHeaders($ch);
$data = $this->__runRequest($ch);
return $data;
} | php | {
"resource": ""
} |
q244571 | Uploader.fromPath | validation | public function fromPath($path, $mime_type = false)
{
if (function_exists('curl_file_create')) {
if ($mime_type) {
$f = curl_file_create($path, $mime_type);
} else {
$f = curl_file_create($path);
}
} else {
if ($mime_type) {
$f = '@' . $path . ';type=' . $mime_type;
} else {
$f = '@' . $path;
}
}
$data = array(
'UPLOADCARE_PUB_KEY' => $this->api->getPublicKey(),
'file' => $f,
);
$ch = $this->__initRequest('base');
$this->__setRequestType($ch);
$this->__setData($ch, $data);
$this->__setHeaders($ch);
$data = $this->__runRequest($ch);
$uuid = $data->file;
return new File($uuid, $this->api);
} | php | {
"resource": ""
} |
q244572 | Uploader.fromResource | validation | public function fromResource($fp)
{
$tmpfile = tempnam(sys_get_temp_dir(), 'ucr');
$temp = fopen($tmpfile, 'w');
while (!feof($fp)) {
fwrite($temp, fread($fp, 8192));
}
fclose($temp);
fclose($fp);
return $this->fromPath($tmpfile);
} | php | {
"resource": ""
} |
q244573 | Uploader.fromContent | validation | public function fromContent($content, $mime_type)
{
$tmpfile = tempnam(sys_get_temp_dir(), 'ucr');
$temp = fopen($tmpfile, 'w');
fwrite($temp, $content);
fclose($temp);
return $this->fromPath($tmpfile, $mime_type);
} | php | {
"resource": ""
} |
q244574 | Uploader.createGroup | validation | public function createGroup($files)
{
$data = array(
'pub_key' => $this->api->getPublicKey(),
);
/**
* @var File $file
*/
foreach ($files as $i => $file) {
$data["files[$i]"] = $file->getUrl();
}
$ch = $this->__initRequest('group');
$this->__setRequestType($ch);
$this->__setData($ch, $data);
$this->__setHeaders($ch);
$resp = $this->__runRequest($ch);
$group = $this->api->getGroup($resp->id);
return $group;
} | php | {
"resource": ""
} |
q244575 | Uploader.__initRequest | validation | private function __initRequest($type, $data = null)
{
$url = sprintf('https://%s/%s/', $this->host, $type);
if (is_array($data)) {
$url = sprintf('%s?%s', $url, http_build_query($data));
}
$ch = curl_init($url);
return $ch;
} | php | {
"resource": ""
} |
q244576 | Uploader.__runRequest | validation | private function __runRequest($ch)
{
$data = curl_exec($ch);
$ch_info = curl_getinfo($ch);
if ($data === false) {
throw new \Exception(curl_error($ch));
} elseif ($ch_info['http_code'] != 200) {
throw new \Exception('Unexpected HTTP status code ' . $ch_info['http_code'] . '.' . curl_error($ch));
}
curl_close($ch);
return json_decode($data);
} | php | {
"resource": ""
} |
q244577 | Widget.getIntegrationData | validation | public function getIntegrationData()
{
$integrationData = '';
$framework = $this->api->getFramework();
if ($framework) {
$integrationData .= $framework;
}
$extension = $this->api->getExtension();
if ($extension) {
$integrationData .= '; '.$extension;
}
return $integrationData;
} | php | {
"resource": ""
} |
q244578 | Widget.getInputTag | validation | public function getInputTag($name, $attributes = array())
{
$to_compile = array();
foreach ($attributes as $key => $value) {
$to_compile[] = sprintf('%s="%s"', $key, $value);
}
return sprintf('<input type="hidden" role="uploadcare-uploader" name="%s" data-upload-url-base="" data-integration="%s" %s />', $name, $this->getIntegrationData(), join(' ', $to_compile));
} | php | {
"resource": ""
} |
q244579 | Api.dateTimeString | validation | public static function dateTimeString($datetime)
{
if ($datetime === null) {
return null;
}
if (is_object($datetime) && !($datetime instanceof \DateTime)) {
throw new \Exception('Only \DateTime objects allowed');
}
if (is_string($datetime)) {
$datetime = new \DateTime($datetime);
}
return $datetime->format("Y-m-d\TH:i:s.uP");
} | php | {
"resource": ""
} |
q244580 | Api.getGroupsChunk | validation | public function getGroupsChunk($options = array(), $reverse = false)
{
$data = $this->__preparedRequest('group_list', 'GET', $options);
$groups_raw = (array)$data->results;
$resultArr = array();
foreach ($groups_raw as $group_raw) {
$resultArr[] = new Group($group_raw->id, $this);
}
return $this->__preparePagedParams($data, $reverse, $resultArr);
} | php | {
"resource": ""
} |
q244581 | Api.getFilesChunk | validation | public function getFilesChunk($options = array(), $reverse = false)
{
$data = $this->__preparedRequest('file_list', 'GET', $options);
$files_raw = (array)$data->results;
$resultArr = array();
foreach ($files_raw as $file_raw) {
$resultArr[] = new File($file_raw->uuid, $this, $file_raw);
}
return $this->__preparePagedParams($data, $reverse, $resultArr);
} | php | {
"resource": ""
} |
q244582 | Api.getFileList | validation | public function getFileList($options = array())
{
$options = array_replace(array(
'from' => null,
'to' => null,
'limit' => null,
'request_limit' => null,
'stored' => $this->defaultFilters['file']['stored'],
'removed' => $this->defaultFilters['file']['removed'],
'reversed' => false,
), $options);
if (!empty($options['from']) && !empty($options['to'])) {
throw new \Exception('Only one of "from" and "to" arguments is allowed');
}
$options['from'] = self::dateTimeString($options['from']);
$options['to'] = self::dateTimeString($options['to']);
foreach ($this->defaultFilters['file'] as $k => $v) {
if (!is_null($options[$k])) {
$options[$k] = self::booleanString($options[$k]);
}
}
return new FileIterator($this, $options);
} | php | {
"resource": ""
} |
q244583 | Api.getGroupList | validation | public function getGroupList($options = array())
{
$options = array_replace(array(
'from' => null,
'to' => null,
'limit' => null,
'request_limit' => null,
'reversed' => false,
), $options);
if (!empty($options['from']) && !empty($options['to'])) {
throw new \Exception('Only one of "from" and "to" arguments is allowed');
}
$options['from'] = self::dateTimeString($options['from']);
$options['to'] = self::dateTimeString($options['to']);
return new GroupIterator($this, $options);
} | php | {
"resource": ""
} |
q244584 | Api.createLocalCopy | validation | public function createLocalCopy($source, $store = true)
{
$data = $this->__preparedRequest('file_copy', 'POST', array(), array('source' => $source, 'store' => $store));
if (array_key_exists('result', (array)$data) == true) {
if ($data->type == 'file') {
return new File((string)$data->result->uuid, $this);
} else {
return (string)$data->result;
}
} else {
return (string)$data->detail;
}
} | php | {
"resource": ""
} |
q244585 | Api.__batchProcessFiles | validation | public function __batchProcessFiles($filesUuidArr, $request_type)
{
$filesChunkedArr = array_chunk($filesUuidArr, $this->batchFilesChunkSize);
$filesArr = array();
$problemsArr = array();
$lastStatus = '';
foreach ($filesChunkedArr as $chunk) {
$res = $this->__batchProcessFilesChunk($chunk, $request_type);
$lastStatus = $res['status'];
if ($lastStatus == "ok") {
$problemsObj = $res['problems'];
if (count(get_object_vars($problemsObj)) > 0) {
$problemsArr [] = $problemsObj;
}
$filesArr = array_merge($filesArr, $res['files']);
} else {
throw new \Exception('Error process multiple files', $res);
}
}
return array(
'status' => $lastStatus,
'files' => $filesArr,
'problems' => $problemsArr,
);
} | php | {
"resource": ""
} |
q244586 | Api.__batchProcessFilesChunk | validation | public function __batchProcessFilesChunk($filesUuidArr, $request_type)
{
if (count($filesUuidArr) > $this->batchFilesChunkSize) {
throw new \Exception('Files number should not exceed '.$this->batchFilesChunkSize.' items per request.');
}
$data = $this->__preparedRequest('files_storage', $request_type, array(), $filesUuidArr);
$files_raw = (array)$data->result;
$result = array();
foreach ($files_raw as $file_raw) {
$result[] = new File($file_raw->uuid, $this, $file_raw);
}
return array(
'status' => (string)$data->status,
'files' => $result,
'problems' => $data->problems,
);
} | php | {
"resource": ""
} |
q244587 | Api.request | validation | public function request($method, $path, $data = array(), $headers = array())
{
$ch = curl_init(sprintf('https://%s%s', $this->api_host, $path));
$this->__setRequestType($ch, $method);
$this->__setHeaders($ch, $headers, $data);
$response = curl_exec($ch);
if ($response === false) {
throw new \Exception(curl_error($ch));
}
$ch_info = curl_getinfo($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
$error = false;
if ($method == 'DELETE') {
if ($ch_info['http_code'] != 302 && $ch_info['http_code'] != 200) {
$error = true;
}
} else {
if (!(($ch_info['http_code'] >= 200) && ($ch_info['http_code'] < 300))) {
$error = true;
}
}
if ($ch_info['http_code'] == 429) {
$exception = new ThrottledRequestException();
$response_headers = Helper::parseHttpHeaders($header);
$exception->setResponseHeaders($response_headers);
throw $exception;
}
if ($error) {
$errorInfo = array_filter(array(curl_error($ch), $body));
throw new \Exception('Request returned unexpected http code '. $ch_info['http_code'] . '. ' . join(', ', $errorInfo));
}
curl_close($ch);
if (!defined('PHPUNIT_UPLOADCARE_TESTSUITE') && ($this->public_key == 'demopublic_key' || $this->secret_key == 'demoprivatekey')) {
trigger_error('You are using the demo account. Please get an Uploadcare account at https://uploadcare.com/accounts/create/', E_USER_WARNING);
}
return json_decode($body);
} | php | {
"resource": ""
} |
q244588 | Api.__preparedRequest | validation | public function __preparedRequest($type, $request_type = 'GET', $params = array(), $data = array(), $retry_throttled = null)
{
$retry_throttled = $retry_throttled ?: $this->retry_throttled;
$path = $this->__getPath($type, $params);
while (true) {
try {
return $this->request($request_type, $path, $data);
} catch (ThrottledRequestException $exception) {
if ($retry_throttled > 0) {
sleep($exception->getTimeout());
$retry_throttled--;
continue;
} else {
throw $exception;
}
}
}
return null;
} | php | {
"resource": ""
} |
q244589 | Api.__preparePagedParams | validation | private function __preparePagedParams($data, $reverse, $resultArr)
{
$nextParamsArr = parse_url($data->next);
$prevParamsArr = parse_url($data->previous);
$nextParamsArr = array_replace(array('query' => null), $nextParamsArr);
$prevParamsArr = array_replace(array('query' => null), $prevParamsArr);
parse_str(parse_url(!$reverse ? $data->next : $data->previous, PHP_URL_QUERY), $params);
if ($reverse) {
$resultArr = array_reverse($resultArr);
}
return array(
'nextParams' => $reverse ? $prevParamsArr : $nextParamsArr,
'prevParams' => !$reverse ? $prevParamsArr : $nextParamsArr,
'params' => $params,
'data' => $resultArr,
);
} | php | {
"resource": ""
} |
q244590 | Api.__getQueryString | validation | private function __getQueryString($queryAr = array(), $prefixIfNotEmpty = '')
{
$queryAr = array_filter($queryAr);
array_walk($queryAr, function (&$val, $key) {
$val = urlencode($key) . '=' . urlencode($val);
});
return $queryAr ? $prefixIfNotEmpty . join('&', $queryAr) : '';
} | php | {
"resource": ""
} |
q244591 | Api.__getPath | validation | private function __getPath($type, $params = array())
{
switch ($type) {
case 'root':
return '/';
case 'account':
return '/account/';
case 'file_list':
return '/files/' . $this->__getQueryString($params, '?');
case 'file_storage':
if (array_key_exists('uuid', $params) == false) {
throw new \Exception('Please provide "uuid" param for request');
}
return sprintf('/files/%s/storage/', $params['uuid']);
case 'file_copy':
return '/files/';
case 'files_storage':
return '/files/storage/';
case 'file':
if (array_key_exists('uuid', $params) == false) {
throw new \Exception('Please provide "uuid" param for request');
}
return sprintf('/files/%s/', $params['uuid']);
case 'group_list':
return '/groups/' . $this->__getQueryString($params, '?');
case 'group':
if (array_key_exists('uuid', $params) == false) {
throw new \Exception('Please provide "uuid" param for request');
}
return sprintf('/groups/%s/', $params['uuid']);
case 'group_storage':
if (array_key_exists('uuid', $params) == false) {
throw new \Exception('Please provide "uuid" param for request');
}
return sprintf('/groups/%s/storage/', $params['uuid']);
default:
throw new \Exception('No api url type is provided for request "' . $type . '". Use store, or appropriate constants.');
}
} | php | {
"resource": ""
} |
q244592 | Api.__setRequestType | validation | private function __setRequestType($ch, $type = 'GET')
{
$this->current_method = strtoupper($type);
switch ($type) {
case 'GET':
break;
case 'POST':
curl_setopt($ch, CURLOPT_POST, true);
break;
case 'PUT':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
break;
case 'DELETE':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
case 'HEAD':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD');
curl_setopt($ch, CURLOPT_NOBODY, true);
break;
case 'OPTIONS':
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'OPTIONS');
break;
default:
throw new \Exception('No request type is provided for request. Use post, put, delete, get or appropriate constants.');
}
} | php | {
"resource": ""
} |
q244593 | Api.getUserAgentHeader | validation | public function getUserAgentHeader()
{
// If has own User-Agent
$userAgentName = $this->getUserAgentName();
if ($userAgentName) {
return $userAgentName;
}
$userAgent = sprintf('%s/%s/%s (PHP/%s.%s.%s', $this->getLibraryName(), $this->getVersion(), $this->getPublicKey(), PHP_MAJOR_VERSION, PHP_MINOR_VERSION, PHP_RELEASE_VERSION);
$framework = $this->getFramework();
if ($framework) {
$userAgent .= '; '.$framework;
}
$extension = $this->getExtension();
if ($extension) {
$userAgent .= '; '.$extension;
}
$userAgent .= ')';
return $userAgent;
} | php | {
"resource": ""
} |
q244594 | File.updateInfo | validation | public function updateInfo()
{
$this->cached_data = (array)$this->api->__preparedRequest('file', 'GET', array('uuid' => $this->uuid));
return $this->cached_data;
} | php | {
"resource": ""
} |
q244595 | File.copy | validation | public function copy($target = null)
{
Helper::deprecate('2.0.0', '3.0.0', 'Use createLocalCopy() or createRemoteCopy() instead');
return $this->api->copyFile($this->getUrl(), $target);
} | php | {
"resource": ""
} |
q244596 | File.getUrl | validation | public function getUrl($postfix = null)
{
$url = sprintf('%s%s', $this->api->getCdnUri(), $this->getPath($postfix));
return $url;
} | php | {
"resource": ""
} |
q244597 | File.getPath | validation | public function getPath($postfix = null)
{
$url = sprintf('/%s/', $this->uuid);
if ($this->default_effects) {
$url = sprintf('%s-/%s', $url, $this->default_effects);
}
if ($this->filename && $postfix === null) {
$postfix = $this->filename;
}
$operations = array();
foreach ($this->operations as $i => $operation_item) {
$part = array();
foreach (array_keys($operation_item) as $operation_type) {
$operation_params = $operation_item[$operation_type];
$part[] = $operation_type;
switch ($operation_type) {
case 'crop':
$part = $this->__addPartSize($part, $operation_params);
$part = $this->__addPartCenter($part, $operation_params);
$part = $this->__addPartFillColor($part, $operation_params);
break;
case 'resize':
$part = $this->__addPartSize($part, $operation_params);
break;
case 'scale_crop':
$part = $this->__addPartSize($part, $operation_params);
$part = $this->__addPartCenter($part, $operation_params);
break;
case 'effect':
$part = $this->__addPartEffect($part, $operation_params);
break;
case 'preview':
$part = $this->__addPartSize($part, $operation_params);
break;
case 'custom':
$part = array($operation_params);
break;
}
$part_str = join('/', $part);
$operations[] = $part_str;
}
}
if (count($operations)) {
$operations_part = join('/-/', $operations);
return $url.'-/'.$operations_part.'/'.$postfix;
} else {
return $url.$postfix;
}
} | php | {
"resource": ""
} |
q244598 | File.getImgTag | validation | public function getImgTag($postfix = null, $attributes = array())
{
$to_compile = array();
foreach ($attributes as $key => $value) {
$to_compile[] = sprintf('%s="%s"', $key, $value);
}
return sprintf('<img src="%s" %s />', $this->getUrl(), join(' ', $to_compile));
} | php | {
"resource": ""
} |
q244599 | File.resize | validation | public function resize($width = false, $height = false)
{
if (!$width && !$height) {
throw new \Exception('Please, provide at least $width or $height for resize');
}
$result = clone $this;
$result->operations[]['resize'] = array(
'width' => $width,
'height' => $height,
);
return $result;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.