_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q13400
Model.get_or
train
public function get_or($fields) { $args = array(); $fieldsValue = $fields; $fields = $this->getFields(); $sql = ''; foreach ($fields as $field) { if (isset($fieldsValue[$field])) { $value = $fieldsValue[$field]; if (is_array($value)) { foreach ($value as $subvalue) { $sql .= '`' . $field . '` = ? OR '; $args[] = $subvalue; } } else { $sql .= '`' . $field . '` = ? OR '; $args[] = $value; } } } if (!empty($sql)) { $sql = substr($sql, 0, -4); return $this->build($this->db->select('SELECT * FROM `' . $this->table_name . '` WHERE ' . $sql, $args)); } return $this->build(array()); }
php
{ "resource": "" }
q13401
Model.get_all
train
public function get_all() { return $this->build($this->db->select('SELECT * FROM `' . $this->table_name . '` WHERE 1', [], $this->getCacheId('all'))); }
php
{ "resource": "" }
q13402
Model.get_others
train
public function get_others() { $index = $this->getIndex(); $value = $this->getFieldValue($index); if (is_string($value) && strlen($value) > 0) { return $this->build($this->db->select('SELECT * FROM `' . $this->table_name . '` WHERE `' . $index . '` != ?', array((string)$value), $this->getCacheId("not_" . $value))); } return $this->get_all(); }
php
{ "resource": "" }
q13403
Model.search
train
public function search($fields, $limit = -1) { if (!is_array($fields)) { $fields = array($this->getIndex() => $fields); } $fieldsValue = $fields; $fields = $this->getFields(); $sql = ''; $args = array(); foreach ($fields as $field) { if (isset($fieldsValue[$field])) { $value = $fieldsValue[$field]; if ($this->isString($field)) { $sql .= '`' . $field . '` LIKE ? OR '; $args[] = '%' . $value . '%'; } else { $sql .= '`' . $field . '` = ? OR '; $args[] = $value; } } } if (!empty($sql)) { $sql = substr($sql, 0, -4); if($limit > 0) { $sql .= " LIMIT $limit"; } return $this->build($this->db->select('SELECT * FROM `' . $this->table_name . '` WHERE ' . $sql, $args)); } return $this->build(array()); }
php
{ "resource": "" }
q13404
Model.save
train
public function save($updateIndex = false) { $this->clearCacheTableIndex(); if ($this->exists()) { return $this->update(); } $result = $this->insert(); if ($result && $updateIndex) { $this->setToIndex($result); } return $result; }
php
{ "resource": "" }
q13405
Model.exists
train
public function exists() { $indexValue = $this->getFieldValue($this->getIndex()); if ($indexValue) { return $this->get($indexValue)->count() > 0; } return false; }
php
{ "resource": "" }
q13406
Model.getFieldValue
train
public function getFieldValue($field, $data = null) { if ($data !== null && isset($data[$field])) { return $data[$field]; } if (isset($this->{$field})) { return $this->{$field}; } return null; }
php
{ "resource": "" }
q13407
Model.getFields
train
public function getFields() { $fields = array(); if (isset($this->definition['index'])) { $fields[] = $this->getIndex(); } if (isset($this->definition['fields'])) { foreach ($this->definition['fields'] as $key => $value) { if (!is_numeric($key)) { $fields[] = $key; } else { $fields[] = $value; } } } return $fields; }
php
{ "resource": "" }
q13408
Model.build
train
public function build($result) { $modelResult = new ModelResult($this); $modelResult->models = $result; if (count($result) > 0) { $modelResult->model = $result[0]; } if ($this->order !== '') { $modelResult->order($this->order); } return $modelResult; }
php
{ "resource": "" }
q13409
Model.setData
train
public function setData($data, $allowEmpty = true, $allowUnset = false) { if ($data != null) { if (is_array($data)) { $fileds = $this->getFields(); foreach ($fileds as $field) { if (isset($data[$field]) && ($allowEmpty || $data[$field] !== '')) { if (strpos($this->getFieldType($field), 'varchar') !== false || $this->getFieldType($field) === 'text') { $encoding = mb_detect_encoding($data[$field]); if ($encoding !== 'utf8') { $this->{$field} = mb_convert_encoding($data[$field], 'utf8', $encoding); } else { $this->{$field} = $data[$field]; } } else { $this->{$field} = $data[$field]; } } elseif ($allowUnset) { $this->{$field} = false; } } } else { $result = $this->get($data); $this->setData($result->model); if (empty($result->model)) { $this->asDefault(); } } } if (empty($data)) { $this->asDefault(); } return $this; }
php
{ "resource": "" }
q13410
Model.getFieldDefinition
train
public function getFieldDefinition($field) { if (isset($this->definition[$field])) { return $this->definition[$field]; } if (isset($this->definition['fields'][$field])) { return $this->definition['fields'][$field]; } return null; }
php
{ "resource": "" }
q13411
Model.getFieldType
train
public function getFieldType($field) { $definition = $this->getFieldDefinition($field); if ($definition && isset($definition['type'])) { return $definition['type']; } }
php
{ "resource": "" }
q13412
Model.getStructureDifferences
train
public function getStructureDifferences($db, $drop = false) { $diff = new DBStructure(); $excepted = $diff->getDefinition($this); return $diff->getStructureDifferences($db, $excepted, $drop); }
php
{ "resource": "" }
q13413
ResponseManager.makeResult
train
public static function makeResult($data, $message) { $result = array(); $result['flag'] = true; $result['message'] = $message; $result['data'] = $data; return $result; }
php
{ "resource": "" }
q13414
ChannelDeletionListener.onChannelPreDelete
train
public function onChannelPreDelete(ResourceControllerEvent $event): void { $channel = $event->getSubject(); if (!$channel instanceof ChannelInterface) { throw new UnexpectedTypeException( $channel, ChannelInterface::class ); } $results = $this->channelRepository->findBy(['enabled' => true]); if (!$results || (count($results) === 1 && current($results) === $channel)) { $event->stop('sylius.channel.delete_error'); } }
php
{ "resource": "" }
q13415
OrderItem.getTaxTotal
train
public function getTaxTotal(): int { $taxTotal = 0; foreach ($this->getAdjustments(AdjustmentInterface::TAX_ADJUSTMENT) as $taxAdjustment) { $taxTotal += $taxAdjustment->getAmount(); } foreach ($this->units as $unit) { $taxTotal += $unit->getTaxTotal(); } return $taxTotal; }
php
{ "resource": "" }
q13416
HasEnabledEntityValidator.isLastEnabledEntity
train
private function isLastEnabledEntity($result, $entity): bool { return !$result || 0 === count($result) || (1 === count($result) && $entity === ($result instanceof \Iterator ? $result->current() : current($result))); }
php
{ "resource": "" }
q13417
Order.recalculateTotal
train
protected function recalculateTotal(): void { $this->total = $this->itemsTotal + $this->adjustmentsTotal; if ($this->total < 0) { $this->total = 0; } }
php
{ "resource": "" }
q13418
SecurityController.loginAction
train
public function loginAction(Request $request): Response { $authenticationUtils = $this->get('security.authentication_utils'); $error = $authenticationUtils->getLastAuthenticationError(); $lastUsername = $authenticationUtils->getLastUsername(); $options = $request->attributes->get('_sylius'); $template = $options['template'] ?? null; Assert::notNull($template, 'Template is not configured.'); $formType = $options['form'] ?? UserLoginType::class; $form = $this->get('form.factory')->createNamed('', $formType); return $this->render($template, [ 'form' => $form->createView(), 'last_username' => $lastUsername, 'error' => $error, ]); }
php
{ "resource": "" }
q13419
Order.getTaxTotal
train
public function getTaxTotal(): int { $taxTotal = 0; foreach ($this->getAdjustments(AdjustmentInterface::TAX_ADJUSTMENT) as $taxAdjustment) { $taxTotal += $taxAdjustment->getAmount(); } foreach ($this->items as $item) { $taxTotal += $item->getTaxTotal(); } return $taxTotal; }
php
{ "resource": "" }
q13420
Order.getShippingTotal
train
public function getShippingTotal(): int { $shippingTotal = $this->getAdjustmentsTotal(AdjustmentInterface::SHIPPING_ADJUSTMENT); $shippingTotal += $this->getAdjustmentsTotal(AdjustmentInterface::ORDER_SHIPPING_PROMOTION_ADJUSTMENT); $shippingTotal += $this->getAdjustmentsTotal(AdjustmentInterface::TAX_ADJUSTMENT); return $shippingTotal; }
php
{ "resource": "" }
q13421
Order.getOrderPromotionTotal
train
public function getOrderPromotionTotal(): int { $orderPromotionTotal = 0; foreach ($this->items as $item) { $orderPromotionTotal += $item->getAdjustmentsTotalRecursively(AdjustmentInterface::ORDER_PROMOTION_ADJUSTMENT); } return $orderPromotionTotal; }
php
{ "resource": "" }
q13422
OrderItem.recalculateTotal
train
protected function recalculateTotal(): void { $this->total = $this->unitsTotal + $this->adjustmentsTotal; if ($this->total < 0) { $this->total = 0; } if (null !== $this->order) { $this->order->recalculateItemsTotal(); } }
php
{ "resource": "" }
q13423
UserProvider.updateUserByOAuthUserResponse
train
private function updateUserByOAuthUserResponse(UserInterface $user, UserResponseInterface $response): SyliusUserInterface { /** @var SyliusUserInterface $user */ Assert::isInstanceOf($user, SyliusUserInterface::class); /** @var UserOAuthInterface $oauth */ $oauth = $this->oauthFactory->createNew(); $oauth->setIdentifier($response->getUsername()); $oauth->setProvider($response->getResourceOwner()->getName()); $oauth->setAccessToken($response->getAccessToken()); $oauth->setRefreshToken($response->getRefreshToken()); $user->addOAuthAccount($oauth); $this->userManager->persist($user); $this->userManager->flush(); return $user; }
php
{ "resource": "" }
q13424
User.serialize
train
public function serialize(): string { return serialize([ $this->password, $this->salt, $this->usernameCanonical, $this->username, $this->locked, $this->enabled, $this->id, $this->encoderName, ]); }
php
{ "resource": "" }
q13425
ApiCallMonitoringMiddleware.wrap
train
public static function wrap( callable $credentialProvider, $options, $region, $service ) { return function (callable $handler) use ( $credentialProvider, $options, $region, $service ) { return new static( $handler, $credentialProvider, $options, $region, $service ); }; }
php
{ "resource": "" }
q13426
DocModel.getOperationDocs
train
public function getOperationDocs($operation) { return isset($this->docs['operations'][$operation]) ? $this->docs['operations'][$operation] : null; }
php
{ "resource": "" }
q13427
DocModel.getErrorDocs
train
public function getErrorDocs($error) { return isset($this->docs['shapes'][$error]['base']) ? $this->docs['shapes'][$error]['base'] : null; }
php
{ "resource": "" }
q13428
DocModel.getShapeDocs
train
public function getShapeDocs($shapeName, $parentName, $ref) { if (!isset($this->docs['shapes'][$shapeName])) { return ''; } $result = ''; $d = $this->docs['shapes'][$shapeName]; if (isset($d['refs']["{$parentName}\$${ref}"])) { $result = $d['refs']["{$parentName}\$${ref}"]; } elseif (isset($d['base'])) { $result = $d['base']; } if (isset($d['append'])) { $result .= $d['append']; } return $this->clean($result); }
php
{ "resource": "" }
q13429
AuthTokenGenerator.createToken
train
public function createToken($endpoint, $region, $username) { $uri = new Uri($endpoint); $uri = $uri->withPath('/'); $uri = $uri->withQuery('Action=connect&DBUser=' . $username); $request = new Request('GET', $uri); $signer = new SignatureV4('rds-db', $region); $provider = $this->credentialProvider; $url = (string) $signer->presign( $request, $provider()->wait(), '+15 minutes' )->getUri(); // Remove 2 extra slash from the presigned url result return substr($url, 2); }
php
{ "resource": "" }
q13430
EndpointProvider.resolve
train
public static function resolve(callable $provider, array $args = []) { $result = $provider($args); if (is_array($result)) { return $result; } throw new UnresolvedEndpointException( 'Unable to resolve an endpoint using the provider arguments: ' . json_encode($args) . '. Note: you can provide an "endpoint" ' . 'option to a client constructor to bypass invoking an endpoint ' . 'provider.'); }
php
{ "resource": "" }
q13431
S3ControlEndpointMiddleware.wrap
train
public static function wrap($region, array $options) { return function (callable $handler) use ($region, $options) { return new self($handler, $region, $options); }; }
php
{ "resource": "" }
q13432
InstructionFileMetadataStrategy.save
train
public function save(MetadataEnvelope $envelope, array $args) { $this->client->putObject([ 'Bucket' => $args['Bucket'], 'Key' => $args['Key'] . $this->suffix, 'Body' => json_encode($envelope) ]); return $args; }
php
{ "resource": "" }
q13433
InstructionFileMetadataStrategy.load
train
public function load(array $args) { $result = $this->client->getObject([ 'Bucket' => $args['Bucket'], 'Key' => $args['Key'] . $this->suffix ]); $metadataHeaders = json_decode($result['Body'], true); $envelope = new MetadataEnvelope(); $constantValues = MetadataEnvelope::getConstantValues(); foreach ($constantValues as $constant) { if (!empty($metadataHeaders[$constant])) { $envelope[$constant] = $metadataHeaders[$constant]; } } return $envelope; }
php
{ "resource": "" }
q13434
Service.createSerializer
train
public static function createSerializer(Service $api, $endpoint) { static $mapping = [ 'json' => 'Aws\Api\Serializer\JsonRpcSerializer', 'query' => 'Aws\Api\Serializer\QuerySerializer', 'rest-json' => 'Aws\Api\Serializer\RestJsonSerializer', 'rest-xml' => 'Aws\Api\Serializer\RestXmlSerializer' ]; $proto = $api->getProtocol(); if (isset($mapping[$proto])) { return new $mapping[$proto]($api, $endpoint); } if ($proto == 'ec2') { return new QuerySerializer($api, $endpoint, new Ec2ParamBuilder()); } throw new \UnexpectedValueException( 'Unknown protocol: ' . $api->getProtocol() ); }
php
{ "resource": "" }
q13435
Service.getOperation
train
public function getOperation($name) { if (!isset($this->operations[$name])) { if (!isset($this->definition['operations'][$name])) { throw new \InvalidArgumentException("Unknown operation: $name"); } $this->operations[$name] = new Operation( $this->definition['operations'][$name], $this->shapeMap ); } return $this->operations[$name]; }
php
{ "resource": "" }
q13436
Service.getOperations
train
public function getOperations() { $result = []; foreach ($this->definition['operations'] as $name => $definition) { $result[$name] = $this->getOperation($name); } return $result; }
php
{ "resource": "" }
q13437
Service.getMetadata
train
public function getMetadata($key = null) { if (!$key) { return $this['metadata']; } if (isset($this->definition['metadata'][$key])) { return $this->definition['metadata'][$key]; } return null; }
php
{ "resource": "" }
q13438
Service.getPaginators
train
public function getPaginators() { if (!isset($this->paginators)) { $res = call_user_func( $this->apiProvider, 'paginator', $this->serviceName, $this->apiVersion ); $this->paginators = isset($res['pagination']) ? $res['pagination'] : []; } return $this->paginators; }
php
{ "resource": "" }
q13439
Service.getPaginatorConfig
train
public function getPaginatorConfig($name) { static $defaults = [ 'input_token' => null, 'output_token' => null, 'limit_key' => null, 'result_key' => null, 'more_results' => null, ]; if ($this->hasPaginator($name)) { return $this->paginators[$name] + $defaults; } throw new \UnexpectedValueException("There is no {$name} " . "paginator defined for the {$this->serviceName} service."); }
php
{ "resource": "" }
q13440
Service.getWaiters
train
public function getWaiters() { if (!isset($this->waiters)) { $res = call_user_func( $this->apiProvider, 'waiter', $this->serviceName, $this->apiVersion ); $this->waiters = isset($res['waiters']) ? $res['waiters'] : []; } return $this->waiters; }
php
{ "resource": "" }
q13441
TreeHash.addChecksum
train
public function addChecksum($checksum, $inBinaryForm = false) { // Error if hash is already calculated if ($this->hash) { throw new \LogicException('You may not add more checksums to a ' . 'complete tree hash.'); } // Convert the checksum to binary form if necessary $this->checksums[] = $inBinaryForm ? $checksum : hex2bin($checksum); return $this; }
php
{ "resource": "" }
q13442
GlacierClient.getChecksumsMiddleware
train
private function getChecksumsMiddleware() { return function (callable $handler) { return function ( CommandInterface $command, RequestInterface $request = null ) use ($handler) { // Accept "ContentSHA256" with a lowercase "c" to match other Glacier params. if (!$command['ContentSHA256'] && $command['contentSHA256']) { $command['ContentSHA256'] = $command['contentSHA256']; unset($command['contentSHA256']); } // If uploading, then make sure checksums are added. $name = $command->getName(); if (($name === 'UploadArchive' || $name === 'UploadMultipartPart') && (!$command['checksum'] || !$command['ContentSHA256']) ) { $body = $request->getBody(); if (!$body->isSeekable()) { throw new CouldNotCreateChecksumException('sha256'); } // Add a tree hash if not provided. if (!$command['checksum']) { $body = new HashingStream( $body, new TreeHash(), function ($result) use ($command, &$request) { $request = $request->withHeader( 'x-amz-sha256-tree-hash', bin2hex($result) ); } ); } // Add a linear content hash if not provided. if (!$command['ContentSHA256']) { $body = new HashingStream( $body, new PhpHash('sha256'), function ($result) use ($command) { $command['ContentSHA256'] = bin2hex($result); } ); } // Read the stream in order to calculate the hashes. while (!$body->eof()) { $body->read(1048576); } $body->seek(0); } // Set the content hash header if a value is in the command. if ($command['ContentSHA256']) { $request = $request->withHeader( 'x-amz-content-sha256', $command['ContentSHA256'] ); } return $handler($command, $request); }; }; }
php
{ "resource": "" }
q13443
GlacierClient.getApiVersionMiddleware
train
private function getApiVersionMiddleware() { return function (callable $handler) { return function ( CommandInterface $command, RequestInterface $request = null ) use ($handler) { return $handler($command, $request->withHeader( 'x-amz-glacier-version', $this->getApi()->getMetadata('apiVersion') )); }; }; }
php
{ "resource": "" }
q13444
LambdaClient.getDefaultCurlOptionsMiddleware
train
public function getDefaultCurlOptionsMiddleware() { return Middleware::mapCommand(function (CommandInterface $cmd) { $defaultCurlOptions = [ CURLOPT_TCP_KEEPALIVE => 1, ]; if (!isset($cmd['@http']['curl'])) { $cmd['@http']['curl'] = $defaultCurlOptions; } else { $cmd['@http']['curl'] += $defaultCurlOptions; } return $cmd; }); }
php
{ "resource": "" }
q13445
ConfigurationProvider.chain
train
public static function chain() { $links = func_get_args(); if (empty($links)) { throw new \InvalidArgumentException('No providers in chain'); } return function () use ($links) { /** @var callable $parent */ $parent = array_shift($links); $promise = $parent(); while ($next = array_shift($links)) { $promise = $promise->otherwise($next); } return $promise; }; }
php
{ "resource": "" }
q13446
ConfigurationProvider.env
train
public static function env() { return function () { // Use credentials from environment variables, if available $enabled = getenv(self::ENV_ENABLED); if ($enabled !== false) { return Promise\promise_for( new Configuration( $enabled, getenv(self::ENV_PORT) ?: self::DEFAULT_PORT, getenv(self:: ENV_CLIENT_ID) ?: self::DEFAULT_CLIENT_ID ) ); } return self::reject('Could not find environment variable CSM config' . ' in ' . self::ENV_ENABLED. '/' . self::ENV_PORT . '/' . self::ENV_CLIENT_ID); }; }
php
{ "resource": "" }
q13447
ConfigurationProvider.fallback
train
public static function fallback() { return function() { return Promise\promise_for( new Configuration( self::DEFAULT_ENABLED, self::DEFAULT_PORT, self::DEFAULT_CLIENT_ID ) ); }; }
php
{ "resource": "" }
q13448
ConfigurationProvider.memoize
train
public static function memoize(callable $provider) { return function () use ($provider) { static $result; static $isConstant; // Constant config will be returned constantly. if ($isConstant) { return $result; } // Create the initial promise that will be used as the cached value // until it expires. if (null === $result) { $result = $provider(); } // Return config and set flag that provider is already set return $result ->then(function (ConfigurationInterface $config) use (&$isConstant) { $isConstant = true; return $config; }); }; }
php
{ "resource": "" }
q13449
CloudFrontClient.getSignedCookie
train
public function getSignedCookie(array $options) { foreach (['key_pair_id', 'private_key'] as $required) { if (!isset($options[$required])) { throw new \InvalidArgumentException("$required is required"); } } $cookieSigner = new CookieSigner( $options['key_pair_id'], $options['private_key'] ); return $cookieSigner->getSignedCookie( isset($options['url']) ? $options['url'] : null, isset($options['expires']) ? $options['expires'] : null, isset($options['policy']) ? $options['policy'] : null ); }
php
{ "resource": "" }
q13450
StreamWrapper.url_stat
train
public function url_stat($path, $flags) { $this->initProtocol($path); // Some paths come through as S3:// for some reason. $split = explode('://', $path); $path = strtolower($split[0]) . '://' . $split[1]; // Check if this path is in the url_stat cache if ($value = $this->getCacheStorage()->get($path)) { return $value; } $stat = $this->createStat($path, $flags); if (is_array($stat)) { $this->getCacheStorage()->set($path, $stat); } return $stat; }
php
{ "resource": "" }
q13451
StreamWrapper.validate
train
private function validate($path, $mode) { $errors = []; if (!$this->getOption('Key')) { $errors[] = 'Cannot open a bucket. You must specify a path in the ' . 'form of s3://bucket/key'; } if (!in_array($mode, ['r', 'w', 'a', 'x'])) { $errors[] = "Mode not supported: {$mode}. " . "Use one 'r', 'w', 'a', or 'x'."; } // When using mode "x" validate if the file exists before attempting // to read if ($mode == 'x' && $this->getClient()->doesObjectExist( $this->getOption('Bucket'), $this->getOption('Key'), $this->getOptions(true) ) ) { $errors[] = "{$path} already exists on Amazon S3"; } return $errors; }
php
{ "resource": "" }
q13452
StreamWrapper.getOptions
train
private function getOptions($removeContextData = false) { // Context is not set when doing things like stat if ($this->context === null) { $options = []; } else { $options = stream_context_get_options($this->context); $options = isset($options[$this->protocol]) ? $options[$this->protocol] : []; } $default = stream_context_get_options(stream_context_get_default()); $default = isset($default[$this->protocol]) ? $default[$this->protocol] : []; $result = $this->params + $options + $default; if ($removeContextData) { unset($result['client'], $result['seekable'], $result['cache']); } return $result; }
php
{ "resource": "" }
q13453
StreamWrapper.triggerError
train
private function triggerError($errors, $flags = null) { // This is triggered with things like file_exists() if ($flags & STREAM_URL_STAT_QUIET) { return $flags & STREAM_URL_STAT_LINK // This is triggered for things like is_link() ? $this->formatUrlStat(false) : false; } // This is triggered when doing things like lstat() or stat() trigger_error(implode("\n", (array) $errors), E_USER_WARNING); return false; }
php
{ "resource": "" }
q13454
StreamWrapper.formatUrlStat
train
private function formatUrlStat($result = null) { $stat = $this->getStatTemplate(); switch (gettype($result)) { case 'NULL': case 'string': // Directory with 0777 access - see "man 2 stat". $stat['mode'] = $stat[2] = 0040777; break; case 'array': // Regular file with 0777 access - see "man 2 stat". $stat['mode'] = $stat[2] = 0100777; // Pluck the content-length if available. if (isset($result['ContentLength'])) { $stat['size'] = $stat[7] = $result['ContentLength']; } elseif (isset($result['Size'])) { $stat['size'] = $stat[7] = $result['Size']; } if (isset($result['LastModified'])) { // ListObjects or HeadObject result $stat['mtime'] = $stat[9] = $stat['ctime'] = $stat[10] = strtotime($result['LastModified']); } } return $stat; }
php
{ "resource": "" }
q13455
StreamWrapper.createBucket
train
private function createBucket($path, array $params) { if ($this->getClient()->doesBucketExist($params['Bucket'])) { return $this->triggerError("Bucket already exists: {$path}"); } return $this->boolCall(function () use ($params, $path) { $this->getClient()->createBucket($params); $this->clearCacheKey($path); return true; }); }
php
{ "resource": "" }
q13456
StreamWrapper.deleteSubfolder
train
private function deleteSubfolder($path, $params) { // Use a key that adds a trailing slash if needed. $prefix = rtrim($params['Key'], '/') . '/'; $result = $this->getClient()->listObjects([ 'Bucket' => $params['Bucket'], 'Prefix' => $prefix, 'MaxKeys' => 1 ]); // Check if the bucket contains keys other than the placeholder if ($contents = $result['Contents']) { return (count($contents) > 1 || $contents[0]['Key'] != $prefix) ? $this->triggerError('Subfolder is not empty') : $this->unlink(rtrim($path, '/') . '/'); } return $result['CommonPrefixes'] ? $this->triggerError('Subfolder contains nested folders') : true; }
php
{ "resource": "" }
q13457
StreamWrapper.boolCall
train
private function boolCall(callable $fn, $flags = null) { try { return $fn(); } catch (\Exception $e) { return $this->triggerError($e->getMessage(), $flags); } }
php
{ "resource": "" }
q13458
StreamWrapper.getSize
train
private function getSize() { $size = $this->body->getSize(); return $size !== null ? $size : $this->size; }
php
{ "resource": "" }
q13459
Operation.getInput
train
public function getInput() { if (!$this->input) { if ($input = $this['input']) { $this->input = $this->shapeFor($input); } else { $this->input = new StructureShape([], $this->shapeMap); } } return $this->input; }
php
{ "resource": "" }
q13460
Operation.getOutput
train
public function getOutput() { if (!$this->output) { if ($output = $this['output']) { $this->output = $this->shapeFor($output); } else { $this->output = new StructureShape([], $this->shapeMap); } } return $this->output; }
php
{ "resource": "" }
q13461
Operation.getErrors
train
public function getErrors() { if ($this->errors === null) { if ($errors = $this['errors']) { foreach ($errors as $key => $error) { $errors[$key] = $this->shapeFor($error); } $this->errors = $errors; } else { $this->errors = []; } } return $this->errors; }
php
{ "resource": "" }
q13462
History.start
train
public function start(CommandInterface $cmd, RequestInterface $req) { $ticket = uniqid(); $this->entries[$ticket] = [ 'command' => $cmd, 'request' => $req, 'result' => null, 'exception' => null, ]; return $ticket; }
php
{ "resource": "" }
q13463
DynamoDbClient.registerSessionHandler
train
public function registerSessionHandler(array $config = []) { $handler = SessionHandler::fromClient($this, $config); $handler->register(); return $handler; }
php
{ "resource": "" }
q13464
StsClient.createCredentials
train
public function createCredentials(Result $result) { if (!$result->hasKey('Credentials')) { throw new \InvalidArgumentException('Result contains no credentials'); } $c = $result['Credentials']; return new Credentials( $c['AccessKeyId'], $c['SecretAccessKey'], isset($c['SessionToken']) ? $c['SessionToken'] : null, isset($c['Expiration']) && $c['Expiration'] instanceof \DateTimeInterface ? (int) $c['Expiration']->format('U') : null ); }
php
{ "resource": "" }
q13465
AbstractRestParser.extractHeader
train
private function extractHeader( $name, Shape $shape, ResponseInterface $response, &$result ) { $value = $response->getHeaderLine($shape['locationName'] ?: $name); switch ($shape->getType()) { case 'float': case 'double': $value = (float) $value; break; case 'long': $value = (int) $value; break; case 'boolean': $value = filter_var($value, FILTER_VALIDATE_BOOLEAN); break; case 'blob': $value = base64_decode($value); break; case 'timestamp': try { if (!empty($shape['timestampFormat']) && $shape['timestampFormat'] === 'unixTimestamp') { $value = DateTimeResult::fromEpoch($value); } $value = new DateTimeResult($value); break; } catch (\Exception $e) { // If the value cannot be parsed, then do not add it to the // output structure. return; } case 'string': if ($shape['jsonvalue']) { $value = $this->parseJson(base64_decode($value), $response); } break; } $result[$name] = $value; }
php
{ "resource": "" }
q13466
AbstractRestParser.extractHeaders
train
private function extractHeaders( $name, Shape $shape, ResponseInterface $response, &$result ) { // Check if the headers are prefixed by a location name $result[$name] = []; $prefix = $shape['locationName']; $prefixLen = strlen($prefix); foreach ($response->getHeaders() as $k => $values) { if (!$prefixLen) { $result[$name][$k] = implode(', ', $values); } elseif (stripos($k, $prefix) === 0) { $result[$name][substr($k, $prefixLen)] = implode(', ', $values); } } }
php
{ "resource": "" }
q13467
AbstractRestParser.extractStatus
train
private function extractStatus( $name, ResponseInterface $response, array &$result ) { $result[$name] = (int) $response->getStatusCode(); }
php
{ "resource": "" }
q13468
SignatureV4.getHeaderBlacklist
train
private function getHeaderBlacklist() { return [ 'cache-control' => true, 'content-type' => true, 'content-length' => true, 'expect' => true, 'max-forwards' => true, 'pragma' => true, 'range' => true, 'te' => true, 'if-match' => true, 'if-none-match' => true, 'if-modified-since' => true, 'if-unmodified-since' => true, 'if-range' => true, 'accept' => true, 'authorization' => true, 'proxy-authorization' => true, 'from' => true, 'referer' => true, 'user-agent' => true, 'x-amzn-trace-id' => true, 'aws-sdk-invocation-id' => true, 'aws-sdk-retry' => true, ]; }
php
{ "resource": "" }
q13469
SignatureV4.getPresignHeaders
train
private function getPresignHeaders(array $headers) { $presignHeaders = []; $blacklist = $this->getHeaderBlacklist(); foreach ($headers as $name => $value) { $lName = strtolower($name); if (!isset($blacklist[$lName]) && $name !== self::AMZ_CONTENT_SHA256_HEADER ) { $presignHeaders[] = $lName; } } return $presignHeaders; }
php
{ "resource": "" }
q13470
SignatureV4.convertPostToGet
train
public static function convertPostToGet(RequestInterface $request) { if ($request->getMethod() !== 'POST') { throw new \InvalidArgumentException('Expected a POST request but ' . 'received a ' . $request->getMethod() . ' request.'); } $sr = $request->withMethod('GET') ->withBody(Psr7\stream_for('')) ->withoutHeader('Content-Type') ->withoutHeader('Content-Length'); // Move POST fields to the query if they are present if ($request->getHeaderLine('Content-Type') === 'application/x-www-form-urlencoded') { $body = (string) $request->getBody(); $sr = $sr->withUri($sr->getUri()->withQuery($body)); } return $sr; }
php
{ "resource": "" }
q13471
ConfigurationProvider.env
train
public static function env($cacheLimit = self::DEFAULT_CACHE_LIMIT) { return function () use ($cacheLimit) { // Use config from environment variables, if available $enabled = getenv(self::ENV_ENABLED); if ($enabled === false || $enabled === '') { $enabled = getenv(self::ENV_ENABLED_ALT); } if ($enabled !== false && $enabled !== '') { return Promise\promise_for( new Configuration($enabled, $cacheLimit) ); } return self::reject('Could not find environment variable config' . ' in ' . self::ENV_ENABLED); }; }
php
{ "resource": "" }
q13472
ConfigurationProvider.ini
train
public static function ini( $profile = null, $filename = null, $cacheLimit = self::DEFAULT_CACHE_LIMIT ) { $filename = $filename ?: (self::getHomeDir() . '/.aws/config'); $profile = $profile ?: (getenv(self::ENV_PROFILE) ?: 'default'); return function () use ($profile, $filename, $cacheLimit) { if (!is_readable($filename)) { return self::reject("Cannot read configuration from $filename"); } $data = \Aws\parse_ini_file($filename, true); if ($data === false) { return self::reject("Invalid config file: $filename"); } if (!isset($data[$profile])) { return self::reject("'$profile' not found in config file"); } if (!isset($data[$profile]['endpoint_discovery_enabled'])) { return self::reject("Required endpoint discovery config values not present in INI profile '{$profile}' ({$filename})"); } return Promise\promise_for( new Configuration( $data[$profile]['endpoint_discovery_enabled'], $cacheLimit ) ); }; }
php
{ "resource": "" }
q13473
MockHandler.appendException
train
public function appendException() { foreach (func_get_args() as $value) { if ($value instanceof \Exception || $value instanceof \Throwable) { $this->queue[] = $value; } else { throw new \InvalidArgumentException('Expected an \Exception or \Throwable.'); } } }
php
{ "resource": "" }
q13474
LogFileReader.read
train
public function read($s3BucketName, $logFileKey) { // Create a command for getting the log file object $command = $this->s3Client->getCommand('GetObject', [ 'Bucket' => (string) $s3BucketName, 'Key' => (string) $logFileKey, 'ResponseContentEncoding' => 'x-gzip' ]); // Make sure gzip encoding header is sent and accepted in order to // inflate the response data. $command['@http']['headers']['Accept-Encoding'] = 'gzip'; // Get the JSON response data and extract the log records $result = $this->s3Client->execute($command); $logData = json_decode($result['Body'], true); return isset($logData['Records']) ? $logData['Records'] : []; }
php
{ "resource": "" }
q13475
WrappedHttpHandler.parseError
train
private function parseError( array $err, RequestInterface $request, CommandInterface $command, array $stats ) { if (!isset($err['exception'])) { throw new \RuntimeException('The HTTP handler was rejected without an "exception" key value pair.'); } $serviceError = "AWS HTTP error: " . $err['exception']->getMessage(); if (!isset($err['response'])) { $parts = ['response' => null]; } else { try { $parts = call_user_func($this->errorParser, $err['response']); $serviceError .= " {$parts['code']} ({$parts['type']}): " . "{$parts['message']} - " . $err['response']->getBody(); } catch (ParserException $e) { $parts = []; $serviceError .= ' Unable to parse error information from ' . "response - {$e->getMessage()}"; } $parts['response'] = $err['response']; } $parts['exception'] = $err['exception']; $parts['request'] = $request; $parts['connection_error'] = !empty($err['connection_error']); $parts['transfer_stats'] = $stats; return new $this->exceptionClass( sprintf( 'Error executing "%s" on "%s"; %s', $command->getName(), $request->getUri(), $serviceError ), $command, $parts, $err['exception'] ); }
php
{ "resource": "" }
q13476
LogFileIterator.buildListObjectsIterator
train
private function buildListObjectsIterator(array $options) { // Extract and normalize the date values from the options $startDate = isset($options[self::START_DATE]) ? $this->normalizeDateValue($options[self::START_DATE]) : null; $endDate = isset($options[self::END_DATE]) ? $this->normalizeDateValue($options[self::END_DATE]) : null; // Determine the parts of the key prefix of the log files being read $parts = [ 'prefix' => isset($options[self::KEY_PREFIX]) ? $options[self::KEY_PREFIX] : null, 'account' => isset($options[self::ACCOUNT_ID]) ? $options[self::ACCOUNT_ID] : self::PREFIX_WILDCARD, 'region' => isset($options[self::LOG_REGION]) ? $options[self::LOG_REGION] : self::PREFIX_WILDCARD, 'date' => $this->determineDateForPrefix($startDate, $endDate), ]; // Determine the longest key prefix that can be used to retrieve all // of the relevant log files. $candidatePrefix = ltrim(strtr(self::PREFIX_TEMPLATE, $parts), '/'); $logKeyPrefix = $candidatePrefix; $index = strpos($candidatePrefix, self::PREFIX_WILDCARD); if ($index !== false) { $logKeyPrefix = substr($candidatePrefix, 0, $index); } // Create an iterator that will emit all of the objects matching the // key prefix. $objectsIterator = $this->s3Client->getIterator('ListObjects', [ 'Bucket' => $this->s3BucketName, 'Prefix' => $logKeyPrefix, ]); // Apply regex and/or date filters to the objects iterator to emit only // log files matching the options. $objectsIterator = $this->applyRegexFilter( $objectsIterator, $logKeyPrefix, $candidatePrefix ); $objectsIterator = $this->applyDateFilter( $objectsIterator, $startDate, $endDate ); return $objectsIterator; }
php
{ "resource": "" }
q13477
LogFileIterator.normalizeDateValue
train
private function normalizeDateValue($date) { if (is_string($date)) { $date = strtotime($date); } elseif ($date instanceof \DateTime) { $date = $date->format('U'); } elseif (!is_int($date)) { throw new \InvalidArgumentException('Date values must be a ' . 'string, an int, or a DateTime object.'); } return $date; }
php
{ "resource": "" }
q13478
LogFileIterator.determineDateForPrefix
train
private function determineDateForPrefix($startDate, $endDate) { // The default date value should look like "*/*/*" after joining $dateParts = array_fill_keys(['Y', 'm', 'd'], self::PREFIX_WILDCARD); // Narrow down the date by replacing the WILDCARDs with values if they // are the same for the start and end date. if ($startDate && $endDate) { foreach ($dateParts as $key => &$value) { $candidateValue = date($key, $startDate); if ($candidateValue === date($key, $endDate)) { $value = $candidateValue; } else { break; } } } return join('/', $dateParts); }
php
{ "resource": "" }
q13479
LogFileIterator.applyRegexFilter
train
private function applyRegexFilter( $objectsIterator, $logKeyPrefix, $candidatePrefix ) { // If the prefix and candidate prefix are not the same, then there were // WILDCARDs. if ($logKeyPrefix !== $candidatePrefix) { // Turn the candidate prefix into a regex by trimming and // converting WILDCARDs to regex notation. $regex = rtrim($candidatePrefix, '/' . self::PREFIX_WILDCARD) . '/'; $regex = strtr($regex, [self::PREFIX_WILDCARD => '[^/]+']); // After trimming WILDCARDs or the end, if the regex is the same as // the prefix, then no regex is needed. if ($logKeyPrefix !== $regex) { // Apply a regex filter iterator to remove files that don't // match the provided options. $objectsIterator = new \CallbackFilterIterator( $objectsIterator, function ($object) use ($regex) { return preg_match("#{$regex}#", $object['Key']); } ); } } return $objectsIterator; }
php
{ "resource": "" }
q13480
LogFileIterator.applyDateFilter
train
private function applyDateFilter($objectsIterator, $startDate, $endDate) { // If either a start or end date was provided, filter out dates that // don't match the date range. if ($startDate || $endDate) { $fn = function ($object) use ($startDate, $endDate) { if (!preg_match('/[0-9]{8}T[0-9]{4}Z/', $object['Key'], $m)) { return false; } $date = strtotime($m[0]); return (!$startDate || $date >= $startDate) && (!$endDate || $date <= $endDate); }; $objectsIterator = new \CallbackFilterIterator($objectsIterator, $fn); } return $objectsIterator; }
php
{ "resource": "" }
q13481
ApiProvider.getVersions
train
public function getVersions($service) { if (!isset($this->manifest)) { $this->buildVersionsList($service); } if (!isset($this->manifest[$service]['versions'])) { return []; } return array_values(array_unique($this->manifest[$service]['versions'])); }
php
{ "resource": "" }
q13482
ApiProvider.buildVersionsList
train
private function buildVersionsList($service) { $dir = "{$this->modelsDir}/{$service}/"; if (!is_dir($dir)) { return; } // Get versions, remove . and .., and sort in descending order. $results = array_diff(scandir($dir, SCANDIR_SORT_DESCENDING), ['..', '.']); if (!$results) { $this->manifest[$service] = ['versions' => []]; } else { $this->manifest[$service] = [ 'versions' => [ 'latest' => $results[0] ] ]; $this->manifest[$service]['versions'] += array_combine($results, $results); } }
php
{ "resource": "" }
q13483
SqsClient.calculateMessageAttributesMd5
train
private static function calculateMessageAttributesMd5($message) { if (empty($message['MessageAttributes']) || !is_array($message['MessageAttributes']) ) { return null; } ksort($message['MessageAttributes']); $attributeValues = ""; foreach ($message['MessageAttributes'] as $name => $details) { $attributeValues .= self::getEncodedStringPiece($name); $attributeValues .= self::getEncodedStringPiece($details['DataType']); if (substr($details['DataType'], 0, 6) === 'Binary') { $attributeValues .= pack('c', 0x02); $attributeValues .= self::getEncodedBinaryPiece( $details['BinaryValue'] ); } else { $attributeValues .= pack('c', 0x01); $attributeValues .= self::getEncodedStringPiece( $details['StringValue'] ); } } return md5($attributeValues); }
php
{ "resource": "" }
q13484
SqsClient.validateMd5
train
private function validateMd5() { return static function (callable $handler) { return function ( CommandInterface $c, RequestInterface $r = null ) use ($handler) { if ($c->getName() !== 'ReceiveMessage') { return $handler($c, $r); } return $handler($c, $r) ->then( function ($result) use ($c, $r) { foreach ((array) $result['Messages'] as $msg) { $bodyMd5 = self::calculateBodyMd5($msg); if (isset($msg['MD5OfBody']) && $bodyMd5 !== $msg['MD5OfBody'] ) { throw new SqsException( sprintf( 'MD5 mismatch. Expected %s, found %s', $msg['MD5OfBody'], $bodyMd5 ), $c, [ 'code' => 'ClientChecksumMismatch', 'request' => $r ] ); } if (isset($msg['MD5OfMessageAttributes'])) { $messageAttributesMd5 = self::calculateMessageAttributesMd5($msg); if ($messageAttributesMd5 !== $msg['MD5OfMessageAttributes']) { throw new SqsException( sprintf( 'Attribute MD5 mismatch. Expected %s, found %s', $msg['MD5OfMessageAttributes'], $messageAttributesMd5 ? $messageAttributesMd5 : 'No Attributes' ), $c, [ 'code' => 'ClientChecksumMismatch', 'request' => $r ] ); } } else if (isset($msg['MessageAttributes'])) { throw new SqsException( sprintf( 'No Attribute MD5 found. Expected %s', self::calculateMessageAttributesMd5($msg) ), $c, [ 'code' => 'ClientChecksumMismatch', 'request' => $r ] ); } } return $result; } ); }; }; }
php
{ "resource": "" }
q13485
DecryptionTrait.decrypt
train
protected function decrypt( $cipherText, MaterialsProvider $provider, MetadataEnvelope $envelope, array $cipherOptions = [] ) { $cipherOptions['Iv'] = base64_decode( $envelope[MetadataEnvelope::IV_HEADER] ); $cipherOptions['TagLength'] = $envelope[MetadataEnvelope::CRYPTO_TAG_LENGTH_HEADER] / 8; $cek = $provider->decryptCek( base64_decode( $envelope[MetadataEnvelope::CONTENT_KEY_V2_HEADER] ), json_decode( $envelope[MetadataEnvelope::MATERIALS_DESCRIPTION_HEADER], true ) ); $cipherOptions['KeySize'] = strlen($cek) * 8; $cipherOptions['Cipher'] = $this->getCipherFromAesName( $envelope[MetadataEnvelope::CONTENT_CRYPTO_SCHEME_HEADER] ); $decryptionSteam = $this->getDecryptingStream( $cipherText, $cek, $cipherOptions ); unset($cek); return $decryptionSteam; }
php
{ "resource": "" }
q13486
Marshaler.marshalJson
train
public function marshalJson($json) { $data = json_decode($json); if (!($data instanceof \stdClass)) { throw new \InvalidArgumentException( 'The JSON document must be valid and be an object at its root.' ); } return current($this->marshalValue($data)); }
php
{ "resource": "" }
q13487
Marshaler.marshalValue
train
public function marshalValue($value) { $type = gettype($value); // Handle string values. if ($type === 'string') { if ($value === '') { return $this->handleInvalid('empty strings are invalid'); } return ['S' => $value]; } // Handle number values. if ($type === 'integer' || $type === 'double' || $value instanceof NumberValue ) { return ['N' => (string) $value]; } // Handle boolean values. if ($type === 'boolean') { return ['BOOL' => $value]; } // Handle null values. if ($type === 'NULL') { return ['NULL' => true]; } // Handle set values. if ($value instanceof SetValue) { if (count($value) === 0) { return $this->handleInvalid('empty sets are invalid'); } $previousType = null; $data = []; foreach ($value as $v) { $marshaled = $this->marshalValue($v); $setType = key($marshaled); if (!$previousType) { $previousType = $setType; } elseif ($setType !== $previousType) { return $this->handleInvalid('sets must be uniform in type'); } $data[] = current($marshaled); } return [$previousType . 'S' => array_values(array_unique($data))]; } // Handle list and map values. $dbType = 'L'; if ($value instanceof \stdClass) { $type = 'array'; $dbType = 'M'; } if ($type === 'array' || $value instanceof \Traversable) { $data = []; $index = 0; foreach ($value as $k => $v) { if ($v = $this->marshalValue($v)) { $data[$k] = $v; if ($dbType === 'L' && (!is_int($k) || $k != $index++)) { $dbType = 'M'; } } } return [$dbType => $data]; } // Handle binary values. if (is_resource($value) || $value instanceof StreamInterface) { $value = $this->binary($value); } if ($value instanceof BinaryValue) { return ['B' => (string) $value]; } // Handle invalid values. return $this->handleInvalid('encountered unexpected value'); }
php
{ "resource": "" }
q13488
BatchDelete.fromListObjects
train
public static function fromListObjects( AwsClientInterface $client, array $listObjectsParams, array $options = [] ) { $iter = $client->getPaginator('ListObjects', $listObjectsParams); $bucket = $listObjectsParams['Bucket']; $fn = function (BatchDelete $that) use ($iter) { return $iter->each(function ($result) use ($that) { $promises = []; if (is_array($result['Contents'])) { foreach ($result['Contents'] as $object) { if ($promise = $that->enqueue($object)) { $promises[] = $promise; } } } return $promises ? Promise\all($promises) : null; }); }; return new self($client, $bucket, $fn, $options); }
php
{ "resource": "" }
q13489
BatchDelete.createPromise
train
private function createPromise() { // Create the promise $promise = call_user_func($this->promiseCreator, $this); $this->promiseCreator = null; // Cleans up the promise state and references. $cleanup = function () { $this->before = $this->client = $this->queue = null; }; // When done, ensure cleanup and that any remaining are processed. return $promise->then( function () use ($cleanup) { return Promise\promise_for($this->flushQueue()) ->then($cleanup); }, function ($reason) use ($cleanup) { $cleanup(); return Promise\rejection_for($reason); } ); }
php
{ "resource": "" }
q13490
CookieSigner.getSignedCookie
train
public function getSignedCookie($url = null, $expires = null, $policy = null) { if ($url) { $this->validateUrl($url); } $cookieParameters = []; $signature = $this->signer->getSignature($url, $expires, $policy); foreach ($signature as $key => $value) { $cookieParameters["CloudFront-$key"] = $value; } return $cookieParameters; }
php
{ "resource": "" }
q13491
EndpointList.getExpired
train
private function getExpired() { if (count($this->expired) < 1) { return null; } $expired = key($this->expired); $this->increment($this->expired); return $expired; }
php
{ "resource": "" }
q13492
WriteRequestBatch.put
train
public function put(array $item, $table = null) { $this->queue[] = [ 'table' => $this->determineTable($table), 'data' => ['PutRequest' => ['Item' => $item]], ]; $this->autoFlush(); return $this; }
php
{ "resource": "" }
q13493
WriteRequestBatch.delete
train
public function delete(array $key, $table = null) { $this->queue[] = [ 'table' => $this->determineTable($table), 'data' => ['DeleteRequest' => ['Key' => $key]], ]; $this->autoFlush(); return $this; }
php
{ "resource": "" }
q13494
WriteRequestBatch.flush
train
public function flush($untilEmpty = true) { // Send BatchWriteItem requests until the queue is empty $keepFlushing = true; while ($this->queue && $keepFlushing) { $commands = $this->prepareCommands(); $pool = new CommandPool($this->client, $commands, [ 'before' => $this->config['before'], 'concurrency' => $this->config['pool_size'], 'fulfilled' => function (ResultInterface $result) { // Re-queue any unprocessed items if ($result->hasKey('UnprocessedItems')) { $this->retryUnprocessed($result['UnprocessedItems']); } }, 'rejected' => function ($reason) { if ($reason instanceof AwsException) { $code = $reason->getAwsErrorCode(); if ($code === 'ProvisionedThroughputExceededException') { $this->retryUnprocessed($reason->getCommand()['RequestItems']); } elseif (is_callable($this->config['error'])) { $this->config['error']($reason); } } } ]); $pool->promise()->wait(); $keepFlushing = (bool) $untilEmpty; } return $this; }
php
{ "resource": "" }
q13495
WriteRequestBatch.autoFlush
train
private function autoFlush() { if ($this->config['autoflush'] && count($this->queue) >= $this->config['threshold'] ) { // Flush only once. Unprocessed items are handled in a later flush. $this->flush(false); } }
php
{ "resource": "" }
q13496
HeadersMetadataStrategy.save
train
public function save(MetadataEnvelope $envelope, array $args) { foreach ($envelope as $header=>$value) { $args['Metadata'][$header] = $value; } return $args; }
php
{ "resource": "" }
q13497
HeadersMetadataStrategy.load
train
public function load(array $args) { $envelope = new MetadataEnvelope(); $constantValues = MetadataEnvelope::getConstantValues(); foreach ($constantValues as $constant) { if (!empty($args['Metadata'][$constant])) { $envelope[$constant] = $args['Metadata'][$constant]; } } return $envelope; }
php
{ "resource": "" }
q13498
XmlBody.build
train
public function build(Shape $shape, array $args) { $xml = new XMLWriter(); $xml->openMemory(); $xml->startDocument('1.0', 'UTF-8'); $this->format($shape, $shape['locationName'] ?: $shape['name'], $args, $xml); $xml->endDocument(); return $xml->outputMemory(); }
php
{ "resource": "" }
q13499
SessionHandler.fromClient
train
public static function fromClient(DynamoDbClient $client, array $config = []) { $config += ['locking' => false]; if ($config['locking']) { $connection = new LockingSessionConnection($client, $config); } else { $connection = new StandardSessionConnection($client, $config); } return new static($connection); }
php
{ "resource": "" }