_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q255200 | AliasProcessor.closeIndex | test | private function closeIndex(Client $client, $indexName)
{
try {
$path = sprintf('%s/_close', $indexName);
$client->request($path, Request::POST);
} catch (ExceptionInterface $e) {
throw new \RuntimeException(
sprintf(
'Failed to close index %s with message: %s',
$indexName,
$e->getMessage()
),
0,
$e
);
}
} | php | {
"resource": ""
} |
q255201 | AliasProcessor.getAliasedIndex | test | private function getAliasedIndex(Client $client, $aliasName)
{
$aliasesInfo = $client->request('_aliases', 'GET')->getData();
$aliasedIndexes = [];
foreach ($aliasesInfo as $indexName => $indexInfo) {
if ($indexName === $aliasName) {
throw new AliasIsIndexException($indexName);
}
if (!isset($indexInfo['aliases'])) {
continue;
}
$aliases = array_keys($indexInfo['aliases']);
if (in_array($aliasName, $aliases)) {
$aliasedIndexes[] = $indexName;
}
}
if (count($aliasedIndexes) > 1) {
throw new \RuntimeException(sprintf(
'Alias %s is used for multiple indexes: [%s]. Make sure it\'s'.
'either not used or is assigned to one index only',
$aliasName,
implode(', ', $aliasedIndexes)
));
}
return array_shift($aliasedIndexes);
} | php | {
"resource": ""
} |
q255202 | Client.logQuery | test | private function logQuery($path, $method, $data, array $query, $queryTime, $engineMS = 0, $itemCount = 0)
{
if (!$this->_logger or !$this->_logger instanceof ElasticaLogger) {
return;
}
$connection = $this->getLastRequest()->getConnection();
$connectionArray = [
'host' => $connection->getHost(),
'port' => $connection->getPort(),
'transport' => $connection->getTransport(),
'headers' => $connection->hasConfig('headers') ? $connection->getConfig('headers') : [],
];
/** @var ElasticaLogger $logger */
$logger = $this->_logger;
$logger->logQuery($path, $method, $data, $queryTime, $connectionArray, $query, $engineMS, $itemCount);
} | php | {
"resource": ""
} |
q255203 | Listener.postPersist | test | public function postPersist(LifecycleEventArgs $eventArgs)
{
$entity = $eventArgs->getObject();
if ($this->objectPersister->handlesObject($entity) && $this->isObjectIndexable($entity)) {
$this->scheduledForInsertion[] = $entity;
}
} | php | {
"resource": ""
} |
q255204 | Listener.postUpdate | test | public function postUpdate(LifecycleEventArgs $eventArgs)
{
$entity = $eventArgs->getObject();
if ($this->objectPersister->handlesObject($entity)) {
if ($this->isObjectIndexable($entity)) {
$this->scheduledForUpdate[] = $entity;
} else {
// Delete if no longer indexable
$this->scheduleForDeletion($entity);
}
}
} | php | {
"resource": ""
} |
q255205 | Listener.preRemove | test | public function preRemove(LifecycleEventArgs $eventArgs)
{
$entity = $eventArgs->getObject();
if ($this->objectPersister->handlesObject($entity)) {
$this->scheduleForDeletion($entity);
}
} | php | {
"resource": ""
} |
q255206 | Listener.persistScheduled | test | private function persistScheduled()
{
if ($this->shouldPersist()) {
if (count($this->scheduledForInsertion)) {
$this->objectPersister->insertMany($this->scheduledForInsertion);
$this->scheduledForInsertion = [];
}
if (count($this->scheduledForUpdate)) {
$this->objectPersister->replaceMany($this->scheduledForUpdate);
$this->scheduledForUpdate = [];
}
if (count($this->scheduledForDeletion)) {
$this->objectPersister->deleteManyByIdentifiers($this->scheduledForDeletion);
$this->scheduledForDeletion = [];
}
}
} | php | {
"resource": ""
} |
q255207 | Listener.scheduleForDeletion | test | private function scheduleForDeletion($object)
{
if ($identifierValue = $this->propertyAccessor->getValue($object, $this->config['identifier'])) {
$this->scheduledForDeletion[] = !is_scalar($identifierValue) ? (string) $identifierValue : $identifierValue;
}
} | php | {
"resource": ""
} |
q255208 | Listener.isObjectIndexable | test | private function isObjectIndexable($object)
{
return $this->indexable->isObjectIndexable(
$this->config['indexName'],
$this->config['typeName'],
$object
);
} | php | {
"resource": ""
} |
q255209 | RepositoryManager.getRepository | test | public function getRepository($entityName)
{
$realEntityName = $entityName;
if (false !== strpos($entityName, ':')) {
list($namespaceAlias, $simpleClassName) = explode(':', $entityName);
$realEntityName = $this->managerRegistry->getAliasNamespace($namespaceAlias).'\\'.$simpleClassName;
}
if (isset($this->entities[$realEntityName])) {
$realEntityName = $this->entities[$realEntityName];
}
return $this->repositoryManager->getRepository($realEntityName);
} | php | {
"resource": ""
} |
q255210 | ModelToElasticaIdentifierTransformer.transform | test | public function transform($object, array $fields)
{
$identifier = $this->propertyAccessor->getValue($object, $this->options['identifier']);
return new Document($identifier);
} | php | {
"resource": ""
} |
q255211 | RepositoryManager.getRepository | test | public function getRepository($typeName)
{
if (isset($this->repositories[$typeName])) {
return $this->repositories[$typeName];
}
if (!isset($this->types[$typeName])) {
throw new RuntimeException(sprintf('No search finder configured for %s', $typeName));
}
$repository = $this->createRepository($typeName);
$this->repositories[$typeName] = $repository;
return $repository;
} | php | {
"resource": ""
} |
q255212 | HashidsFactory.make | test | public function make(array $config): Hashids
{
$config = $this->getConfig($config);
return $this->getClient($config);
} | php | {
"resource": ""
} |
q255213 | HashidsServiceProvider.registerFactory | test | protected function registerFactory(): void
{
$this->app->singleton('hashids.factory', function () {
return new HashidsFactory();
});
$this->app->alias('hashids.factory', HashidsFactory::class);
} | php | {
"resource": ""
} |
q255214 | Api.verifyHash | test | public function verifyHash(array $params)
{
if (empty($params['HASH'])) {
return false;
}
$hash = $params['HASH'];
unset($params['HASH']);
return $hash === $this->calculateHash($params);
} | php | {
"resource": ""
} |
q255215 | HttpClientFactory.createGuzzle | test | public static function createGuzzle()
{
$client = null;
if (!class_exists(Client::class)) {
@trigger_error('The function "HttpClientFactory::createGuzzle" is depcrecated and will be removed in 2.0.', E_USER_DEPRECATED);
throw new \LogicException('Can not use "HttpClientFactory::createGuzzle" since Guzzle is not installed. This function is deprecated and will be removed in 2.0.');
}
$version = \GuzzleHttp\ClientInterface::VERSION;
if (substr($version, 0, 1) !== '6') {
throw new \LogicException('This version of Guzzle is not supported.');
}
$curl = curl_version();
$curlOptions = [
CURLOPT_USERAGENT => sprintf('Payum/1.x curl/%s PHP/%s', $curl['version'], phpversion()),
];
return new \GuzzleHttp\Client([
'curl' => $curlOptions,
]);
} | php | {
"resource": ""
} |
q255216 | CookieJar.addCookie | test | public function addCookie(Cookie $cookie): void
{
$this->cookies[$this->getHash($cookie)] = $cookie;
} | php | {
"resource": ""
} |
q255217 | CookieJar.addCookieHeaders | test | public function addCookieHeaders(RequestInterface $request): RequestInterface
{
$cookies = [];
foreach ($this->getCookies() as $cookie) {
if ($cookie->matchesRequest($request)) {
$cookies[] = $cookie->toCookieHeader();
}
}
if ($cookies) {
$request = $request->withAddedHeader('Cookie', implode('; ', $cookies));
}
return $request;
} | php | {
"resource": ""
} |
q255218 | CookieJar.clearExpiredCookies | test | public function clearExpiredCookies(): void
{
$cookies = $this->getCookies();
foreach ($cookies as $i => $cookie) {
if ($cookie->isExpired()) {
unset($cookies[$i]);
}
}
$this->clear();
$this->setCookies(array_values($cookies));
} | php | {
"resource": ""
} |
q255219 | CookieJar.getHash | test | private function getHash(Cookie $cookie): string
{
return sha1(sprintf(
'%s|%s|%s',
$cookie->getName(),
$cookie->getAttribute(Cookie::ATTR_DOMAIN),
$cookie->getAttribute(Cookie::ATTR_PATH)
));
} | php | {
"resource": ""
} |
q255220 | ResponseBuilder.addHeader | test | public function addHeader(string $input): void
{
list($key, $value) = explode(':', $input, 2);
$this->response = $this->response->withAddedHeader(trim($key), trim($value));
} | php | {
"resource": ""
} |
q255221 | ResponseBuilder.parseHttpHeaders | test | public function parseHttpHeaders(array $headers): void
{
$headers = $this->filterHeaders($headers);
$statusLine = array_shift($headers);
try {
$this->setStatus($statusLine);
} catch (InvalidArgumentException $e) {
array_unshift($headers, $statusLine);
}
foreach ($headers as $header) {
$this->addHeader($header);
}
} | php | {
"resource": ""
} |
q255222 | DigestAuthMiddleware.handleRequest | test | public function handleRequest(RequestInterface $request, callable $next)
{
$this->setUri($request->getUri()->getPath());
$this->setMethod(strtoupper($request->getMethod()));
$this->setEntityBody($request->getBody()->__toString());
$header = $this->getHeader();
if (null !== $header) {
$request = $request->withHeader('Authorization', $header);
}
return $next($request);
} | php | {
"resource": ""
} |
q255223 | DigestAuthMiddleware.setOptions | test | public function setOptions($options): void
{
if ($options & self::OPTION_QOP_AUTH_INT) {
if ($options & self::OPTION_QOP_AUTH) {
throw new \InvalidArgumentException('DigestAuthMiddleware: Only one value of OPTION_QOP_AUTH_INT or OPTION_QOP_AUTH may be set.');
}
$this->options = $this->options | self::OPTION_QOP_AUTH_INT;
} elseif ($options & self::OPTION_QOP_AUTH) {
$this->options = $this->options | self::OPTION_QOP_AUTH;
}
if ($options & self::OPTION_IGNORE_DOWNGRADE_REQUEST) {
$this->options = $this->options | self::OPTION_IGNORE_DOWNGRADE_REQUEST;
}
if ($options & self::OPTION_DISCARD_CLIENT_NONCE) {
$this->options = $this->options | self::OPTION_DISCARD_CLIENT_NONCE;
}
} | php | {
"resource": ""
} |
q255224 | DigestAuthMiddleware.getClientNonce | test | private function getClientNonce(): ?string
{
if (null == $this->clientNonce) {
$this->clientNonce = uniqid();
if (null == $this->nonceCount) {
// If nonceCount is not set then set it to 00000001.
$this->nonceCount = '00000001';
} else {
// If it is set then increment it.
++$this->nonceCount;
// Ensure nonceCount is zero-padded at the start of the string to a length of 8
while (\strlen($this->nonceCount) < 8) {
$this->nonceCount = '0'.$this->nonceCount;
}
}
}
return $this->clientNonce;
} | php | {
"resource": ""
} |
q255225 | DigestAuthMiddleware.getHA1 | test | private function getHA1(): ?string
{
$username = $this->getUsername();
$password = $this->getPassword();
$realm = $this->getRealm();
if (($username) && ($password) && ($realm)) {
$algorithm = $this->getAlgorithm();
if ('MD5' === $algorithm) {
$A1 = "{$username}:{$realm}:{$password}";
return $this->hash($A1);
} elseif ('MD5-sess' === $algorithm) {
$nonce = $this->getNonce();
$cnonce = $this->getClientNonce();
if (($nonce) && ($cnonce)) {
$A1 = $this->hash("{$username}:{$realm}:{$password}").":{$nonce}:{$cnonce}";
return $this->hash($A1);
}
}
}
return null;
} | php | {
"resource": ""
} |
q255226 | DigestAuthMiddleware.getHA2 | test | private function getHA2(): ?string
{
$method = $this->getMethod();
$uri = $this->getUri();
if (($method) && ($uri)) {
$qop = $this->getQOP();
if (null === $qop || 'auth' === $qop) {
$A2 = "{$method}:{$uri}";
} elseif ('auth-int' === $qop) {
$entityBody = (string) $this->getEntityBody();
$A2 = "{$method}:{$uri}:".(string) $this->hash($entityBody);
} else {
return null;
}
$HA2 = $this->hash($A2);
return $HA2;
}
return null;
} | php | {
"resource": ""
} |
q255227 | DigestAuthMiddleware.getHeader | test | private function getHeader(): ?string
{
if ('Digest' == $this->getAuthenticationMethod()) {
$username = $this->getUsername();
$realm = $this->getRealm();
$nonce = $this->getNonce();
$response = $this->getResponse();
if (($username) && ($realm) && ($nonce) && ($response)) {
$uri = $this->getUri();
$opaque = $this->getOpaque();
$qop = $this->getQOP();
$header = 'Digest';
$header .= ' username="'.$username.'",';
$header .= ' realm="'.$realm.'",';
$header .= ' nonce="'.$nonce.'",';
$header .= ' response="'.$response.'",';
if ($uri) {
$header .= ' uri="'.$uri.'",';
}
if ($opaque) {
$header .= ' opaque="'.$opaque.'",';
}
if ($qop) {
$header .= ' qop='.$qop.',';
$cnonce = $this->getClientNonce();
$nc = $this->getNonceCount();
if ($cnonce) {
$header .= ' nc='.$nc.',';
}
if ($cnonce) {
$header .= ' cnonce="'.$cnonce.'",';
}
}
// Remove the last comma from the header
$header = substr($header, 0, \strlen($header) - 1);
// Discard the Client Nonce if OPTION_DISCARD_CLIENT_NONCE is set.
if ($this->options & self::OPTION_DISCARD_CLIENT_NONCE) {
$this->discardClientNonce();
}
return $header;
}
}
if ('Basic' == $this->getAuthenticationMethod()) {
$username = $this->getUsername();
$password = $this->getPassword();
if (($username) && ($password)) {
$header = 'Basic '.base64_encode("{$username}:{$password}");
return $header;
}
}
return null;
} | php | {
"resource": ""
} |
q255228 | DigestAuthMiddleware.getResponse | test | private function getResponse(): ?string
{
$HA1 = $this->getHA1();
$nonce = $this->getNonce();
$HA2 = $this->getHA2();
if (null !== $HA1 && ($nonce) && null !== $HA2) {
$qop = $this->getQOP();
if (empty($qop)) {
$response = $this->hash("{$HA1}:{$nonce}:{$HA2}");
return $response;
}
$cnonce = $this->getClientNonce();
$nc = $this->getNonceCount();
if (($cnonce) && ($nc)) {
$response = $this->hash("{$HA1}:{$nonce}:{$nc}:{$cnonce}:{$qop}:{$HA2}");
return $response;
}
}
return null;
} | php | {
"resource": ""
} |
q255229 | DigestAuthMiddleware.getQOP | test | private function getQOP(): ?string
{
// Has the server specified any options for Quality of Protection
if (\count($this->qop) > 0) {
if ($this->options & self::OPTION_QOP_AUTH_INT) {
if (\in_array('auth-int', $this->qop)) {
return 'auth-int';
}
if (\in_array('auth', $this->qop)) {
return 'auth';
}
}
if ($this->options & self::OPTION_QOP_AUTH) {
if (\in_array('auth', $this->qop)) {
return 'auth';
}
if (\in_array('auth-int', $this->qop)) {
return 'auth-int';
}
}
}
// Server has not specified any value for Quality of Protection so return null
return null;
} | php | {
"resource": ""
} |
q255230 | DigestAuthMiddleware.hash | test | private function hash($value): ?string
{
$algorithm = $this->getAlgorithm();
if (('MD5' == $algorithm) || ('MD5-sess' == $algorithm)) {
return hash('md5', $value);
}
return null;
} | php | {
"resource": ""
} |
q255231 | DigestAuthMiddleware.parseAuthenticationInfoHeader | test | private function parseAuthenticationInfoHeader(string $authenticationInfo): void
{
$nameValuePairs = $this->parseNameValuePairs($authenticationInfo);
foreach ($nameValuePairs as $name => $value) {
switch ($name) {
case 'message-qop':
break;
case 'nextnonce':
// This function needs to only set the Nonce once the rspauth has been verified.
$this->setNonce($value);
break;
case 'rspauth':
// Check server rspauth value
break;
}
}
} | php | {
"resource": ""
} |
q255232 | DigestAuthMiddleware.parseNameValuePairs | test | private function parseNameValuePairs(string $nameValuePairs): array
{
$parsedNameValuePairs = [];
$nameValuePairs = explode(',', $nameValuePairs);
foreach ($nameValuePairs as $nameValuePair) {
// Trim the Whitespace from the start and end of the name value pair string
$nameValuePair = trim($nameValuePair);
// Split $nameValuePair (name=value) into $name and $value
list($name, $value) = explode('=', $nameValuePair, 2);
// Remove quotes if the string is quoted
$value = $this->unquoteString($value);
// Add pair to array[name] => value
$parsedNameValuePairs[$name] = $value;
}
return $parsedNameValuePairs;
} | php | {
"resource": ""
} |
q255233 | DigestAuthMiddleware.parseWwwAuthenticateHeader | test | private function parseWwwAuthenticateHeader(string $wwwAuthenticate): void
{
if ('Digest ' == substr($wwwAuthenticate, 0, 7)) {
$this->setAuthenticationMethod('Digest');
// Remove "Digest " from start of header
$wwwAuthenticate = substr($wwwAuthenticate, 7, \strlen($wwwAuthenticate) - 7);
$nameValuePairs = $this->parseNameValuePairs($wwwAuthenticate);
foreach ($nameValuePairs as $name => $value) {
switch ($name) {
case 'algorithm':
$this->setAlgorithm($value);
break;
case 'domain':
$this->setDomain($value);
break;
case 'nonce':
$this->setNonce($value);
break;
case 'realm':
$this->setRealm($value);
break;
case 'opaque':
$this->setOpaque($value);
break;
case 'qop':
$this->setQOP(explode(',', $value));
break;
}
}
}
if ('Basic ' == substr($wwwAuthenticate, 0, 6)) {
$this->setAuthenticationMethod('Basic');
// Remove "Basic " from start of header
$wwwAuthenticate = substr($wwwAuthenticate, 6, \strlen($wwwAuthenticate) - 6);
$nameValuePairs = $this->parseNameValuePairs($wwwAuthenticate);
foreach ($nameValuePairs as $name => $value) {
switch ($name) {
case 'realm':
$this->setRealm($value);
break;
}
}
}
} | php | {
"resource": ""
} |
q255234 | DigestAuthMiddleware.setAlgorithm | test | private function setAlgorithm(string $algorithm): void
{
if (('MD5' == $algorithm) || ('MD5-sess' == $algorithm)) {
$this->algorithm = $algorithm;
} else {
throw new \InvalidArgumentException('DigestAuthMiddleware: Only MD5 and MD5-sess algorithms are currently supported.');
}
} | php | {
"resource": ""
} |
q255235 | DigestAuthMiddleware.setMethod | test | private function setMethod(string $method = null): void
{
if ('GET' == $method) {
$this->method = 'GET';
return;
}
if ('POST' == $method) {
$this->method = 'POST';
return;
}
if ('PUT' == $method) {
$this->method = 'PUT';
return;
}
if ('DELETE' == $method) {
$this->method = 'DELETE';
return;
}
if ('HEAD' == $method) {
$this->method = 'HEAD';
return;
}
throw new \InvalidArgumentException('DigestAuthMiddleware: Only GET,POST,PUT,DELETE,HEAD HTTP methods are currently supported.');
} | php | {
"resource": ""
} |
q255236 | DigestAuthMiddleware.unquoteString | test | private function unquoteString(string $str = null): ?string
{
if ($str) {
if ('"' == substr($str, 0, 1)) {
$str = substr($str, 1, \strlen($str) - 1);
}
if ('"' == substr($str, \strlen($str) - 1, 1)) {
$str = substr($str, 0, \strlen($str) - 1);
}
}
return $str;
} | php | {
"resource": ""
} |
q255237 | ParameterBag.add | test | public function add(array $parameters = []): self
{
// Make sure to merge Curl parameters
if (isset($this->parameters['curl'])
&& isset($parameters['curl'])
&& \is_array($this->parameters['curl'])
&& \is_array($parameters['curl'])) {
$parameters['curl'] = array_replace($this->parameters['curl'], $parameters['curl']);
}
$newParameters = array_replace($this->parameters, $parameters);
return new self($newParameters);
} | php | {
"resource": ""
} |
q255238 | HeaderConverter.toBuzzHeaders | test | public static function toBuzzHeaders(array $headers): array
{
$buzz = [];
foreach ($headers as $key => $values) {
if (!\is_array($values)) {
$buzz[] = sprintf('%s: %s', $key, $values);
} else {
foreach ($values as $value) {
$buzz[] = sprintf('%s: %s', $key, $value);
}
}
}
return $buzz;
} | php | {
"resource": ""
} |
q255239 | HeaderConverter.toPsrHeaders | test | public static function toPsrHeaders(array $headers): array
{
$psr = [];
foreach ($headers as $header) {
list($key, $value) = explode(':', $header, 2);
$psr[trim($key)][] = trim($value);
}
return $psr;
} | php | {
"resource": ""
} |
q255240 | MultiCurl.sendAsyncRequest | test | public function sendAsyncRequest(RequestInterface $request, array $options = []): void
{
$options = $this->validateOptions($options);
$this->addToQueue($request, $options);
} | php | {
"resource": ""
} |
q255241 | MultiCurl.sendRequest | test | public function sendRequest(RequestInterface $request, array $options = []): ResponseInterface
{
$options = $this->validateOptions($options);
$originalCallback = $options->get('callback');
$responseToReturn = null;
$options = $options->add(['callback' => function (RequestInterface $request, ResponseInterface $response = null, ClientException $e = null) use (&$responseToReturn, $originalCallback) {
$responseToReturn = $response;
$originalCallback($request, $response, $e);
if (null !== $e) {
throw $e;
}
}]);
$this->addToQueue($request, $options);
$this->flush();
return $responseToReturn;
} | php | {
"resource": ""
} |
q255242 | MultiCurl.proceed | test | public function proceed(): void
{
if (empty($this->queue)) {
return;
}
if (!$this->curlm) {
$this->initMultiCurlHandle();
}
$this->initQueue();
$exception = null;
do {
// Start processing each handler in the stack
$mrc = curl_multi_exec($this->curlm, $stillRunning);
} while (CURLM_CALL_MULTI_PERFORM === $mrc);
while ($info = curl_multi_info_read($this->curlm)) {
// handle any completed requests
if (CURLMSG_DONE !== $info['msg']) {
continue;
}
$handled = false;
/** @var RequestInterface $request */
/** @var ParameterBag $options */
/** @var ResponseBuilder $responseBuilder */
foreach ($this->queue as $i => list($request, $options, $curl, $responseBuilder)) {
// Try to find the correct handle from the queue.
if ($curl !== $info['handle']) {
continue;
}
$handled = true;
$response = null;
try {
$this->parseError($request, $info['result'], $curl);
$response = $responseBuilder->getResponse();
if ($options->get('expose_curl_info', false)) {
$response = $response->withHeader('__curl_info', json_encode(curl_getinfo($curl)));
}
} catch (\Throwable $e) {
if (null === $exception) {
$exception = $e;
}
}
// remove from queue
curl_multi_remove_handle($this->curlm, $curl);
$this->releaseHandle($curl);
unset($this->queue[$i]);
// callback
\call_user_func($options->get('callback'), $request, $response, $exception);
$exception = null;
}
if (!$handled) {
// It must be a pushed response.
$this->handlePushedResponse($info['handle']);
}
}
$this->cleanup();
} | php | {
"resource": ""
} |
q255243 | MultiCurl.initMultiCurlHandle | test | private function initMultiCurlHandle(): void
{
$this->curlm = curl_multi_init();
if (false === $this->curlm) {
throw new ClientException('Unable to create a new cURL multi handle');
}
if ($this->serverPushSupported) {
$userCallbacks = $this->pushFunctions;
curl_multi_setopt($this->curlm, CURLMOPT_PIPELINING, CURLPIPE_MULTIPLEX);
// We need to use $this->pushCb[] because of a bug in PHP
curl_multi_setopt(
$this->curlm,
CURLMOPT_PUSHFUNCTION,
$this->pushCb[] = function ($parent, $pushed, $headers) use ($userCallbacks) {
// If any callback say no, then do not accept.
foreach ($userCallbacks as $callback) {
if (CURL_PUSH_DENY === $callback($parent, $pushed, $headers)) {
return CURL_PUSH_DENY;
}
}
curl_setopt($pushed, CURLOPT_RETURNTRANSFER, true);
curl_setopt($pushed, CURLOPT_HEADER, true);
$this->addPushHandle($headers, $pushed);
return CURL_PUSH_OK;
}
);
}
} | php | {
"resource": ""
} |
q255244 | MultiCurl.cleanup | test | private function cleanup(): void
{
if (empty($this->queue)) {
curl_multi_close($this->curlm);
$this->curlm = null;
$this->pushFunctions = [];
$this->pushCb = [];
}
} | php | {
"resource": ""
} |
q255245 | Cookie.matchesRequest | test | public function matchesRequest(RequestInterface $request): bool
{
$uri = $request->getUri();
// domain
if (!$this->matchesDomain($uri->getHost())) {
return false;
}
// path
if (!$this->matchesPath($uri->getPath())) {
return false;
}
// secure
if ($this->hasAttribute(static::ATTR_SECURE) && 'https' !== $uri->getScheme()) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q255246 | Cookie.isExpired | test | public function isExpired(): bool
{
$maxAge = $this->getAttribute(static::ATTR_MAX_AGE);
if ($maxAge && time() - $this->getCreatedAt() > $maxAge) {
return true;
}
$expires = $this->getAttribute(static::ATTR_EXPIRES);
if ($expires && strtotime($expires) < time()) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q255247 | Cookie.matchesDomain | test | public function matchesDomain(string $domain): bool
{
$cookieDomain = $this->getAttribute(static::ATTR_DOMAIN) ?? '';
if (0 === strpos($cookieDomain, '.')) {
$pattern = '/\b'.preg_quote(substr($cookieDomain, 1), '/').'$/i';
return (bool) preg_match($pattern, $domain);
} else {
return 0 == strcasecmp($cookieDomain, $domain);
}
} | php | {
"resource": ""
} |
q255248 | Cookie.matchesPath | test | public function matchesPath(string $path): bool
{
$needle = $this->getAttribute(static::ATTR_PATH);
return null === $needle || 0 === strpos($path, $needle);
} | php | {
"resource": ""
} |
q255249 | Cookie.fromSetCookieHeader | test | public function fromSetCookieHeader(string $header, string $issuingDomain): void
{
list($this->name, $header) = explode('=', $header, 2);
if (false === strpos($header, ';')) {
$this->value = $header;
$header = null;
} else {
list($this->value, $header) = explode(';', $header, 2);
}
$this->clearAttributes();
if (null !== $header) {
foreach (array_map('trim', explode(';', trim($header))) as $pair) {
if (false === strpos($pair, '=')) {
$name = $pair;
$value = null;
} else {
list($name, $value) = explode('=', $pair);
}
$this->setAttribute($name, $value);
}
}
if (!$this->getAttribute(static::ATTR_DOMAIN)) {
$this->setAttribute(static::ATTR_DOMAIN, $issuingDomain);
}
} | php | {
"resource": ""
} |
q255250 | AbstractCurl.releaseHandle | test | protected function releaseHandle($curl): void
{
if (\count($this->handles) >= $this->maxHandles) {
curl_close($curl);
} else {
// Remove all callback functions as they can hold onto references
// and are not cleaned up by curl_reset. Using curl_setopt_array
// does not work for some reason, so removing each one
// individually.
curl_setopt($curl, CURLOPT_HEADERFUNCTION, null);
curl_setopt($curl, CURLOPT_READFUNCTION, null);
curl_setopt($curl, CURLOPT_WRITEFUNCTION, null);
curl_setopt($curl, CURLOPT_PROGRESSFUNCTION, null);
curl_reset($curl);
if (!\in_array($curl, $this->handles)) {
$this->handles[] = $curl;
}
}
} | php | {
"resource": ""
} |
q255251 | AbstractCurl.prepare | test | protected function prepare($curl, RequestInterface $request, ParameterBag $options): ResponseBuilder
{
if (\defined('CURLOPT_PROTOCOLS')) {
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
curl_setopt($curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS);
}
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
$this->setOptionsFromParameterBag($curl, $options);
$this->setOptionsFromRequest($curl, $request);
$responseBuilder = new ResponseBuilder($this->responseFactory);
curl_setopt($curl, CURLOPT_HEADERFUNCTION, function ($ch, $data) use ($responseBuilder) {
$str = trim($data);
if ('' !== $str) {
if (0 === strpos(strtolower($str), 'http/')) {
$responseBuilder->setStatus($str);
} else {
$responseBuilder->addHeader($str);
}
}
return \strlen($data);
});
curl_setopt($curl, CURLOPT_WRITEFUNCTION, function ($ch, $data) use ($responseBuilder) {
return $responseBuilder->writeBody($data);
});
// apply additional options
curl_setopt_array($curl, $options->get('curl'));
return $responseBuilder;
} | php | {
"resource": ""
} |
q255252 | AbstractCurl.setOptionsFromRequest | test | private function setOptionsFromRequest($curl, RequestInterface $request): void
{
$options = [
CURLOPT_CUSTOMREQUEST => $request->getMethod(),
CURLOPT_URL => $request->getUri()->__toString(),
CURLOPT_HTTPHEADER => HeaderConverter::toBuzzHeaders($request->getHeaders()),
];
if (0 !== $version = $this->getProtocolVersion($request)) {
$options[CURLOPT_HTTP_VERSION] = $version;
}
if ($request->getUri()->getUserInfo()) {
$options[CURLOPT_USERPWD] = $request->getUri()->getUserInfo();
}
switch (strtoupper($request->getMethod())) {
case 'HEAD':
$options[CURLOPT_NOBODY] = true;
break;
case 'GET':
$options[CURLOPT_HTTPGET] = true;
break;
case 'POST':
case 'PUT':
case 'DELETE':
case 'PATCH':
case 'OPTIONS':
$body = $request->getBody();
$bodySize = $body->getSize();
if (0 !== $bodySize) {
if ($body->isSeekable()) {
$body->rewind();
}
// Message has non empty body.
if (null === $bodySize || $bodySize > 1024 * 1024) {
// Avoid full loading large or unknown size body into memory
$options[CURLOPT_UPLOAD] = true;
if (null !== $bodySize) {
$options[CURLOPT_INFILESIZE] = $bodySize;
}
$options[CURLOPT_READFUNCTION] = function ($ch, $fd, $length) use ($body) {
return $body->read($length);
};
} else {
// Small body can be loaded into memory
$options[CURLOPT_POSTFIELDS] = (string) $body;
}
}
}
curl_setopt_array($curl, $options);
} | php | {
"resource": ""
} |
q255253 | Browser.sendRequest | test | public function sendRequest(RequestInterface $request, array $options = []): ResponseInterface
{
$chain = $this->createMiddlewareChain($this->middleware, function (RequestInterface $request, callable $responseChain) use ($options) {
$response = $this->client->sendRequest($request, $options);
$responseChain($request, $response);
}, function (RequestInterface $request, ResponseInterface $response) {
$this->lastRequest = $request;
$this->lastResponse = $response;
});
// Call the chain
$chain($request);
return $this->lastResponse;
} | php | {
"resource": ""
} |
q255254 | Journal.record | test | public function record(RequestInterface $request, ResponseInterface $response, float $duration = null): void
{
$this->addEntry(new Entry($request, $response, $duration));
} | php | {
"resource": ""
} |
q255255 | Image.createImage | test | protected function createImage()
{
if ($this->_isCreated) {
return false;
}
$command = $this->getCommand();
$fileName = $this->getImageFilename();
$command->addArgs($this->_options);
// Always escape input and output filename
$command->addArg((string) $this->_page, null, true);
$command->addArg($fileName, null, true);
if (!$command->execute()) {
$this->_error = $command->getError();
if (!(file_exists($fileName) && filesize($fileName)!==0 && $this->ignoreWarnings)) {
return false;
}
}
$this->_isCreated = true;
return true;
} | php | {
"resource": ""
} |
q255256 | Pdf.addCover | test | public function addCover($input, $options = array(), $type = null)
{
$options['input'] = ($this->version9 ? '--' : '') . 'cover';
$options['inputArg'] = $this->ensureUrlOrFile($input, $type);
$this->_objects[] = $this->ensureUrlOrFileOptions($options);
return $this;
} | php | {
"resource": ""
} |
q255257 | Pdf.addToc | test | public function addToc($options = array())
{
$options['input'] = ($this->version9 ? '--' : '') . 'toc';
$this->_objects[] = $this->ensureUrlOrFileOptions($options);
return $this;
} | php | {
"resource": ""
} |
q255258 | Pdf.createPdf | test | protected function createPdf()
{
if ($this->_isCreated) {
return false;
}
$command = $this->getCommand();
$fileName = $this->getPdfFilename();
$command->addArgs($this->_options);
foreach ($this->_objects as $object) {
$command->addArgs($object);
}
$command->addArg($fileName, null, true); // Always escape filename
if (!$command->execute()) {
$this->_error = $command->getError();
if (!(file_exists($fileName) && filesize($fileName) !== 0 && $this->ignoreWarnings)) {
return false;
}
}
$this->_isCreated = true;
return true;
} | php | {
"resource": ""
} |
q255259 | Pdf.ensureUrlOrFile | test | protected function ensureUrlOrFile($input, $type = null)
{
if ($input instanceof File) {
$this->_tmpFiles[] = $input;
return $input;
} elseif (preg_match(self::REGEX_URL, $input)) {
return $input;
} elseif ($type === self::TYPE_XML || $type === null && preg_match(self::REGEX_XML, $input)) {
$ext = '.xml';
} else {
// First check for obvious HTML content to avoid is_file() as much
// as possible as it can trigger open_basedir restriction warnings
// with long strings.
$isHtml = $type === self::TYPE_HTML || preg_match(self::REGEX_HTML, $input);
if (!$isHtml) {
$maxPathLen = defined('PHP_MAXPATHLEN') ?
constant('PHP_MAXPATHLEN') : self::MAX_PATHLEN;
if (strlen($input) <= $maxPathLen && is_file($input)) {
return $input;
}
}
$ext = '.html';
}
$file = new File($input, $ext, self::TMP_PREFIX, $this->tmpDir);
$this->_tmpFiles[] = $file;
return $file;
} | php | {
"resource": ""
} |
q255260 | ServiceRestProxy.createClient | test | private static function createClient(array $options)
{
$verify = true;
//Disable SSL if proxy has been set, and set the proxy in the client.
$proxy = getenv('HTTP_PROXY');
// For testing with Fiddler
// $proxy = 'localhost:8888';
// $verify = false;
if (!empty($proxy)) {
$options['proxy'] = $proxy;
}
if (!empty($options['verify'])) {
$verify = $options['verify'];
}
return (new \GuzzleHttp\Client(
array_merge(
$options,
array(
"defaults" => array(
"allow_redirects" => true,
"exceptions" => true,
"decode_content" => true,
),
'cookies' => true,
'verify' => $verify,
)
)
));
} | php | {
"resource": ""
} |
q255261 | ServiceRestProxy.createMiddlewareStack | test | protected function createMiddlewareStack(ServiceOptions $serviceOptions)
{
//If handler stack is not defined by the user, create a default
//middleware stack.
$stack = null;
if (array_key_exists('stack', $this->options['http'])) {
$stack = $this->options['http']['stack'];
} elseif ($serviceOptions->getMiddlewareStack() != null) {
$stack = $serviceOptions->getMiddlewareStack();
} else {
$stack = new MiddlewareStack();
}
//Push all the middlewares specified in the $serviceOptions to the
//handlerstack.
if ($serviceOptions->getMiddlewares() != array()) {
foreach ($serviceOptions->getMiddlewares() as $middleware) {
$stack->push($middleware);
}
}
//Push all the middlewares specified in the $options to the
//handlerstack.
if (array_key_exists('middlewares', $this->options)) {
foreach ($this->options['middlewares'] as $middleware) {
$stack->push($middleware);
}
}
//Push all the middlewares specified in $this->middlewares to the
//handlerstack.
foreach ($this->getMiddlewares() as $middleware) {
$stack->push($middleware);
}
return $stack;
} | php | {
"resource": ""
} |
q255262 | ServiceRestProxy.createRequest | test | protected function createRequest(
$method,
array $headers,
array $queryParams,
array $postParameters,
$path,
$locationMode,
$body = Resources::EMPTY_STRING
) {
if ($locationMode == LocationMode::SECONDARY_ONLY ||
$locationMode == LocationMode::SECONDARY_THEN_PRIMARY) {
$uri = $this->psrSecondaryUri;
} else {
$uri = $this->psrPrimaryUri;
}
//Append the path, not replacing it.
if ($path != null) {
$exPath = $uri->getPath();
if ($exPath != '') {
//Remove the duplicated slash in the path.
if ($path != '' && $path[0] == '/') {
$path = $exPath . substr($path, 1);
} else {
$path = $exPath . $path;
}
}
$uri = $uri->withPath($path);
}
// add query parameters into headers
if ($queryParams != null) {
$queryString = Psr7\build_query($queryParams);
$uri = $uri->withQuery($queryString);
}
// add post parameters into bodys
$actualBody = null;
if (empty($body)) {
if (empty($headers['content-type'])) {
$headers['content-type'] = 'application/x-www-form-urlencoded';
$actualBody = Psr7\build_query($postParameters);
}
} else {
$actualBody = $body;
}
$request = new Request(
$method,
$uri,
$headers,
$actualBody
);
//add content-length to header
$bodySize = $request->getBody()->getSize();
if ($bodySize > 0) {
$request = $request->withHeader('content-length', $bodySize);
}
return $request;
} | php | {
"resource": ""
} |
q255263 | ServiceRestProxy.sendAsync | test | protected function sendAsync(
$method,
array $headers,
array $queryParams,
array $postParameters,
$path,
$expected = Resources::STATUS_OK,
$body = Resources::EMPTY_STRING,
ServiceOptions $serviceOptions = null
) {
if ($serviceOptions == null) {
$serviceOptions = new ServiceOptions();
}
$this->addOptionalQueryParam(
$queryParams,
Resources::QP_TIMEOUT,
$serviceOptions->getTimeout()
);
$request = $this->createRequest(
$method,
$headers,
$queryParams,
$postParameters,
$path,
$serviceOptions->getLocationMode(),
$body
);
$client = $this->client;
$middlewareStack = $this->createMiddlewareStack($serviceOptions);
$sendAsync = function ($request, $options) use ($client) {
return $client->sendAsync($request, $options);
};
$handler = $middlewareStack->apply($sendAsync);
$requestOptions =
$this->generateRequestOptions($serviceOptions, $handler);
if ($request->getMethod() == 'HEAD') {
$requestOptions[Resources::ROS_DECODE_CONTENT] = false;
}
$promise = \call_user_func($handler, $request, $requestOptions);
return $promise->then(
function ($response) use ($expected, $requestOptions) {
self::throwIfError(
$response,
$expected
);
return self::addLocationHeaderToResponse(
$response,
$requestOptions[Resources::ROS_LOCATION_MODE]
);
},
function ($reason) use ($expected) {
if (!($reason instanceof RequestException)) {
throw $reason;
}
$response = $reason->getResponse();
if ($response != null) {
self::throwIfError(
$response,
$expected
);
} else {
//if could not get response but promise rejected, throw reason.
throw $reason;
}
return $response;
}
);
} | php | {
"resource": ""
} |
q255264 | ServiceRestProxy.generateRequestOptions | test | protected function generateRequestOptions(
ServiceOptions $serviceOptions,
callable $handler
) {
$result = array();
$result[Resources::ROS_LOCATION_MODE] = $serviceOptions->getLocationMode();
$result[Resources::ROS_STREAM] = $serviceOptions->getIsStreaming();
$result[Resources::ROS_DECODE_CONTENT] = $serviceOptions->getDecodeContent();
$result[Resources::ROS_HANDLER] = $handler;
$result[Resources::ROS_SECONDARY_URI] = $this->getPsrSecondaryUri();
$result[Resources::ROS_PRIMARY_URI] = $this->getPsrPrimaryUri();
return $result;
} | php | {
"resource": ""
} |
q255265 | ServiceRestProxy.sendContextAsync | test | protected function sendContextAsync(HttpCallContext $context)
{
return $this->sendAsync(
$context->getMethod(),
$context->getHeaders(),
$context->getQueryParameters(),
$context->getPostParameters(),
$context->getPath(),
$context->getStatusCodes(),
$context->getBody(),
$context->getServiceOptions()
);
} | php | {
"resource": ""
} |
q255266 | ServiceRestProxy.throwIfError | test | public static function throwIfError(ResponseInterface $response, $expected)
{
$expectedStatusCodes = is_array($expected) ? $expected : array($expected);
if (!in_array($response->getStatusCode(), $expectedStatusCodes)) {
throw new ServiceException($response);
}
} | php | {
"resource": ""
} |
q255267 | ServiceRestProxy.addPostParameter | test | public function addPostParameter(
array $postParameters,
$key,
$value
) {
Validate::isArray($postParameters, 'postParameters');
$postParameters[$key] = $value;
return $postParameters;
} | php | {
"resource": ""
} |
q255268 | ServiceRestProxy.addMetadataHeaders | test | protected function addMetadataHeaders(array $headers, array $metadata = null)
{
Utilities::validateMetadata($metadata);
$metadata = $this->generateMetadataHeaders($metadata);
$headers = array_merge($headers, $metadata);
return $headers;
} | php | {
"resource": ""
} |
q255269 | ServiceRestProxy.addLocationHeaderToResponse | test | private static function addLocationHeaderToResponse(
ResponseInterface $response,
$locationMode
) {
//If the response already has this header, return itself.
if ($response->hasHeader(Resources::X_MS_CONTINUATION_LOCATION_MODE)) {
return $response;
}
//Otherwise, add the header that indicates the endpoint to be used if
//continuation token is used for subsequent request. Notice that if the
//response does not have location header set at the moment, it means
//that the user have not set a retry middleware.
if ($locationMode == LocationMode::PRIMARY_THEN_SECONDARY) {
$response = $response->withHeader(
Resources::X_MS_CONTINUATION_LOCATION_MODE,
LocationMode::PRIMARY_ONLY
);
} elseif ($locationMode == LocationMode::SECONDARY_THEN_PRIMARY) {
$response = $response->withHeader(
Resources::X_MS_CONTINUATION_LOCATION_MODE,
LocationMode::SECONDARY_ONLY
);
} elseif ($locationMode == LocationMode::SECONDARY_ONLY ||
$locationMode == LocationMode::PRIMARY_ONLY) {
$response = $response->withHeader(
Resources::X_MS_CONTINUATION_LOCATION_MODE,
$locationMode
);
}
return $response;
} | php | {
"resource": ""
} |
q255270 | Entity._validateProperties | test | private function _validateProperties($properties)
{
Validate::isArray($properties, 'entity properties');
foreach ($properties as $key => $value) {
Validate::canCastAsString($key, 'key');
Validate::isTrue(
$value instanceof Property,
Resources::INVALID_PROP_MSG
);
Validate::isTrue(
EdmType::validateEdmValue(
$value->getEdmType(),
$value->getValue(),
$condition
),
sprintf(Resources::INVALID_PROP_VAL_MSG, $key, $condition)
);
}
} | php | {
"resource": ""
} |
q255271 | Entity.getPropertyValue | test | public function getPropertyValue($name)
{
$p = Utilities::tryGetValue($this->_properties, $name);
return is_null($p) ? null : $p->getValue();
} | php | {
"resource": ""
} |
q255272 | Entity.setPropertyValue | test | public function setPropertyValue($name, $value)
{
$p = Utilities::tryGetValue($this->_properties, $name);
if (!is_null($p)) {
$p->setValue($value);
}
} | php | {
"resource": ""
} |
q255273 | Entity.setProperty | test | public function setProperty($name, $property)
{
Validate::isTrue($property instanceof Property, Resources::INVALID_PROP_MSG);
$this->_properties[$name] = $property;
} | php | {
"resource": ""
} |
q255274 | Entity.addProperty | test | public function addProperty($name, $edmType, $value, $rawValue = '')
{
$p = new Property();
$p->setEdmType($edmType);
$p->setValue($value);
$p->setRawValue($rawValue);
$this->setProperty($name, $p);
} | php | {
"resource": ""
} |
q255275 | Entity.isValid | test | public function isValid(&$msg = null)
{
try {
$this->_validateProperties($this->_properties);
} catch (\Exception $exc) {
$msg = $exc->getMessage();
return false;
}
if (is_null($this->getPartitionKey())
|| is_null($this->getRowKey())
) {
$msg = Resources::NULL_TABLE_KEY_MSG;
return false;
} else {
return true;
}
} | php | {
"resource": ""
} |
q255276 | GetTableResult.create | test | public static function create($body, $odataSerializer)
{
$result = new GetTableResult();
$name = $odataSerializer->parseTable($body);
$result->setName($name);
return $result;
} | php | {
"resource": ""
} |
q255277 | SharedKeyAuthScheme.computeSignature | test | protected function computeSignature(
array $headers,
$url,
array $queryParams,
$httpMethod
) {
$canonicalizedHeaders = $this->computeCanonicalizedHeaders($headers);
$canonicalizedResource = $this->computeCanonicalizedResource(
$url,
$queryParams
);
$stringToSign = array();
$stringToSign[] = strtoupper($httpMethod);
foreach ($this->includedHeaders as $header) {
$stringToSign[] = Utilities::tryGetValue($headers, $header);
}
if (count($canonicalizedHeaders) > 0) {
$stringToSign[] = implode("\n", $canonicalizedHeaders);
}
$stringToSign[] = $canonicalizedResource;
$stringToSign = implode("\n", $stringToSign);
return $stringToSign;
} | php | {
"resource": ""
} |
q255278 | SharedKeyAuthScheme.getAuthorizationHeader | test | public function getAuthorizationHeader(
array $headers,
$url,
array $queryParams,
$httpMethod
) {
$signature = $this->computeSignature(
$headers,
$url,
$queryParams,
$httpMethod
);
return 'SharedKey ' . $this->accountName . ':' . base64_encode(
hash_hmac('sha256', $signature, base64_decode($this->accountKey), true)
);
} | php | {
"resource": ""
} |
q255279 | SharedKeyAuthScheme.computeCanonicalizedHeaders | test | protected function computeCanonicalizedHeaders($headers)
{
$canonicalizedHeaders = array();
$normalizedHeaders = array();
$validPrefix = Resources::X_MS_HEADER_PREFIX;
if (is_null($normalizedHeaders)) {
return $canonicalizedHeaders;
}
foreach ($headers as $header => $value) {
// Convert header to lower case.
$header = strtolower($header);
// Retrieve all headers for the resource that begin with x-ms-,
// including the x-ms-date header.
if (Utilities::startsWith($header, $validPrefix)) {
// Unfold the string by replacing any breaking white space
// (meaning what splits the headers, which is \r\n) with a single
// space.
$value = str_replace("\r\n", ' ', $value);
// Trim any white space around the colon in the header.
$value = ltrim($value);
$header = rtrim($header);
$normalizedHeaders[$header] = $value;
}
}
// Sort the headers lexicographically by header name, in ascending order.
// Note that each header may appear only once in the string.
ksort($normalizedHeaders);
foreach ($normalizedHeaders as $key => $value) {
$canonicalizedHeaders[] = $key . ':' . $value;
}
return $canonicalizedHeaders;
} | php | {
"resource": ""
} |
q255280 | SharedKeyAuthScheme.computeCanonicalizedResourceForTable | test | protected function computeCanonicalizedResourceForTable($url, $queryParams)
{
$queryParams = array_change_key_case($queryParams);
// 1. Beginning with an empty string (""), append a forward slash (/),
// followed by the name of the account that owns the accessed resource.
$canonicalizedResource = '/' . $this->accountName;
// 2. Append the resource's encoded URI path, without any query parameters.
$canonicalizedResource .= parse_url($url, PHP_URL_PATH);
// 3. The query string should include the question mark and the comp
// parameter (for example, ?comp=metadata). No other parameters should
// be included on the query string.
if (array_key_exists(Resources::QP_COMP, $queryParams)) {
$canonicalizedResource .= '?' . Resources::QP_COMP . '=';
$canonicalizedResource .= $queryParams[Resources::QP_COMP];
}
return $canonicalizedResource;
} | php | {
"resource": ""
} |
q255281 | SharedKeyAuthScheme.computeCanonicalizedResource | test | protected function computeCanonicalizedResource($url, $queryParams)
{
$queryParams = array_change_key_case($queryParams);
// 1. Beginning with an empty string (""), append a forward slash (/),
// followed by the name of the account that owns the accessed resource.
$canonicalizedResource = '/' . $this->accountName;
// 2. Append the resource's encoded URI path, without any query parameters.
$canonicalizedResource .= parse_url($url, PHP_URL_PATH);
// 3. Retrieve all query parameters on the resource URI, including the comp
// parameter if it exists.
// 4. Sort the query parameters lexicographically by parameter name, in
// ascending order.
if (count($queryParams) > 0) {
ksort($queryParams);
}
// 5. Convert all parameter names to lowercase.
// 6. URL-decode each query parameter name and value.
// 7. Append each query parameter name and value to the string in the
// following format:
// parameter-name:parameter-value
// 9. Group query parameters
// 10. Append a new line character (\n) after each name-value pair.
foreach ($queryParams as $key => $value) {
// $value must already be ordered lexicographically
// See: ServiceRestProxy::groupQueryValues
$canonicalizedResource .= "\n" . $key . ':' . $value;
}
return $canonicalizedResource;
} | php | {
"resource": ""
} |
q255282 | ACLBase.toXml | test | public function toXml(XmlSerializer $serializer)
{
$properties = array(
XmlSerializer::DEFAULT_TAG => Resources::XTAG_SIGNED_IDENTIFIER,
XmlSerializer::ROOT_NAME => Resources::XTAG_SIGNED_IDENTIFIERS
);
return $serializer->serialize($this->toArray(), $properties);
} | php | {
"resource": ""
} |
q255283 | ACLBase.fromXmlArray | test | public function fromXmlArray(array $parsed = null)
{
$this->setSignedIdentifiers(array());
// Initialize signed identifiers.
if (!empty($parsed) &&
is_array($parsed[Resources::XTAG_SIGNED_IDENTIFIER])
) {
$entries = $parsed[Resources::XTAG_SIGNED_IDENTIFIER];
$temp = Utilities::getArray($entries);
foreach ($temp as $value) {
$accessPolicy = $value[Resources::XTAG_ACCESS_POLICY];
$startString = urldecode(
$accessPolicy[Resources::XTAG_SIGNED_START]
);
$expiryString = urldecode(
$accessPolicy[Resources::XTAG_SIGNED_EXPIRY]
);
$start = Utilities::convertToDateTime($startString);
$expiry = Utilities::convertToDateTime($expiryString);
$permission = $accessPolicy[Resources::XTAG_SIGNED_PERMISSION];
$id = $value[Resources::XTAG_SIGNED_ID];
$this->addSignedIdentifier($id, $start, $expiry, $permission);
}
}
} | php | {
"resource": ""
} |
q255284 | ACLBase.addSignedIdentifier | test | public function addSignedIdentifier(
$id,
\DateTime $start,
\DateTime $expiry,
$permissions
) {
Validate::canCastAsString($id, 'id');
if ($start != null) {
Validate::isDate($start);
}
Validate::isDate($expiry);
Validate::canCastAsString($permissions, 'permissions');
$accessPolicy = static::createAccessPolicy();
$accessPolicy->setStart($start);
$accessPolicy->setExpiry($expiry);
$accessPolicy->setPermission($permissions);
$signedIdentifier = new SignedIdentifier();
$signedIdentifier->setId($id);
$signedIdentifier->setAccessPolicy($accessPolicy);
// Remove the signed identifier with the same ID.
$this->removeSignedIdentifier($id);
// There can be no more than 5 signed identifiers at the same time.
Validate::isTrue(
count($this->getSignedIdentifiers()) < 5,
Resources::ERROR_TOO_MANY_SIGNED_IDENTIFIERS
);
$this->signedIdentifiers[] = $signedIdentifier;
} | php | {
"resource": ""
} |
q255285 | ACLBase.removeSignedIdentifier | test | public function removeSignedIdentifier($id)
{
Validate::canCastAsString($id, 'id');
//var_dump($this->signedIdentifiers);
for ($i = 0; $i < count($this->signedIdentifiers); ++$i) {
if ($this->signedIdentifiers[$i]->getId() == $id) {
array_splice($this->signedIdentifiers, $i, 1);
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q255286 | BatchOperations.setOperations | test | public function setOperations(array $operations)
{
$this->_operations = array();
foreach ($operations as $operation) {
$this->addOperation($operation);
}
} | php | {
"resource": ""
} |
q255287 | BatchOperations.addOperation | test | public function addOperation($operation)
{
Validate::isTrue(
$operation instanceof BatchOperation,
Resources::INVALID_BO_TYPE_MSG
);
$this->_operations[] = $operation;
} | php | {
"resource": ""
} |
q255288 | BatchOperations.addInsertEntity | test | public function addInsertEntity($table, Entity $entity)
{
Validate::canCastAsString($table, 'table');
Validate::notNullOrEmpty($entity, 'entity');
$operation = new BatchOperation();
$type = BatchOperationType::INSERT_ENTITY_OPERATION;
$operation->setType($type);
$operation->addParameter(BatchOperationParameterName::BP_TABLE, $table);
$operation->addParameter(BatchOperationParameterName::BP_ENTITY, $entity);
$this->addOperation($operation);
} | php | {
"resource": ""
} |
q255289 | BatchOperations.addDeleteEntity | test | public function addDeleteEntity($table, $partitionKey, $rowKey, $etag = null)
{
Validate::canCastAsString($table, 'table');
Validate::isTrue(!is_null($partitionKey), Resources::NULL_TABLE_KEY_MSG);
Validate::isTrue(!is_null($rowKey), Resources::NULL_TABLE_KEY_MSG);
$operation = new BatchOperation();
$type = BatchOperationType::DELETE_ENTITY_OPERATION;
$operation->setType($type);
$operation->addParameter(BatchOperationParameterName::BP_TABLE, $table);
$operation->addParameter(BatchOperationParameterName::BP_ROW_KEY, $rowKey);
$operation->addParameter(BatchOperationParameterName::BP_ETAG, $etag);
$operation->addParameter(
BatchOperationParameterName::BP_PARTITION_KEY,
$partitionKey
);
$this->addOperation($operation);
} | php | {
"resource": ""
} |
q255290 | CopyFileResult.create | test | public static function create(array $headers)
{
$result = new CopyFileResult();
$headers = array_change_key_case($headers);
$date = $headers[Resources::LAST_MODIFIED];
$date = Utilities::rfc1123ToDateTime($date);
$result->setCopyStatus($headers[Resources::X_MS_COPY_STATUS]);
$result->setCopyID($headers[Resources::X_MS_COPY_ID]);
$result->setETag($headers[Resources::ETAG]);
$result->setLastModified($date);
return $result;
} | php | {
"resource": ""
} |
q255291 | QueueMessage.createFromListMessages | test | public static function createFromListMessages(array $parsedResponse)
{
$timeNextVisible = $parsedResponse['TimeNextVisible'];
$msg = self::createFromPeekMessages($parsedResponse);
$date = Utilities::rfc1123ToDateTime($timeNextVisible);
$msg->setTimeNextVisible($date);
$msg->setPopReceipt($parsedResponse['PopReceipt']);
return $msg;
} | php | {
"resource": ""
} |
q255292 | QueueMessage.createFromPeekMessages | test | public static function createFromPeekMessages(array $parsedResponse)
{
$msg = new QueueMessage();
$expirationDate = $parsedResponse['ExpirationTime'];
$insertionDate = $parsedResponse['InsertionTime'];
$msg->setDequeueCount(intval($parsedResponse['DequeueCount']));
$date = Utilities::rfc1123ToDateTime($expirationDate);
$msg->setExpirationDate($date);
$date = Utilities::rfc1123ToDateTime($insertionDate);
$msg->setInsertionDate($date);
$msg->setMessageId($parsedResponse['MessageId']);
$msg->setMessageText($parsedResponse['MessageText']);
return $msg;
} | php | {
"resource": ""
} |
q255293 | QueueMessage.createFromCreateMessage | test | public static function createFromCreateMessage(array $parsedResponse)
{
$msg = new QueueMessage();
$expirationDate = $parsedResponse['ExpirationTime'];
$insertionDate = $parsedResponse['InsertionTime'];
$timeNextVisible = $parsedResponse['TimeNextVisible'];
$date = Utilities::rfc1123ToDateTime($expirationDate);
$msg->setExpirationDate($date);
$date = Utilities::rfc1123ToDateTime($insertionDate);
$msg->setInsertionDate($date);
$date = Utilities::rfc1123ToDateTime($timeNextVisible);
$msg->setTimeNextVisible($date);
$msg->setMessageId($parsedResponse['MessageId']);
$msg->setPopReceipt($parsedResponse['PopReceipt']);
return $msg;
} | php | {
"resource": ""
} |
q255294 | StorageServiceSettings.init | test | protected static function init()
{
self::$useDevelopmentStorageSetting = self::setting(
Resources::USE_DEVELOPMENT_STORAGE_NAME,
'true'
);
self::$developmentStorageProxyUriSetting = self::settingWithFunc(
Resources::DEVELOPMENT_STORAGE_PROXY_URI_NAME,
Validate::getIsValidUri()
);
self::$defaultEndpointsProtocolSetting = self::setting(
Resources::DEFAULT_ENDPOINTS_PROTOCOL_NAME,
'http',
'https'
);
self::$accountNameSetting = self::setting(Resources::ACCOUNT_NAME_NAME);
self::$accountKeySetting = self::settingWithFunc(
Resources::ACCOUNT_KEY_NAME,
// base64_decode will return false if the $key is not in base64 format.
function ($key) {
$isValidBase64String = base64_decode($key, true);
if ($isValidBase64String) {
return true;
} else {
throw new \RuntimeException(
sprintf(Resources::INVALID_ACCOUNT_KEY_FORMAT, $key)
);
}
}
);
self::$sasTokenSetting = self::setting(Resources::SAS_TOKEN_NAME);
self::$blobEndpointSetting = self::settingWithFunc(
Resources::BLOB_ENDPOINT_NAME,
Validate::getIsValidUri()
);
self::$queueEndpointSetting = self::settingWithFunc(
Resources::QUEUE_ENDPOINT_NAME,
Validate::getIsValidUri()
);
self::$tableEndpointSetting = self::settingWithFunc(
Resources::TABLE_ENDPOINT_NAME,
Validate::getIsValidUri()
);
self::$fileEndpointSetting = self::settingWithFunc(
Resources::FILE_ENDPOINT_NAME,
Validate::getIsValidUri()
);
self::$endpointSuffixSetting = self::settingWithFunc(
Resources::ENDPOINT_SUFFIX_NAME,
Validate::getIsValidHostname()
);
self::$validSettingKeys[] = Resources::USE_DEVELOPMENT_STORAGE_NAME;
self::$validSettingKeys[] = Resources::DEVELOPMENT_STORAGE_PROXY_URI_NAME;
self::$validSettingKeys[] = Resources::DEFAULT_ENDPOINTS_PROTOCOL_NAME;
self::$validSettingKeys[] = Resources::ACCOUNT_NAME_NAME;
self::$validSettingKeys[] = Resources::ACCOUNT_KEY_NAME;
self::$validSettingKeys[] = Resources::SAS_TOKEN_NAME;
self::$validSettingKeys[] = Resources::BLOB_ENDPOINT_NAME;
self::$validSettingKeys[] = Resources::QUEUE_ENDPOINT_NAME;
self::$validSettingKeys[] = Resources::TABLE_ENDPOINT_NAME;
self::$validSettingKeys[] = Resources::FILE_ENDPOINT_NAME;
self::$validSettingKeys[] = Resources::ENDPOINT_SUFFIX_NAME;
} | php | {
"resource": ""
} |
q255295 | StorageServiceSettings.getDevelopmentStorageAccount | test | private static function getDevelopmentStorageAccount($proxyUri)
{
if (is_null($proxyUri)) {
return self::developmentStorageAccount();
}
$scheme = parse_url($proxyUri, PHP_URL_SCHEME);
$host = parse_url($proxyUri, PHP_URL_HOST);
$prefix = $scheme . "://" . $host;
return new StorageServiceSettings(
Resources::DEV_STORE_NAME,
Resources::DEV_STORE_KEY,
$prefix . ':10000/devstoreaccount1/',
$prefix . ':10001/devstoreaccount1/',
$prefix . ':10002/devstoreaccount1/',
null
);
} | php | {
"resource": ""
} |
q255296 | StorageServiceSettings.developmentStorageAccount | test | public static function developmentStorageAccount()
{
if (is_null(self::$devStoreAccount)) {
self::$devStoreAccount = self::getDevelopmentStorageAccount(
Resources::DEV_STORE_URI
);
}
return self::$devStoreAccount;
} | php | {
"resource": ""
} |
q255297 | StorageServiceSettings.getServiceEndpoint | test | private static function getServiceEndpoint(
$scheme,
$accountName,
$dnsPrefix,
$dnsSuffix = null,
$isSecondary = false
) {
if ($isSecondary) {
$accountName .= Resources::SECONDARY_STRING;
}
if ($dnsSuffix === null) {
$dnsSuffix = Resources::DEFAULT_ENDPOINT_SUFFIX;
}
return sprintf(
Resources::SERVICE_URI_FORMAT,
$scheme,
$accountName,
$dnsPrefix.$dnsSuffix
);
} | php | {
"resource": ""
} |
q255298 | StorageServiceSettings.createStorageServiceSettings | test | private static function createStorageServiceSettings(
array $settings,
$blobEndpointUri = null,
$queueEndpointUri = null,
$tableEndpointUri = null,
$fileEndpointUri = null,
$blobSecondaryEndpointUri = null,
$queueSecondaryEndpointUri = null,
$tableSecondaryEndpointUri = null,
$fileSecondaryEndpointUri = null
) {
$blobEndpointUri = Utilities::tryGetValueInsensitive(
Resources::BLOB_ENDPOINT_NAME,
$settings,
$blobEndpointUri
);
$queueEndpointUri = Utilities::tryGetValueInsensitive(
Resources::QUEUE_ENDPOINT_NAME,
$settings,
$queueEndpointUri
);
$tableEndpointUri = Utilities::tryGetValueInsensitive(
Resources::TABLE_ENDPOINT_NAME,
$settings,
$tableEndpointUri
);
$fileEndpointUri = Utilities::tryGetValueInsensitive(
Resources::FILE_ENDPOINT_NAME,
$settings,
$fileEndpointUri
);
$accountName = Utilities::tryGetValueInsensitive(
Resources::ACCOUNT_NAME_NAME,
$settings
);
$accountKey = Utilities::tryGetValueInsensitive(
Resources::ACCOUNT_KEY_NAME,
$settings
);
$sasToken = Utilities::tryGetValueInsensitive(
Resources::SAS_TOKEN_NAME,
$settings
);
return new StorageServiceSettings(
$accountName,
$accountKey,
$blobEndpointUri,
$queueEndpointUri,
$tableEndpointUri,
$fileEndpointUri,
$blobSecondaryEndpointUri,
$queueSecondaryEndpointUri,
$tableSecondaryEndpointUri,
$fileSecondaryEndpointUri,
$sasToken
);
} | php | {
"resource": ""
} |
q255299 | StorageServiceSettings.createFromConnectionString | test | public static function createFromConnectionString($connectionString)
{
$tokenizedSettings = self::parseAndValidateKeys($connectionString);
// Devstore case
$matchedSpecs = self::matchedSpecification(
$tokenizedSettings,
self::allRequired(self::$useDevelopmentStorageSetting),
self::optional(self::$developmentStorageProxyUriSetting)
);
if ($matchedSpecs) {
$proxyUri = Utilities::tryGetValueInsensitive(
Resources::DEVELOPMENT_STORAGE_PROXY_URI_NAME,
$tokenizedSettings
);
return self::getDevelopmentStorageAccount($proxyUri);
}
// Automatic case
$matchedSpecs = self::matchedSpecification(
$tokenizedSettings,
self::allRequired(
self::$defaultEndpointsProtocolSetting,
self::$accountNameSetting,
self::$accountKeySetting
),
self::optional(
self::$blobEndpointSetting,
self::$queueEndpointSetting,
self::$tableEndpointSetting,
self::$fileEndpointSetting,
self::$endpointSuffixSetting
)
);
if ($matchedSpecs) {
$scheme = Utilities::tryGetValueInsensitive(
Resources::DEFAULT_ENDPOINTS_PROTOCOL_NAME,
$tokenizedSettings
);
$accountName = Utilities::tryGetValueInsensitive(
Resources::ACCOUNT_NAME_NAME,
$tokenizedSettings
);
$endpointSuffix = Utilities::tryGetValueInsensitive(
Resources::ENDPOINT_SUFFIX_NAME,
$tokenizedSettings
);
return self::createStorageServiceSettings(
$tokenizedSettings,
self::getServiceEndpoint(
$scheme,
$accountName,
Resources::BLOB_DNS_PREFIX,
$endpointSuffix
),
self::getServiceEndpoint(
$scheme,
$accountName,
Resources::QUEUE_DNS_PREFIX,
$endpointSuffix
),
self::getServiceEndpoint(
$scheme,
$accountName,
Resources::TABLE_DNS_PREFIX,
$endpointSuffix
),
self::getServiceEndpoint(
$scheme,
$accountName,
Resources::FILE_DNS_PREFIX,
$endpointSuffix
),
self::getServiceEndpoint(
$scheme,
$accountName,
Resources::BLOB_DNS_PREFIX,
$endpointSuffix,
true
),
self::getServiceEndpoint(
$scheme,
$accountName,
Resources::QUEUE_DNS_PREFIX,
$endpointSuffix,
true
),
self::getServiceEndpoint(
$scheme,
$accountName,
Resources::TABLE_DNS_PREFIX,
$endpointSuffix,
true
),
self::getServiceEndpoint(
$scheme,
$accountName,
Resources::FILE_DNS_PREFIX,
$endpointSuffix,
true
)
);
}
// Explicit case for AccountName/AccountKey combination
$matchedSpecs = self::matchedSpecification(
$tokenizedSettings,
self::atLeastOne(
self::$blobEndpointSetting,
self::$queueEndpointSetting,
self::$tableEndpointSetting,
self::$fileEndpointSetting
),
self::allRequired(
self::$accountNameSetting,
self::$accountKeySetting
)
);
if ($matchedSpecs) {
return self::createStorageServiceSettings($tokenizedSettings);
}
// Explicit case for SAS token
$matchedSpecs = self::matchedSpecification(
$tokenizedSettings,
self::atLeastOne(
self::$blobEndpointSetting,
self::$queueEndpointSetting,
self::$tableEndpointSetting,
self::$fileEndpointSetting
),
self::allRequired(
self::$sasTokenSetting
)
);
if ($matchedSpecs) {
return self::createStorageServiceSettings($tokenizedSettings);
}
self::noMatch($connectionString);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.