_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q242800 | DeserializesAttributes.fillAttributes | validation | protected function fillAttributes($record, Collection $attributes)
{
$record->fill(
$this->deserializeAttributes($attributes, $record)
);
} | php | {
"resource": ""
} |
q242801 | DeserializesAttributes.modelKeyForField | validation | protected function modelKeyForField($field, $model)
{
if (isset($this->attributes[$field])) {
return $this->attributes[$field];
}
$key = $model::$snakeAttributes ? Str::underscore($field) : Str::camelize($field);
return $this->attributes[$field] = $key;
} | php | {
"resource": ""
} |
q242802 | DeserializesAttributes.deserializeAttributes | validation | protected function deserializeAttributes($attributes, $record)
{
return collect($attributes)->reject(function ($v, $field) use ($record) {
return $this->isNotFillable($field, $record);
})->mapWithKeys(function ($value, $field) use ($record) {
$key = $this->modelKeyForField($field, $record);
return [$key => $this->deserializeAttribute($value, $field, $record)];
})->all();
} | php | {
"resource": ""
} |
q242803 | DeserializesAttributes.deserializeAttribute | validation | protected function deserializeAttribute($value, $field, $record)
{
if ($this->isDateAttribute($field, $record)) {
return $this->deserializeDate($value, $field, $record);
}
$method = 'deserialize' . Str::classify($field) . 'Field';
if (method_exists($this, $method)) {
return $this->{$method}($value, $record);
}
return $value;
} | php | {
"resource": ""
} |
q242804 | DeserializesAttributes.isDateAttribute | validation | protected function isDateAttribute($field, $record)
{
if (empty($this->dates)) {
return in_array($this->modelKeyForField($field, $record), $record->getDates(), true);
}
return in_array($field, $this->dates, true);
} | php | {
"resource": ""
} |
q242805 | ClientJob.setResource | validation | public function setResource($resource): ClientJob
{
$schema = $this->getApi()->getContainer()->getSchema($resource);
$this->fill([
'resource_type' => $schema->getResourceType(),
'resource_id' => $schema->getId($resource),
]);
return $this;
} | php | {
"resource": ""
} |
q242806 | ClientJob.getResource | validation | public function getResource()
{
if (!$this->resource_type || !$this->resource_id) {
return null;
}
return $this->getApi()->getStore()->find(
ResourceIdentifier::create($this->resource_type, (string) $this->resource_id)
);
} | php | {
"resource": ""
} |
q242807 | Route.substituteBindings | validation | public function substituteBindings(StoreInterface $store): void
{
/** Cache the ID values so that we still have access to them. */
$this->resourceId = $this->getResourceId() ?: false;
$this->processId = $this->getProcessId() ?: false;
/** Bind the domain record. */
if ($this->resourceId) {
$this->route->setParameter(
ResourceRegistrar::PARAM_RESOURCE_ID,
$store->findOrFail($this->getResourceType(), $this->resourceId)
);
}
/** Bind the async process. */
if ($this->processId) {
$this->route->setParameter(
ResourceRegistrar::PARAM_PROCESS_ID,
$store->findOrFail($this->getProcessType(), $this->processId)
);
}
} | php | {
"resource": ""
} |
q242808 | Route.getType | validation | public function getType(): string
{
if ($resource = $this->getResource()) {
return get_class($resource);
}
$resourceType = $this->getResourceType();
if (!$type = $this->resolver->getType($resourceType)) {
throw new RuntimeException("JSON API resource type {$resourceType} is not registered.");
}
return $type;
} | php | {
"resource": ""
} |
q242809 | Route.getResourceId | validation | public function getResourceId(): ?string
{
if (is_null($this->resourceId)) {
return $this->parameter(ResourceRegistrar::PARAM_RESOURCE_ID);
}
return $this->resourceId ?: null;
} | php | {
"resource": ""
} |
q242810 | Route.getResourceIdentifier | validation | public function getResourceIdentifier(): ?ResourceIdentifierInterface
{
if (!$resourceId = $this->getResourceId()) {
return null;
}
return ResourceIdentifier::create($this->getResourceType(), $resourceId);
} | php | {
"resource": ""
} |
q242811 | Route.getResource | validation | public function getResource()
{
$resource = $this->parameter(ResourceRegistrar::PARAM_RESOURCE_ID);
return is_object($resource) ? $resource : null;
} | php | {
"resource": ""
} |
q242812 | Route.getProcessId | validation | public function getProcessId(): ?string
{
if (is_null($this->processId)) {
return $this->parameter(ResourceRegistrar::PARAM_PROCESS_ID);
}
return $this->processId ?: null;
} | php | {
"resource": ""
} |
q242813 | Route.getProcess | validation | public function getProcess(): ?AsynchronousProcess
{
$process = $this->parameter(ResourceRegistrar::PARAM_PROCESS_ID);
return ($process instanceof AsynchronousProcess) ? $process : null;
} | php | {
"resource": ""
} |
q242814 | Route.getProcessIdentifier | validation | public function getProcessIdentifier(): ?ResourceIdentifierInterface
{
if (!$id = $this->getProcessId()) {
return null;
}
return ResourceIdentifier::create($this->getProcessType(), $id);
} | php | {
"resource": ""
} |
q242815 | JsonApiService.defaultApi | validation | public function defaultApi($apiName = null)
{
if (is_null($apiName)) {
return LaravelJsonApi::$defaultApi;
}
LaravelJsonApi::defaultApi($apiName);
return $apiName;
} | php | {
"resource": ""
} |
q242816 | JsonApiService.api | validation | public function api($apiName = null)
{
/** @var Repository $repo */
$repo = $this->container->make(Repository::class);
return $repo->createApi($apiName ?: $this->defaultApi());
} | php | {
"resource": ""
} |
q242817 | JsonApiService.register | validation | public function register($apiName, $options = [], Closure $routes = null): ApiRegistration
{
/** @var JsonApiRegistrar $registrar */
$registrar = $this->container->make('json-api.registrar');
return $registrar->api($apiName, $options, $routes);
} | php | {
"resource": ""
} |
q242818 | CreateResource.validateDocumentCompliance | validation | protected function validateDocumentCompliance($document, ?ValidatorFactoryInterface $validators): void
{
$this->passes(
$this->factory->createNewResourceDocumentValidator(
$document,
$this->getResourceType(),
$validators && $validators->supportsClientIds()
)
);
} | php | {
"resource": ""
} |
q242819 | ResourceObject.create | validation | public static function create(array $data): self
{
if (!isset($data['type'])) {
throw new \InvalidArgumentException('Expecting a resource type.');
}
return new self(
$data['type'],
$data['id'] ?? null,
$data['attributes'] ?? [],
$data['relationships'] ?? [],
$data['meta'] ?? [],
$data['links'] ?? []
);
} | php | {
"resource": ""
} |
q242820 | ResourceObject.withType | validation | public function withType(string $type): self
{
if (empty($type)) {
throw new \InvalidArgumentException('Expecting a non-empty string.');
}
$copy = clone $this;
$copy->type = $type;
$copy->normalize();
return $copy;
} | php | {
"resource": ""
} |
q242821 | ResourceObject.withId | validation | public function withId(?string $id): self
{
$copy = clone $this;
$copy->id = $id ?: null;
$copy->normalize();
return $copy;
} | php | {
"resource": ""
} |
q242822 | ResourceObject.withAttributes | validation | public function withAttributes($attributes): self
{
$copy = clone $this;
$copy->attributes = collect($attributes)->all();
$copy->normalize();
return $copy;
} | php | {
"resource": ""
} |
q242823 | ResourceObject.withRelationships | validation | public function withRelationships($relationships): self
{
$copy = clone $this;
$copy->relationships = collect($relationships)->all();
$copy->normalize();
return $copy;
} | php | {
"resource": ""
} |
q242824 | ResourceObject.getRelations | validation | public function getRelations(): Collection
{
return $this->getRelationships()->filter(function (array $relation) {
return array_key_exists('data', $relation);
})->map(function (array $relation) {
return $relation['data'];
});
} | php | {
"resource": ""
} |
q242825 | ResourceObject.withMeta | validation | public function withMeta($meta): self
{
$copy = clone $this;
$copy->meta = collect($meta)->all();
return $copy;
} | php | {
"resource": ""
} |
q242826 | ResourceObject.withLinks | validation | public function withLinks($links): self
{
$copy = clone $this;
$copy->links = collect($links)->all();
return $copy;
} | php | {
"resource": ""
} |
q242827 | ResourceObject.pointer | validation | public function pointer(string $key, string $prefix = ''): string
{
$prefix = rtrim($prefix, '/');
if ('type' === $key) {
return $prefix . '/type';
}
if ('id' === $key) {
return $prefix . '/id';
}
$parts = collect(explode('.', $key));
$field = $parts->first();
if ($this->isAttribute($field)) {
return $prefix . '/attributes/' . $parts->implode('/');
}
if ($this->isRelationship($field)) {
$name = 1 < $parts->count() ? $field . '/' . $parts->put(0, 'data')->implode('/') : $field;
return $prefix . "/relationships/{$name}";
}
return $prefix ? $prefix : '/';
} | php | {
"resource": ""
} |
q242828 | ResourceObject.pointerForRelationship | validation | public function pointerForRelationship(string $key, string $default = '/'): string
{
$field = collect(explode('.', $key))->first();
if (!$this->isRelationship($field)) {
throw new \InvalidArgumentException("Field {$field} is not a relationship.");
}
$pointer = $this->pointer($key);
return Str::after($pointer, "relationships/{$field}") ?: $default;
} | php | {
"resource": ""
} |
q242829 | MetaMemberTrait.getMeta | validation | public function getMeta()
{
$meta = $this->hasMeta() ? $this->get(DocumentInterface::KEYWORD_META) : new StandardObject();
if (!is_null($meta) && !$meta instanceof StandardObjectInterface) {
throw new RuntimeException('Data member is not an object.');
}
return $meta;
} | php | {
"resource": ""
} |
q242830 | InvokesHooks.invoke | validation | protected function invoke(string $hook, ...$arguments)
{
if (!method_exists($this, $hook)) {
return null;
}
$result = $this->{$hook}(...$arguments);
return $this->isInvokedResult($result) ? $result : null;
} | php | {
"resource": ""
} |
q242831 | InvokesHooks.invokeMany | validation | protected function invokeMany(iterable $hooks, ...$arguments)
{
foreach ($hooks as $hook) {
$result = $this->invoke($hook, ...$arguments);
if (!is_null($result)) {
return $result;
}
}
return null;
} | php | {
"resource": ""
} |
q242832 | CreateResourceValidator.validateData | validation | protected function validateData(): bool
{
if (!property_exists($this->document, 'data')) {
$this->memberRequired('/', 'data');
return false;
}
$data = $this->document->data;
if (!is_object($data)) {
$this->memberNotObject('/', 'data');
return false;
}
return true;
} | php | {
"resource": ""
} |
q242833 | CreateResourceValidator.validateResource | validation | protected function validateResource(): bool
{
$identifier = $this->validateTypeAndId();
$attributes = $this->validateAttributes();
$relationships = $this->validateRelationships();
if ($attributes && $relationships) {
return $this->validateAllFields() && $identifier;
}
return $identifier && $attributes && $relationships;
} | php | {
"resource": ""
} |
q242834 | CreateResourceValidator.validateTypeAndId | validation | protected function validateTypeAndId(): bool
{
if (!($this->validateType() && $this->validateId())) {
return false;
}
$type = $this->dataGet('type');
$id = $this->dataGet('id');
if ($id && !$this->isNotFound($type, $id)) {
$this->resourceExists($type, $id);
return false;
}
return true;
} | php | {
"resource": ""
} |
q242835 | CreateResourceValidator.validateType | validation | protected function validateType(): bool
{
if (!$this->dataHas('type')) {
$this->memberRequired('/data', 'type');
return false;
}
$value = $this->dataGet('type');
if (!$this->validateTypeMember($value, '/data')) {
return false;
}
if ($this->expectedType !== $value) {
$this->resourceTypeNotSupported($value);
return false;
}
return true;
} | php | {
"resource": ""
} |
q242836 | CreateResourceValidator.validateId | validation | protected function validateId(): bool
{
if (!$this->dataHas('id')) {
return true;
}
$valid = $this->validateIdMember($this->dataGet('id'), '/data');
if (!$this->supportsClientIds()) {
$valid = false;
$this->resourceDoesNotSupportClientIds($this->expectedType);
}
return $valid;
} | php | {
"resource": ""
} |
q242837 | CreateResourceValidator.validateAttributes | validation | protected function validateAttributes(): bool
{
if (!$this->dataHas('attributes')) {
return true;
}
$attrs = $this->dataGet('attributes');
if (!is_object($attrs)) {
$this->memberNotObject('/data', 'attributes');
return false;
}
$disallowed = collect(['type', 'id'])->filter(function ($field) use ($attrs) {
return property_exists($attrs, $field);
});
$this->memberFieldsNotAllowed('/data', 'attributes', $disallowed);
return $disallowed->isEmpty();
} | php | {
"resource": ""
} |
q242838 | CreateResourceValidator.validateRelationships | validation | protected function validateRelationships(): bool
{
if (!$this->dataHas('relationships')) {
return true;
}
$relationships = $this->dataGet('relationships');
if (!is_object($relationships)) {
$this->memberNotObject('/data', 'relationships');
return false;
}
$disallowed = collect(['type', 'id'])->filter(function ($field) use ($relationships) {
return property_exists($relationships, $field);
});
$valid = $disallowed->isEmpty();
$this->memberFieldsNotAllowed('/data', 'relationships', $disallowed);
foreach ($relationships as $field => $relation) {
if (!$this->validateRelationship($relation, $field)) {
$valid = false;
}
}
return $valid;
} | php | {
"resource": ""
} |
q242839 | CreateResourceValidator.validateAllFields | validation | protected function validateAllFields(): bool
{
$duplicates = collect(
(array) $this->dataGet('attributes', [])
)->intersectByKeys(
(array) $this->dataGet('relationships', [])
)->keys();
$this->resourceFieldsExistInAttributesAndRelationships($duplicates);
return $duplicates->isEmpty();
} | php | {
"resource": ""
} |
q242840 | AuthorizesRequests.authenticate | validation | protected function authenticate()
{
if (empty($this->guards) && Auth::check()) {
return;
}
foreach ($this->guards as $guard) {
if (Auth::guard($guard)->check()) {
Auth::shouldUse($guard);
return;
}
}
throw new AuthenticationException('Unauthenticated.', $this->guards);
} | php | {
"resource": ""
} |
q242841 | ClientSerializer.serialize | validation | public function serialize($record, $meta = null, array $links = [])
{
$serializer = clone $this->serializer;
$serializer->withMeta($meta)->withLinks($links);
$serialized = $serializer->serializeData($record, $this->createEncodingParameters());
$resourceLinks = null;
if (empty($serialized['data']['id'])) {
unset($serialized['data']['id']);
$resourceLinks = false; // links will not be valid so strip them out.
}
$resource = $this->parsePrimaryResource($serialized['data'], $resourceLinks);
$document = ['data' => $resource];
if (isset($serialized['included']) && $this->doesSerializeCompoundDocuments()) {
$document['included'] = $this->parseIncludedResources($serialized['included']);
}
return $document;
} | php | {
"resource": ""
} |
q242842 | SeoService.injectRobots | validation | public function injectRobots ()
{
$headers = \Craft::$app->getResponse()->getHeaders();
// If devMode always noindex
if (\Craft::$app->config->general->devMode)
{
$headers->set('x-robots-tag', 'none, noimageindex');
return;
}
list($field, $element) = $this->_getElementAndSeoFields();
// Robots
$robots = $field->robots;
if ($robots !== null)
$headers->set('x-robots-tag', $robots);
// Get Expiry Date
/** @var \DateTime $expiry */
if (isset($element->expiryDate))
$expiry = $element->expiryDate->format(\DATE_RFC850);
else
$expiry = null;
// If we've got an expiry time, add an additional header
if ($expiry)
$headers->add('x-robots-tag', 'unavailable_after: ' . $expiry);
} | php | {
"resource": ""
} |
q242843 | SeoData._getSocialFallback | validation | private function _getSocialFallback ()
{
$image = null;
$assets = \Craft::$app->assets;
$fieldFallback = $this->_fieldSettings['socialImage'];
if (!empty($fieldFallback))
$image = $assets->getAssetById((int)$fieldFallback[0]);
else {
$seoFallback = $this->_seoSettings['socialImage'];
if (!empty($seoFallback))
$image = $assets->getAssetById((int)$seoFallback[0]);
}
return [
'title' => $this->title,
'description' => $this->description,
'image' => $image,
];
} | php | {
"resource": ""
} |
q242844 | SeoData._getVariables | validation | private function _getVariables ()
{
$variables = $this->_overrideObject;
if ($this->_element !== null)
{
foreach ($this->_element->attributes() as $name)
if ($name !== $this->_handle)
$variables[$name] = $this->_element->$name;
$variables = array_merge(
$variables,
$this->_element->toArray($this->_element->extraFields())
);
}
return $variables;
} | php | {
"resource": ""
} |
q242845 | RedirectsService.onException | validation | public function onException (ExceptionEvent $event)
{
$exception = $event->exception;
$craft = \Craft::$app;
if (!($exception instanceof HttpException) || $exception->statusCode !== 404)
return;
$path = $craft->request->getFullPath();
$query = $craft->request->getQueryStringWithoutPath();
if ($query)
$path .= '?' . $query;
if ($redirect = $this->findRedirectByPath($path))
{
$event->handled = true;
$craft->response->redirect($redirect['to'], $redirect['type'])
->send();
$craft->end();
}
} | php | {
"resource": ""
} |
q242846 | RedirectsService.findAllRedirects | validation | public function findAllRedirects ($currentSiteOnly = false)
{
if ($currentSiteOnly)
return RedirectRecord::find()->where(
'[[siteId]] IS NULL OR [[siteId]] = ' .
\Craft::$app->sites->currentSite->id
)->orderBy('siteId asc')->all();
return array_reduce(
RedirectRecord::find()->all(),
function ($a, RedirectRecord $record) {
$a[$record->siteId ?? 'null'][] = $record;
return $a;
},
array_reduce(
\Craft::$app->sites->allSiteIds,
function ($a, $id) {
$a[$id] = [];
return $a;
},
[]
)
);
} | php | {
"resource": ""
} |
q242847 | RedirectsService.findRedirectByPath | validation | public function findRedirectByPath ($path)
{
$redirects = $this->findAllRedirects(true);
foreach ($redirects as $redirect)
{
$to = false;
if (trim($redirect['uri'], '/') == $path)
$to = $redirect['to'];
elseif ($uri = $this->_isRedirectRegex($redirect['uri']))
if (preg_match($uri, $path))
$to = preg_replace($uri, $redirect['to'], $path);
if ($to)
{
return [
'to' => strpos($to, '://') !== false
? $to
: UrlHelper::siteUrl($to),
'type' => $redirect['type'],
];
}
}
return false;
} | php | {
"resource": ""
} |
q242848 | RedirectsService.save | validation | public function save ($uri, $to, $type, $siteId = null, $id = null)
{
if ($siteId === 'null')
$siteId = null;
if ($id)
{
$record = RedirectRecord::findOne(compact('id'));
if (!$record)
return 'Unable to find redirect with ID: ' . $id;
}
else
{
$existing = RedirectRecord::findOne(compact('uri', 'siteId'));
if ($existing)
return 'A redirect with that URI already exists!';
$record = new RedirectRecord();
}
$record->uri = $uri;
$record->to = $to;
$record->type = $type;
if ($siteId !== false)
$record->siteId = $siteId;
if (!$record->save())
return $record->getErrors();
return $record->id;
} | php | {
"resource": ""
} |
q242849 | RedirectsService.bulk | validation | public function bulk ($redirects, $separator, $type, $siteId)
{
$rawRedirects = array_map(function ($line) use ($separator) {
return str_getcsv($line, $separator);
}, explode(PHP_EOL, $redirects));
$newFormatted = [];
foreach ($rawRedirects as $redirect)
{
$record = new RedirectRecord();
$record->uri = $redirect[0];
$record->to = $redirect[1];
$record->type = array_key_exists(2, $redirect) ? $redirect[2] : $type;
$record->siteId = $siteId;
$record->save();
$newFormatted[] = [
'id' => $record->id,
'uri' => $record->uri,
'to' => $record->to,
'type' => $record->type,
'siteId' => $record->siteId,
];
}
return [$newFormatted, false];
} | php | {
"resource": ""
} |
q242850 | RedirectsService.delete | validation | public function delete ($id)
{
$redirect = RedirectRecord::findOne(compact('id'))->delete();
if ($redirect === false)
return 'Unable find redirect with ID: ' . $id;
return false;
} | php | {
"resource": ""
} |
q242851 | RedirectsService._isRedirectRegex | validation | private function _isRedirectRegex ($uri)
{
// If the URI doesn't look like a regex...
if (preg_match('/\/(.*)\/([g|m|i|x|X|s|u|U|A|J|D]+)/m', $uri) === 0)
{
// Escape all non-escaped `?` not inside parentheses
$i = preg_match_all(
'/(?<!\\\\)\?(?![^(]*\))/',
$uri,
$matches,
PREG_OFFSET_CAPTURE
);
while ($i--)
{
$x = $matches[0][$i][1];
$uri = substr_replace($uri, '\?', $x, 1);
}
// Escape all non-escaped `/` not inside parentheses
$i = preg_match_all(
'/(?<!\\\\)\/(?![^(]*\))/',
$uri,
$matches,
PREG_OFFSET_CAPTURE
);
while ($i--)
{
$x = $matches[0][$i][1];
$uri = substr_replace($uri, '\/', $x, 1);
}
}
// Check if contains a valid regex
if (@preg_match($uri, null) === false)
$uri = '/^' . $uri . '$/i';
if (@preg_match($uri, null) !== false)
return $uri;
return false;
} | php | {
"resource": ""
} |
q242852 | SitemapService._createDocument | validation | private function _createDocument ($withUrlSet = true)
{
// Create the XML Document
$document = new \DOMDocument('1.0', 'utf-8');
// Pretty print for debugging
if (\Craft::$app->config->general->devMode)
$document->formatOutput = true;
if ($withUrlSet)
{
$urlSet = $document->createElement('urlset');
$urlSet->setAttribute(
'xmlns',
'http://www.sitemaps.org/schemas/sitemap/0.9'
);
$urlSet->setAttribute(
'xmlns:xhtml',
'http://www.w3.org/1999/xhtml'
);
$document->appendChild($urlSet);
$this->_urlSet = $urlSet;
}
$this->_document = $document;
} | php | {
"resource": ""
} |
q242853 | SitemapService._setCriteriaIdByType | validation | private function _setCriteriaIdByType ($criteria, Element $type, $id)
{
switch ($type::className()) {
case 'Entry':
$criteria->sectionId = $id;
break;
case 'Category':
$criteria->groupId = $id;
break;
}
} | php | {
"resource": ""
} |
q242854 | Connection.close | validation | public function close()
{
if ($this->_socket !== false) {
$connection = ($this->unixSocket ?: $this->hostname . ':' . $this->port) . ', database=' . $this->database;
\Yii::trace('Closing DB connection: ' . $connection, __METHOD__);
try {
$this->executeCommand('QUIT');
} catch (SocketException $e) {
// ignore errors when quitting a closed connection
}
fclose($this->_socket);
$this->_socket = false;
}
} | php | {
"resource": ""
} |
q242855 | Connection.sendCommandInternal | validation | private function sendCommandInternal($command, $params)
{
$written = @fwrite($this->_socket, $command);
if ($written === false) {
throw new SocketException("Failed to write to socket.\nRedis command was: " . $command);
}
if ($written !== ($len = mb_strlen($command, '8bit'))) {
throw new SocketException("Failed to write to socket. $written of $len bytes written.\nRedis command was: " . $command);
}
return $this->parseResponse(implode(' ', $params));
} | php | {
"resource": ""
} |
q242856 | Session.readSession | validation | public function readSession($id)
{
$data = $this->redis->executeCommand('GET', [$this->calculateKey($id)]);
return $data === false || $data === null ? '' : $data;
} | php | {
"resource": ""
} |
q242857 | ActiveQuery.count | validation | public function count($q = '*', $db = null)
{
if ($this->emulateExecution) {
return 0;
}
if ($this->where === null) {
/* @var $modelClass ActiveRecord */
$modelClass = $this->modelClass;
if ($db === null) {
$db = $modelClass::getDb();
}
return $db->executeCommand('LLEN', [$modelClass::keyPrefix()]);
} else {
return $this->executeScript($db, 'Count');
}
} | php | {
"resource": ""
} |
q242858 | ActiveQuery.column | validation | public function column($column, $db = null)
{
if ($this->emulateExecution) {
return [];
}
// TODO add support for orderBy
return $this->executeScript($db, 'Column', $column);
} | php | {
"resource": ""
} |
q242859 | ActiveQuery.scalar | validation | public function scalar($attribute, $db = null)
{
if ($this->emulateExecution) {
return null;
}
$record = $this->one($db);
if ($record !== null) {
return $record->hasAttribute($attribute) ? $record->$attribute : null;
} else {
return null;
}
} | php | {
"resource": ""
} |
q242860 | LuaScriptBuilder.buildAll | validation | public function buildAll($query)
{
/* @var $modelClass ActiveRecord */
$modelClass = $query->modelClass;
$key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
return $this->build($query, "n=n+1 pks[n]=redis.call('HGETALL',$key .. pk)", 'pks');
} | php | {
"resource": ""
} |
q242861 | LuaScriptBuilder.buildOne | validation | public function buildOne($query)
{
/* @var $modelClass ActiveRecord */
$modelClass = $query->modelClass;
$key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
return $this->build($query, "do return redis.call('HGETALL',$key .. pk) end", 'pks');
} | php | {
"resource": ""
} |
q242862 | LuaScriptBuilder.buildColumn | validation | public function buildColumn($query, $column)
{
// TODO add support for indexBy
/* @var $modelClass ActiveRecord */
$modelClass = $query->modelClass;
$key = $this->quoteValue($modelClass::keyPrefix() . ':a:');
return $this->build($query, "n=n+1 pks[n]=redis.call('HGET',$key .. pk," . $this->quoteValue($column) . ")", 'pks');
} | php | {
"resource": ""
} |
q242863 | LuaScriptBuilder.addColumn | validation | private function addColumn($column, &$columns)
{
if (isset($columns[$column])) {
return $columns[$column];
}
$name = 'c' . preg_replace("/[^a-z]+/i", "", $column) . count($columns);
return $columns[$column] = $name;
} | php | {
"resource": ""
} |
q242864 | LuaScriptBuilder.buildCondition | validation | public function buildCondition($condition, &$columns)
{
static $builders = [
'not' => 'buildNotCondition',
'and' => 'buildAndCondition',
'or' => 'buildAndCondition',
'between' => 'buildBetweenCondition',
'not between' => 'buildBetweenCondition',
'in' => 'buildInCondition',
'not in' => 'buildInCondition',
'like' => 'buildLikeCondition',
'not like' => 'buildLikeCondition',
'or like' => 'buildLikeCondition',
'or not like' => 'buildLikeCondition',
'>' => 'buildCompareCondition',
'>=' => 'buildCompareCondition',
'<' => 'buildCompareCondition',
'<=' => 'buildCompareCondition',
];
if (!is_array($condition)) {
throw new NotSupportedException('Where condition must be an array in redis ActiveRecord.');
}
if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
$operator = strtolower($condition[0]);
if (isset($builders[$operator])) {
$method = $builders[$operator];
array_shift($condition);
return $this->$method($operator, $condition, $columns);
} else {
throw new Exception('Found unknown operator in query: ' . $operator);
}
} else { // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
return $this->buildHashCondition($condition, $columns);
}
} | php | {
"resource": ""
} |
q242865 | Mutex.releaseLock | validation | protected function releaseLock($name)
{
static $releaseLuaScript = <<<LUA
if redis.call("GET",KEYS[1])==ARGV[1] then
return redis.call("DEL",KEYS[1])
else
return 0
end
LUA;
if (!isset($this->_lockValues[$name]) || !$this->redis->executeCommand('EVAL', [
$releaseLuaScript,
1,
$this->calculateKey($name),
$this->_lockValues[$name]
])) {
return false;
} else {
unset($this->_lockValues[$name]);
return true;
}
} | php | {
"resource": ""
} |
q242866 | ActiveRecord.updateAllCounters | validation | public static function updateAllCounters($counters, $condition = null)
{
if (empty($counters)) {
return 0;
}
$db = static::getDb();
$n = 0;
foreach (self::fetchPks($condition) as $pk) {
$key = static::keyPrefix() . ':a:' . static::buildKey($pk);
foreach ($counters as $attribute => $value) {
$db->executeCommand('HINCRBY', [$key, $attribute, $value]);
}
$n++;
}
return $n;
} | php | {
"resource": ""
} |
q242867 | ActiveRecord.buildKey | validation | public static function buildKey($key)
{
if (is_numeric($key)) {
return $key;
} elseif (is_string($key)) {
return ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key);
} elseif (is_array($key)) {
if (count($key) == 1) {
return self::buildKey(reset($key));
}
ksort($key); // ensure order is always the same
$isNumeric = true;
foreach ($key as $value) {
if (!is_numeric($value)) {
$isNumeric = false;
}
}
if ($isNumeric) {
return implode('-', $key);
}
}
return md5(json_encode($key, JSON_NUMERIC_CHECK));
} | php | {
"resource": ""
} |
q242868 | MultiLogger.useFiles | validation | public function useFiles($path, $level = 'debug')
{
foreach ($this->loggers as $logger) {
if ($logger instanceof Log) {
$logger->useFiles($path, $level);
}
}
} | php | {
"resource": ""
} |
q242869 | MultiLogger.useDailyFiles | validation | public function useDailyFiles($path, $days = 0, $level = 'debug')
{
foreach ($this->loggers as $logger) {
if ($logger instanceof Log) {
$logger->useDailyFiles($path, $days, $level);
}
}
} | php | {
"resource": ""
} |
q242870 | MultiLogger.getMonolog | validation | public function getMonolog()
{
foreach ($this->loggers as $logger) {
if (is_callable([$logger, 'getMonolog'])) {
$monolog = $logger->getMonolog();
if ($monolog === null) {
continue;
}
return $monolog;
}
}
} | php | {
"resource": ""
} |
q242871 | LaravelResolver.resolve | validation | public function resolve()
{
$request = $this->app->make(Request::class);
if ($this->app->runningInConsole()) {
$command = $request->server('argv', []);
if (!is_array($command)) {
$command = explode(' ', $command);
}
return new ConsoleRequest($command);
}
return new LaravelRequest($request);
} | php | {
"resource": ""
} |
q242872 | LaravelRequest.getMetaData | validation | public function getMetaData()
{
$data = [];
$data['url'] = $this->request->fullUrl();
$data['httpMethod'] = $this->request->getMethod();
$data['params'] = $this->request->input();
$data['clientIp'] = $this->request->getClientIp();
if ($agent = $this->request->header('User-Agent')) {
$data['userAgent'] = $agent;
}
if ($headers = $this->request->headers->all()) {
$data['headers'] = $headers;
}
return ['request' => $data];
} | php | {
"resource": ""
} |
q242873 | EventTrait.log | validation | public function log($level, $message, array $context = [])
{
parent::log($level, $message, $context);
$this->fireLogEvent($level, $message, $context);
} | php | {
"resource": ""
} |
q242874 | EventTrait.fireLogEvent | validation | protected function fireLogEvent($level, $message, array $context = [])
{
// If the event dispatcher is set, we will pass along the parameters to the
// log listeners. These are useful for building profilers or other tools
// that aggregate all of the log messages for a given "request" cycle.
if (!isset($this->dispatcher)) {
return;
}
if (class_exists(MessageLogged::class)) {
$this->dispatcher->dispatch(new MessageLogged($level, $message, $context));
} else {
$this->dispatcher->fire('illuminate.log', compact('level', 'message', 'context'));
}
} | php | {
"resource": ""
} |
q242875 | AuthServiceProvider.boot | validation | public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
$this->app['auth']->viaRequest('api', function ($request) {
if ($request->input('api_token')) {
return User::where('api_token', $request->input('api_token'))->first();
}
});
} | php | {
"resource": ""
} |
q242876 | BugsnagServiceProvider.setupEvents | validation | protected function setupEvents(Dispatcher $events, array $config)
{
if (isset($config['auto_capture_sessions']) && $config['auto_capture_sessions']) {
$events->listen(RouteMatched::class, function ($event) {
$this->app->bugsnag->getSessionTracker()->startSession();
});
}
if (isset($config['query']) && !$config['query']) {
return;
}
$show = isset($config['bindings']) && $config['bindings'];
if (class_exists(QueryExecuted::class)) {
$events->listen(QueryExecuted::class, function (QueryExecuted $query) use ($show) {
$this->app->bugsnag->leaveBreadcrumb(
'Query executed',
Breadcrumb::PROCESS_TYPE,
$this->formatQuery($query->sql, $show ? $query->bindings : [], $query->time, $query->connectionName)
);
});
} else {
$events->listen('illuminate.query', function ($sql, array $bindings, $time, $connection) use ($show) {
$this->app->bugsnag->leaveBreadcrumb(
'Query executed',
Breadcrumb::PROCESS_TYPE,
$this->formatQuery($sql, $show ? $bindings : [], $time, $connection)
);
});
}
} | php | {
"resource": ""
} |
q242877 | BugsnagServiceProvider.formatQuery | validation | protected function formatQuery($sql, array $bindings, $time, $connection)
{
$data = ['sql' => $sql];
foreach ($bindings as $index => $binding) {
$data["binding {$index}"] = $binding;
}
$data['time'] = "{$time}ms";
$data['connection'] = $connection;
return $data;
} | php | {
"resource": ""
} |
q242878 | BugsnagServiceProvider.setupQueue | validation | protected function setupQueue(QueueManager $queue)
{
$queue->looping(function () {
$this->app->bugsnag->flush();
$this->app->bugsnag->clearBreadcrumbs();
$this->app->make(Tracker::class)->clear();
});
if (!class_exists(JobProcessing::class)) {
return;
}
$queue->before(function (JobProcessing $event) {
$this->app->bugsnag->setFallbackType('Queue');
$job = [
'name' => $event->job->getName(),
'queue' => $event->job->getQueue(),
'attempts' => $event->job->attempts(),
'connection' => $event->connectionName,
];
if (method_exists($event->job, 'resolveName')) {
$job['resolved'] = $event->job->resolveName();
}
$this->app->make(Tracker::class)->set($job);
});
} | php | {
"resource": ""
} |
q242879 | BugsnagServiceProvider.getGuzzle | validation | protected function getGuzzle(array $config)
{
$options = [];
if (isset($config['proxy']) && $config['proxy']) {
if (isset($config['proxy']['http']) && php_sapi_name() != 'cli') {
unset($config['proxy']['http']);
}
$options['proxy'] = $config['proxy'];
}
return Client::makeGuzzle(isset($config['endpoint']) ? $config['endpoint'] : null, $options);
} | php | {
"resource": ""
} |
q242880 | BugsnagServiceProvider.setupCallbacks | validation | protected function setupCallbacks(Client $client, Container $app, array $config)
{
if (!isset($config['callbacks']) || $config['callbacks']) {
$client->registerDefaultCallbacks();
$client->registerCallback(function (Report $report) use ($app) {
$tracker = $app->make(Tracker::class);
if ($context = $tracker->context()) {
$report->setContext($context);
}
if ($job = $tracker->get()) {
$report->setMetaData(['job' => $job]);
}
});
}
if (!isset($config['user']) || $config['user']) {
$client->registerCallback(new CustomUser(function () use ($app) {
if ($user = $app->auth->user()) {
if (method_exists($user, 'attributesToArray') && is_callable([$user, 'attributesToArray'])) {
return $user->attributesToArray();
}
if ($user instanceof GenericUser) {
$reflection = new ReflectionClass($user);
$property = $reflection->getProperty('attributes');
$property->setAccessible(true);
return $property->getValue($user);
}
}
}));
}
} | php | {
"resource": ""
} |
q242881 | BugsnagServiceProvider.setupPaths | validation | protected function setupPaths(Client $client, $base, $path, $strip, $project)
{
if ($strip) {
$client->setStripPath($strip);
if (!$project) {
$client->setProjectRoot("{$strip}/app");
}
return;
}
if ($project) {
if ($base && substr($project, 0, strlen($base)) === $base) {
$client->setStripPath($base);
}
$client->setProjectRoot($project);
return;
}
$client->setStripPath($base);
$client->setProjectRoot($path);
} | php | {
"resource": ""
} |
q242882 | BugsnagServiceProvider.setupSessionTracking | validation | protected function setupSessionTracking(Client $client, $endpoint, $events)
{
$client->setAutoCaptureSessions(true);
if (!is_null($endpoint)) {
$client->setSessionEndpoint($endpoint);
}
$sessionTracker = $client->getSessionTracker();
$sessionStorage = function ($session = null) {
if (is_null($session)) {
return session('bugsnag-session', []);
} else {
session(['bugsnag-session' => $session]);
}
};
$sessionTracker->setSessionFunction($sessionStorage);
$cache = $this->app->cache;
$genericStorage = function ($key, $value = null) use ($cache) {
if (is_null($value)) {
return $cache->get($key, null);
} else {
$cache->put($key, $value, 60);
}
};
$sessionTracker->setStorageFunction($genericStorage);
} | php | {
"resource": ""
} |
q242883 | CoordinateFactory.fromString | validation | public static function fromString(string $string, Ellipsoid $ellipsoid = null): Coordinate
{
$string = self::mergeSecondsToMinutes($string);
$result = self::parseDecimalMinutesWithoutCardinalLetters($string, $ellipsoid);
if ($result instanceof Coordinate) {
return $result;
}
$result = self::parseDecimalMinutesWithCardinalLetters($string, $ellipsoid);
if ($result instanceof Coordinate) {
return $result;
}
$result = self::parseDecimalDegreesWithoutCardinalLetters($string, $ellipsoid);
if ($result instanceof Coordinate) {
return $result;
}
$result = self::parseDecimalDegreesWithCardinalLetters($string, $ellipsoid);
if ($result instanceof Coordinate) {
return $result;
}
throw new InvalidArgumentException('Format of coordinates was not recognized');
} | php | {
"resource": ""
} |
q242884 | Bounds.getCenter | validation | public function getCenter(): Coordinate
{
$centerLat = ($this->getNorth() + $this->getSouth()) / 2;
return new Coordinate($centerLat, $this->getCenterLng());
} | php | {
"resource": ""
} |
q242885 | SimplifyBearing.simplify | validation | public function simplify(Polyline $polyline): Polyline
{
$counterPoints = $polyline->getNumberOfPoints();
if ($counterPoints < 3) {
return clone $polyline;
}
$result = new Polyline();
$bearingCalc = new BearingEllipsoidal();
$points = $polyline->getPoints();
$index = 0;
// add the first point to the resulting polyline
$result->addPoint($points[$index]);
do {
$index++;
// preserve the last point of the original polyline
if ($index === ($counterPoints - 1)) {
$result->addPoint($points[$index]);
break;
}
$bearing1 = $bearingCalc->calculateBearing($points[$index - 1], $points[$index]);
$bearing2 = $bearingCalc->calculateBearing($points[$index], $points[$index + 1]);
$bearingDifference = min(
fmod($bearing1 - $bearing2 + 360, 360),
fmod($bearing2 - $bearing1 + 360, 360)
);
if ($bearingDifference > $this->bearingAngle) {
$result->addPoint($points[$index]);
}
} while ($index < $counterPoints);
return $result;
} | php | {
"resource": ""
} |
q242886 | Coordinate.getDistance | validation | public function getDistance(Coordinate $coordinate, DistanceInterface $calculator): float
{
return $calculator->getDistance($this, $coordinate);
} | php | {
"resource": ""
} |
q242887 | Polyline.getLength | validation | public function getLength(DistanceInterface $calculator): float
{
$distance = 0.0;
if (count($this->points) <= 1) {
return $distance;
}
foreach ($this->getSegments() as $segment) {
$distance += $segment->getLength($calculator);
}
return $distance;
} | php | {
"resource": ""
} |
q242888 | BearingSpherical.calculateBearing | validation | public function calculateBearing(Coordinate $point1, Coordinate $point2): float
{
$lat1 = deg2rad($point1->getLat());
$lat2 = deg2rad($point2->getLat());
$lng1 = deg2rad($point1->getLng());
$lng2 = deg2rad($point2->getLng());
$y = sin($lng2 - $lng1) * cos($lat2);
$x = cos($lat1) * sin($lat2) - sin($lat1) * cos($lat2) * cos($lng2 - $lng1);
$bearing = rad2deg(atan2($y, $x));
if ($bearing < 0) {
$bearing = fmod($bearing + 360, 360);
}
return $bearing;
} | php | {
"resource": ""
} |
q242889 | BearingSpherical.calculateFinalBearing | validation | public function calculateFinalBearing(Coordinate $point1, Coordinate $point2): float
{
$initialBearing = $this->calculateBearing($point2, $point1);
return fmod($initialBearing + 180, 360);
} | php | {
"resource": ""
} |
q242890 | Polygon.getLats | validation | public function getLats(): array
{
$lats = [];
foreach ($this->points as $point) {
/** @var Coordinate $point */
$lats[] = $point->getLat();
}
return $lats;
} | php | {
"resource": ""
} |
q242891 | Polygon.getLngs | validation | public function getLngs(): array
{
$lngs = [];
foreach ($this->points as $point) {
/** @var Coordinate $point */
$lngs[] = $point->getLng();
}
return $lngs;
} | php | {
"resource": ""
} |
q242892 | Polygon.containsGeometry | validation | public function containsGeometry(GeometryInterface $geometry): bool
{
$geometryInPolygon = true;
foreach ($geometry->getPoints() as $point) {
$geometryInPolygon = $geometryInPolygon && $this->contains($point);
}
return $geometryInPolygon;
} | php | {
"resource": ""
} |
q242893 | Polygon.getPerimeter | validation | public function getPerimeter(DistanceInterface $calculator): float
{
$perimeter = 0.0;
if (count($this->points) < 2) {
return $perimeter;
}
foreach ($this->getSegments() as $segment) {
$perimeter += $segment->getLength($calculator);
}
return $perimeter;
} | php | {
"resource": ""
} |
q242894 | Polygon.getArea | validation | public function getArea(): float
{
$area = 0;
if ($this->getNumberOfPoints() <= 2) {
return $area;
}
$referencePoint = $this->points[0];
$radius = $referencePoint->getEllipsoid()->getArithmeticMeanRadius();
$segments = $this->getSegments();
foreach ($segments as $segment) {
/** @var Coordinate $point1 */
$point1 = $segment->getPoint1();
/** @var Coordinate $point2 */
$point2 = $segment->getPoint2();
$x1 = deg2rad($point1->getLng() - $referencePoint->getLng()) * cos(deg2rad($point1->getLat()));
$y1 = deg2rad($point1->getLat() - $referencePoint->getLat());
$x2 = deg2rad($point2->getLng() - $referencePoint->getLng()) * cos(deg2rad($point2->getLat()));
$y2 = deg2rad($point2->getLat() - $referencePoint->getLat());
$area += ($x2 * $y1 - $x1 * $y2);
}
$area *= 0.5 * $radius ** 2;
return (float)abs($area);
} | php | {
"resource": ""
} |
q242895 | Polygon.getReverse | validation | public function getReverse(): Polygon
{
$reversed = new static();
foreach (array_reverse($this->points) as $point) {
$reversed->addPoint($point);
}
return $reversed;
} | php | {
"resource": ""
} |
q242896 | Client.handleConnectedSocks | validation | public function handleConnectedSocks(ConnectionInterface $stream, $host, $port, Deferred $deferred, $uri)
{
$reader = new StreamReader();
$stream->on('data', array($reader, 'write'));
$stream->on('error', $onError = function (Exception $e) use ($deferred, $uri) {
$deferred->reject(new RuntimeException(
'Connection to ' . $uri . ' failed because connection to proxy caused a stream error (EIO)',
defined('SOCKET_EIO') ? SOCKET_EIO : 5, $e)
);
});
$stream->on('close', $onClose = function () use ($deferred, $uri) {
$deferred->reject(new RuntimeException(
'Connection to ' . $uri . ' failed because connection to proxy was lost while waiting for response from proxy (ECONNRESET)',
defined('SOCKET_ECONNRESET') ? SOCKET_ECONNRESET : 104)
);
});
if ($this->protocolVersion === 5) {
$promise = $this->handleSocks5($stream, $host, $port, $reader, $uri);
} else {
$promise = $this->handleSocks4($stream, $host, $port, $reader, $uri);
}
$promise->then(function () use ($deferred, $stream, $reader, $onError, $onClose) {
$stream->removeListener('data', array($reader, 'write'));
$stream->removeListener('error', $onError);
$stream->removeListener('close', $onClose);
$deferred->resolve($stream);
}, function (Exception $error) use ($deferred, $stream, $uri) {
// pass custom RuntimeException through as-is, otherwise wrap in protocol error
if (!$error instanceof RuntimeException) {
$error = new RuntimeException(
'Connection to ' . $uri . ' failed because proxy returned invalid response (EBADMSG)',
defined('SOCKET_EBADMSG') ? SOCKET_EBADMSG: 71,
$error
);
}
$deferred->reject($error);
$stream->close();
});
} | php | {
"resource": ""
} |
q242897 | Conversation.add | validation | public function add($message)
{
if (is_string($message)) {
$this->messages[] = new SimpleResponse($message);
} elseif ($message instanceof ResponseInterface) {
$this->messages[] = $message;
} elseif ($message instanceof QuestionInterface) {
$this->messages[] = $message;
}
return $this;
} | php | {
"resource": ""
} |
q242898 | Arguments.get | validation | public function get($name)
{
foreach ($this->arguments as $argument) {
if ($argument['name'] == $name) {
if (isset($this->mapArgumentName[$name])) {
return $this->{$this->mapArgumentName[$name]}($argument);
} else {
return $argument;
}
}
}
} | php | {
"resource": ""
} |
q242899 | Arguments.getDateTime | validation | private function getDateTime($argument)
{
$datetimeValue = $argument['datetimeValue'];
$year = $datetimeValue['date']['year'];
$month = $datetimeValue['date']['month'];
$day = $datetimeValue['date']['day'];
$hours = $datetimeValue['time']['hours'];
$minutes = isset($datetimeValue['time']['minutes']) ? $datetimeValue['time']['minutes'] : 0;
return Carbon::create($year, $month, $day, $hours, $minutes, 0);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.