_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q13500 | SessionHandler.close | train | public function close()
{
$id = session_id();
// Make sure the session is unlocked and the expiration time is updated,
// even if the write did not occur
if ($this->openSessionId !== $id || !$this->sessionWritten) {
$result = $this->connection->write($this->formatId($id), '', false);
$this->sessionWritten = (bool) $result;
}
return $this->sessionWritten;
} | php | {
"resource": ""
} |
q13501 | SessionHandler.read | train | public function read($id)
{
$this->openSessionId = $id;
// PHP expects an empty string to be returned from this method if no
// data is retrieved
$this->dataRead = '';
// Get session data using the selected locking strategy
$item = $this->connection->read($this->formatId($id));
// Return the data if it is not expired. If it is expired, remove it
if (isset($item['expires']) && isset($item['data'])) {
$this->dataRead = $item['data'];
if ($item['expires'] <= time()) {
$this->dataRead = '';
$this->destroy($id);
}
}
return $this->dataRead;
} | php | {
"resource": ""
} |
q13502 | SessionHandler.write | train | public function write($id, $data)
{
$changed = $id !== $this->openSessionId
|| $data !== $this->dataRead;
$this->openSessionId = $id;
// Write the session data using the selected locking strategy
$this->sessionWritten = $this->connection
->write($this->formatId($id), $data, $changed);
return $this->sessionWritten;
} | php | {
"resource": ""
} |
q13503 | SessionHandler.destroy | train | public function destroy($id)
{
$this->openSessionId = $id;
// Delete the session data using the selected locking strategy
$this->sessionWritten
= $this->connection->delete($this->formatId($id));
return $this->sessionWritten;
} | php | {
"resource": ""
} |
q13504 | AbstractUploader.isEof | train | private function isEof($seekable)
{
return $seekable
? $this->source->tell() < $this->source->getSize()
: !$this->source->eof();
} | php | {
"resource": ""
} |
q13505 | AbstractUploader.determineSource | train | private function determineSource($source)
{
// Use the contents of a file as the data source.
if (is_string($source)) {
$source = Psr7\try_fopen($source, 'r');
}
// Create a source stream.
$stream = Psr7\stream_for($source);
if (!$stream->isReadable()) {
throw new IAE('Source stream must be readable.');
}
return $stream;
} | php | {
"resource": ""
} |
q13506 | PollyClient.createSynthesizeSpeechPreSignedUrl | train | public function createSynthesizeSpeechPreSignedUrl(array $args)
{
$uri = new Uri($this->getEndpoint());
$uri = $uri->withPath('/v1/speech');
// Formatting parameters follows rest-json protocol
$this->formatter = $this->formatter ?: new JsonBody($this->getApi());
$queryArray = json_decode(
$this->formatter->build(
$this->getApi()->getOperation('SynthesizeSpeech')->getInput(),
$args
),
true
);
// Mocking a 'GET' request in pre-signing the Url
$query = Psr7\build_query($queryArray);
$uri = $uri->withQuery($query);
$request = new Request('GET', $uri);
$request = $request->withBody(Psr7\stream_for(''));
$signer = new SignatureV4('polly', $this->getRegion());
return (string) $signer->presign(
$request,
$this->getCredentials()->wait(),
'+15 minutes'
)->getUri();
} | php | {
"resource": ""
} |
q13507 | ClassAnnotationUpdater.update | train | public function update()
{
// copy the code into memory
$backup = file($this->reflection->getFileName());
list($preamble, $class) = $this->splitClassFile($backup);
$preamble = $this->stripOutExistingDocBlock($preamble);
$preamble .= $this->buildUpdatedDocBlock();
if ($this->writeClassFile(implode(PHP_EOL, [$preamble, $class]))
&& $this->commandLineLint($this->reflection->getFileName())
) {
return true;
}
$this->writeClassFile(implode('', $backup));
return false;
} | php | {
"resource": ""
} |
q13508 | TimestampShape.format | train | public static function format($value, $format)
{
if ($value instanceof \DateTime) {
$value = $value->getTimestamp();
} elseif (is_string($value)) {
$value = strtotime($value);
} elseif (!is_int($value)) {
throw new \InvalidArgumentException('Unable to handle the provided'
. ' timestamp type: ' . gettype($value));
}
switch ($format) {
case 'iso8601':
return gmdate('Y-m-d\TH:i:s\Z', $value);
case 'rfc822':
return gmdate('D, d M Y H:i:s \G\M\T', $value);
case 'unixTimestamp':
return $value;
default:
throw new \UnexpectedValueException('Unknown timestamp format: '
. $format);
}
} | php | {
"resource": ""
} |
q13509 | SignatureProvider.resolve | train | public static function resolve(callable $provider, $version, $service, $region)
{
$result = $provider($version, $service, $region);
if ($result instanceof SignatureInterface) {
return $result;
}
throw new UnresolvedSignatureException(
"Unable to resolve a signature for $version/$service/$region.\n"
. "Valid signature versions include v4 and anonymous."
);
} | php | {
"resource": ""
} |
q13510 | SignatureProvider.memoize | train | public static function memoize(callable $provider)
{
$cache = [];
return function ($version, $service, $region) use (&$cache, $provider) {
$key = "($version)($service)($region)";
if (!isset($cache[$key])) {
$cache[$key] = $provider($version, $service, $region);
}
return $cache[$key];
};
} | php | {
"resource": ""
} |
q13511 | SesClient.generateSmtpPassword | train | public static function generateSmtpPassword(CredentialsInterface $creds)
{
static $version = "\x02";
static $algo = 'sha256';
static $message = 'SendRawEmail';
$signature = hash_hmac($algo, $message, $creds->getSecretKey(), true);
return base64_encode($version . $signature);
} | php | {
"resource": ""
} |
q13512 | CommandPool.batch | train | public static function batch(
AwsClientInterface $client,
$commands,
array $config = []
) {
$results = [];
self::cmpCallback($config, 'fulfilled', $results);
self::cmpCallback($config, 'rejected', $results);
return (new self($client, $commands, $config))
->promise()
->then(static function () use (&$results) {
ksort($results);
return $results;
})
->wait();
} | php | {
"resource": ""
} |
q13513 | CommandPool.cmpCallback | train | private static function cmpCallback(array &$config, $name, array &$results)
{
if (!isset($config[$name])) {
$config[$name] = function ($v, $k) use (&$results) {
$results[$k] = $v;
};
} else {
$currentFn = $config[$name];
$config[$name] = function ($v, $k) use (&$results, $currentFn) {
$currentFn($v, $k);
$results[$k] = $v;
};
}
} | php | {
"resource": ""
} |
q13514 | EndpointDiscoveryMiddleware.parseEndpoint | train | private function parseEndpoint($endpoint)
{
$parsed = parse_url($endpoint);
// parse_url() will correctly parse full URIs with schemes
if (isset($parsed['host'])) {
return $parsed;
}
// parse_url() will put host & path in 'path' if scheme is not provided
if (isset($parsed['path'])) {
$split = explode('/', $parsed['path'], 2);
$parsed['host'] = $split[0];
if (isset($split[1])) {
$parsed['path'] = $split[1];
} else {
$parsed['path'] = '';
}
return $parsed;
}
throw new UnresolvedEndpointException("The supplied endpoint '"
. "{$endpoint}' is invalid.");
} | php | {
"resource": ""
} |
q13515 | MachineLearningClient.predictEndpoint | train | private function predictEndpoint()
{
return static function (callable $handler) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler) {
if ($command->getName() === 'Predict') {
$request = $request->withUri(new Uri($command['PredictEndpoint']));
}
return $handler($command, $request);
};
};
} | php | {
"resource": ""
} |
q13516 | S3Client.isBucketDnsCompatible | train | public static function isBucketDnsCompatible($bucket)
{
$bucketLen = strlen($bucket);
return ($bucketLen >= 3 && $bucketLen <= 63) &&
// Cannot look like an IP address
!filter_var($bucket, FILTER_VALIDATE_IP) &&
preg_match('/^[a-z0-9]([a-z0-9\-\.]*[a-z0-9])?$/', $bucket);
} | php | {
"resource": ""
} |
q13517 | S3Client.getLocationConstraintMiddleware | train | private function getLocationConstraintMiddleware()
{
$region = $this->getRegion();
return static function (callable $handler) use ($region) {
return function (Command $command, $request = null) use ($handler, $region) {
if ($command->getName() === 'CreateBucket') {
$locationConstraint = isset($command['CreateBucketConfiguration']['LocationConstraint'])
? $command['CreateBucketConfiguration']['LocationConstraint']
: null;
if ($locationConstraint === 'us-east-1') {
unset($command['CreateBucketConfiguration']);
} elseif ('us-east-1' !== $region && empty($locationConstraint)) {
$command['CreateBucketConfiguration'] = ['LocationConstraint' => $region];
}
}
return $handler($command, $request);
};
};
} | php | {
"resource": ""
} |
q13518 | S3Client.getSaveAsParameter | train | private function getSaveAsParameter()
{
return static function (callable $handler) {
return function (Command $command, $request = null) use ($handler) {
if ($command->getName() === 'GetObject' && isset($command['SaveAs'])) {
$command['@http']['sink'] = $command['SaveAs'];
unset($command['SaveAs']);
}
return $handler($command, $request);
};
};
} | php | {
"resource": ""
} |
q13519 | S3Client.getHeadObjectMiddleware | train | private function getHeadObjectMiddleware()
{
return static function (callable $handler) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler) {
if ($command->getName() === 'HeadObject'
&& !isset($command['@http']['decode_content'])
) {
$command['@http']['decode_content'] = false;
}
return $handler($command, $request);
};
};
} | php | {
"resource": ""
} |
q13520 | MultipartUploader.decorateWithHashes | train | private function decorateWithHashes(Stream $stream, array &$data)
{
// Decorate source with a hashing stream
$hash = new PhpHash('sha256');
return new HashingStream($stream, $hash, function ($result) use (&$data) {
$data['ContentSHA256'] = bin2hex($result);
});
} | php | {
"resource": ""
} |
q13521 | HandlerList.appendInit | train | public function appendInit(callable $middleware, $name = null)
{
$this->add(self::INIT, $name, $middleware);
} | php | {
"resource": ""
} |
q13522 | HandlerList.prependInit | train | public function prependInit(callable $middleware, $name = null)
{
$this->add(self::INIT, $name, $middleware, true);
} | php | {
"resource": ""
} |
q13523 | HandlerList.appendValidate | train | public function appendValidate(callable $middleware, $name = null)
{
$this->add(self::VALIDATE, $name, $middleware);
} | php | {
"resource": ""
} |
q13524 | HandlerList.prependValidate | train | public function prependValidate(callable $middleware, $name = null)
{
$this->add(self::VALIDATE, $name, $middleware, true);
} | php | {
"resource": ""
} |
q13525 | HandlerList.appendBuild | train | public function appendBuild(callable $middleware, $name = null)
{
$this->add(self::BUILD, $name, $middleware);
} | php | {
"resource": ""
} |
q13526 | HandlerList.prependBuild | train | public function prependBuild(callable $middleware, $name = null)
{
$this->add(self::BUILD, $name, $middleware, true);
} | php | {
"resource": ""
} |
q13527 | HandlerList.appendSign | train | public function appendSign(callable $middleware, $name = null)
{
$this->add(self::SIGN, $name, $middleware);
} | php | {
"resource": ""
} |
q13528 | HandlerList.prependSign | train | public function prependSign(callable $middleware, $name = null)
{
$this->add(self::SIGN, $name, $middleware, true);
} | php | {
"resource": ""
} |
q13529 | HandlerList.appendAttempt | train | public function appendAttempt(callable $middleware, $name = null)
{
$this->add(self::ATTEMPT, $name, $middleware);
} | php | {
"resource": ""
} |
q13530 | HandlerList.prependAttempt | train | public function prependAttempt(callable $middleware, $name = null)
{
$this->add(self::ATTEMPT, $name, $middleware, true);
} | php | {
"resource": ""
} |
q13531 | HandlerList.before | train | public function before($findName, $withName, callable $middleware)
{
$this->splice($findName, $withName, $middleware, true);
} | php | {
"resource": ""
} |
q13532 | HandlerList.remove | train | public function remove($nameOrInstance)
{
if (is_callable($nameOrInstance)) {
$this->removeByInstance($nameOrInstance);
} elseif (is_string($nameOrInstance)) {
$this->removeByName($nameOrInstance);
}
} | php | {
"resource": ""
} |
q13533 | HandlerList.sortMiddleware | train | private function sortMiddleware()
{
$this->sorted = [];
if (!$this->interposeFn) {
foreach ($this->steps as $step) {
foreach ($step as $fn) {
$this->sorted[] = $fn[0];
}
}
return;
}
$ifn = $this->interposeFn;
// Interpose the interposeFn into the handler stack.
foreach ($this->steps as $stepName => $step) {
foreach ($step as $fn) {
$this->sorted[] = $ifn($stepName, $fn[1]);
$this->sorted[] = $fn[0];
}
}
} | php | {
"resource": ""
} |
q13534 | HandlerList.add | train | private function add($step, $name, callable $middleware, $prepend = false)
{
$this->sorted = null;
if ($prepend) {
$this->steps[$step][] = [$middleware, $name];
} else {
array_unshift($this->steps[$step], [$middleware, $name]);
}
if ($name) {
$this->named[$name] = $step;
}
} | php | {
"resource": ""
} |
q13535 | ResultPaginator.each | train | public function each(callable $handleResult)
{
return Promise\coroutine(function () use ($handleResult) {
$nextToken = null;
do {
$command = $this->createNextCommand($this->args, $nextToken);
$result = (yield $this->client->executeAsync($command));
$nextToken = $this->determineNextToken($result);
$retVal = $handleResult($result);
if ($retVal !== null) {
yield Promise\promise_for($retVal);
}
} while ($nextToken);
});
} | php | {
"resource": ""
} |
q13536 | ResultPaginator.search | train | public function search($expression)
{
// Apply JMESPath expression on each result, but as a flat sequence.
return flatmap($this, function (Result $result) use ($expression) {
return (array) $result->search($expression);
});
} | php | {
"resource": ""
} |
q13537 | ShapeMap.resolve | train | public function resolve(array $shapeRef)
{
$shape = $shapeRef['shape'];
if (!isset($this->definitions[$shape])) {
throw new \InvalidArgumentException('Shape not found: ' . $shape);
}
$isSimple = count($shapeRef) == 1;
if ($isSimple && isset($this->simple[$shape])) {
return $this->simple[$shape];
}
$definition = $shapeRef + $this->definitions[$shape];
$definition['name'] = $definition['shape'];
unset($definition['shape']);
$result = Shape::create($definition, $this);
if ($isSimple) {
$this->simple[$shape] = $result;
}
return $result;
} | php | {
"resource": ""
} |
q13538 | EncryptionTrait.encrypt | train | protected function encrypt(
Stream $plaintext,
array $cipherOptions,
MaterialsProvider $provider,
MetadataEnvelope $envelope
) {
$materialsDescription = $provider->getMaterialsDescription();
$cipherOptions = array_intersect_key(
$cipherOptions,
self::$allowedOptions
);
if (empty($cipherOptions['Cipher'])) {
throw new \InvalidArgumentException('An encryption cipher must be'
. ' specified in the "cipher_options".');
}
if (!self::isSupportedCipher($cipherOptions['Cipher'])) {
throw new \InvalidArgumentException('The cipher requested is not'
. ' supported by the SDK.');
}
if (empty($cipherOptions['KeySize'])) {
$cipherOptions['KeySize'] = 256;
}
if (!is_int($cipherOptions['KeySize'])) {
throw new \InvalidArgumentException('The cipher "KeySize" must be'
. ' an integer.');
}
if (!MaterialsProvider::isSupportedKeySize(
$cipherOptions['KeySize']
)) {
throw new \InvalidArgumentException('The cipher "KeySize" requested'
. ' is not supported by AES (128, 192, or 256).');
}
$cipherOptions['Iv'] = $provider->generateIv(
$this->getCipherOpenSslName(
$cipherOptions['Cipher'],
$cipherOptions['KeySize']
)
);
$cek = $provider->generateCek($cipherOptions['KeySize']);
list($encryptingStream, $aesName) = $this->getEncryptingStream(
$plaintext,
$cek,
$cipherOptions
);
// Populate envelope data
$envelope[MetadataEnvelope::CONTENT_KEY_V2_HEADER] =
$provider->encryptCek(
$cek,
$materialsDescription
);
unset($cek);
$envelope[MetadataEnvelope::IV_HEADER] =
base64_encode($cipherOptions['Iv']);
$envelope[MetadataEnvelope::KEY_WRAP_ALGORITHM_HEADER] =
$provider->getWrapAlgorithmName();
$envelope[MetadataEnvelope::CONTENT_CRYPTO_SCHEME_HEADER] = $aesName;
$envelope[MetadataEnvelope::UNENCRYPTED_CONTENT_LENGTH_HEADER] =
strlen($plaintext);
$envelope[MetadataEnvelope::UNENCRYPTED_CONTENT_MD5_HEADER] =
base64_encode(md5($plaintext));
$envelope[MetadataEnvelope::MATERIALS_DESCRIPTION_HEADER] =
json_encode($materialsDescription);
if (!empty($cipherOptions['Tag'])) {
$envelope[MetadataEnvelope::CRYPTO_TAG_LENGTH_HEADER] =
strlen($cipherOptions['Tag']) * 8;
}
return $encryptingStream;
} | php | {
"resource": ""
} |
q13539 | PartitionEndpointProvider.getPartition | train | public function getPartition($region, $service)
{
foreach ($this->partitions as $partition) {
if ($partition->isRegionMatch($region, $service)) {
return $partition;
}
}
return $this->getPartitionByName($this->defaultPartition);
} | php | {
"resource": ""
} |
q13540 | PartitionEndpointProvider.getPartitionByName | train | public function getPartitionByName($name)
{
foreach ($this->partitions as $partition) {
if ($name === $partition->getName()) {
return $partition;
}
}
} | php | {
"resource": ""
} |
q13541 | PartitionEndpointProvider.mergePrefixData | train | public static function mergePrefixData($data, $prefixData)
{
$prefixGroups = $prefixData['prefix-groups'];
foreach ($data["partitions"] as $index => $partition) {
foreach ($prefixGroups as $current => $old) {
$serviceData = Env::search("services.{$current}", $partition);
if (!empty($serviceData)) {
foreach ($old as $prefix) {
if (empty(Env::search("services.{$prefix}", $partition))) {
$data["partitions"][$index]["services"][$prefix] = $serviceData;
}
}
}
}
}
return $data;
} | php | {
"resource": ""
} |
q13542 | CredentialProvider.env | train | public static function env()
{
return function () {
// Use credentials from environment variables, if available
$key = getenv(self::ENV_KEY);
$secret = getenv(self::ENV_SECRET);
if ($key && $secret) {
return Promise\promise_for(
new Credentials($key, $secret, getenv(self::ENV_SESSION) ?: NULL)
);
}
return self::reject('Could not find environment variable '
. 'credentials in ' . self::ENV_KEY . '/' . self::ENV_SECRET);
};
} | php | {
"resource": ""
} |
q13543 | CredentialProvider.ini | train | public static function ini($profile = null, $filename = null)
{
$filename = $filename ?: (self::getHomeDir() . '/.aws/credentials');
$profile = $profile ?: (getenv(self::ENV_PROFILE) ?: 'default');
return function () use ($profile, $filename) {
if (!is_readable($filename)) {
return self::reject("Cannot read credentials from $filename");
}
$data = \Aws\parse_ini_file($filename, true, INI_SCANNER_RAW);
if ($data === false) {
return self::reject("Invalid credentials file: $filename");
}
if (!isset($data[$profile])) {
return self::reject("'$profile' not found in credentials file");
}
if (!isset($data[$profile]['aws_access_key_id'])
|| !isset($data[$profile]['aws_secret_access_key'])
) {
return self::reject("No credentials present in INI profile "
. "'$profile' ($filename)");
}
if (empty($data[$profile]['aws_session_token'])) {
$data[$profile]['aws_session_token']
= isset($data[$profile]['aws_security_token'])
? $data[$profile]['aws_security_token']
: null;
}
return Promise\promise_for(
new Credentials(
$data[$profile]['aws_access_key_id'],
$data[$profile]['aws_secret_access_key'],
$data[$profile]['aws_session_token']
)
);
};
} | php | {
"resource": ""
} |
q13544 | CredentialProvider.process | train | public static function process($profile = null, $filename = null)
{
$filename = $filename ?: (self::getHomeDir() . '/.aws/credentials');
$profile = $profile ?: (getenv(self::ENV_PROFILE) ?: 'default');
return function () use ($profile, $filename) {
if (!is_readable($filename)) {
return self::reject("Cannot read process credentials from $filename");
}
$data = \Aws\parse_ini_file($filename, true, INI_SCANNER_RAW);
if ($data === false) {
return self::reject("Invalid credentials file: $filename");
}
if (!isset($data[$profile])) {
return self::reject("'$profile' not found in credentials file");
}
if (!isset($data[$profile]['credential_process'])
) {
return self::reject("No credential_process present in INI profile "
. "'$profile' ($filename)");
}
$credentialProcess = $data[$profile]['credential_process'];
$json = shell_exec($credentialProcess);
$processData = json_decode($json, true);
// Only support version 1
if (isset($processData['Version'])) {
if ($processData['Version'] !== 1) {
return self::reject("credential_process does not return Version == 1");
}
}
if (!isset($processData['AccessKeyId']) || !isset($processData['SecretAccessKey'])) {
return self::reject("credential_process does not return valid credentials");
}
if (isset($processData['Expiration'])) {
try {
$expiration = new DateTimeResult($processData['Expiration']);
} catch (\Exception $e) {
return self::reject("credential_process returned invalid expiration");
}
$now = new DateTimeResult();
if ($expiration < $now) {
return self::reject("credential_process returned expired credentials");
}
} else {
$processData['Expiration'] = null;
}
if (empty($processData['SessionToken'])) {
$processData['SessionToken'] = null;
}
return Promise\promise_for(
new Credentials(
$processData['AccessKeyId'],
$processData['SecretAccessKey'],
$processData['SessionToken'],
$processData['Expiration']
)
);
};
} | php | {
"resource": ""
} |
q13545 | Middleware.requestBuilder | train | public static function requestBuilder(callable $serializer)
{
return function (callable $handler) use ($serializer) {
return function (CommandInterface $command) use ($serializer, $handler) {
return $handler($command, $serializer($command));
};
};
} | php | {
"resource": ""
} |
q13546 | Middleware.signer | train | public static function signer(callable $credProvider, callable $signatureFunction)
{
return function (callable $handler) use ($signatureFunction, $credProvider) {
return function (
CommandInterface $command,
RequestInterface $request
) use ($handler, $signatureFunction, $credProvider) {
$signer = $signatureFunction($command);
return $credProvider()->then(
function (CredentialsInterface $creds)
use ($handler, $command, $signer, $request) {
return $handler(
$command,
$signer->signRequest($request, $creds)
);
}
);
};
};
} | php | {
"resource": ""
} |
q13547 | Middleware.tap | train | public static function tap(callable $fn)
{
return function (callable $handler) use ($fn) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $fn) {
$fn($command, $request);
return $handler($command, $request);
};
};
} | php | {
"resource": ""
} |
q13548 | Middleware.invocationId | train | public static function invocationId()
{
return function (callable $handler) {
return function (
CommandInterface $command,
RequestInterface $request
) use ($handler){
return $handler($command, $request->withHeader(
'aws-sdk-invocation-id',
md5(uniqid(gethostname(), true))
));
};
};
} | php | {
"resource": ""
} |
q13549 | Middleware.contentType | train | public static function contentType(array $operations)
{
return function (callable $handler) use ($operations) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $operations) {
if (!$request->hasHeader('Content-Type')
&& in_array($command->getName(), $operations, true)
&& ($uri = $request->getBody()->getMetadata('uri'))
) {
$request = $request->withHeader(
'Content-Type',
Psr7\mimetype_from_filename($uri) ?: 'application/octet-stream'
);
}
return $handler($command, $request);
};
};
} | php | {
"resource": ""
} |
q13550 | Middleware.history | train | public static function history(History $history)
{
return function (callable $handler) use ($history) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $history) {
$ticket = $history->start($command, $request);
return $handler($command, $request)
->then(
function ($result) use ($history, $ticket) {
$history->finish($ticket, $result);
return $result;
},
function ($reason) use ($history, $ticket) {
$history->finish($ticket, $reason);
return Promise\rejection_for($reason);
}
);
};
};
} | php | {
"resource": ""
} |
q13551 | Middleware.mapRequest | train | public static function mapRequest(callable $f)
{
return function (callable $handler) use ($f) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $f) {
return $handler($command, $f($request));
};
};
} | php | {
"resource": ""
} |
q13552 | Middleware.mapCommand | train | public static function mapCommand(callable $f)
{
return function (callable $handler) use ($f) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $f) {
return $handler($f($command), $request);
};
};
} | php | {
"resource": ""
} |
q13553 | Middleware.mapResult | train | public static function mapResult(callable $f)
{
return function (callable $handler) use ($f) {
return function (
CommandInterface $command,
RequestInterface $request = null
) use ($handler, $f) {
return $handler($command, $request)->then($f);
};
};
} | php | {
"resource": ""
} |
q13554 | AbstractUploadManager.determineState | train | private function determineState()
{
// If the state was provided via config, then just use it.
if ($this->config['state'] instanceof UploadState) {
return $this->config['state'];
}
// Otherwise, construct a new state from the provided identifiers.
$required = $this->info['id'];
$id = [$required['upload_id'] => null];
unset($required['upload_id']);
foreach ($required as $key => $param) {
if (!$this->config[$key]) {
throw new IAE('You must provide a value for "' . $key . '" in '
. 'your config for the MultipartUploader for '
. $this->client->getApi()->getServiceFullName() . '.');
}
$id[$param] = $this->config[$key];
}
$state = new UploadState($id);
$state->setPartSize($this->determinePartSize());
return $state;
} | php | {
"resource": ""
} |
q13555 | S3ClientTrait.checkExistenceWithCommand | train | private function checkExistenceWithCommand(CommandInterface $command)
{
try {
$this->execute($command);
return true;
} catch (S3Exception $e) {
if ($e->getAwsErrorCode() == 'AccessDenied') {
return true;
}
if ($e->getStatusCode() >= 500) {
throw $e;
}
return false;
}
} | php | {
"resource": ""
} |
q13556 | MultipartUploader.decorateWithHashes | train | private function decorateWithHashes(Stream $stream, array &$data)
{
// Make sure that a tree hash is calculated.
$stream = new HashingStream($stream, new TreeHash(),
function ($result) use (&$data) {
$data['checksum'] = bin2hex($result);
}
);
// Make sure that a linear SHA256 hash is calculated.
$stream = new HashingStream($stream, new PhpHash('sha256'),
function ($result) use (&$data) {
$data['ContentSHA256'] = bin2hex($result);
}
);
return $stream;
} | php | {
"resource": ""
} |
q13557 | MultipartUploader.parseRange | train | private static function parseRange($range, $partSize)
{
// Strip away the prefix and suffix.
if (strpos($range, 'bytes') !== false) {
$range = substr($range, 6, -2);
}
// Split that range into it's parts.
list($firstByte, $lastByte) = explode('-', $range);
// Calculate and return range index and range size
return [
intval($firstByte / $partSize) + 1,
$lastByte - $firstByte + 1,
];
} | php | {
"resource": ""
} |
q13558 | JsonBody.build | train | public function build(Shape $shape, array $args)
{
$result = json_encode($this->format($shape, $args));
return $result == '[]' ? '{}' : $result;
} | php | {
"resource": ""
} |
q13559 | PhpHash.getContext | train | private function getContext()
{
if (!$this->context) {
$key = isset($this->options['key']) ? $this->options['key'] : null;
$this->context = hash_init(
$this->algo,
$key ? HASH_HMAC : 0,
$key
);
}
return $this->context;
} | php | {
"resource": ""
} |
q13560 | Waiter.getArgsForAttempt | train | private function getArgsForAttempt($attempt)
{
$args = $this->args;
// Determine the delay.
$delay = ($attempt === 1)
? $this->config['initDelay']
: $this->config['delay'];
if (is_callable($delay)) {
$delay = $delay($attempt);
}
// Set the delay. (Note: handlers except delay in milliseconds.)
if (!isset($args['@http'])) {
$args['@http'] = [];
}
$args['@http']['delay'] = $delay * 1000;
return $args;
} | php | {
"resource": ""
} |
q13561 | Waiter.determineState | train | private function determineState($result)
{
foreach ($this->config['acceptors'] as $acceptor) {
$matcher = 'matches' . ucfirst($acceptor['matcher']);
if ($this->{$matcher}($result, $acceptor)) {
return $acceptor['state'];
}
}
return $result instanceof \Exception ? 'failed' : 'retry';
} | php | {
"resource": ""
} |
q13562 | Transfer.promise | train | public function promise()
{
// If the promise has been created, just return it.
if (!$this->promise) {
// Create an upload/download promise for the transfer.
$this->promise = $this->sourceMetadata['scheme'] === 'file'
? $this->createUploadPromise()
: $this->createDownloadPromise();
}
return $this->promise;
} | php | {
"resource": ""
} |
q13563 | Transfer.getS3Args | train | private function getS3Args($path)
{
$parts = explode('/', str_replace('s3://', '', $path), 2);
$args = ['Bucket' => $parts[0]];
if (isset($parts[1])) {
$args['Key'] = $parts[1];
}
return $args;
} | php | {
"resource": ""
} |
q13564 | ClientResolver.resolve | train | public function resolve(array $args, HandlerList $list)
{
$args['config'] = [];
foreach ($this->argDefinitions as $key => $a) {
// Add defaults, validate required values, and skip if not set.
if (!isset($args[$key])) {
if (isset($a['default'])) {
// Merge defaults in when not present.
if (is_callable($a['default'])
&& (
is_array($a['default'])
|| $a['default'] instanceof \Closure
)
) {
$args[$key] = $a['default']($args);
} else {
$args[$key] = $a['default'];
}
} elseif (empty($a['required'])) {
continue;
} else {
$this->throwRequired($args);
}
}
// Validate the types against the provided value.
foreach ($a['valid'] as $check) {
if (isset(self::$typeMap[$check])) {
$fn = self::$typeMap[$check];
if ($fn($args[$key])) {
goto is_valid;
}
} elseif ($args[$key] instanceof $check) {
goto is_valid;
}
}
$this->invalidType($key, $args[$key]);
// Apply the value
is_valid:
if (isset($a['fn'])) {
$a['fn']($args[$key], $args, $list);
}
if ($a['type'] === 'config') {
$args['config'][$key] = $args[$key];
}
}
return $args;
} | php | {
"resource": ""
} |
q13565 | ClientResolver.getArgMessage | train | private function getArgMessage($name, $args = [], $useRequired = false)
{
$arg = $this->argDefinitions[$name];
$msg = '';
$modifiers = [];
if (isset($arg['valid'])) {
$modifiers[] = implode('|', $arg['valid']);
}
if (isset($arg['choice'])) {
$modifiers[] = 'One of ' . implode(', ', $arg['choice']);
}
if ($modifiers) {
$msg .= '(' . implode('; ', $modifiers) . ')';
}
$msg = wordwrap("{$name}: {$msg}", 75, "\n ");
if ($useRequired && is_callable($arg['required'])) {
$msg .= "\n\n ";
$msg .= str_replace("\n", "\n ", call_user_func($arg['required'], $args));
} elseif (isset($arg['doc'])) {
$msg .= wordwrap("\n\n {$arg['doc']}", 75, "\n ");
}
return $msg;
} | php | {
"resource": ""
} |
q13566 | ClientResolver.invalidType | train | private function invalidType($name, $provided)
{
$expected = implode('|', $this->argDefinitions[$name]['valid']);
$msg = "Invalid configuration value "
. "provided for \"{$name}\". Expected {$expected}, but got "
. describe_type($provided) . "\n\n"
. $this->getArgMessage($name);
throw new IAE($msg);
} | php | {
"resource": ""
} |
q13567 | ClientResolver.throwRequired | train | private function throwRequired(array $args)
{
$missing = [];
foreach ($this->argDefinitions as $k => $a) {
if (empty($a['required'])
|| isset($a['default'])
|| isset($args[$k])
) {
continue;
}
$missing[] = $this->getArgMessage($k, $args, true);
}
$msg = "Missing required client configuration options: \n\n";
$msg .= implode("\n\n", $missing);
throw new IAE($msg);
} | php | {
"resource": ""
} |
q13568 | AbstractMonitoringMiddleware.sendEventData | train | private function sendEventData(array $eventData)
{
$socket = $this->prepareSocket();
$datagram = json_encode($eventData);
$result = socket_write($socket, $datagram, strlen($datagram));
if ($result === false) {
$this->prepareSocket(true);
}
return $result;
} | php | {
"resource": ""
} |
q13569 | AbstractMonitoringMiddleware.unwrappedOptions | train | private function unwrappedOptions()
{
if (!($this->options instanceof ConfigurationInterface)) {
$this->options = ConfigurationProvider::unwrap($this->options);
}
return $this->options;
} | php | {
"resource": ""
} |
q13570 | CloudSearchDomainClient.searchByPost | train | private function searchByPost()
{
return static function (callable $handler) {
return function (
CommandInterface $c,
RequestInterface $r = null
) use ($handler) {
if ($c->getName() !== 'Search') {
return $handler($c, $r);
}
return $handler($c, self::convertGetToPost($r));
};
};
} | php | {
"resource": ""
} |
q13571 | CloudSearchDomainClient.convertGetToPost | train | public static function convertGetToPost(RequestInterface $r)
{
if ($r->getMethod() === 'POST') {
return $r;
}
$query = $r->getUri()->getQuery();
$req = $r->withMethod('POST')
->withBody(Psr7\stream_for($query))
->withHeader('Content-Length', strlen($query))
->withHeader('Content-Type', 'application/x-www-form-urlencoded')
->withUri($r->getUri()->withQuery(''));
return $req;
} | php | {
"resource": ""
} |
q13572 | Validator.validate | train | public function validate($name, Shape $shape, array $input)
{
$this->dispatch($shape, $input);
if ($this->errors) {
$message = sprintf(
"Found %d error%s while validating the input provided for the "
. "%s operation:\n%s",
count($this->errors),
count($this->errors) > 1 ? 's' : '',
$name,
implode("\n", $this->errors)
);
$this->errors = [];
throw new \InvalidArgumentException($message);
}
} | php | {
"resource": ""
} |
q13573 | S3EncryptionClient.getObjectAsync | train | public function getObjectAsync(array $args)
{
$provider = $this->getMaterialsProvider($args);
unset($args['@MaterialsProvider']);
$instructionFileSuffix = $this->getInstructionFileSuffix($args);
unset($args['@InstructionFileSuffix']);
$strategy = $this->getMetadataStrategy($args, $instructionFileSuffix);
unset($args['@MetadataStrategy']);
$saveAs = null;
if (!empty($args['SaveAs'])) {
$saveAs = $args['SaveAs'];
}
$promise = $this->client->getObjectAsync($args)
->then(
function ($result) use (
$provider,
$instructionFileSuffix,
$strategy,
$args
) {
if ($strategy === null) {
$strategy = $this->determineGetObjectStrategy(
$result,
$instructionFileSuffix
);
}
$envelope = $strategy->load($args + [
'Metadata' => $result['Metadata']
]);
$provider = $provider->fromDecryptionEnvelope($envelope);
$result['Body'] = $this->decrypt(
$result['Body'],
$provider,
$envelope,
isset($args['@CipherOptions'])
? $args['@CipherOptions']
: []
);
return $result;
}
)->then(
function ($result) use ($saveAs) {
if (!empty($saveAs)) {
file_put_contents(
$saveAs,
(string)$result['Body'],
LOCK_EX
);
}
return $result;
}
);
return $promise;
} | php | {
"resource": ""
} |
q13574 | AwsClient.parseClass | train | private function parseClass()
{
$klass = get_class($this);
if ($klass === __CLASS__) {
return ['', 'Aws\Exception\AwsException'];
}
$service = substr($klass, strrpos($klass, '\\') + 1, -6);
return [
strtolower($service),
"Aws\\{$service}\\Exception\\{$service}Exception"
];
} | php | {
"resource": ""
} |
q13575 | StructureShape.getMember | train | public function getMember($name)
{
$members = $this->getMembers();
if (!isset($members[$name])) {
throw new \InvalidArgumentException('Unknown member ' . $name);
}
return $members[$name];
} | php | {
"resource": ""
} |
q13576 | IdempotencyTokenMiddleware.wrap | train | public static function wrap(
Service $service,
callable $bytesGenerator = null
) {
return function (callable $handler) use ($service, $bytesGenerator) {
return new self($handler, $service, $bytesGenerator);
};
} | php | {
"resource": ""
} |
q13577 | IdempotencyTokenMiddleware.getUuidV4 | train | private static function getUuidV4($bytes)
{
// set version to 0100
$bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40);
// set bits 6-7 to 10
$bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
} | php | {
"resource": ""
} |
q13578 | CheckstyleErrorFormatter.formatErrors | train | public function formatErrors(
AnalysisResult $analysisResult,
OutputStyle $style
): int
{
$style->writeln('<?xml version="1.0" encoding="UTF-8"?>');
$style->writeln('<checkstyle>');
foreach ($this->groupByFile($analysisResult) as $relativeFilePath => $errors) {
$style->writeln(sprintf(
'<file name="%s">',
$this->escape($relativeFilePath)
));
foreach ($errors as $error) {
$style->writeln(sprintf(
' <error line="%d" column="1" severity="error" message="%s" />',
$this->escape((string) $error->getLine()),
$this->escape((string) $error->getMessage())
));
}
$style->writeln('</file>');
}
$notFileSpecificErrors = $analysisResult->getNotFileSpecificErrors();
if (count($notFileSpecificErrors) > 0) {
$style->writeln('<file>');
foreach ($notFileSpecificErrors as $error) {
$style->writeln(sprintf(' <error severity="error" message="%s" />', $this->escape($error)));
}
$style->writeln('</file>');
}
$style->writeln('</checkstyle>');
return $analysisResult->hasErrors() ? 1 : 0;
} | php | {
"resource": ""
} |
q13579 | CheckstyleErrorFormatter.groupByFile | train | private function groupByFile(AnalysisResult $analysisResult): array
{
$files = [];
/** @var \PHPStan\Analyser\Error $fileSpecificError */
foreach ($analysisResult->getFileSpecificErrors() as $fileSpecificError) {
$relativeFilePath = $this->relativePathHelper->getRelativePath(
$fileSpecificError->getFile()
);
$files[$relativeFilePath][] = $fileSpecificError;
}
return $files;
} | php | {
"resource": ""
} |
q13580 | Pay.registerLogService | train | protected function registerLogService()
{
$logger = Log::createLogger(
$this->config->get('log.file'),
'yansongda.pay',
$this->config->get('log.level', 'warning'),
$this->config->get('log.type', 'daily'),
$this->config->get('log.max_file', 30)
);
Log::setLogger($logger);
} | php | {
"resource": ""
} |
q13581 | Wechat.refund | train | public function refund($order): Collection
{
$this->payload = Support::filterPayload($this->payload, $order, true);
Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Wechat', 'Refund', $this->gateway, $this->payload));
return Support::requestApi(
'secapi/pay/refund',
$this->payload,
true
);
} | php | {
"resource": ""
} |
q13582 | Wechat.download | train | public function download(array $params): string
{
unset($this->payload['spbill_create_ip']);
$this->payload = Support::filterPayload($this->payload, $params, true);
Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Wechat', 'Download', $this->gateway, $this->payload));
$result = Support::getInstance()->post(
'pay/downloadbill',
Support::getInstance()->toXml($this->payload)
);
if (is_array($result)) {
throw new GatewayException('Get Wechat API Error: '.$result['return_msg'], $result);
}
return $result;
} | php | {
"resource": ""
} |
q13583 | Support.getSignContent | train | public static function getSignContent($data): string
{
$buff = '';
foreach ($data as $k => $v) {
$buff .= ($k != 'sign' && $v != '' && !is_array($v)) ? $k.'='.$v.'&' : '';
}
Log::debug('Wechat Generate Sign Content Before Trim', [$data, $buff]);
return trim($buff, '&');
} | php | {
"resource": ""
} |
q13584 | Support.decryptRefundContents | train | public static function decryptRefundContents($contents): string
{
return openssl_decrypt(
base64_decode($contents),
'AES-256-ECB',
md5(self::$instance->key),
OPENSSL_RAW_DATA
);
} | php | {
"resource": ""
} |
q13585 | Support.toXml | train | public static function toXml($data): string
{
if (!is_array($data) || count($data) <= 0) {
throw new InvalidArgumentException('Convert To Xml Error! Invalid Array!');
}
$xml = '<xml>';
foreach ($data as $key => $val) {
$xml .= is_numeric($val) ? '<'.$key.'>'.$val.'</'.$key.'>' :
'<'.$key.'><![CDATA['.$val.']]></'.$key.'>';
}
$xml .= '</xml>';
return $xml;
} | php | {
"resource": ""
} |
q13586 | Support.fromXml | train | public static function fromXml($xml): array
{
if (!$xml) {
throw new InvalidArgumentException('Convert To Array Error! Invalid Xml!');
}
libxml_disable_entity_loader(true);
return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA), JSON_UNESCAPED_UNICODE), true);
} | php | {
"resource": ""
} |
q13587 | Support.getConfig | train | public function getConfig($key = null, $default = null)
{
if (is_null($key)) {
return $this->config->all();
}
if ($this->config->has($key)) {
return $this->config[$key];
}
return $default;
} | php | {
"resource": ""
} |
q13588 | Alipay.cancel | train | public function cancel($order): Collection
{
$this->payload['method'] = 'alipay.trade.cancel';
$this->payload['biz_content'] = json_encode(is_array($order) ? $order : ['out_trade_no' => $order]);
$this->payload['sign'] = Support::generateSign($this->payload);
Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Alipay', 'Cancel', $this->gateway, $this->payload));
return Support::requestApi($this->payload);
} | php | {
"resource": ""
} |
q13589 | Alipay.success | train | public function success(): Response
{
Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Alipay', 'Success', $this->gateway));
return Response::create('success');
} | php | {
"resource": ""
} |
q13590 | Support.getSignContent | train | public static function getSignContent(array $data, $verify = false): string
{
$data = self::encoding($data, $data['charset'] ?? 'gb2312', 'utf-8');
ksort($data);
$stringToBeSigned = '';
foreach ($data as $k => $v) {
if ($verify && $k != 'sign' && $k != 'sign_type') {
$stringToBeSigned .= $k.'='.$v.'&';
}
if (!$verify && $v !== '' && !is_null($v) && $k != 'sign' && '@' != substr($v, 0, 1)) {
$stringToBeSigned .= $k.'='.$v.'&';
}
}
Log::debug('Alipay Generate Sign Content Before Trim', [$data, $stringToBeSigned]);
return trim($stringToBeSigned, '&');
} | php | {
"resource": ""
} |
q13591 | Support.setHttpOptions | train | protected function setHttpOptions(): self
{
if ($this->config->has('http') && is_array($this->config->get('http'))) {
$this->config->forget('http.base_uri');
$this->httpOptions = $this->config->get('http');
}
return $this;
} | php | {
"resource": ""
} |
q13592 | Gateway.preOrder | train | protected function preOrder($payload): Collection
{
$payload['sign'] = Support::generateSign($payload);
Events::dispatch(Events::METHOD_CALLED, new Events\MethodCalled('Wechat', 'PreOrder', '', $payload));
return Support::requestApi('pay/unifiedorder', $payload);
} | php | {
"resource": ""
} |
q13593 | SchemaParser.render | train | public function render()
{
$results = '';
foreach ($this->toArray() as $column => $attributes) {
$results .= $this->createField($column, $attributes);
}
return $results;
} | php | {
"resource": ""
} |
q13594 | SchemaParser.parse | train | public function parse($schema)
{
$this->schema = $schema;
$parsed = [];
foreach ($this->getSchemas() as $schemaArray) {
$column = $this->getColumn($schemaArray);
$attributes = $this->getAttributes($column, $schemaArray);
$parsed[$column] = $attributes;
}
return $parsed;
} | php | {
"resource": ""
} |
q13595 | SchemaParser.getAttributes | train | public function getAttributes($column, $schema)
{
$fields = str_replace($column . ':', '', $schema);
return $this->hasCustomAttribute($column) ? $this->getCustomAttribute($column) : explode(':', $fields);
} | php | {
"resource": ""
} |
q13596 | SchemaParser.down | train | public function down()
{
$results = '';
foreach ($this->toArray() as $column => $attributes) {
$results .= $this->createField($column, $attributes, 'remove');
}
return $results;
} | php | {
"resource": ""
} |
q13597 | RulesParser.parse | train | public function parse($rules)
{
$this->rules = $rules;
$parsed = [];
foreach ($this->getRules() as $rulesArray) {
$column = $this->getColumn($rulesArray);
$attributes = $this->getAttributes($column, $rulesArray);
$parsed[$column] = $attributes;
}
return $parsed;
} | php | {
"resource": ""
} |
q13598 | RepositoryEloquentGenerator.getFillable | train | public function getFillable()
{
if (!$this->fillable) {
return '[]';
}
$results = '[' . PHP_EOL;
foreach ($this->getSchemaParser()->toArray() as $column => $value) {
$results .= "\t\t'{$column}'," . PHP_EOL;
}
return $results . "\t" . ']';
} | php | {
"resource": ""
} |
q13599 | CacheableRepository.getCacheRepository | train | public function getCacheRepository()
{
if (is_null($this->cacheRepository)) {
$this->cacheRepository = app(config('repository.cache.repository', 'cache'));
}
return $this->cacheRepository;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.