_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q245700 | EventsManager.fireQueue | validation | private function fireQueue(SplPriorityQueue $queue, AbstractUserEvent $event)
{
$eventHappening = $event::getHappening();
$iterator = clone $queue;
$iterator->top();
$arguments = null;
$status = null;
while ($iterator->valid()) {
$handler = $iterator->current();
$iterator->next();
if (is_object($handler)) {
if ($handler instanceof \Closure) {
$arguments = $arguments ?: [$event];
$status = call_user_func_array($handler, $arguments);
} else {
if (method_exists($handler, $eventHappening)) {
$status = $handler->{$eventHappening}($event);
}
}
}
}
return $status;
} | php | {
"resource": ""
} |
q245701 | ForkingWorker.fork | validation | private function fork(&$socket): int
{
$pair = [];
$domain = (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ? AF_INET : AF_UNIX);
if (\socket_create_pair($domain, SOCK_STREAM, 0, $pair) === false) {
$error = socket_strerror(socket_last_error($pair[0] ?? null));
$this->logger->error('{type}: unable to create socket pair; ' . $error, $this->logContext);
exit(0);
}
// Fork child worker.
$pid = pcntl_fork();
if ($pid === -1) {
throw new RuntimeException('Unable to fork child worker.');
}
if ($pid !== 0) {
// MASTER
$this->childProcesses++;
$socket = $pair[0];
socket_close($pair[1]);
// wait up to 10ms to receive data
socket_set_option(
$socket,
SOL_SOCKET,
SO_RCVTIMEO,
['sec' => 0, 'usec' => 10000]
);
return $pid;
}
$socket = $pair[1];
socket_close($pair[0]);
register_shutdown_function($this->handleChildErrors($socket));
return $pid;
} | php | {
"resource": ""
} |
q245702 | ForkingWorker.handleChildErrors | validation | private function handleChildErrors(&$socket): Closure
{
// This storage is freed on error (case of allowed memory exhausted).
$reserved = str_repeat('*', 32 * 1024);
return function () use (&$reserved, &$socket): void {
unset($reserved);
$error = error_get_last();
if ($error === null) {
unset($reserved);
return;
}
$handler = new ErrorFormatter();
if ($handler->constant($error['type']) === null) {
$this->logger->warning(
'{type}: Unable to recognize error type. Skip sending error to master: {message}',
$this->logContext + ['message' => $error['message']]
);
return;
}
if (is_resource($socket) == false) {
$this->logger->warning(
'{type}: supplied resource is not a valid socket resource. Skip sending error to master: {message}',
$this->logContext + ['message' => $error['message']]
);
return;
}
$this->logger->debug('{type}: sending error to master', $this->logContext);
$data = serialize($error);
do {
$len = socket_write($socket, $data);
if ($len === false || $len === 0) {
break;
}
$data = substr($data, $len);
} while (is_numeric($len) && $len > 0 && is_resource($socket));
};
} | php | {
"resource": ""
} |
q245703 | ForkingWorker.readErrorFromSocket | validation | private function readErrorFromSocket($socket): ?string
{
$error = '';
while (!empty($res = socket_read($socket, 8192))) {
$error .= $res;
}
$error = unserialize($error);
if (is_array($error)) {
$handler = new ErrorFormatter();
return sprintf(
'%s: %s in %s on line %d',
$handler->constant($error['type']) ?: 'Unknown',
$error['message'],
$error['file'],
$error['line']
);
}
return null;
} | php | {
"resource": ""
} |
q245704 | ForkingWorker.handleProcessExitStatus | validation | private function handleProcessExitStatus(int $pid, int $childType, int $exitStatus)
{
switch ($childType) {
case self::PROCESS_TYPE_JOB:
$childType = 'Child';
break;
default:
$childType = 'Watchdog';
}
if ($exitStatus === 0) {
$this->logger->debug("{type}: {$childType} process exited successfully", $this->logContext);
return false;
}
$error = $this->readErrorFromSocket($this->sockets[$pid]);
$jobFailedMessage = $error ?: "{$childType} process failed with status: {$exitStatus}";
$this->logger->error("{type}: fatal error in {$childType} process: {$jobFailedMessage}", $this->logContext);
return $jobFailedMessage;
} | php | {
"resource": ""
} |
q245705 | ForkingWorker.childPerform | validation | public function childPerform(BaseJob $job): void
{
$loggerContext = ['job' => $job->jid, 'type' => $this->who];
try {
if ($this->jobPerformHandler) {
if ($this->jobPerformHandler instanceof EventsManagerAwareInterface) {
$this->jobPerformHandler->setEventsManager($this->client->getEventsManager());
}
if (method_exists($this->jobPerformHandler, 'setUp')) {
$this->jobPerformHandler->setUp();
}
$this->getEventsManager()->fire(new JobEvent\BeforePerform($this->jobPerformHandler, $job));
$this->jobPerformHandler->perform($job);
$this->getEventsManager()->fire(new JobEvent\AfterPerform($this->jobPerformHandler, $job));
if (method_exists($this->jobPerformHandler, 'tearDown')) {
$this->jobPerformHandler->tearDown();
}
} else {
$job->perform();
}
$this->logger->notice('{type}: job {job} has finished', $loggerContext);
} catch (\Throwable $e) {
$loggerContext['stack'] = $e->getMessage();
$this->logger->critical('{type}: job {job} has failed {stack}', $loggerContext);
$job->fail(
'system:fatal',
sprintf('%s: %s in %s on line %d', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine())
);
}
} | php | {
"resource": ""
} |
q245706 | LuaScript.run | validation | public function run(string $command, array $args)
{
if (empty($this->sha)) {
$this->reload();
}
$arguments = $this->normalizeCommandArgs($command, $args);
try {
return call_user_func_array([$this->redis, 'evalsha'], $arguments);
} catch (\Exception $exception) {
throw ExceptionFactory::fromErrorMessage($exception->getMessage());
}
} | php | {
"resource": ""
} |
q245707 | LuaScript.normalizeCommandArgs | validation | private function normalizeCommandArgs(string $command, array $args): array
{
$arguments = array_merge([$command, microtime(true)], $args);
array_unshift($arguments, 0);
array_unshift($arguments, $this->sha);
return $arguments;
} | php | {
"resource": ""
} |
q245708 | LuaScript.reload | validation | private function reload(): void
{
$this->sha = (string) @sha1_file($this->corePath);
if (empty($this->sha)) {
throw new RuntimeException(
'Unable to locate qless-core file at path: ' . $this->corePath
);
}
$res = $this->redis->script('exists', $this->sha);
if ($res[0] !== 1) {
$this->sha = $this->redis->script('load', file_get_contents($this->corePath));
}
} | php | {
"resource": ""
} |
q245709 | BaseJob.setPriority | validation | public function setPriority(int $priority): void
{
if ($this->client->call('priority', $this->jid, $priority)) {
parent::setPriority($priority);
}
} | php | {
"resource": ""
} |
q245710 | BaseJob.cancel | validation | public function cancel($dependents = false): array
{
if ($dependents && !empty($this->rawData['dependents'])) {
return call_user_func_array(
[$this->client, 'cancel'],
array_merge([$this->jid], $this->rawData['dependents'])
);
}
return $this->client->cancel($this->jid);
} | php | {
"resource": ""
} |
q245711 | BaseJob.complete | validation | public function complete(?string $nextq = null, int $delay = 0, array $depends = []): string
{
if ($this->completed || $this->failed) {
throw new JobAlreadyFinishedException();
}
$params = [
$this->jid,
$this->worker,
$this->queue,
json_encode($this->data, JSON_UNESCAPED_SLASHES) ?: '{}'
];
if ($nextq) {
$next = ['next', $nextq, 'delay', $delay, 'depends', json_encode($depends, JSON_UNESCAPED_SLASHES)];
$params = array_merge($params, $next);
}
$this->completed = true;
return call_user_func_array(
[$this->client, 'complete'],
$params
);
} | php | {
"resource": ""
} |
q245712 | BaseJob.requeue | validation | public function requeue(?string $queue = null, array $opts = []): string
{
$opts = array_merge(
[
'delay' => 0,
'data' => $this->data,
'priority' => $this->priority,
'retries' => $this->retries,
'tags' => $this->tags,
'depends' => $this->dependencies,
],
$opts
);
$queueName = $queue ?: $this->queue;
$data = json_encode($opts['data'], JSON_UNESCAPED_SLASHES) ?: '{}';
return $this->client
->requeue(
$this->worker,
$queueName,
$this->jid,
$this->klass,
$data,
$opts['delay'],
'priority',
$opts['priority'],
'tags',
json_encode($opts['tags'], JSON_UNESCAPED_SLASHES),
'retries',
$opts['retries'],
'depends',
json_encode($opts['depends'], JSON_UNESCAPED_SLASHES)
);
} | php | {
"resource": ""
} |
q245713 | BaseJob.retry | validation | public function retry($group, $message, $delay = 0)
{
return $this->client
->retry(
$this->jid,
$this->queue,
$this->worker,
$delay,
$group,
$message
);
} | php | {
"resource": ""
} |
q245714 | BaseJob.heartbeat | validation | public function heartbeat(array $data = []): float
{
try {
$this->expires = $this->client->heartbeat(
$this->jid,
$this->worker,
json_encode($data, JSON_UNESCAPED_SLASHES)
);
} catch (QlessException $e) {
throw new LostLockException($e->getMessage(), 'Heartbeat', $this->jid, $e->getCode(), $e);
}
return $this->expires;
} | php | {
"resource": ""
} |
q245715 | BaseJob.perform | validation | public function perform(): bool
{
try {
$instance = $this->getInstance();
if (method_exists($instance, 'setUp')) {
$instance->setUp();
}
$this->getEventsManager()->fire(new JobEvent\BeforePerform($this, $this));
$performMethod = $this->getPerformMethod();
$instance->$performMethod($this);
$this->getEventsManager()->fire(new JobEvent\AfterPerform($this, $this));
if (method_exists($instance, 'tearDown')) {
$instance->tearDown();
}
} catch (\Throwable $e) {
$this->fail(
'system:fatal',
sprintf('%s: %s in %s on line %d', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine())
);
return false;
}
return true;
} | php | {
"resource": ""
} |
q245716 | BaseJob.fail | validation | public function fail(string $group, string $message)
{
if ($this->completed || $this->failed) {
throw new JobAlreadyFinishedException();
}
$jsonData = json_encode($this->data, JSON_UNESCAPED_SLASHES) ?: '{}';
$this->getEventsManager()->fire(new JobEvent\OnFailure($this, $this, $group, $message));
$this->failed = true;
return $this->client->fail($this->jid, $this->worker, $group, $message, $jsonData);
} | php | {
"resource": ""
} |
q245717 | BaseJob.track | validation | public function track(): void
{
if ($this->client->call('track', 'track', $this->jid)) {
$this->tracked = true;
}
} | php | {
"resource": ""
} |
q245718 | BaseJob.untrack | validation | public function untrack(): void
{
if ($this->client->call('track', 'untrack', $this->jid)) {
$this->tracked = false;
}
} | php | {
"resource": ""
} |
q245719 | BaseJob.getInstance | validation | public function getInstance()
{
if ($this->instance === null) {
$this->instance = $this->jobFactory->create(
$this->klass,
$this->getPerformMethod()
);
}
return $this->instance;
} | php | {
"resource": ""
} |
q245720 | AbstractJob.tag | validation | public function tag(...$tags): void
{
$response = call_user_func_array(
[$this->client, 'call'],
array_merge(['tag', 'add', $this->jid], array_values(func_get_args()))
);
$this->setTags(json_decode($response, true));
} | php | {
"resource": ""
} |
q245721 | AbstractJob.setData | validation | public function setData($data): void
{
if (is_array($data) == false && is_string($data) == false && $data instanceof JobData == false) {
throw new InvalidArgumentException(
sprintf(
"Job's data must be either an array, or a JobData instance, or a JSON string, %s given.",
gettype($data)
)
);
}
if (is_array($data) == true) {
$data = new JobData($data);
} elseif (is_string($data) == true) {
// Assume this is JSON
$data = new JobData(json_decode($data, true));
}
$this->data = $data;
} | php | {
"resource": ""
} |
q245722 | RecurringJob.setInterval | validation | public function setInterval(int $interval): void
{
if ($this->client->call('recur.update', $this->jid, 'interval', $interval)) {
$this->interval = $interval;
}
} | php | {
"resource": ""
} |
q245723 | RecurringJob.setBacklog | validation | public function setBacklog(int $backlog): void
{
if ($this->client->call('recur.update', $this->jid, 'backlog', $backlog)) {
$this->backlog = $backlog;
}
} | php | {
"resource": ""
} |
q245724 | RecurringJob.requeue | validation | public function requeue(string $queue): void
{
if ($this->client->call('recur.update', $this->jid, 'queue', $queue)) {
$this->setQueue($queue);
}
} | php | {
"resource": ""
} |
q245725 | SignalsAwareSubscriber.registerSignalHandler | validation | protected function registerSignalHandler(WorkerInterface $worker): void
{
$this->logger->info('Register a signal handler that a worker should respond to');
SignalHandler::create(
SignalHandler::KNOWN_SIGNALS,
function (int $signal, string $signalName) use ($worker) {
$this->logger->info('{type}: Was received recognized signal {signal}', [
'type' => $worker->getName(),
'signal' => $signalName,
]);
switch ($signal) {
case SIGTERM:
$worker->shutDownNow();
break;
case SIGINT:
$worker->shutDownNow();
break;
case SIGQUIT:
$worker->shutdown();
break;
case SIGUSR1:
$worker->killChildren();
break;
case SIGUSR2:
$worker->pauseProcessing();
break;
case SIGCONT:
$worker->unPauseProcessing();
break;
}
}
);
} | php | {
"resource": ""
} |
q245726 | WatchdogSubscriber.watchdog | validation | public function watchdog(string $jid, string $worker, ?int $pid = null)
{
if (empty($this->channels) || $pid === null) {
return;
}
ini_set('default_socket_timeout', self::UNLIMITED);
/**
* Initialize a new pubsub consumer.
*
* @var Consumer $pubsub|null
*/
$pubsub = $this->redis->pubSubLoop();
$callable = [$pubsub, 'subscribe'];
if (!is_callable($callable)) {
return;
}
call_user_func_array($callable, $this->channels);
/** @var \stdClass $message */
foreach ($pubsub as $message) {
if ($message->kind !== 'message' || empty($message->payload)) {
continue;
}
$payload = json_decode($message->payload, true);
if (empty($payload)) {
continue;
}
if (empty($payload['event']) || !is_array($payload)) {
continue;
}
if (!in_array($payload['event'], self::WATCHDOG_EVENTS, true) || empty($payload['jid'])) {
continue;
}
if ($payload['jid'] !== $jid) {
continue;
}
$who = 'watchdog:' . $worker;
switch ($payload['event']) {
case self::LOCK_LOST:
if (!empty($payload['worker']) && $payload['worker'] === $worker) {
$this->logger->info(
"{type}: sending SIGKILL to child {$pid}; job {jid} handed out to another worker",
['type' => $who, 'jid' => $jid]
);
$this->system->posixKill($pid, SIGKILL);
$pubsub->stop();
}
break;
case self::CANCELED:
if (!empty($payload['worker']) && $payload['worker'] === $worker) {
$this->logger->info(
"{type}: sending SIGKILL to child {$pid}; job {jid} canceled",
['type' => $who, 'jid' => $jid]
);
$this->system->posixKill($pid, SIGKILL);
$pubsub->stop();
}
break;
case self::COMPLETED:
case self::FAILED:
$pubsub->stop();
break;
}
}
// Always unset the pubsub consumer instance when you are done! The
// class destructor will take care of cleanups and prevent protocol
// desynchronizations between the client and the server.
unset($pubsub);
ini_set('default_socket_timeout', $this->defaultSocketTimeout);
} | php | {
"resource": ""
} |
q245727 | Messages.broadcast | validation | public function broadcast(Message $message, ?string $platform = null)
{
if (null !== $platform && !isset($this->arns[$platform])) {
throw new PlatformNotConfiguredException("There is no configured ARN for $platform");
}
if ($platform) {
$this->broadcastToPlatform($message, $platform);
} else {
foreach ($this->arns as $platform => $arn) {
$this->broadcastToPlatform($message, $platform);
}
}
} | php | {
"resource": ""
} |
q245728 | Messages.send | validation | public function send($message, string $endpointArn)
{
if ($this->debug) {
$this->logger && $this->logger->notice(
"Message would have been sent to $endpointArn",
[
'Message' => $message,
]
);
return;
}
if (!($message instanceof Message)) {
$message = new Message($message);
}
$this->sns->publish(
[
'TargetArn' => $endpointArn,
'Message' => $this->encodeMessage($message),
'MessageStructure' => 'json',
]
);
} | php | {
"resource": ""
} |
q245729 | Messages.broadcastToPlatform | validation | private function broadcastToPlatform($message, string $platform)
{
if ($this->debug) {
$this->logger && $this->logger->notice(
"Message would have been sent to $platform",
[
'Message' => $message,
]
);
return;
}
foreach ($this->sns->getPaginator('ListEndpointsByPlatformApplication', [
'PlatformApplicationArn' => $this->arns[$platform],
]) as $endpointsResult) {
foreach ($endpointsResult['Endpoints'] as $endpoint) {
if ($endpoint['Attributes']['Enabled'] == 'true') {
try {
$this->send($message, $endpoint['EndpointArn']);
} catch (\Exception $e) {
$this->logger && $this->logger->error(
"Failed to push to {$endpoint['EndpointArn']}",
[
'Message' => $message,
'Exception' => $e,
'Endpoint' => $endpoint,
]
);
}
} else {
$this->logger && $this->logger->info(
"Disabled endpoint {$endpoint['EndpointArn']}",
[
'Message' => $message,
'Endpoint' => $endpoint,
]
);
}
}
}
} | php | {
"resource": ""
} |
q245730 | Devices.registerDevice | validation | public function registerDevice(string $deviceId, string $platform, ?string $userData = null): string
{
if (!isset($this->arns[$platform])) {
throw new PlatformNotConfiguredException("There is no configured ARN for $platform");
}
try {
$args = [
'PlatformApplicationArn' => $this->arns[$platform],
'Token' => $deviceId,
'Attributes' => [
'Enabled' => 'true',
],
];
if ($userData) {
$args['CustomUserData'] = $userData;
}
$res = $this->sns->createPlatformEndpoint($args);
} catch (SnsException $e) {
preg_match('/Endpoint (.+?) already/', $e->getMessage(), $matches);
if (isset($matches[1])) {
$this->sns->setEndpointAttributes(
[
'EndpointArn' => $matches[1],
'Attributes' => [
'Enabled' => 'true',
],
]
);
return $matches[1];
} else {
throw $e;
}
}
return $res['EndpointArn'];
} | php | {
"resource": ""
} |
q245731 | Topics.createTopic | validation | public function createTopic(string $name): string
{
$res = $this->sns->createTopic(
[
'Name' => $name,
]
);
return $res['TopicArn'];
} | php | {
"resource": ""
} |
q245732 | Topics.registerDeviceOnTopic | validation | public function registerDeviceOnTopic(string $deviceArn, string $topicArn)
{
$this->sns->subscribe(
[
'TopicArn' => $topicArn,
'Protocol' => 'application',
'Endpoint' => $deviceArn,
]
);
} | php | {
"resource": ""
} |
q245733 | Topics.broadcast | validation | public function broadcast(Message $message, string $topicArn)
{
if ($this->debug) {
$this->logger && $this->logger->notice(
"Message would have been sent to $topicArn",
[
'Message' => $message,
]
);
return;
}
$this->messages->send($message, $topicArn);
} | php | {
"resource": ""
} |
q245734 | Message.setLocalizedText | validation | public function setLocalizedText(?string $key, ?array $arguments = null): self
{
$this->setLocalizedKey($key);
$this->setLocalizedArguments($arguments);
return $this;
} | php | {
"resource": ""
} |
q245735 | Message.getApnsJsonInner | validation | private function getApnsJsonInner(?string $text): array
{
$apns = [
'aps' => [],
];
if (null !== $this->localizedKey) {
$apns['aps']['alert'] = [
'loc-key' => $this->localizedKey,
];
if ($this->localizedArguments) {
$apns['aps']['alert']['loc-args'] = $this->localizedArguments;
}
} elseif (null !== $text) {
$apns['aps']['alert'] = $text;
}
if ($this->isContentAvailable()) {
$apns['aps']['content-available'] = 1;
}
if (null !== $this->badge) {
$apns['aps']['badge'] = $this->badge;
}
if (null !== $this->sound) {
$apns['aps']['sound'] = $this->sound;
}
$merged = $this->arrayMergeDeep($apns, $this->custom, $this->apnsData ? $this->apnsData : []);
// Force aps to be an object, because it shouldnt get encoded as [] but as {}
if (!\count($merged['aps'])) {
$merged['aps'] = new \stdClass();
}
return $merged;
} | php | {
"resource": ""
} |
q245736 | Message.getAdmJson | validation | private function getAdmJson(): string
{
$adm = [
'data' => $this->getTrimmedJson([$this, 'getAdmJsonInner'], static::ADM_MAX_LENGTH, 'You message for ADM is too long'),
'expiresAfter' => $this->ttl,
];
foreach ($adm['data'] as $key => $value) {
if (!\is_string($value)) {
$adm['data']["{$key}_json"] = json_encode($value);
unset($adm['data'][$key]);
}
}
if ($this->collapseKey != static::NO_COLLAPSE) {
$adm['consolidationKey'] = $this->collapseKey;
}
return json_encode($adm, JSON_UNESCAPED_UNICODE);
} | php | {
"resource": ""
} |
q245737 | Message.getGcmJson | validation | private function getGcmJson(): string
{
return json_encode([
'collapse_key' => $this->collapseKey,
'time_to_live' => $this->ttl,
'delay_while_idle' => $this->delayWhileIdle,
'priority' => $this->priority,
'data' => $this->getTrimmedJson([$this, 'getGcmJsonInner'], static::GCM_MAX_LENGTH, 'You message for GCM is too long'),
], JSON_UNESCAPED_UNICODE);
} | php | {
"resource": ""
} |
q245738 | Message.getAndroidJsonInner | validation | private function getAndroidJsonInner(?string $text): array
{
$data = [];
if (null !== $text) {
$data['message'] = $text;
}
if (null !== $this->localizedKey) {
$data['message-loc-key'] = $this->localizedKey;
if ($this->localizedArguments) {
$data['message-loc-args'] = $this->localizedArguments;
}
}
return $data;
} | php | {
"resource": ""
} |
q245739 | Message.getTrimmedJson | validation | private function getTrimmedJson(callable $inner, int $limit, string $error): array
{
$gcmInner = $inner($this->text);
$gcmInnerJson = json_encode($gcmInner, JSON_UNESCAPED_UNICODE);
if (($gcmInnerJsonLength = \strlen($gcmInnerJson)) > $limit) {
$cut = $gcmInnerJsonLength - $limit;
//Note that strlen returns the byte length of the string
if ($this->text && ($textLength = \strlen($this->text)) > $cut && $this->allowTrimming) {
$gcmInner = $inner(mb_strcut($this->text, 0, $textLength - $cut - 3, 'utf8').'...');
} else {
throw new MessageTooLongException("$error $gcmInnerJson");
}
}
return $gcmInner;
} | php | {
"resource": ""
} |
q245740 | Message.arrayMergeDeep | validation | private function arrayMergeDeep(array $array1, array $array2): array
{
$result = [];
foreach (\func_get_args() as $array) {
foreach ($array as $key => $value) {
// Renumber integer keys as array_merge_recursive() does. Note that PHP
// automatically converts array keys that are integer strings (e.g., '1')
// to integers.
if (\is_int($key)) {
$result[] = $value;
} elseif (isset($result[$key]) && \is_array($result[$key]) && \is_array($value)) {
// Recurse when both values are arrays.
$result[$key] = $this->arrayMergeDeep($result[$key], $value);
} else {
// Otherwise, use the latter value, overriding any previous value.
$result[$key] = $value;
}
}
}
return $result;
} | php | {
"resource": ""
} |
q245741 | Element.matches | validation | public function matches(string $selectors):bool {
$matches = $this->getRootDocument()->querySelectorAll($selectors);
$i = $matches->length;
while(--$i >= 0 && $matches->item($i) !== $this) {
;
}
return ($i >= 0);
} | php | {
"resource": ""
} |
q245742 | Element.getElementsByClassName | validation | public function getElementsByClassName(string $names):HTMLCollection {
$namesArray = explode(" ", $names);
$dots = "." . implode(".", $namesArray);
return $this->css($dots);
} | php | {
"resource": ""
} |
q245743 | ChildNode.after | validation | public function after(DOMNode $node):void {
$this->parentNode->insertBefore($node, $this->nextSibling);
} | php | {
"resource": ""
} |
q245744 | ChildNode.replaceWith | validation | public function replaceWith(DOMNode $replacement):void {
$this->parentNode->insertBefore($replacement, $this);
$this->remove();
} | php | {
"resource": ""
} |
q245745 | NodeList.item | validation | public function item($index) {
$count = 0;
foreach($this as $element) {
if($index === $count) {
return $element;
}
$count++;
}
return null;
} | php | {
"resource": ""
} |
q245746 | OrganizationPersonaService.getList | validation | public function getList(Parameters $parameters = null): array
{
$options = [];
if ($parameters) {
$options['query'] = (array) $parameters->toObject(true);
if (array_key_exists('organizationUuid', $options['query'])) {
$options['query']['organization.uuid'] = $options['query']['organizationUuid'];
unset($options['query']['organizationUuid']);
}
}
$objects = $this->execute('GET', static::RESOURCE_LIST, $options);
$list = [];
foreach ($objects as $object) {
$model = static::toModel($object);
$list[] = $model;
}
return $list;
} | php | {
"resource": ""
} |
q245747 | OrganizationPersonaService.create | validation | public function create(OrganizationPersona $persona, Parameters $parameters = null): OrganizationPersona
{
$options = [];
$options['json'] = (array) static::toObject($persona);
if ($parameters) {
$options['query'] = (array) $parameters->toObject(true);
}
$object = $this->execute('POST', static::RESOURCE_LIST, $options);
/** @var \Ds\Component\Api\Model\OrganizationPersona $persona */
$persona = static::toModel($object);
return $persona;
} | php | {
"resource": ""
} |
q245748 | IpListener.created | validation | public function created(JWTCreatedEvent $event)
{
$request = $this->requestStack->getCurrentRequest();
$data = $event->getData();
$this->accessor->setValue($data, $this->property, $request->getClientIp());
$event->setData($data);
} | php | {
"resource": ""
} |
q245749 | IpListener.decoded | validation | public function decoded(JWTDecodedEvent $event)
{
$request = $this->requestStack->getCurrentRequest();
$payload = $event->getPayload();
// Make property accessor paths compatible by converting payload to recursive associative array
$payload = json_decode(json_encode($payload), true);
if (!$this->accessor->isReadable($payload, $this->property)) {
$event->markAsInvalid();
} elseif ($this->validate && $this->accessor->getValue($payload, $this->property) !== $request->getClientIp()) {
$event->markAsInvalid();
}
} | php | {
"resource": ""
} |
q245750 | TenantService.getContext | validation | public function getContext(): string
{
$tenant = $this->parameterService->get('ds_tenant.tenant.default');
$request = $this->requestStack->getCurrentRequest();
if ($request->request->has('tenant') && $request->request->get('tenant')) {
$tenant = $request->request->get('tenant');
}
if ($request->query->has('tenant') && $request->query->get('tenant')) {
$tenant = $request->query->get('tenant');
}
$token = $this->tokenStorage->getToken();
if ($token) {
$user = $token->getUser();
if ($user instanceof User) {
$tenant = $user->getTenant();
}
}
return $tenant;
} | php | {
"resource": ""
} |
q245751 | UuidListener.created | validation | public function created(JWTCreatedEvent $event)
{
$data = $event->getData();
$user = $event->getUser();
$this->accessor->setValue($data, $this->property, $user->getUuid());
$event->setData($data);
} | php | {
"resource": ""
} |
q245752 | UuidListener.decoded | validation | public function decoded(JWTDecodedEvent $event)
{
$payload = $event->getPayload();
// Make property accessor paths compatible by converting payload to recursive associative array
$payload = json_decode(json_encode($payload), true);
if (!$this->accessor->isReadable($payload, $this->property)) {
$event->markAsInvalid();
}
} | php | {
"resource": ""
} |
q245753 | LocaleListener.kernelView | validation | public function kernelView(GetResponseForControllerResultEvent $event)
{
$request = $event->getRequest();
if (!$request->query->has('locale')) {
return;
}
$controllerResult = $event->getControllerResult();
$locale = $request->query->get('locale');
if ($controllerResult instanceof Paginator || is_array($controllerResult)) {
foreach ($controllerResult as $model) {
if ($model instanceof Localizable) {
$this->localeService->localize($model, $locale);
}
}
} elseif ($controllerResult instanceof Localizable) {
$this->localeService->localize($controllerResult, $locale);
}
$event->setControllerResult($controllerResult);
} | php | {
"resource": ""
} |
q245754 | Data.toObject | validation | public function toObject(): stdClass
{
$object = new stdClass;
$object->timestamp = $this->timestamp;
$object->collection = $this->collection->toArray();
foreach ($object->collection as $alias => $status) {
$object->collection[$alias] = $status->toObject();
}
return $object;
} | php | {
"resource": ""
} |
q245755 | Objects.parse | validation | public static function parse(string $string, array $data = []): array
{
if ($data) {
$string = Parameters::replace($string, $data);
}
$data = Yaml::parse($string, Yaml::PARSE_OBJECT_FOR_MAP);
if (!property_exists($data,'objects')) {
throw new LogicException('Property "objects" does not exist.');
}
if (!is_array($data->objects)) {
throw new LogicException('Property "objects" is not an array.');
}
$prototype = [];
if (property_exists($data,'prototype')) {
if (!is_object($data->prototype)) {
throw new LogicException('Property "prototype" is not an object.');
}
$prototype = $data->prototype;
}
$objects = [];
foreach ($data->objects as $object) {
$objects[] = (object) array_merge((array) $prototype, (array) $object);
}
return $objects;
} | php | {
"resource": ""
} |
q245756 | Objects.parseFile | validation | public static function parseFile(string $file, array $data = []): array
{
$string = file_get_contents($file);
return static::parse($string, $data);
} | php | {
"resource": ""
} |
q245757 | SortOrder.setSortOrder | validation | public function setSortOrder(?string $sortOrder)
{
$this->sortOrder = $sortOrder;
$this->_sortOrder = null !== $sortOrder;
return $this;
} | php | {
"resource": ""
} |
q245758 | PostUpdateListener.postUpdate | validation | public function postUpdate(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof Parameter) {
return;
}
$entity->setValue(unserialize($entity->getValue()));
} | php | {
"resource": ""
} |
q245759 | PreFlushListener.preFlush | validation | public function preFlush(PreFlushEventArgs $args)
{
$entities = $args->getEntityManager()->getUnitOfWork()->getScheduledEntityInsertions();
foreach ($entities as $entity) {
if (!$entity instanceof Parameter) {
continue;
}
$entity->setValue(serialize($entity->getValue()));
}
} | php | {
"resource": ""
} |
q245760 | ParameterService.get | validation | public function get(string $key)
{
$parameter = $this->repository->findOneBy(['key' => $key]);
if (!$parameter) {
throw new OutOfRangeException('Parameter "'.$key.'" does not exist.');
}
$this->manager->detach($parameter);
return $parameter->getValue();
} | php | {
"resource": ""
} |
q245761 | ParameterService.set | validation | public function set(string $key, $value)
{
$parameter = $this->repository->findOneBy(['key' => $key]);
if (!$parameter) {
throw new OutOfRangeException('Parameter "'.$key.'" does not exist.');
}
$parameter
->setKey($key)
->setValue($value);
$this->manager->persist($parameter);
$this->manager->flush();
$this->manager->detach($parameter);
} | php | {
"resource": ""
} |
q245762 | TypeListener.created | validation | public function created(JWTCreatedEvent $event)
{
$data = $event->getData();
$user = $event->getUser();
// @todo Standardize interface between app user entity and security user model
if ($user instanceof User) {
$this->accessor->setValue($data, $this->property, $user->getIdentity()->getType());
} else {
$this->accessor->setValue($data, $this->property, $user->getIdentity());
}
$event->setData($data);
} | php | {
"resource": ""
} |
q245763 | EncryptListener.postLoad | validation | public function postLoad(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof Config) {
return;
}
$key = $entity->getKey();
$encrypt = $this->configCollection->get($key)['encrypt'];
$entity->setEncrypt($encrypt);
} | php | {
"resource": ""
} |
q245764 | ZoneRepository.loadDefinition | validation | protected function loadDefinition($id)
{
$filename = $this->definitionPath . $id . '.json';
$definition = @file_get_contents($filename);
if (empty($definition)) {
throw new UnknownZoneException($id);
}
$definition = json_decode($definition, true);
$definition['id'] = $id;
return $definition;
} | php | {
"resource": ""
} |
q245765 | ZoneRepository.createZoneFromDefinition | validation | protected function createZoneFromDefinition(array $definition)
{
$zone = new Zone();
// Bind the closure to the Zone object, giving it access to
// its protected properties. Faster than both setters and reflection.
$setValues = \Closure::bind(function ($definition) {
$this->id = $definition['id'];
$this->name = $definition['name'];
if (isset($definition['scope'])) {
$this->scope = $definition['scope'];
}
if (isset($definition['priority'])) {
$this->priority = $definition['priority'];
}
}, $zone, '\CommerceGuys\Zone\Model\Zone');
$setValues($definition);
// Add the zone members.
foreach ($definition['members'] as $memberDefinition) {
if ($memberDefinition['type'] == 'country') {
$zoneMember = $this->createZoneMemberCountryFromDefinition($memberDefinition);
$zone->addMember($zoneMember);
} elseif ($memberDefinition['type'] == 'zone') {
$zoneMember = $this->createZoneMemberZoneFromDefinition($memberDefinition);
$zone->addMember($zoneMember);
}
}
return $zone;
} | php | {
"resource": ""
} |
q245766 | ZoneRepository.createZoneMemberCountryFromDefinition | validation | protected function createZoneMemberCountryFromDefinition(array $definition)
{
$zoneMember = new ZoneMemberCountry();
$setValues = \Closure::bind(function ($definition) {
$this->id = $definition['id'];
$this->name = $definition['name'];
$this->countryCode = $definition['country_code'];
if (isset($definition['administrative_area'])) {
$this->administrativeArea = $definition['administrative_area'];
}
if (isset($definition['locality'])) {
$this->locality = $definition['locality'];
}
if (isset($definition['dependent_locality'])) {
$this->dependentLocality = $definition['dependent_locality'];
}
if (isset($definition['included_postal_codes'])) {
$this->includedPostalCodes = $definition['included_postal_codes'];
}
if (isset($definition['excluded_postal_codes'])) {
$this->excludedPostalCodes = $definition['excluded_postal_codes'];
}
}, $zoneMember, '\CommerceGuys\Zone\Model\ZoneMemberCountry');
$setValues($definition);
return $zoneMember;
} | php | {
"resource": ""
} |
q245767 | ZoneRepository.createZoneMemberZoneFromDefinition | validation | protected function createZoneMemberZoneFromDefinition(array $definition)
{
$zone = $this->get($definition['zone']);
$zoneMember = new ZoneMemberZone();
$zoneMember->setZone($zone);
$setValues = \Closure::bind(function ($definition) {
$this->id = $definition['id'];
}, $zoneMember, '\CommerceGuys\Zone\Model\ZoneMemberZone');
$setValues($definition);
return $zoneMember;
} | php | {
"resource": ""
} |
q245768 | IdentitiableListener.prePersist | validation | public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof Identitiable) {
return;
}
$this->identityService->generateIdentity($entity);
} | php | {
"resource": ""
} |
q245769 | ValueListener.postLoad | validation | public function postLoad(Permission $permission, LifecycleEventArgs $event)
{
$item = $this->permissionCollection->get($permission->getKey());
if (!$item) {
throw new UnexpectedValueException('Permission "'.$permission->getKey().'" does not exist.');
}
$permission
->setType($item->getType())
->setValue($item->getValue());
} | php | {
"resource": ""
} |
q245770 | ContentListener.kernelRequest | validation | public function kernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
$content = $request->getContent();
if ('' === $content) {
return;
}
try {
$filters = json_decode($content, true);
} catch (Exception $exception) {
throw new BadRequestHttpException('Request body should be an object.', $exception);
}
if (!is_array($filters)) {
throw new BadRequestHttpException('Request body should be an object.');
}
$current = $request->attributes->get('_api_filters', []);
$query = $request->query->all();
$filters = array_merge($current, $query, $filters);
$request->attributes->set('_api_filters', $filters);
} | php | {
"resource": ""
} |
q245771 | UserUuid.setUserUuid | validation | public function setUserUuid(?string $userUuid)
{
if (null !== $userUuid) {
if (!preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i', $userUuid)) {
throw new InvalidArgumentException('Uuid is not valid.');
}
}
$this->userUuid = $userUuid;
return $this;
} | php | {
"resource": ""
} |
q245772 | LoaderPass.process | validation | public function process(ContainerBuilder $container)
{
$definition = $container->findDefinition(LoaderCollection::class);
$services = $container->findTaggedServiceIds('ds_tenant.loader');
$items = [];
foreach ($services as $id => $tags) {
foreach ($tags as $tag) {
$items[] = [
'id' => $id,
'priority' => array_key_exists('priority', $tag) ? $tag['priority'] : 0,
'alias' => array_key_exists('alias', $tag) ? $tag['alias'] : null
];
}
}
usort($items, function($a, $b) {
return
$a['priority'] === $b['priority'] ? 0
: $a['priority'] < $b['priority'] ? -1
: 1;
});
foreach ($items as $item) {
if (null !== $item['alias']) {
$definition->addMethodCall('set', [$item['alias'], new Reference($item['id'])]);
} else {
$definition->addMethodCall('add', [new Reference($item['id'])]);
}
}
} | php | {
"resource": ""
} |
q245773 | FirstResult.setFirstResult | validation | public function setFirstResult(?int $firstResult)
{
$this->firstResult = $firstResult;
$this->_firstResult = null !== $firstResult;
return $this;
} | php | {
"resource": ""
} |
q245774 | VariableService.getList | validation | public function getList($task, Parameters $parameters = null)
{
$resource = str_replace('{id}', $task, static::VARIABLE_LIST);
$options = [
'headers' => [
'Accept' => 'application/json'
],
'query' => (array) $parameters->toObject(true)
];
$objects = $this->execute('GET', $resource, $options);
$list = [];
foreach ($objects as $name => $object) {
$object->name = $name;
$model = static::toModel($object);
$list[$name] = $model;
}
return $list;
} | php | {
"resource": ""
} |
q245775 | CandidateGroup.setCandidateGroup | validation | public function setCandidateGroup(?string$candidateGroup)
{
$this->candidateGroup = $candidateGroup;
$this->_candidateGroup = null !== $candidateGroup;
return $this;
} | php | {
"resource": ""
} |
q245776 | TenantableListener.prePersist | validation | public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof Tenantable) {
return;
}
if (null !== $entity->getTenant()) {
return;
}
$tenant = $this->container->get(TenantService::class)->getContext();
$entity->setTenant($tenant);
} | php | {
"resource": ""
} |
q245777 | TenantIdIn.setTenantIdIn | validation | public function setTenantIdIn(array $tenantIdIn)
{
$this->tenantIdIn = $tenantIdIn;
$this->_tenantIdIn = null !== $tenantIdIn;
return $this;
} | php | {
"resource": ""
} |
q245778 | UuidentifiableListener.prePersist | validation | public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if (!$entity instanceof Uuidentifiable) {
return;
}
$this->idService->generateUuid($entity);
} | php | {
"resource": ""
} |
q245779 | TenantId.setTenantId | validation | public function setTenantId(?string $tenantId)
{
$this->tenantId = $tenantId;
$this->_tenantId = null !== $tenantId;
return $this;
} | php | {
"resource": ""
} |
q245780 | IndividualUuid.setIndividualUuid | validation | public function setIndividualUuid(?string $individualUuid)
{
$this->individualUuid = $individualUuid;
$this->_individualUuid = true;
return $this;
} | php | {
"resource": ""
} |
q245781 | ConfigService.get | validation | public function get(string $key)
{
$config = $this->repository->findOneBy(['key' => $key]);
if (!$config) {
throw new OutOfRangeException('Config "'.$key.'" does not exist.');
}
$this->manager->detach($config);
return $config->getValue();
} | php | {
"resource": ""
} |
q245782 | ConfigService.set | validation | public function set(string $key, $value)
{
$config = $this->repository->findOneBy(['key' => $key]);
if (!$config) {
throw new OutOfRangeException('Config "'.$key.'" does not exist.');
}
$config
->setKey($key)
->setValue($value);
$this->manager->persist($config);
$this->manager->flush();
$this->manager->detach($config);
} | php | {
"resource": ""
} |
q245783 | PostFlushListener.postFlush | validation | public function postFlush(PostFlushEventArgs $args)
{
$maps = $args->getEntityManager()->getUnitOfWork()->getIdentityMap();
foreach ($maps as $entities) {
foreach ($entities as $entity) {
if (!$entity instanceof Parameter) {
continue;
}
$entity->setValue(unserialize($entity->getValue()));
}
}
} | php | {
"resource": ""
} |
q245784 | TenantFilter.addFilterConstraint | validation | public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
{
if (!$targetEntity->reflClass->implementsInterface(Tenantable::class)) {
return '';
}
$tenant = trim($this->getParameter('tenant'), '\'');
if ('' === $tenant) {
$constraint = sprintf('%s.tenant is NULL', $targetTableAlias);
} else {
$constraint = sprintf('%s.tenant = \'%s\'', $targetTableAlias, $tenant);
}
return $constraint;
} | php | {
"resource": ""
} |
q245785 | ExceptionListener.kernelException | validation | public function kernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
if ($exception instanceof ValidationException) {
return;
}
$data = [
'type' => 'https://tools.ietf.org/html/rfc2616#section-10',
'title' =>'An error occurred'
];
if (in_array($this->environment, ['dev', 'test'], true)) {
$data['detail'] = $exception->getMessage();
$data['trace'] = $exception->getTrace();
}
$request = $event->getRequest();
$contentTypes = $request->getAcceptableContentTypes();
$accept = array_shift($contentTypes);
switch ($accept) {
case 'application/json':
case 'application/ld+json':
$code = Response::HTTP_INTERNAL_SERVER_ERROR;
if ($exception instanceof HttpException) {
$code = $exception->getStatusCode();
}
$response = new JsonResponse($data, $code);
$event->setResponse($response);
break;
}
} | php | {
"resource": ""
} |
q245786 | SortBy.setSortBy | validation | public function setSortBy(?string $sortBy)
{
$this->sortBy = $sortBy;
$this->_sortBy = null !== $sortBy;
return $this;
} | php | {
"resource": ""
} |
q245787 | IncludeAssignedTasks.setIncludeAssignedTasks | validation | public function setIncludeAssignedTasks(?bool $includeAssignedTasks)
{
$this->includeAssignedTasks = $includeAssignedTasks;
$this->_includeAssignedTasks = null !== $includeAssignedTasks;
return $this;
} | php | {
"resource": ""
} |
q245788 | HealthService.check | validation | public function check($alias = null)
{
if (null === $alias) {
$statuses = new Statuses;
$statuses->setHealthy(true);
foreach ($this->checkCollection as $check) {
$status = $check->execute();
$statuses->getCollection()->add($status);
if (!$status->getHealthy()) {
$statuses->setHealthy(false);
}
}
return $statuses;
} else {
$check = $this->checkCollection->filter(function($element) use($alias) {
return $element->getAlias() === $alias;
})->first();
if (!$check) {
throw new InvalidAliasException('Check alias does not exist.');
}
$status = $check->execute();
return $status;
}
} | php | {
"resource": ""
} |
q245789 | StatisticService.getAll | validation | public function getAll(): Data
{
$data = new Data;
foreach ($this->statCollection as $stat) {
$datum = $stat->get();
$data->getCollection()->add($datum);
}
return $data;
} | php | {
"resource": ""
} |
q245790 | StatisticService.get | validation | public function get(string $alias)
{
$stat = $this->statCollection->filter(function($element) use($alias) {
return $element->getAlias() === $alias;
})->first();
if (!$stat) {
throw new InvalidAliasException('Stat alias "'.$alias.'" does not exist.');
}
$datum = $stat->get();
return $datum;
} | php | {
"resource": ""
} |
q245791 | AssigneeLike.setAssigneeLike | validation | public function setAssigneeLike(?string $assigneeLike)
{
$this->assigneeLike = $assigneeLike;
$this->_assigneeLike = null !== $assigneeLike;
return $this;
} | php | {
"resource": ""
} |
q245792 | UserService.getList | validation | public function getList($form): array
{
$objects = $this->execute('GET', 'http://www.mocky.io/v2/592c3c86110000f8016df7de');
$list = [];
foreach ($objects as $object) {
$model = static::toModel($object);
$list[] = $model;
}
return $list;
} | php | {
"resource": ""
} |
q245793 | UserService.exists | validation | public function exists(UserParameters $parameters = null)
{
$object = $this->execute('GET', 'http://www.mocky.io/v2/592c6f7311000029066df850');
if ($object && property_exists($object, '_id') && $object->_id) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q245794 | ModifierListener.created | validation | public function created(JWTCreatedEvent $event)
{
$data = $event->getData();
foreach ($this->removed as $property) {
if (!array_key_exists($property, $data)) {
throw new OutOfRangeException('Property does not exist.');
}
unset($data[$property]);
}
$event->setData($data);
} | php | {
"resource": ""
} |
q245795 | ModifierListener.decoded | validation | public function decoded(JWTDecodedEvent $event)
{
$payload = $event->getPayload();
// Make property accessor paths compatible by converting payload to recursive associative array
$payload = json_decode(json_encode($payload), true);
foreach ($this->removed as $property) {
if (array_key_exists($property, $payload)) {
$event->markAsInvalid();
break;
}
}
} | php | {
"resource": ""
} |
q245796 | Translation.addJoinTranslation | validation | protected function addJoinTranslation(QueryBuilder $queryBuilder, string $resourceClass)
{
$rootAlias = $queryBuilder->getRootAliases()[0];
$translationAlias = $rootAlias.'_t';
$translationClass = call_user_func($resourceClass.'::getTranslationEntityClass');
$parts = $queryBuilder->getDQLParts()['join'];
foreach ($parts as $joins) {
foreach ($joins as $join) {
if ($translationAlias === $join->getAlias()) {
return $translationAlias;
}
}
}
$queryBuilder->leftJoin(
$translationClass,
$translationAlias,
Join::WITH,
$rootAlias.'.id = '.$translationAlias.'.translatable'
);
return $translationAlias;
} | php | {
"resource": ""
} |
q245797 | OrganizationUuid.setOrganizationUuid | validation | public function setOrganizationUuid(?string $organizationUuid)
{
$this->organizationUuid = $organizationUuid;
$this->_organizationUuid = true;
return $this;
} | php | {
"resource": ""
} |
q245798 | IdService.generateCustomId | validation | public function generateCustomId(CustomIdentifiable $entity, bool $overwrite = false)
{
if (null === $entity->getCustomId() || $overwrite) {
$customId = uniqid();
$entity->setCustomId($customId);
}
return $this;
} | php | {
"resource": ""
} |
q245799 | IdService.generateUuid | validation | public function generateUuid(Uuidentifiable $entity, bool $overwrite = false)
{
if (null === $entity->getUuid() || $overwrite) {
$uuid = Uuid::uuid4()->toString();
$entity->setUuid($uuid);
}
return $this;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.