_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q10200 | ImageService.index | train | public function index($params = [], $optParams = [])
{
if ($optParams instanceof IndexParams) {
$optParams = $optParams->toArray(true);
}
if (is_string($params)) {
$params = ['cloudId' => $params];
}
return $this->sendRequest(['cloudId'], [
'restAction' => 'index',
'uri' => '/c/<cloudId>',
'params' => $params,
'getParams' => $optParams,
], function ($response) use ($params) {
$images = [];
foreach ($response->data['items'] as $image) {
if (!isset($image['cloudId'])) {
$image['cloudId'] = $this->client->getParam($params, 'cloudId');
}
$images[] = new Image($image);
}
return new Index([
'models' => $images,
'nextPageToken' => $response->data['nextPageToken'],
]);
});
} | php | {
"resource": ""
} |
q10201 | ImageService.view | train | public function view($params, $optParams = [])
{
if (is_string($params)) {
$params = ['publicId' => $params];
}
if ($optParams instanceof ViewParams) {
$optParams = $optParams->toArray(true);
}
return $this->sendRequest(['cloudId', 'publicId'], [
'restAction' => 'view',
'uri' => '/c/<cloudId>/o/<publicId>',
'params' => $params,
'getParams' => $optParams,
], function ($response) use ($params) {
if ($response->data && !isset($response->data['cloudId'])) {
$response->data['cloudId'] = $this->client->getParam($params, 'cloudId');
}
return isset($response->data) ? new Image($response->data) : $response;
});
} | php | {
"resource": ""
} |
q10202 | ImageService.rename | train | public function rename($params, $optParams = [])
{
return $this->sendRequest(['cloudId', 'publicId', 'newPublicId'], [
'restAction' => 'update',
'uri' => '/c/<cloudId>/o/<publicId>/rename/o/<newPublicId>',
'params' => $params,
'getParams' => $optParams,
], function ($response) use ($params) {
if ($response->data && !isset($response->data['cloudId'])) {
$response->data['cloudId'] = $this->client->getParam($params, 'cloudId');
}
return isset($response->data) ? new Image($response->data) : $response;
});
} | php | {
"resource": ""
} |
q10203 | ImageService.delete | train | public function delete($params, $optParams = [])
{
if (is_string($params)) {
$params = ['publicId' => $params];
}
return $this->sendRequest(['cloudId', 'publicId'], [
'restAction' => 'delete',
'uri' => '/c/<cloudId>/o/<publicId>',
'params' => $params,
'getParams' => $optParams,
], function ($response) {
return $response->success;
});
} | php | {
"resource": ""
} |
q10204 | ImageService.deleteByTag | train | public function deleteByTag($params, $optParams = [])
{
if (is_string($params)) {
$params = ['tag' => $params];
}
return $this->sendRequest(['cloudId', 'tag'], [
'restAction' => 'delete',
'uri' => '/c/<cloudId>/t/<tag>',
'params' => $params,
'getParams' => $optParams,
], function ($response) {
return isset($response->data) ? new Job($response->data) : $response;
});
} | php | {
"resource": ""
} |
q10205 | ImageService.exists | train | public function exists($params, $optParams = [])
{
if (is_string($params)) {
$params = ['publicId' => $params];
}
return $this->sendRequest(['cloudId', 'publicId'], [
'restAction' => 'exists',
'uri' => '/c/<cloudId>/o/<publicId>',
'params' => $params,
'getParams' => $optParams,
], function ($response) {
return $response->success;
});
} | php | {
"resource": ""
} |
q10206 | ReadableStreamTrait.buffer | train | public function buffer(Context $context): Promise
{
return $context->task(function (Context $context) {
$buffer = '';
try {
while (null !== ($chunk = yield $this->read($context, 0xFFFF))) {
$buffer .= $chunk;
}
} finally {
$this->close();
}
return $buffer;
});
} | php | {
"resource": ""
} |
q10207 | ReadableStreamTrait.pipe | train | public function pipe(Context $context, WritableStream $stream, bool $close = false): Promise
{
return $context->task(function (Context $context) use ($stream, $close) {
$len = 0;
try {
while (null != ($chunk = yield $this->read($context, 0xFFFF))) {
$len += yield $stream->write($context, $chunk);
}
} finally {
$this->close();
if ($close) {
$stream->close();
}
}
return $len;
});
} | php | {
"resource": ""
} |
q10208 | ReadableStreamTrait.discard | train | public function discard(Context $context): Promise
{
return $context->task(function (Context $context) {
$len = 0;
try {
while (null !== ($chunk = yield $this->read($context, 0xFFFF))) {
$len += \strlen($chunk);
}
} catch (StreamClosedException $e) {
// Ignore this case as we are discarding all data anyways.
} finally {
$this->close();
}
return $len;
});
} | php | {
"resource": ""
} |
q10209 | Descriptor.addDataFixtures | train | public function addDataFixtures(array $fixturesPaths): Descriptor
{
if (!empty($fixturesPaths)) {
foreach ($fixturesPaths as $path) {
$this->dataFixtures->add($path);
}
}
return $this;
} | php | {
"resource": ""
} |
q10210 | Descriptor.getShortName | train | public function getShortName(): string
{
if (empty($this->shortName)) {
$name = strtolower($this->getName());
$replaced = preg_replace('|bundle$|', '', $name);
$this->shortName = trim($replaced);
}
return $this->shortName;
} | php | {
"resource": ""
} |
q10211 | Descriptor.toArray | train | public function toArray(bool $withParentAndChild = true): array
{
$array = [
'name' => $this->getName(),
'shortName' => $this->getShortName(),
'configurationRootName' => $this->getConfigurationRootName(),
'rootNamespace' => $this->getRootNamespace(),
'path' => $this->getPath(),
'dataFixtures' => $this->getDataFixtures()->toArray(),
];
if ($withParentAndChild) {
if (null !== $this->getParentBundleDescriptor()) {
$array['parentBundleDescriptor'] = $this->getParentBundleDescriptor()->toArray(false);
}
if (null !== $this->getChildBundleDescriptor()) {
$array['childBundleDescriptor'] = $this->getChildBundleDescriptor()->toArray(false);
}
}
return $array;
} | php | {
"resource": ""
} |
q10212 | Descriptor.fromArray | train | public static function fromArray(array $data): Descriptor
{
// Default values
$name = '';
$configurationRootName = '';
$rootNamespace = '';
$path = '';
$parentBundleDescriptor = null;
$childBundleDescriptor = null;
// Grab values from provided array
if (array_key_exists('name', $data) && !empty($data['name'])) {
$name = $data['name'];
}
if (array_key_exists('configurationRootName', $data) && !empty($data['configurationRootName'])) {
$configurationRootName = $data['configurationRootName'];
}
if (array_key_exists('rootNamespace', $data) && !empty($data['rootNamespace'])) {
$rootNamespace = $data['rootNamespace'];
}
if (array_key_exists('path', $data) && !empty($data['path'])) {
$path = $data['path'];
}
if (array_key_exists('parentBundleDescriptor', $data) && !empty($data['parentBundleDescriptor'])) {
$parentData = $data['parentBundleDescriptor'];
$parentBundleDescriptor = static::fromArray($parentData);
}
if (array_key_exists('childBundleDescriptor', $data) && !empty($data['childBundleDescriptor'])) {
$childData = $data['childBundleDescriptor'];
$childBundleDescriptor = static::fromArray($childData);
}
return new static(
$name,
$configurationRootName,
$rootNamespace,
$path,
$parentBundleDescriptor,
$childBundleDescriptor
);
} | php | {
"resource": ""
} |
q10213 | Descriptor.fromBundle | train | public static function fromBundle(Bundle $bundle): Descriptor
{
// Values from bundle
$name = $bundle->getName();
$rootNamespace = $bundle->getNamespace();
$path = $bundle->getPath();
// Default values, not provided by bundle directly
$configurationRootName = '';
return new static($name, $configurationRootName, $rootNamespace, $path);
} | php | {
"resource": ""
} |
q10214 | Select2.addJavascripts | train | public static function addJavascripts($culture = null)
{
$path = sfConfig::get('sf_sfSelect2Widgets_select2_web_dir');
$available_cultures = sfConfig::get('sf_sfSelect2Widgets_available_cultures');
$javascripts = array($path . '/select2.js');
if ($culture != 'en' && in_array($culture, $available_cultures)) {
$javascripts[] = $path . '/select2_locale_' . $culture . '.js';
}
return $javascripts;
} | php | {
"resource": ""
} |
q10215 | AbstractHealthAggregator.aggregate | train | public function aggregate($healths)
{
$statusCandidates = [];
foreach ($healths as $key => $health) {
$statusCandidates[] = $health->getStatus();
}
$status = $this->aggregateStatus($statusCandidates);
$details = $this->aggregateDetails($healths);
$builder = new HealthBuilder($status, $details);
return $builder->build();
} | php | {
"resource": ""
} |
q10216 | UploadService.upload | train | public function upload($params, $optParams = [])
{
$resource = null;
if (is_string($params) || is_resource($params)) {
$params = ['file' => $params];
} elseif (is_array($params) && isset($params['tmp_name'])) {
$params = ['file' => $params['tmp_name']];
}
if (isset($params['file']) && is_array($params['file']) && isset($params['file']['tmp_name'])) {
$params['file'] = $params['file']['tmp_name'];
}
if (isset($params['file']) && is_string($params['file'])) {
$resource = $params['file'] = fopen($params['file'], 'r');
}
ArrayHelper::stringify($optParams, [
'transformation',
]);
return $this->sendRequest(['cloudId', 'file'], [
'restAction' => 'create',
'uri' => '/c/<cloudId>',
'params' => $params,
'postParams' => array_merge($params, $optParams),
], function ($response) use ($resource) {
if (is_resource($resource)) {
fclose($resource);
}
return isset($response->data) ? new Image($response->data) : $response;
});
} | php | {
"resource": ""
} |
q10217 | StdString.concat | train | public function concat($string): self
{
Assert::typeOf(['string', __CLASS__], $string);
return new static($this->data . $string, $this->encoding);
} | php | {
"resource": ""
} |
q10218 | StdString.copyValueOf | train | public static function copyValueOf($charList): self
{
Assert::typeOf(['string', 'array', __CLASS__], $charList);
// Convert to native string before creating a new string object
$string = '';
if (\is_array($charList)) {
foreach ($charList as $value) {
$string .= static::valueOf($value);
}
} else {
$string = (string) $charList;
}
return new static($string);
} | php | {
"resource": ""
} |
q10219 | StdString.explode | train | public function explode($delimiter): array
{
Assert::typeOf(['string', __CLASS__], $delimiter);
$response = [];
$results = explode((string) $delimiter, $this->data);
if ($results === false) {
throw new RuntimeException('An unknown error occurred while splitting string!');
}
foreach ($results as $result) {
$response[] = new static($result, $this->encoding);
}
return $response;
} | php | {
"resource": ""
} |
q10220 | StdString.format | train | public static function format($format, ...$args): self
{
Assert::typeOf(['string', __CLASS__], $format);
return new static(sprintf((string) $format, ...$args));
} | php | {
"resource": ""
} |
q10221 | StdString.getChars | train | public function getChars(int $begin, int $end, array &$destination, int $dstBegin): void
{
$length = $end - $begin + 1;
for ($i = 0; $i < $length; $i++) {
$destination[$dstBegin + $i] = $this->charAt($begin + $i);
}
} | php | {
"resource": ""
} |
q10222 | StdString.indexOf | train | public function indexOf($string, int $offset = 0): int
{
Assert::typeOf(['string', __CLASS__], $string);
$pos = mb_strpos($this->data, (string) $string, $offset, $this->encoding);
return $pos > -1 ? $pos : -1;
} | php | {
"resource": ""
} |
q10223 | StdString.lastIndexOf | train | public function lastIndexOf($string, int $offset = 0): int
{
Assert::typeOf(['string', __CLASS__], $string);
$pos = mb_strrpos($this->data, (string) $string, $offset, $this->encoding);
return $pos > -1 ? $pos : -1;
} | php | {
"resource": ""
} |
q10224 | StdString.matches | train | public function matches($pattern): bool
{
Assert::typeOf(['string', __CLASS__], $pattern);
return preg_match((string) $pattern, $this->data) === 1;
} | php | {
"resource": ""
} |
q10225 | StdString.regionMatches | train | public function regionMatches(int $offset, $string, int $strOffset, int $len, bool $ignoreCase = false): bool
{
Assert::typeOf(['string', __CLASS__], $string);
$strLen = \is_string($string) ? mb_strlen($string, $this->encoding) : $string->length();
if ($offset < 0 || $strOffset < 0 || ($strOffset + $len) > $strLen || ($offset + $len) > $this->length()) {
return false;
}
$stringA = mb_substr($this->data, $offset, $len, $this->encoding);
$stringB = mb_substr((string) $string, $strOffset, $len, $this->encoding);
// Compare strings
if ($ignoreCase) {
$result = strcmp(mb_strtolower($stringA, $this->encoding), mb_strtolower($stringB, $this->encoding));
} else {
$result = strcmp($stringA, $stringB);
}
return $result === 0;
} | php | {
"resource": ""
} |
q10226 | StdString.replaceFirst | train | public function replaceFirst($pattern, $replacement): self
{
Assert::typeOf(['string', __CLASS__], $pattern, $replacement);
$result = preg_replace($pattern, $replacement, $this->data, 1);
return new static($result ?: $this->data, $this->encoding);
} | php | {
"resource": ""
} |
q10227 | StdString.split | train | public function split($pattern, int $limit = -1): array
{
Assert::typeOf(['string', __CLASS__], $pattern);
$response = [];
$results = preg_split((string) $pattern, $this->data, $limit);
if ($results === false) {
throw new RuntimeException('An unknown error occurred while splitting string!');
}
foreach ($results as $result) {
$response[] = new static($result, $this->encoding);
}
return $response;
} | php | {
"resource": ""
} |
q10228 | StdString.substr | train | public function substr(int $start, int $length = null): self
{
if ($start < 0) {
throw new InvalidArgumentException('Negative index is not allowed!');
}
return new static(mb_substr($this->data, $start, $length, $this->encoding), $this->encoding);
} | php | {
"resource": ""
} |
q10229 | StdString.valueOf | train | public static function valueOf($value): self
{
$strVal = null;
switch (gettype($value)) {
case 'object':
if ($value instanceof StdObject || (\is_object($value) && method_exists($value, '__toString'))) {
$strVal = (string) $value;
}
break;
case 'boolean':
$strVal = $value ? 'true' : 'false';
break;
case 'double':
case 'integer':
case 'string':
$strVal = (string) $value;
break;
}
if ($strVal === null) {
throw new InvalidArgumentException('Unsupported value type!');
}
return new static($strVal);
} | php | {
"resource": ""
} |
q10230 | String.read | train | public function read(AbstractStream $stream)
{
return $stream->getBuffer()->read($this->getSize(), $this->getEndian());
} | php | {
"resource": ""
} |
q10231 | BackButtonTrait.handleBackActions | train | public function handleBackActions(): void
{
if (!$this->request->getSession()->check('back_action')) {
$this->request->getSession()->write('back_action', []);
}
if (!empty($this->request->getQuery('back_action'))) {
$requestedBackAction = $this->request->getQuery('back_action');
$requestedAction = $this->getRequestedAction();
if (!$this->request->getSession()->check('back_action.' . $requestedBackAction)
|| ($this->request->getSession()->check('back_action.' . $requestedBackAction)
&& $this->request->getSession()->read('back_action.' . $requestedBackAction) != $requestedAction
)
&& !$this->request->getSession()->check('back_action.' . $requestedAction)
) {
$this->request->getSession()->write('back_action.' . $requestedAction, $requestedBackAction);
}
}
} | php | {
"resource": ""
} |
q10232 | BackButtonTrait.augmentUrlByBackParam | train | public function augmentUrlByBackParam(array $url): array
{
$backAction = $this->request->getRequestTarget();
if ($this->request->is('ajax')) {
$backAction = $this->request->referer(true);
}
$backAction = preg_replace('/back_action=.*?(&|$)/', '', $backAction);
$url['?']['back_action'] = preg_replace('/\\?$/', '', $backAction);
return $url;
} | php | {
"resource": ""
} |
q10233 | BaseThanTodayValidator.getDifference | train | private function getDifference($value): ?int
{
// Let's prepare the dates...
$now = (new \DateTime())->setTime(0, 0);
$date = Date::getDateTime($value);
// ...and make comparison with "day" as unit
if ($date instanceof \DateTime) {
return Date::getDateDifference($now, $date, Date::DATE_DIFFERENCE_UNIT_DAYS);
}
return null;
} | php | {
"resource": ""
} |
q10234 | BaseThanTodayValidator.isValid | train | private function isValid(Constraint $constraint, int $difference): bool
{
/*
* It's a earlier than today date?
* Nothing to do
*/
if ($constraint instanceof EarlierThanToday && $difference < 0) {
return true;
}
/*
* It's a earlier than or equal today date?
* Nothing to do
*/
if ($constraint instanceof EarlierThanOrEqualToday && $difference <= 0) {
return true;
}
/*
* It's a later than today date?
* Nothing to do
*/
if ($constraint instanceof LaterThanToday && $difference > 0) {
return true;
}
/*
* It's a later than or equal today date?
* Nothing to do
*/
if ($constraint instanceof LaterThanOrEqualToday && $difference >= 0) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q10235 | ArraySupport.exists | train | public static function exists($array, $key)
{
$key = static::normalizeKey($key);
if ($key === null || $key === '' || static::isEmpty($array))
{
return false;
}
$keys = explode('.', $key);
$currentElement = $array;
foreach ($keys as $currentKey)
{
if (!is_array($currentElement) || !array_key_exists($currentKey, $currentElement))
{
return false;
}
$currentElement = $currentElement[(string) $currentKey];
}
return true;
} | php | {
"resource": ""
} |
q10236 | ArraySupport.get | train | public static function get($array, $key, $default = null)
{
$key = static::normalizeKey($key);
if ($key === null || $key === '')
{
return $array;
}
$keys = explode('.', $key);
$currentElement = $array;
foreach ($keys as $currentKey)
{
if (!is_array($currentElement) || !array_key_exists($currentKey, $currentElement))
{
return $default;
}
$currentElement = $currentElement[(string) $currentKey];
}
return $currentElement;
} | php | {
"resource": ""
} |
q10237 | ArraySupport.set | train | public static function set(&$array, $key, $value)
{
$key = static::normalizeKey($key);
if ($key === null || $key === '')
{
return ($array = $value);
}
$keys = explode('.', $key);
$last = array_pop($keys);
$currentElement =& $array;
foreach ($keys as $currentKey)
{
if (!array_key_exists($currentKey, $currentElement) || !is_array($currentElement[$currentKey]))
{
$currentElement[$currentKey] = [];
}
$currentElement =& $currentElement[$currentKey];
}
$currentElement[$last] = $value;
return $array;
} | php | {
"resource": ""
} |
q10238 | ArraySupport.expand | train | public static function expand($array)
{
$multiArray = [];
foreach ($array as $key=>&$value)
{
$keys = explode('.', $key);
$lastKey = array_pop($keys);
$currentPointer = &$multiArray;
foreach ($keys as $currentKey)
{
if (!isset($currentPointer[$currentKey]))
{
$currentPointer[$currentKey] = [];
}
$currentPointer = &$currentPointer[$currentKey];
}
$currentPointer[$lastKey] = $value;
}
return $multiArray;
} | php | {
"resource": ""
} |
q10239 | ArraySupport.merge | train | public static function merge($arrays)
{
$merged = [];
foreach ($arrays as $array)
{
$merged = array_merge($merged, static::flatten($array));
}
return static::expand($merged);
} | php | {
"resource": ""
} |
q10240 | ArraySupport.flattenRecursive | train | protected static function flattenRecursive(&$recursion, $prefix)
{
$values = [];
foreach ($recursion as $key=>&$value)
{
if (is_array($value) && !empty($value))
{
$values = array_merge($values, static::flattenRecursive($value, $prefix . $key . '.'));
}
else
{
$values[$prefix . $key] = $value;
}
}
return $values;
} | php | {
"resource": ""
} |
q10241 | AbstractFinder.registerFindables | train | public function registerFindables(ConfigInterface $config)
{
$findables = (array) $config->getKey($this->getFindablesConfigKey());
foreach ($findables as $findableKey => $findableObject) {
$this->findables->set($findableKey, $findableObject);
}
} | php | {
"resource": ""
} |
q10242 | AbstractFinder.initializeNullObject | train | protected function initializeNullObject($arguments = null)
{
$this->nullObject = $this->maybeInstantiateFindable($this->nullObject, $arguments);
} | php | {
"resource": ""
} |
q10243 | AbstractFinder.initializeFindables | train | protected function initializeFindables($arguments = null): Findables
{
return $this->findables->map(function ($findable) use ($arguments) {
return $this->initializeFindable($findable, $arguments);
});
} | php | {
"resource": ""
} |
q10244 | AbstractFinder.maybeInstantiateFindable | train | protected function maybeInstantiateFindable($findable, $arguments = null): Findable
{
if (is_string($findable)) {
$findable = $this->instantiateFindableFromString($findable, $arguments);
}
if (is_callable($findable)) {
$findable = $this->instantiateFindableFromCallable($findable, $arguments);
}
if (! $findable instanceof Findable) {
throw new FailedToInstantiateFindable(
sprintf(
_('Could not instantiate Findable "%s".'),
serialize($findable)
)
);
}
return $findable;
} | php | {
"resource": ""
} |
q10245 | SystemService.ping | train | public function ping($params = [], $optParams = [])
{
return $this->sendRequest([], [
'restAction' => 'view',
'restId' => 'ping',
'getParams' => $optParams,
], function ($response) {
return isset($response->data) ? new Ping($response->data) : $response;
});
} | php | {
"resource": ""
} |
q10246 | Utf8Encoding.encodeUtf8 | train | public function encodeUtf8($data)
{
if ($data === null || $data === '') {
return $data;
}
if (is_array($data)) {
foreach ($data as $key => $value) {
$data[$key] = $this->encodeUtf8($value);
}
return $data;
} else {
if (!mb_check_encoding($data, 'UTF-8')) {
return mb_convert_encoding($data, 'UTF-8');
}
return $data;
}
} | php | {
"resource": ""
} |
q10247 | Timestamp.getDateTimeFormatString | train | public function getDateTimeFormatString()
{
$format = $this->getDateTimeType() . 'Format';
$page = $this->getObjPage();
if ($page && $page->$format) {
return $page->$format;
}
return Config::get($format);
} | php | {
"resource": ""
} |
q10248 | Category.boot | train | public static function boot()
{
parent::boot();
// Delete hierarchies first.
static::deleting(function($model)
{
$model->children()->detach();
$model->parents()->detach();
});
} | php | {
"resource": ""
} |
q10249 | Category.makeChildOf | train | public function makeChildOf(CategoryInterface $category)
{
$this->save();
$this->parents()->sync(array($category->getKey()));
return $this;
} | php | {
"resource": ""
} |
q10250 | Category.deleteWithChildren | train | public function deleteWithChildren()
{
$ids = array();
$children = $this->getChildren()->toArray();
array_walk_recursive($children, function($i, $k) use (&$ids) { if ($k == 'id') $ids[] = $i; });
foreach ($ids as $id)
{
$this->destroy($id);
}
} | php | {
"resource": ""
} |
q10251 | ApplicationInspectorListener.collectInspectionsOnApplicationFinish | train | public function collectInspectionsOnApplicationFinish(EventInterface $event)
{
$inspection = $this->inspector->inspect($event);
$uuid = $this->uuidGenerator->generateUUID();
$this->inspectionRepository->add($uuid, $inspection);
$event->setParam(self::PARAM_INSPECTION, $inspection);
$event->setParam(self::PARAM_INSPECTION_ID, $uuid);
return $uuid;
} | php | {
"resource": ""
} |
q10252 | Active.route | train | public function route($routes, $class = null, $fallback = null)
{
return $this->getCssClass(
$this->isRoute($routes), $class, $fallback
);
} | php | {
"resource": ""
} |
q10253 | Active.path | train | public function path($routes, $class = null, $fallback = null)
{
return $this->getCssClass(
$this->isPath($routes), $class, $fallback
);
} | php | {
"resource": ""
} |
q10254 | Active.is | train | protected function is($object, $routes)
{
list($routes, $ignored) = $this->parseRoutes(Arr::wrap($routes));
return $this->isIgnored($ignored)
? false
: call_user_func_array([$object, 'is'], $routes);
} | php | {
"resource": ""
} |
q10255 | Active.parseRoutes | train | protected function parseRoutes(array $allRoutes)
{
return Collection::make($allRoutes)
->partition(function ($route) {
return ! Str::startsWith($route, ['not:']);
})
->transform(function (Collection $routes, $index) {
return $index === 0
? $routes
: $routes->transform(function ($route) { return substr($route, 4); });
})
->toArray();
} | php | {
"resource": ""
} |
q10256 | BaseController.redirectToReferer | train | protected function redirectToReferer(): RedirectResponse
{
$url = $this->requestService->fetchRefererUrl();
// Oops, url of referer is unknown
if ('' === $url) {
throw CannotRedirectToEmptyRefererUrlException::create();
}
return $this->redirect($url);
} | php | {
"resource": ""
} |
q10257 | Int.read | train | public function read(AbstractStream $stream)
{
return $stream->getBuffer()->readInt($this->getSize(), $this->getSigned(), $this->getEndian());
} | php | {
"resource": ""
} |
q10258 | SetTypeValidator.validate | train | public function validate($value, Constraint $constraint)
{
/** @var SetType $constraint */
if (!$constraint->class) {
throw new ConstraintDefinitionException('Target is not specified');
}
/** @var string $class class name of inheriting \Okapon\DoctrineSetTypeBundle\DBAL\Types\AbstractSetType */
$class = $constraint->class;
if (!class_exists($class)) {
throw new TargetClassNotExistException('Target class not exist.');
}
$constraint->choices = $class::getValues();
$constraint->multiple =true;
parent::validate($value, $constraint);
} | php | {
"resource": ""
} |
q10259 | ConfigurationFileType.getTypeFromFileName | train | public static function getTypeFromFileName(string $fileName): string
{
$fileExtension = strtolower(Miscellaneous::getFileExtension($fileName));
// Oops, incorrect type/extension of configuration file
if (false === (new static())->isCorrectType($fileExtension)) {
throw UnknownConfigurationFileTypeException::createException($fileExtension);
}
return $fileExtension;
} | php | {
"resource": ""
} |
q10260 | MessageEncryptor.encrypt | train | public function encrypt($message, $userPublicKey, $userAuthToken, $regenerateKeys = false)
{
if (self::MAX_MESSAGE_LENGTH < strlen($message)) {
throw new \RuntimeException(sprintf(
'Length of message must not be greater than %d octets.', self::MAX_MESSAGE_LENGTH
));
}
// pad the message
$message = self::padMessage($message);
if ($regenerateKeys) {
$this->initialize();
}
$userPublicKey = Base64Url::decode($userPublicKey);
$userAuthToken = Base64Url::decode($userAuthToken);
// get the shared secret
$sharedSecret = $this->getSharedSecret($userPublicKey);
$ikm = !empty($userAuthToken) ?
self::hkdf($userAuthToken, $sharedSecret, 'Content-Encoding: auth'.chr(0), 32) :
$sharedSecret;
$context = $this->createContext($userPublicKey);
// derive the Content Encryption Key
$contentEncryptionKey = self::hkdf($this->salt, $ikm, self::createInfo('aesgcm', $context), 16);
// derive the nonce
$nonce = self::hkdf($this->salt, $ikm, self::createInfo('nonce', $context), 12);
if (version_compare(PHP_VERSION, '7.1') >= 0) {
$encryptedText = openssl_encrypt($message, 'aes-128-gcm', $contentEncryptionKey, OPENSSL_RAW_DATA, $nonce, $tag);
} else {
list($encryptedText, $tag) = \AESGCM\AESGCM::encrypt($contentEncryptionKey, $nonce, $message, '');
}
return $encryptedText.$tag;
} | php | {
"resource": ""
} |
q10261 | MessageEncryptor.initialize | train | private function initialize()
{
// generate key pair.
$this->privateKey = $this->generator->createPrivateKey();
$this->publicKey = $this->privateKey->getPublicKey();
// generate salt
$this->salt = openssl_random_pseudo_bytes(16);
$this->publicKeyContent = hex2bin($this->serializer->serialize($this->publicKey->getPoint()));
} | php | {
"resource": ""
} |
q10262 | MessageEncryptor.getSharedSecret | train | private function getSharedSecret($userPublicKey)
{
$userPublicKeyPoint = $this->serializer->unserialize($this->curve, bin2hex($userPublicKey));
$userPublicKeyObject = $this->generator->getPublicKeyFrom(
$userPublicKeyPoint->getX(),
$userPublicKeyPoint->getY(),
$this->generator->getOrder()
);
$point = $userPublicKeyObject->getPoint()->mul($this->privateKey->getSecret())->getX();
return hex2bin($this->adapter->decHex((string) $point));
} | php | {
"resource": ""
} |
q10263 | ErrorDeserializer.populateErrorData | train | protected function populateErrorData(\Throwable $e, array $data): \Throwable
{
static $cache = [];
static $props = [
'code',
'message',
'file',
'line'
];
$type = ($e instanceof \Error) ? \Error::class : \Exception::class;
if (!isset($cache[$type])) {
$cache[$type] = [];
foreach ($props as $k) {
$ref = new \ReflectionProperty($type, $k);
$ref->setAccessible(true);
$cache[$type][$k] = $ref;
}
}
foreach ($props as $k) {
if (isset($data[$k])) {
$cache[$type][$k]->setValue($e, $data[$k]);
}
}
return $e;
} | php | {
"resource": ""
} |
q10264 | InitAction.run | train | public function run()
{
$force = $this->controller->force;
$this->stdout("initialize ip database:\n", Console::FG_GREEN);
foreach ($this->ipv4->getQueries() as $name => $query) {
$providers = $query->getProviders();
if (empty($providers)) {
$this->download($query, $name, $force);
} else {
$this->division();
$this->generate($query, $name, $force);
}
}
} | php | {
"resource": ""
} |
q10265 | ToolbarInjectorListener.injectToolbarHtml | train | public function injectToolbarHtml(MvcEvent $event)
{
if (! $inspection = $event->getParam(ApplicationInspectorListener::PARAM_INSPECTION)) {
return;
}
$response = $event->getResponse();
if (! $response instanceof Response) {
return;
}
$headers = $response->getHeaders();
$contentType = $headers->get('Content-Type');
if ($contentType) {
if (!$contentType instanceof ContentType) {
return;
}
if (false === strpos(strtolower($contentType->getFieldValue()), 'html')) {
return;
}
}
$response->setContent(preg_replace(
'/<\/body>/i',
$this->renderer->render($this->inspectionRenderer->render($inspection)) . '</body>',
$response->getContent(),
1
));
} | php | {
"resource": ""
} |
q10266 | DateTime.modifiedDate | train | public function modifiedDate(WP_Post $post, string $format): string
{
Assert::stringNotEmpty($format);
$postDate = get_the_modified_date($format, $post);
$this->bailIfInvalidValue($postDate, $post);
return $postDate;
} | php | {
"resource": ""
} |
q10267 | DateTime.modifiedTime | train | public function modifiedTime(WP_Post $post, string $format): string
{
Assert::stringNotEmpty($format);
$postDate = get_the_modified_time($format, $post);
$this->bailIfInvalidValue($postDate, $post);
return $postDate;
} | php | {
"resource": ""
} |
q10268 | DateTime.date | train | public function date(WP_Post $post, string $format): string
{
Assert::stringNotEmpty($format);
$postDate = get_the_date($format, $post);
$this->bailIfInvalidValue($postDate, $post);
return $postDate;
} | php | {
"resource": ""
} |
q10269 | DateTime.time | train | public function time(WP_Post $post, string $format): string
{
Assert::stringNotEmpty($format);
$postTime = get_the_time($format, $post);
$this->bailIfInvalidValue($postTime, $post);
return $postTime;
} | php | {
"resource": ""
} |
q10270 | DateTime.dateTime | train | public function dateTime(WP_Post $post, string $format, string $separator): string
{
// phpcs:enable
Assert::stringNotEmpty($format);
Assert::stringNotEmpty($separator);
$postDate = $this->date($post, $format);
$postTime = $this->time($post, $format);
return implode([$postDate, $postTime], $separator);
} | php | {
"resource": ""
} |
q10271 | MethodCall.createCallback | train | protected function createCallback(string $method): \Closure
{
return \Closure::bind(static function (...$args) use ($method) {
return self::$method(...$args);
}, null, $this->type);
} | php | {
"resource": ""
} |
q10272 | PasswordResetRepository.exists | train | public function exists($token)
{
$reset = PasswordReset::where('token', $token)->first();
return $reset and ! $reset->isExpired();
} | php | {
"resource": ""
} |
q10273 | CkToolsHelper.countries | train | public function countries(array $countryCodes = null): array
{
if (!Configure::read('countries')) {
Configure::load('CkTools.countries');
}
if ($countryCodes) {
$countries = Configure::read('countries');
$subset = [];
foreach ($countryCodes as $countryCode) {
$subset[$countryCode] = $countries[$countryCode] ?? $countryCode;
}
return $subset;
}
return Configure::read('countries');
} | php | {
"resource": ""
} |
q10274 | CkToolsHelper.country | train | public function country(string $country): string
{
if (!Configure::read('countries')) {
Configure::load('CkTools.countries');
}
$countries = Configure::read('countries');
return $countries[$country] ?? $country;
} | php | {
"resource": ""
} |
q10275 | CkToolsHelper.datepickerInput | train | public function datepickerInput(string $field, array $options = []): string
{
$options = Hash::merge([
'type' => 'date',
], $options);
return $this->Form->input($field, $options);
} | php | {
"resource": ""
} |
q10276 | CkToolsHelper.editButton | train | public function editButton(EntityInterface $entity, array $options = []): string
{
$options = Hash::merge([
'url' => null,
'title' => __d('ck_tools', 'edit'),
'icon' => 'fa fa-pencil',
'escape' => false,
'class' => 'btn btn-default btn-xs btn-edit',
], $options);
$url = $options['url'];
$title = $options['title'];
$icon = $options['icon'];
unset($options['url'], $options['title'], $options['icon']);
if (!$url) {
// phpcs:ignore
list($plugin, $controller) = pluginSplit($entity->source());
$url = [
'plugin' => $this->_View->request->plugin,
'controller' => $controller,
'action' => 'edit',
$entity->id,
];
$url = $this->augmentUrlByBackParam($url);
}
if ($icon) {
$title = '<i class="' . $icon . '"></i> ' . '<span class="button-text">' . $title . '</span>';
$options['escape'] = false;
}
return $this->Html->link($title, $url, $options);
} | php | {
"resource": ""
} |
q10277 | CkToolsHelper.addButton | train | public function addButton(string $title = null, array $options = []): string
{
if (!$title) {
$title = __d('ck_tools', 'add');
}
$options = Hash::merge([
'url' => null,
'icon' => 'fa fa-plus',
'class' => 'btn btn-default btn-xs btn-add',
], $options);
$url = $options['url'];
if (!$url) {
$url = ['action' => 'add'];
$url = $this->augmentUrlByBackParam($url);
}
$icon = $options['icon'];
unset($options['url'], $options['icon']);
if ($icon) {
$title = '<i class="' . $icon . '"></i> ' . '<span class="button-text">' . $title . '</span>';
$options['escape'] = false;
}
return $this->Html->link($title, $url, $options);
} | php | {
"resource": ""
} |
q10278 | CkToolsHelper.formButtons | train | public function formButtons(array $options = []): string
{
$url = ['action' => 'index'];
$options = Hash::merge([
'useReferer' => false,
'horizontalLine' => true,
'cancelButton' => true,
'saveButtonTitle' => __d('ck_tools', 'save'),
'cancelButtonTitle' => __d('ck_tools', 'cancel'),
], $options);
if (!empty($options['useReferer']) && $this->request->referer() !== '/') {
$url = $this->request->referer();
}
$formButtons = '<div class="submit-group">';
if ($options['horizontalLine']) {
$formButtons .= '<hr>';
}
$formButtons .= $this->Form->button($options['saveButtonTitle'], ['class' => 'btn-success']);
if ($options['cancelButton']) {
$formButtons .= $this->backButton($options['cancelButtonTitle'], $url, ['class' => 'btn btn-default cancel-button', 'icon' => null]);
}
$formButtons .= '</div>';
return $formButtons;
} | php | {
"resource": ""
} |
q10279 | CkToolsHelper.backButton | train | public function backButton(string $title = null, $url = null, array $options = []): string
{
$options = Hash::merge([
'icon' => 'arrow-left',
'escape' => false,
], $options);
if (!$title) {
$title = '<span class="button-text">' . __d('ck_tools', 'Back') . '</span>';
}
$here = $this->getRequestedAction();
if ($this->request->getSession()->check('back_action.' . $here)) {
$url = $this->request->getSession()->read('back_action.' . $here);
}
if (empty($url)) {
$url = [
'action' => 'index',
];
}
return $this->button($title, $url, $options);
} | php | {
"resource": ""
} |
q10280 | CkToolsHelper.nestedList | train | public function nestedList(array $data, string $content, int $level = 0, array $isActiveCallback = null): string
{
$tabs = "\n" . str_repeat(' ', $level * 2);
$liTabs = $tabs . ' ';
$output = $tabs . '<ul>';
foreach ($data as $record) {
$liClasses = [];
$liContent = $content;
if ($isActiveCallback !== null) {
$additionalArguments = !empty($isActiveCallback['arguments']) ? $isActiveCallback['arguments'] : [];
$isActive = call_user_func_array($isActiveCallback['callback'], [&$record, $additionalArguments]);
if ($isActive) {
$liClasses[] = 'active';
}
}
// find the model variables
preg_match_all("/\{\{([a-z0-9\._]+)\}\}/i", $liContent, $matches);
if (!empty($matches)) {
$variables = array_unique($matches[1]);
foreach ($variables as $modelField) {
$liContent = str_replace('{{' . $modelField . '}}', $record[$modelField], $liContent);
}
}
if (!empty($record['children'])) {
$liClasses[] = 'has-children';
}
$output .= $liTabs . '<li class="' . implode(' ', $liClasses) . '">' . $liContent;
if (isset($record['children'][0])) {
$output .= $this->nestedList($record['children'], $content, $level + 1, $isActiveCallback);
$output .= $liTabs . '</li>';
} else {
$output .= '</li>';
}
}
$output .= $tabs . '</ul>';
return $output;
} | php | {
"resource": ""
} |
q10281 | CkToolsHelper.historyBackButton | train | public function historyBackButton(array $options = []): string
{
//FIXME: Add detection for IE8 & IE9 and create fallback
$options = Hash::merge([
'icon' => 'fa fa-arrow-left',
'class' => 'btn btn-default btn-xs',
], $options);
$div = '<div class="' . $options['class'] . '" onclick="history.back()">';
$i = '<i class="' . $options['icon'] . '"></i>';
return $div . $i . ' ' . __d('ck_tools', 'history_back_button') . '</div>';
} | php | {
"resource": ""
} |
q10282 | CkToolsHelper.displayStructuredData | train | public function displayStructuredData(array $data, array $options = []): string
{
$options = Hash::merge([
'expanded' => true,
'expandLinkText' => __d('ck_tools', 'utility.toggle_content'),
'type' => 'array',
], $options);
switch ($options['type']) {
case 'table':
$list = $this->arrayToTable($data, $options);
break;
case 'array':
default:
$list = $this->arrayToUnorderedList($data);
break;
}
if (!$options['expanded']) {
$id = 'dsd-' . uniqid();
$out = $this->Html->link($options['expandLinkText'], 'javascript:', [
'type' => 'button',
'data-toggle' => 'collapse',
'aria-expanded' => 'false',
'aria-controls' => $id,
'data-target' => '#' . $id,
]);
$out .= '<div class="collapse" id="' . $id . '">' . $list . '</div>';
} else {
$out = $list;
}
return $out;
} | php | {
"resource": ""
} |
q10283 | Web.createMessageBody | train | protected function createMessageBody(MessageInterface $message)
{
$body = [];
if ($message instanceof BaseOptionedModel) {
$body = $message->getOptions();
}
$body['message'] = $message->getText();
return json_encode($body);
} | php | {
"resource": ""
} |
q10284 | Web.createSignatureToken | train | protected function createSignatureToken($origin, \DateTime $expiration = null)
{
if (is_null($expiration)) {
$expiration = new \DateTime('+ 1 hours');
}
$signer = new ES256();
$privateKey = new Key('file://'.$this->getParameter('privateKey'));
$builder = new Builder();
$token = $builder
->setAudience($origin)
->setExpiration($expiration->getTimestamp())
->sign($signer, $privateKey)
->getToken();
return $token;
} | php | {
"resource": ""
} |
q10285 | JsonEncoding.encodeJson | train | public function encodeJson($data): string
{
if ($data instanceof JsonSerializable) {
$data = $data->jsonSerialize();
}
$result = json_encode($this->utf8Encoding->encodeUtf8($data), 512, JSON_THROW_ON_ERROR);
if ($result === false) {
throw new JsonException('Json encoding failed');
}
return $result;
} | php | {
"resource": ""
} |
q10286 | InternationalizationShell.getOptionParser | train | public function getOptionParser(): ConsoleOptionParser
{
$parser = parent::getOptionParser();
$updateFromCatalogParser = parent::getOptionParser();
$updateFromCatalogParser->addOption('domain', [
'default' => 'default',
'help' => 'The domain to use',
]);
$updateFromCatalogParser->addOption('overwrite', [
'default' => false,
'help' => 'If set, there will be no interactive question whether to continue.',
'boolean' => true,
]);
$updateFromCatalogParser->addOption('strip-references', [
'boolean' => true,
'help' => 'Whether to remove file usage references from resulting po and mo files.',
]);
return $parser
->setDescription([
'CkTools Shell',
'',
'Utilities',
])
->addSubcommand('updateFromCatalog', [
'help' => 'Updates the PO file from the given catalog',
'parser' => $updateFromCatalogParser,
]);
} | php | {
"resource": ""
} |
q10287 | InternationalizationShell.updateFromCatalog | train | public function updateFromCatalog(): void
{
$domain = $this->params['domain'];
$localePath = ROOT . '/src/Locale/';
$catalogFile = $localePath . $domain . '.pot';
if (!file_exists($catalogFile)) {
$this->abort(sprintf('Catalog File %s not found.', $catalogFile));
}
$poFiles = [];
$folder = new Folder($localePath);
$tree = $folder->tree();
foreach ($tree[1] as $file) {
$basename = basename($file);
if ($domain . '.po' === $basename) {
$poFiles[] = $file;
}
}
if (empty($poFiles)) {
$this->abort(sprintf('I could not find any matching po files in the given locale path (%s) for the domain (%s)', $localePath, $domain));
}
if (!$this->params['overwrite']) {
$this->out('I will update the following .po files and their corresponding .mo file with the keys from catalog: ' . $catalogFile);
foreach ($poFiles as $poFile) {
$this->out(' - ' . $poFile);
}
$response = $this->in('Would you like to continue?', ['y', 'n'], 'n');
if ($response !== 'y') {
$this->abort('Aborted');
}
}
foreach ($poFiles as $poFile) {
$catalogEntries = Translations::fromPoFile($catalogFile);
$moFile = str_replace('.po', '.mo', $poFile);
$translationEntries = Translations::fromPoFile($poFile);
$newTranslationEntries = $catalogEntries->mergeWith($translationEntries, Merge::REFERENCES_THEIRS);
$newTranslationEntries->deleteHeaders();
foreach ($translationEntries->getHeaders() as $key => $value) {
$newTranslationEntries->setHeader($key, $value);
}
if ($this->params['strip-references']) {
foreach ($newTranslationEntries as $translation) {
$translation->deleteReferences();
}
}
$newTranslationEntries->toPoFile($poFile);
$newTranslationEntries->toMoFile($moFile);
$this->out('Updated ' . $poFile);
$this->out('Updated ' . $moFile);
}
} | php | {
"resource": ""
} |
q10288 | Handler.register | train | public function register(callable $callback): void
{
$hint = $this->handlerHint($callback);
$this->handlers[$hint] = $callback;
} | php | {
"resource": ""
} |
q10289 | Handler.getHttpStatusCode | train | protected function getHttpStatusCode(Exception $exception): int
{
if ($exception instanceof ApiException) {
return $exception->apiMessage->getHttpStatusCode();
}
if ($exception instanceof HttpExceptionInterface && method_exists($exception, 'getStatusCode')) {
return $exception->getStatusCode();
}
return 500;
} | php | {
"resource": ""
} |
q10290 | Handler.handlerHint | train | protected function handlerHint(callable $callback): string
{
$reflection = new ReflectionFunction($callback);
$exception = $reflection->getParameters()[0];
return $exception->getClass()->getName();
} | php | {
"resource": ""
} |
q10291 | TokenManager.createNewTokens | train | protected function createNewTokens()
{
$logger = $this->getLogger();
$logger->debug('Starting request to create fresh access & refresh tokens');
$body = [
'client_id' => 'anonymous',
'grant_type' => 'password',
'response_type' => 'token',
'scope' => 'openid',
'username' => $this->credentials->getUsername(),
'password' => $this->credentials->getPassword(),
];
$response = $this->sendPostRequest($body);
$logger->debug('Successfully retrieved new access & refresh tokens', $response);
return [
'accessToken' => new Token(
$response['access_token'],
$this->tokenExtractor->extract($response['access_token'])
),
'refreshToken' => new Token(
$response['refresh_token'],
$this->tokenExtractor->extract($response['refresh_token'])
),
];
} | php | {
"resource": ""
} |
q10292 | TokenManager.createAccessTokenFromRefreshToken | train | protected function createAccessTokenFromRefreshToken(Token $refreshToken)
{
$logger = $this->getLogger();
$logger->debug('Starting request to create fresh access token from refresh token');
$body = [
'client_id' => 'anonymous',
'grant_type' => 'refresh_token',
'refresh_token' => $refreshToken->getTokenString(),
];
$response = $this->sendPostRequest($body);
$logger->debug('Successfully retrieved new access token', $response);
return new Token(
$response['access_token'],
$this->tokenExtractor->extract($response['access_token'])
);
} | php | {
"resource": ""
} |
q10293 | TokenManager.logTokenData | train | protected function logTokenData()
{
$this->getLogger()->debug('Token information', [
'accessTokenExists' => isset($this->accessToken),
'accessTokenExpiration' => isset($this->accessToken) ? $this->accessToken->getTokenData()['exp'] : null,
'accessTokenHasExpired' => isset($this->accessToken) ? $this->accessToken->expired() : null,
'refreshTokenExists' => isset($this->refreshToken),
'refreshTokenExpiration' => isset($this->refreshToken) ? $this->refreshToken->getTokenData()['exp'] : null,
'refreshTokenHasExpired' => isset($this->refreshToken) ? $this->refreshToken->expired() : null,
'localTime' => time(),
]);
} | php | {
"resource": ""
} |
q10294 | TokenManager.getToken | train | public function getToken()
{
$logger = $this->getLogger();
$this->logTokenData();
$cacheKey = sha1(sprintf('%s.%s', __METHOD__, json_encode(func_get_args())));
$cacheItem = $this->cacheItemPool->getItem($cacheKey);
if (!$this->accessToken && $cacheItem->isHit()) {
$this->accessToken = $cacheItem->get();
}
// Access token has expired, but expiration token has not expired.
// Issue ourselves a new access token for the same video manager.
if (!is_null($this->accessToken)
&& $this->accessToken->expired()
&& !is_null($this->refreshToken)
&& !$this->refreshToken->expired()) {
$logger->info('Access token has expired - getting new one for same video manager with refresh token');
$this->accessToken = $this->createAccessTokenFromRefreshToken($this->refreshToken);
} elseif (is_null($this->accessToken)
|| (!is_null($this->refreshToken) && $this->refreshToken->expired())) {
// Either we have no token, or the refresh token has expired
// so we will need to generate completely new tokens
$logger->info('No access token, or refresh token has expired - generate completely new ones');
$tokenData = $this->createNewTokens();
$this->accessToken = $tokenData['accessToken'];
$this->refreshToken = $tokenData['refreshToken'];
}
$cacheItem->set($this->accessToken);
$cacheItem->expiresAt((new \DateTime())
->setTimestamp($this->accessToken->getTokenData()['exp'])
->sub(new \DateInterval('PT30S'))
);
$this->cacheItemPool->save($cacheItem);
return $this->accessToken->getTokenString();
} | php | {
"resource": ""
} |
q10295 | TokenManager.sendPostRequest | train | private function sendPostRequest(array $body)
{
$requestBodyKey = version_compare(ClientInterface::VERSION, '6.0', '>=') ? 'form_params' : 'body';
$response = $this->httpClient->post('', [
$requestBodyKey => $body,
]);
return \json_decode($response->getBody(), true);
} | php | {
"resource": ""
} |
q10296 | Resolver.awaitFirstResult | train | protected function awaitFirstResult(Context $context, array $tasks, CancellationHandler $cancel, array & $errors): \Generator
{
if (empty($tasks)) {
return;
}
try {
$result = yield $context->first($tasks, $cancel, $errors);
} catch (MultiReasonException $e) {
$result = null;
}
return $result;
} | php | {
"resource": ""
} |
q10297 | Resolver.query | train | protected function query(Context $context, string $server, string $host, int $type): \Generator
{
$response = yield $this->getUdpConnector($server)->send($context, $this->createRequest($host, $type));
if ($response->isTruncated()) {
$response = yield $this->getTcpConnector($server)->send($context, $this->createRequest($host, $type));
}
$resolved = [];
$ttl = \PHP_INT_MAX;
foreach ($response->getAnswers() as $record) {
if ($record['type'] === $type) {
$resolved[] = new Address($record['data']);
$ttl = \min($ttl, $record['ttl']);
}
}
if (empty($resolved)) {
throw new \RuntimeException(\sprintf('Unable to resolve host "%s" into an IP using DNS server %s', $host, $server));
}
return [
'ttl' => \max(1, \min(300, $ttl)),
'ips' => $resolved
];
} | php | {
"resource": ""
} |
q10298 | Resolver.getUdpConnector | train | protected function getUdpConnector(string $server): UdpConnector
{
if (empty($this->udp[$server])) {
$this->udp[$server] = new UdpConnector($server, $this->timeout);
}
return $this->udp[$server];
} | php | {
"resource": ""
} |
q10299 | Resolver.getTcpConnector | train | protected function getTcpConnector(string $server): TcpConnector
{
if (empty($this->tcp[$server])) {
$this->tcp[$server] = new TcpConnector($server, $this->timeout);
}
return $this->tcp[$server];
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.