_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q7100 | EntityLoaderPresenterTrait.storeRequest | train | public function storeRequest($request = null, $expiration = '+ 10 minutes'): string
{
// Both parameters are optional.
if ($request === null) {
$request = $this->getRequest();
} elseif (!$request instanceof Request) {
$expiration = $request;
$request = $this->getRequest();
}
assert($request instanceof Request);
$request = clone $request;
$this->unloader->filterOut($request);
$session = $this->getSession('Arachne.Application/requests');
do {
$key = Random::generate(5);
} while (isset($session[$key]));
$session[$key] = [$this->user !== null ? $this->user->getId() : null, $request];
$session->setExpiration($expiration, $key);
return $key;
} | php | {
"resource": ""
} |
q7101 | EntityLoaderPresenterTrait.restoreRequest | train | public function restoreRequest($key): void
{
$session = $this->getSession('Arachne.Application/requests');
if (!isset($session[$key]) || ($this->user !== null && $session[$key][0] !== null && $session[$key][0] !== $this->user->getId())) {
return;
}
$request = clone $session[$key][1];
unset($session[$key]);
try {
$this->loader->filterIn($request);
} catch (BadRequestException $e) {
return;
}
$request->setFlag(Request::RESTORED, true);
$parameters = $request->getParameters();
$parameters[self::FLASH_KEY] = $this->getParameter(self::FLASH_KEY);
$request->setParameters($parameters);
$this->sendResponse(new ForwardResponse($request));
} | php | {
"resource": ""
} |
q7102 | Builder.build | train | public function build()
{
$client = $this->buildClient();
$requestHandler = $this->getRequestHandler();
// Pass through any configuration options set here which need to be made
// available elsewhere in the ThisData instance.
$configuration = [
self::CONF_EXPECT_JS_COOKIE => $this->expectJsCookie
];
return new ThisData($client, $requestHandler, $configuration);
} | php | {
"resource": ""
} |
q7103 | Context.translate | train | public function translate($key, $dictionaryName = null) {
//If a dictionary name is specified,
if(null !== $dictionaryName) {
// Use the nearest dictionary by this name,
// in current file upwards.
$dictionary = $this->getDictionary($dictionaryName);
if (null == $dictionary) {
throw new DictionaryNotFoundException($dictionaryName, $this->getFilename(), $this->tag->getLineNumber());
}
try {
return $dictionary->translate($key);
} catch (DictionaryEntryNotFoundException $ex) {
$ex->setDictionaryName($dictionaryName);
$ex->setTemplateFile($this->getFilename(), $this->tag->getLineNumber());
throw $ex;
}
}
//Walk the array of dictionaries, to try the lookup in all of them.
foreach($this->dictionaries[count($this->dictionaries) - 1] as $dictionary) {
try {
return $dictionary->translate($key);
} catch(DictionaryEntryNotFoundException $ex) {
// It is perfectly legitimate to not find a key in the first few registered dictionaries.
// But if in the end, we still didn't find a translation, it will be time to
// throw the exception.
}
}
throw new DictionaryEntryNotFoundException($key, $this->getFilename(), $this->tag->getLineNumber());
} | php | {
"resource": ""
} |
q7104 | PhpReports.getMailTransport | train | protected static function getMailTransport() {
if(!isset(PhpReports::$config['mail_settings'])) PhpReports::$config['mail_settings'] = array();
if(!isset(PhpReports::$config['mail_settings']['method'])) PhpReports::$config['mail_settings']['method'] = 'mail';
switch(PhpReports::$config['mail_settings']['method']) {
case 'mail':
return Swift_MailTransport::newInstance();
case 'sendmail':
return Swift_MailTransport::newInstance(
isset(PhpReports::$config['mail_settings']['command'])? PhpReports::$config['mail_settings']['command'] : '/usr/sbin/sendmail -bs'
);
case 'smtp':
if(!isset(PhpReports::$config['mail_settings']['server'])) throw new Exception("SMTP server must be configured");
$transport = Swift_SmtpTransport::newInstance(
PhpReports::$config['mail_settings']['server'],
isset(PhpReports::$config['mail_settings']['port'])? PhpReports::$config['mail_settings']['port'] : 25
);
//if username/password
if(isset(PhpReports::$config['mail_settings']['username'])) {
$transport->setUsername(PhpReports::$config['mail_settings']['username']);
$transport->setPassword(PhpReports::$config['mail_settings']['password']);
}
//if using encryption
if(isset(PhpReports::$config['mail_settings']['encryption'])) {
$transport->setEncryption(PhpReports::$config['mail_settings']['encryption']);
}
return $transport;
default:
throw new Exception("Mail method must be either 'mail', 'sendmail', or 'smtp'");
}
} | php | {
"resource": ""
} |
q7105 | AbstractEndpoint.findValue | train | protected function findValue($key, $pool, $default = null)
{
if (is_null($pool)) {
return $default;
} else {
return array_key_exists($key, $pool) ? $pool[$key] : $default;
}
} | php | {
"resource": ""
} |
q7106 | AbstractEndpoint.synchronousExecute | train | protected function synchronousExecute($method, $verb, array $data = [])
{
$request = new Request($method, $verb, [], $this->serialize($data));
$response = $this->client->send($request);
return $response;
} | php | {
"resource": ""
} |
q7107 | TypeUtil.resolveObjectType | train | public static function resolveObjectType(Endpoint $endpoint, $object): ?string
{
if ($object instanceof PolymorphicObjectInterface && $object->getConcreteType()) {
return $object->getConcreteType();
}
$class = DoctrineClassUtils::getClass($object);
if (!$endpoint->hasTypeForClass($class)) {
return null;
}
$types = $endpoint->getTypesForClass($class);
//if only one type for given object class return the type
if (count($types) === 1) {
return $types[0];
}
//in case of multiple types using polymorphic definitions
foreach ($types as $type) {
$definition = $endpoint->getType($type);
if ($definition instanceof PolymorphicDefinitionInterface) {
return self::resolveConcreteType($endpoint, $definition, $object);
}
}
//as fallback use the first type in the list
return $types[0];
} | php | {
"resource": ""
} |
q7108 | TypeUtil.resolveConcreteType | train | public static function resolveConcreteType(Endpoint $endpoint, PolymorphicDefinitionInterface $definition, $object)
{
//if discriminator map is set is used to get the value type
if ($map = $definition->getDiscriminatorMap()) {
//get concrete type based on property
if ($definition->getDiscriminatorProperty()) {
$property = $definition->getDiscriminatorProperty();
$accessor = new PropertyAccessor();
$propValue = $accessor->getValue($object, $property);
$resolvedType = $map[$propValue] ?? null;
}
//get concrete type based on class
if (!$resolvedType) {
$class = DoctrineClassUtils::getClass($object);
$resolvedType = $map[$class] ?? null;
}
}
//final solution in case of not mapping is guess type based on class
if (!$resolvedType && $definition instanceof InterfaceDefinition) {
foreach ($definition->getImplementors() as $implementor) {
$implementorDef = $endpoint->getType($implementor);
if ($implementorDef instanceof ClassAwareDefinitionInterface
&& $implementorDef->getClass() === DoctrineClassUtils::getClass($object)) {
$resolvedType = $implementorDef->getName();
}
}
}
if ($endpoint->hasType($resolvedType)) {
$resolvedTypeDefinition = $endpoint->getType($resolvedType);
if ($resolvedTypeDefinition instanceof PolymorphicDefinitionInterface) {
$resolvedType = self::resolveConcreteType($endpoint, $resolvedTypeDefinition, $object);
}
}
return $resolvedType;
} | php | {
"resource": ""
} |
q7109 | Theme.showByType | train | public function showByType(Selector $listener, string $type)
{
if (! in_array($type, $this->type)) {
return $listener->themeFailedVerification();
}
$current = $this->memory->get("site.theme.{$type}");
$themes = $this->getAvailableTheme($type);
return $listener->showThemeSelection(compact('current', 'themes', 'type'));
} | php | {
"resource": ""
} |
q7110 | Theme.activate | train | public function activate(Selector $listener, string $type, string $id)
{
$theme = $this->getAvailableTheme($type)->get($id);
if (! in_array($type, $this->type) || is_null($theme)) {
return $listener->themeFailedVerification();
}
$this->memory->put("site.theme.{$type}", $id);
return $listener->themeHasActivated($type, $id);
} | php | {
"resource": ""
} |
q7111 | Theme.getAvailableTheme | train | protected function getAvailableTheme(string $type): Collection
{
$themes = $this->foundation->make('orchestra.theme.finder')->detect();
return $themes->filter(function ($manifest) use ($type) {
if (! empty($manifest->type) && ! in_array($type, $manifest->type)) {
return null;
}
return $manifest;
});
} | php | {
"resource": ""
} |
q7112 | JSONBuilder.object | train | public static function object(\Closure $callback) {
$obj = new Object;
$callback->__invoke($obj);
return json_encode($obj);
} | php | {
"resource": ""
} |
q7113 | AllNodesWithPagination.applyFilters | train | protected function applyFilters(QueryBuilder $qb, array $filters)
{
$definition = $this->objectDefinition;
foreach ($filters as $field => $value) {
if (!$definition->hasField($field) || !$prop = $definition->getField($field)->getOriginName()) {
continue;
}
$entityField = sprintf('%s.%s', $this->queryAlias, $prop);
switch (gettype($value)) {
case 'string':
$qb->andWhere($qb->expr()->eq($entityField, $qb->expr()->literal($value)));
break;
case 'integer':
case 'double':
$qb->andWhere($qb->expr()->eq($entityField, $value));
break;
case 'boolean':
$qb->andWhere($qb->expr()->eq($entityField, (int) $value));
break;
case 'array':
if (empty($value)) {
$qb->andWhere($qb->expr()->isNull($entityField));
} else {
$qb->andWhere($qb->expr()->in($entityField, $value));
}
break;
case 'NULL':
$qb->andWhere($qb->expr()->isNull($entityField));
break;
}
}
} | php | {
"resource": ""
} |
q7114 | Alias.isMetaField | train | protected function isMetaField($strField)
{
$strField = \trim($strField);
if (\in_array($strField, $this->getMetaModelsSystemColumns())) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q7115 | AdminController.save | train | public function save(Request $request, FileUploader $fileUploader)
{
$data = $request->except('_token');
if ($request->hasFile('image')) {
$file = $fileUploader->handle($request->file('image'), 'settings');
$this->deleteImage();
$data['image'] = $file['filename'];
}
foreach ($data as $group_name => $array) {
if (!is_array($array)) {
$array = [$group_name => $array];
$group_name = 'config';
}
foreach ($array as $key_name => $value) {
$model = Setting::firstOrCreate(['key_name' => $key_name, 'group_name' => $group_name]);
$model->value = $value;
$model->save();
$this->repository->forgetCache();
}
}
return redirect()->route('admin::index-settings');
} | php | {
"resource": ""
} |
q7116 | AdminController.deleteImage | train | public function deleteImage()
{
if ($filename = Setting::where('key_name', 'image')->value('value')) {
try {
Croppa::delete('storage/settings/'.$filename);
} catch (Exception $e) {
Log::info($e->getMessage());
}
}
Setting::where('key_name', 'image')->delete();
$this->repository->forgetCache();
} | php | {
"resource": ""
} |
q7117 | ListCommand.doExecute | train | protected function doExecute(InputInterface $input, OutputInterface $output): int
{
$descriptor = new DescriptorHelper;
$this->getHelperSet()->set($descriptor);
$descriptor->describe(
$output,
$this->getApplication(),
[
'namespace' => $input->getArgument('namespace'),
]
);
return 0;
} | php | {
"resource": ""
} |
q7118 | Item.isVisible | train | public function isVisible(): bool
{
if (!empty($this->item['permission'])) {
return $this->vault->getGuard()->allows($this->item['permission']);
}
//Remove :action
$target = current(explode(':', $this->getTarget()));
return $this->vault->getGuard()->allows(
"{$this->vault->getConfig()->guardNamespace()}.{$target}"
);
} | php | {
"resource": ""
} |
q7119 | Transaction.runQuery | train | function runQuery(\Plasma\QueryBuilderInterface $query): \React\Promise\PromiseInterface {
if($this->driver === null) {
throw new \Plasma\TransactionException('Transaction has been committed or rolled back');
}
return $this->driver->runQuery($this->client, $query);
} | php | {
"resource": ""
} |
q7120 | Transaction.commit | train | function commit(): \React\Promise\PromiseInterface {
return $this->query('COMMIT')->then(function () {
$this->driver->endTransaction();
$this->client->checkinConnection($this->driver);
$this->driver = null;
});
} | php | {
"resource": ""
} |
q7121 | Transaction.createSavepoint | train | function createSavepoint(string $identifier): \React\Promise\PromiseInterface {
return $this->query('SAVEPOINT '.$this->quote($identifier));
} | php | {
"resource": ""
} |
q7122 | ApplicationErrorEvent.getExitCode | train | public function getExitCode(): int
{
return $this->exitCode ?: (\is_int($this->error->getCode()) && $this->error->getCode() !== 0 ? $this->error->getCode() : 1);
} | php | {
"resource": ""
} |
q7123 | DatabaseContext.shouldExistInTableARecordMatching | train | public function shouldExistInTableARecordMatching($table, YamlStringNode $criteria)
{
$count = $this->countRecordsInTableMatching($table, $criteria->toArray());
Assert::assertEquals(1, $count, sprintf('Does not exist any record in the database "%s" matching given conditions', $table));
} | php | {
"resource": ""
} |
q7124 | DatabaseContext.shouldExistInTableRecordsMatching | train | public function shouldExistInTableRecordsMatching($table, YamlStringNode $criteria)
{
foreach ($criteria->toArray() as $row) {
$count = $this->countRecordsInTableMatching($table, $row);
Assert::assertEquals(1, $count, sprintf('Does not exist any record in the database "%s" matching given conditions', $table));
}
} | php | {
"resource": ""
} |
q7125 | DatabaseContext.countRecordsInTableMatching | train | public function countRecordsInTableMatching($table, $criteria = []): int
{
$where = '';
foreach ($criteria as $field => $vale) {
if ($where) {
$where .= ' AND ';
}
if ($vale === null) {
$where .= sprintf('%s IS NULL', $field);
} else {
$where .= sprintf('%s = :%s', $field, $field);
}
}
$query = sprintf('SELECT count(*) AS records FROM %s WHERE %s', $table, $where);
/** @var EntityManager $manager */
$manager = $this->client->getContainer()->get('doctrine')->getManager();
$rsm = new ResultSetMapping();
$rsm->addScalarResult('records', 'records', 'integer');
$query = $manager->createNativeQuery($query, $rsm);
$query->setParameters($criteria);
return (int) $query->getSingleScalarResult();
} | php | {
"resource": ""
} |
q7126 | BackportedTranslator.loadLanguageFile | train | private function loadLanguageFile($name)
{
/** @var System $system */
$system = $this->framework->getAdapter(System::class);
$system->loadLanguageFile($name);
} | php | {
"resource": ""
} |
q7127 | LangArrayTranslator.loadDomain | train | protected function loadDomain($domain, $locale)
{
$event = new LoadLanguageFileEvent($domain, $locale);
$this->eventDispatcher->dispatch(ContaoEvents::SYSTEM_LOAD_LANGUAGE_FILE, $event);
} | php | {
"resource": ""
} |
q7128 | DeferredBuffer.getLoadedEntity | train | public function getLoadedEntity(NodeInterface $entity): NodeInterface
{
$class = ClassUtils::getClass($entity);
if (isset(self::$deferred[$class][$entity->getId()]) && self::$deferred[$class][$entity->getId()] instanceof NodeInterface) {
return self::$deferred[$class][$entity->getId()];
}
//fallback
return $entity;
} | php | {
"resource": ""
} |
q7129 | DeferredBuffer.loadBuffer | train | public function loadBuffer(): void
{
if (self::$loaded) {
return;
}
self::$loaded = true;
foreach (self::$deferred as $class => $ids) {
/** @var EntityRepository $repo */
$repo = $this->registry->getRepository($class);
$qb = $repo->createQueryBuilder('o', 'o.id');
$entities = $qb->where($qb->expr()->in('o.id', array_values($ids)))
->getQuery()
->getResult();
foreach ($entities as $entity) {
if ($entity instanceof NodeInterface) {
self::$deferred[$class][$entity->getId()] = $entity;
}
}
}
} | php | {
"resource": ""
} |
q7130 | Vault.uri | train | public function uri(string $target, $parameters = []): UriInterface
{
if (strpos($target, ':') !== false) {
list($controller, $action) = explode(':', $target);
} else {
$controller = $target;
$action = $parameters['action'] ?? null;
}
if (!$this->config->hasController($controller)) {
throw new VaultException("Unable to generate uri, undefined controller '{$controller}'");
}
return $this->route->withDefaults(compact('controller', 'action'))->uri($parameters);
} | php | {
"resource": ""
} |
q7131 | StepAggregator.buildPipeline | train | private function buildPipeline()
{
$nextCallable = function ($item) {
// the final callable is a no-op
};
foreach ($this->getStepsSortedDescByPriority() as $step) {
$nextCallable = function ($item) use ($step, $nextCallable) {
return $step->process($item, $nextCallable);
};
}
return $nextCallable;
} | php | {
"resource": ""
} |
q7132 | StepAggregator.getStepsSortedDescByPriority | train | private function getStepsSortedDescByPriority()
{
$steps = $this->steps;
// Use illogically large and small priorities
$steps[-255][] = new Step\ArrayCheckStep;
foreach ($this->writers as $writer) {
$steps[-256][] = new Step\WriterStep($writer);
}
krsort($steps);
$sortedStep = [];
/** @var Step[] $stepsAtSamePriority */
foreach ($steps as $stepsAtSamePriority) {
foreach ($stepsAtSamePriority as $step) {
$sortedStep[] = $step;
}
}
return array_reverse($sortedStep);
} | php | {
"resource": ""
} |
q7133 | RevisionAuditTool.close | train | public function close()
{
$userId = 0;
$userName = 'guest';
$userEmail = '';
if ($this->authenticationService) {
if ($this->authenticationService->getIdentity() instanceof OAuth2AuthenticatedIdentity) {
$user = $this->authenticationService->getIdentity()->getUser();
if (method_exists($user, 'getId')) {
$userId = $user->getId();
}
if (method_exists($user, 'getDisplayName')) {
$userName = $user->getDisplayName();
}
if (method_exists($user, 'getEmail')) {
$userEmail = $user->getEmail();
}
} elseif ($this->authenticationService->getIdentity() instanceof AuthenticatedIdentity) {
$userId = $this->authenticationService->getIdentity()->getAuthenticationIdentity()['user_id'];
$userName = $this->authenticationService->getIdentity()->getName();
} elseif ($this->authenticationService->getIdentity() instanceof GuestIdentity) {
} else {
// Is null or other identity
}
}
$query = $this->getObjectManager()
->createNativeQuery(
"
SELECT close_revision_audit(:userId, :userName, :userEmail, :comment)
",
new ResultSetMapping()
)
->setParameter('userId', $userId)
->setParameter('userName', $userName)
->setParameter('userEmail', $userEmail)
->setParameter('comment', $this->revisionComment->getComment());
;
$query->getResult();
// Reset the revision comment
$this->revisionComment->setComment('');
} | php | {
"resource": ""
} |
q7134 | Navigation.getSections | train | public function getSections(): \Generator
{
foreach ($this->vault->getConfig()->navigationSections() as $section) {
yield new Section($this->vault, $section);
}
} | php | {
"resource": ""
} |
q7135 | Uuid.createFromData | train | public static function createFromData($data, $upper = false): string
{
if (\is_array($data) || \is_object($data)) {
$data = serialize($data);
}
$hash = $upper ? strtoupper(md5($data)) : strtolower(md5($data));
return implode(
'-',
[
substr($hash, 0, 8),
substr($hash, 8, 4),
substr($hash, 12, 4),
substr($hash, 16, 4),
substr($hash, 20, 8),
]
);
} | php | {
"resource": ""
} |
q7136 | ParameterFinder.getMapping | train | public function getMapping(Request $request): array
{
return $this->cache->load($this->getCacheKey($request), function (&$dependencies) use ($request) {
return $this->loadMapping($request->getPresenterName(), $request->getParameters(), $dependencies);
});
} | php | {
"resource": ""
} |
q7137 | SiteTreePermissionIndexExtension.additionalSolrValues | train | public function additionalSolrValues() {
if(($this->owner->CanViewType === 'Inherit') && $this->owner->ParentID) {
// Recursively determine the site tree element permissions where required.
return $this->owner->Parent()->additionalSolrValues();
}
else if($this->owner->CanViewType === 'OnlyTheseUsers') {
// Return the listing of groups that have access.
$groups = array();
foreach($this->owner->ViewerGroups() as $group) {
$groups[] = (string)$group->ID;
}
return array(
$this->index => $groups
);
}
else if($this->owner->CanViewType === 'LoggedInUsers') {
// Return an appropriate flag for logged in access.
return array(
$this->index => array(
'logged-in'
)
);
}
else {
// Return an appropriate flag for general public access.
return array(
$this->index => array(
'anyone'
)
);
}
} | php | {
"resource": ""
} |
q7138 | SolrGeoExtension.getGeoSelectableFields | train | public function getGeoSelectableFields() {
$all = $this->owner->getSelectableFields(null, false);
$listTypes = $this->owner->searchableTypes('Page');
$geoFields = array();
foreach ($listTypes as $classType) {
$db = Config::inst()->get($classType, 'db');
foreach ($db as $name => $type) {
if (is_subclass_of($type, 'SolrGeoPoint') || $type == 'SolrGeoPoint') {
$geoFields[$name] = $name;
}
}
}
ksort($geoFields);
return $geoFields;
} | php | {
"resource": ""
} |
q7139 | MessageManager.image | train | public function image($file, $caption = null)
{
$this->messages[] = $this->media->compile($file, $caption, 'image');
} | php | {
"resource": ""
} |
q7140 | MessageManager.location | train | public function location($longitude, $latitude, $caption = null, $url = null)
{
$location = new stdClass();
$location->type = 'location';
$location->longitude = $longitude;
$location->latitude = $latitude;
$location->caption = $caption;
$location->url = $url;
$this->messages[] = $location;
} | php | {
"resource": ""
} |
q7141 | MessageManager.vcard | train | public function vcard($name, VCard $vcard)
{
$card = new stdClass();
$card->type = 'vcard';
$card->name = $name;
$card->vcard = $vcard;
$this->messages[] = $card;
} | php | {
"resource": ""
} |
q7142 | MessageManager.video | train | public function video($file, $caption = null)
{
$this->messages[] = $this->media->compile($file, $caption, 'video');
} | php | {
"resource": ""
} |
q7143 | MessageManager.transformMessages | train | public function transformMessages(array $messages)
{
$transformed = null;
if(count($messages))
{
$transformed = [];
foreach ($messages as $message)
{
$attributes = (object) $message->getAttributes();
$attributes->timestamp = $attributes->t;
unset($attributes->t);
// Add encryption check
$child = is_null($message->getChild(1)) ? $message->getChild(0) : $message->getChild(1);
$node = new stdClass();
$node->tag = $child->getTag();
$node->attributes = (object) $child->getAttributes();
$node->data = $child->getData();
$attributes->body = $node;
if($attributes->type == 'media')
{
if($attributes->body->attributes->type == 'vcard')
{
$vcard = new VCardReader(null, $child->getChild(0)->getData());
if(count($vcard) == 1)
{
$attributes->body->vcard[] = $vcard->parse($vcard);
}
else
{
foreach ($vcard as $card)
{
$attributes->body->vcard[] = $vcard->parse($card);
}
}
}
else
{
$tmp = $this->media->link($attributes);
$attributes->body->file = $tmp->file;
$attributes->body->html = $tmp->html;
$attributes->body->attributes2 = $node->attributes;
}
}
$transformed[] = $attributes;
}
}
return $transformed;
} | php | {
"resource": ""
} |
q7144 | CacheService.findCached | train | public function findCached(): array
{
$output = [];
$introspect = $this->introspection->introspect();
$tags = $this->introspection->findTags(CachedDataSource::class);
foreach ($tags as $tag) {
foreach ($tag as $key => $value) {
foreach ($introspect as $item) {
if ($item->tags['services']['subreport'] === $value) {
$output[] = [
'id' => $item->rid . '.' . $item->sid,
'report_id' => $item->rid,
'subreport_id' => $item->sid,
'report' => $item->tags['services']['report'],
'subreport' => $item->tags['services']['subreport'],
'key' => $item->tags['services']['subreport'],
'cache' => $item->tags['cache'],
];
}
}
}
}
return $output;
} | php | {
"resource": ""
} |
q7145 | CacheService.warmupSubreport | train | public function warmupSubreport(string $subreport): Resultable
{
$subreport = $this->introspection->getService($subreport);
if (!($subreport instanceof Subreport)) {
throw new InvalidStateException(sprintf('Service "%s" is not subreport', get_class($subreport)));
}
return $subreport->getDataSource()->compile($subreport->getParameters());
} | php | {
"resource": ""
} |
q7146 | TimeInterval.addDays | train | private function addDays($extraSpec)
{
if (preg_match('/(\d+)D$/', $extraSpec, $matches)) {
$days = end($matches);
$this->dateInterval = DateInterval::__set_state(
array(
'y' => $this->dateInterval->y,
'm' => $this->dateInterval->m,
'd' => $this->dateInterval->d,
'h' => $this->dateInterval->h,
'i' => $this->dateInterval->i,
's' => $this->dateInterval->s,
'invert' => $this->dateInterval->invert,
'days' => $days
)
);
}
} | php | {
"resource": ""
} |
q7147 | ControlledErrorManager.clear | train | public function clear(): void
{
$this->errors = [];
if (file_exists($this->cacheFileName())) {
@unlink($this->cacheFileName());
}
} | php | {
"resource": ""
} |
q7148 | Imgur.upload | train | public function upload($file, $format = 'json', $album = null, $name = null, $title = null, $description = null)
{
return $this->post('https://api.imgur.com/3/image.' . $format, array(
'image' => $file,
'album' => $album,
'name' => $name,
'title' => $title,
'description' => $description
), array(
'Authorization: Client-ID ' . $this->key
));
} | php | {
"resource": ""
} |
q7149 | FileSystemCache.store | train | public static function store(FileSystemCacheKey $key, $data, $ttl=null) {
$filename = $key->getFileName();
$data = new FileSystemCacheValue($key,$data,$ttl);
$fh = self::getFileHandle($filename,'c');
if(!$fh) return false;
if(!self::putContents($fh,$data)) return false;
return true;
} | php | {
"resource": ""
} |
q7150 | FileSystemCache.retrieve | train | public static function retrieve(FileSystemCacheKey $key, $newer_than=null) {
$filename = $key->getFileName();
if(!file_exists($filename)) return false;
//if cached data is not newer than $newer_than
if($newer_than && filemtime($filename) < $newer_than) return false;
$fh = self::getFileHandle($filename,'r');
if(!$fh) return false;
$data = self::getContents($fh,$key);
if(!$data) return false;
self::closeFile($fh);
return $data->value;
} | php | {
"resource": ""
} |
q7151 | FileSystemCache.getAndModify | train | public static function getAndModify(FileSystemCacheKey $key, \Closure $callback, $resetTtl=false) {
$filename = $key->getFileName();
if(!file_exists($filename)) return false;
//open a file handle
$fh = self::getFileHandle($filename,'c+');
if(!$fh) return false;
//get the data
$data = self::getContents($fh,$key);
if(!$data) return false;
//get new value from callback function
$old_value = $data->value;
$data->value = $callback($data->value);
//if the callback function returns false
if($data->value === false) {
self::closeFile($fh);
//delete the cache file
self::invalidate($key);
return false;
}
//if value didn't change
if(!$resetTtl && $data->value === $old_value) {
self::closeFile($fh);
return $data->value;
}
//if we're resetting the ttl to now
if($resetTtl) {
$data->created = time();
if($data->ttl) {
$data->expires = $data->created + $data->ttl;
}
}
if(!self::emptyFile($fh)) return false;
//write contents and close the file handle
self::putContents($fh,$data);
//return the new value after modifying
return $data->value;
} | php | {
"resource": ""
} |
q7152 | FileSystemCache.invalidate | train | public static function invalidate(FileSystemCacheKey $key) {
$filename = $key->getFileName();
if(file_exists($filename)) {
try{
unlink($filename);
} catch (\Exception $ex) {
}
}
return true;
} | php | {
"resource": ""
} |
q7153 | FileSystemCache.invalidateGroup | train | public static function invalidateGroup($name=null, $recursive=true) {
//if invalidating a group, make sure it's valid
if($name) {
//it needs to have a trailing slash and no leading slashes
$name = trim($name,'/').'/';
//make sure the key isn't going up a directory
if(strpos($name,'..') !== false) {
throw new Exception("Invalidate path cannot go up directories.");
}
}
array_map("unlink", glob(self::$cacheDir.'/'.$name.'*.cache'));
//if recursively invalidating
if($recursive) {
$subdirs = glob(self::$cacheDir.'/'.$name.'*',GLOB_ONLYDIR);
foreach($subdirs as $dir) {
$dir = basename($dir);
//skip all subdirectories that start with '.'
if($dir[0] == '.') continue;
self::invalidateGroup($name.$dir,true);
}
}
} | php | {
"resource": ""
} |
q7154 | FileSystemCache.getFileHandle | train | private static function getFileHandle($filename, $mode='c') {
$write = in_array($mode,array('c','c+'));
if($write) {
//make sure the directory exists and is writable
$directory = dirname($filename);
if(!file_exists($directory)) {
if(!mkdir($directory,0777,true)) {
return false;
}
}
elseif(!is_dir($directory)) {
return false;
}
elseif(!is_writable($directory)) {
return false;
}
}
//get file pointer
$fh = fopen($filename,$mode);
if(!$fh) return false;
//lock file with appropriate lock type
if($write) {
if(!flock($fh,LOCK_EX)) {
self::closeFile($fh);
return false;
}
}
else {
if(!flock($fh,LOCK_SH)) {
self::closeFile($fh);
return false;
}
}
return $fh;
} | php | {
"resource": ""
} |
q7155 | FileSystemCache.emptyFile | train | private static function emptyFile($fh) {
rewind($fh);
if(!ftruncate($fh,0)) {
//release lock
self::closeFile($fh);
return false;
}
else {
return true;
}
} | php | {
"resource": ""
} |
q7156 | FileSystemCache.getContents | train | private static function getContents($fh,FileSystemCacheKey $key) {
//get the existing file contents
$contents = stream_get_contents($fh);
$data = @unserialize($contents);
//if we can't unserialize the data or if the data is expired
if(!$data || !($data instanceof FileSystemCacheValue) || $data->isExpired()) {
//release lock
self::closeFile($fh);
//delete the cache file so we don't try to retrieve it again
self::invalidate($key);
return false;
}
return $data;
} | php | {
"resource": ""
} |
q7157 | FileSystemCache.putContents | train | private static function putContents($fh,FileSystemCacheValue $data) {
try{
fwrite($fh,serialize($data));
fflush($fh);
} catch (\Exception $ex){}
//release lock
self::closeFile($fh);
return true;
} | php | {
"resource": ""
} |
q7158 | DefinitionRegistry.getEndpoint | train | public function getEndpoint($name = self::DEFAULT_ENDPOINT): Endpoint
{
$endpoints = $this->endpointsConfig;
unset($endpoints[self::DEFAULT_ENDPOINT]);
$endpointsNames = array_keys($endpoints);
if (self::DEFAULT_ENDPOINT !== $name && !\in_array($name, $endpointsNames)) {
throw new EndpointNotValidException($name, $endpointsNames);
}
//use first static cache
if (isset(self::$endpoints[$name])) {
return self::$endpoints[$name];
}
//use file cache
self::$endpoints[$name] = $this->loadCache($name);
//retry after load from file
if (isset(self::$endpoints[$name]) && self::$endpoints[$name] instanceof Endpoint) {
return self::$endpoints[$name];
}
$this->initialize($name);
return self::$endpoints[$name];
} | php | {
"resource": ""
} |
q7159 | DefinitionRegistry.clearCache | train | public function clearCache($warmUp = false)
{
@unlink($this->cacheFileName('default.raw'));
foreach ($this->endpointsConfig as $name => $config) {
unset(self::$endpoints[$name]);
@unlink($this->cacheFileName($name));
if ($warmUp) {
$this->initialize($name);
}
}
} | php | {
"resource": ""
} |
q7160 | DefinitionRegistry.compile | train | protected function compile(Endpoint $endpoint): void
{
//run all extensions for each definition
foreach ($this->plugins as $plugin) {
//run extensions recursively in all types and fields
foreach ($endpoint->allTypes() as $type) {
$this->configureDefinition($plugin, $type, $endpoint);
if ($type instanceof FieldsAwareDefinitionInterface) {
foreach ($type->getFields() as $field) {
$this->configureDefinition($plugin, $field, $endpoint);
foreach ($field->getArguments() as $argument) {
$this->configureDefinition($plugin, $argument, $endpoint);
}
}
}
}
//run extension in all queries
foreach ($endpoint->allQueries() as $query) {
$this->configureDefinition($plugin, $query, $endpoint);
foreach ($query->getArguments() as $argument) {
$this->configureDefinition($plugin, $argument, $endpoint);
}
}
//run extensions in all mutations
foreach ($endpoint->allMutations() as $mutation) {
$this->configureDefinition($plugin, $mutation, $endpoint);
foreach ($mutation->getArguments() as $argument) {
$this->configureDefinition($plugin, $argument, $endpoint);
}
}
//run extensions in all subscriptions
foreach ($endpoint->allSubscriptions() as $subscription) {
$this->configureDefinition($plugin, $subscription, $endpoint);
foreach ($subscription->getArguments() as $argument) {
$this->configureDefinition($plugin, $argument, $endpoint);
}
}
$plugin->configureEndpoint($endpoint);
}
} | php | {
"resource": ""
} |
q7161 | Table.addColumn | train | public function addColumn($content, $columnIndex = null, $rowIndex = null)
{
$rowIndex = $rowIndex === null
? $this->rowIndex
: $rowIndex;
if ($columnIndex === null) {
$columnIndex = isset($this->rows[ $rowIndex ])
? count($this->rows[ $rowIndex ])
: 0;
}
$this->rows[ $rowIndex ][ $columnIndex ] = $content;
return $this;
} | php | {
"resource": ""
} |
q7162 | TagFigCdata.fig_cdata | train | private function fig_cdata(Context $context) {
$filename = $this->dataFile;
$realfilename = dirname($context->getFilename()).'/'.$filename;
if(! file_exists($realfilename)) {
$message = "File not found: $filename called from: " . $context->getFilename(). '(' . $this->xmlLineNumber . ')';
throw new FileNotFoundException($message, $filename);
}
$cdata = file_get_contents($realfilename);
return $cdata;
} | php | {
"resource": ""
} |
q7163 | HPack.resizeTable | train | public function resizeTable(int $maxSize = null) {
if ($maxSize !== null) {
$this->maxSize = $maxSize;
}
while ($this->size > $this->maxSize) {
list($name, $value) = \array_pop($this->headers);
$this->size -= 32 + \strlen($name) + \strlen($value);
}
} | php | {
"resource": ""
} |
q7164 | SchemaSnapshot.collapseType | train | private function collapseType(array $originDefinition): ?array
{
$definition = [];
if ($type = $originDefinition['type'] ?? null) {
$typeName = $type['name'];
if (!empty($type['ofType'] ?? [])) {
$typeName = $type['ofType']['name'];
$ofType = $type;
if (in_array($ofType['kind'], ['NON_NULL', 'LIST'])) {
$typeName = '%s';
while ($ofType) {
if ($ofType['kind'] === 'NON_NULL') {
$typeName = str_replace('%s', '%s!', $typeName);
} elseif ($ofType['kind'] === 'LIST') {
$typeName = str_replace('%s', '[%s]', $typeName);
} else {
$typeName = sprintf($typeName, $ofType['name']);
break;
}
$ofType = $ofType['ofType'] ?? null;
}
}
}
$definition['type'] = $typeName;
}
if ($fields = $originDefinition['fields'] ?? null) {
foreach ($fields as $field) {
$definition['fields'][$field['name']] = $this->collapseType($field);
}
}
if ($inputFields = $originDefinition['inputFields'] ?? null) {
foreach ($inputFields as $inputField) {
$definition['inputFields'][$inputField['name']] = $this->collapseType($inputField);
}
}
if ($args = $originDefinition['args'] ?? null) {
foreach ($args as $arg) {
$definition['args'][$arg['name']] = $this->collapseType($arg);
}
}
if ($possibleTypes = $originDefinition['possibleTypes'] ?? null) {
foreach ($possibleTypes as $possibleType) {
$definition['possibleTypes'][$possibleType['name']] = $this->collapseType($possibleType);
}
}
if ($interfaces = $originDefinition['interfaces'] ?? null) {
foreach ($interfaces as $interface) {
$definition['interfaces'][] = $interface['name'];
}
}
if ($enumValues = $originDefinition['enumValues'] ?? null) {
foreach ($enumValues as $enumValue) {
$definition['enumValues'][] = $enumValue['name'];
}
}
return empty($definition) ? null : $definition;
} | php | {
"resource": ""
} |
q7165 | AbstractInput.getDefinition | train | protected function getDefinition(): Definition
{
if (isset(self::$definitions[static::class])) {
return self::$definitions[static::class];
}
$definition = new Definition();
$this->buildDefinition($definition);
return self::$definitions[static::class] = $definition;
} | php | {
"resource": ""
} |
q7166 | AbstractMutationResolver.publicPropertyPath | train | private function publicPropertyPath(FormInterface $form, $path)
{
$pathArray = [$path];
if (strpos($path, '.') !== false) { // object.child.property
$pathArray = explode('.', $path);
}
if (strpos($path, '[') !== false) { //[array][child][property]
$path = str_replace(']', null, $path);
$pathArray = explode('[', $path);
}
if (in_array($pathArray[0], ['data', 'children'])) {
array_shift($pathArray);
}
$contextForm = $form;
foreach ($pathArray as &$propName) {
//for some reason some inputs are resolved as "inputName.data" or "inputName.children"
//because the original form property is children[inputName].data
//this is the case of DEMO AddUserInput form the login field is validated as path children[login].data
//the following statements remove the trailing ".data"
if (preg_match('/\.(data|children)$/', $propName)) {
$propName = preg_replace('/\.(data|children)/', null, $propName);
}
$index = null;
if (preg_match('/(\w+)(\[\d+\])$/', $propName, $matches)) {
list(, $propName, $index) = $matches;
}
if (!$contextForm->has($propName)) {
foreach ($contextForm->all() as $child) {
if ($child->getConfig()->getOption('property_path') === $propName) {
$propName = $child->getName();
}
}
}
if ($index) {
$propName = sprintf('%s%s', $propName, $index);
}
}
unset($propName);
return implode('.', $pathArray);
} | php | {
"resource": ""
} |
q7167 | Role.index | train | public function index($listener)
{
$eloquent = $this->model->newQuery();
$table = $this->presenter->table($eloquent);
$this->fireEvent('list', [$eloquent, $table]);
// Once all event listening to `orchestra.list: role` is executed,
// we can add we can now add the final column, edit and delete
// action for roles.
$this->presenter->actions($table);
return $listener->indexSucceed(compact('eloquent', 'table'));
} | php | {
"resource": ""
} |
q7168 | Role.edit | train | public function edit($listener, $id)
{
$eloquent = $this->model->findOrFail($id);
$form = $this->presenter->form($eloquent);
$this->fireEvent('form', [$eloquent, $form]);
return $listener->editSucceed(compact('eloquent', 'form'));
} | php | {
"resource": ""
} |
q7169 | Role.store | train | public function store($listener, array $input)
{
$validation = $this->validator->on('create')->with($input);
if ($validation->fails()) {
return $listener->storeValidationFailed($validation);
}
$role = $this->model;
try {
$this->saving($role, $input, 'create');
} catch (Exception $e) {
return $listener->storeFailed(['error' => $e->getMessage()]);
}
return $listener->storeSucceed($role);
} | php | {
"resource": ""
} |
q7170 | Role.update | train | public function update($listener, array $input, $id)
{
if ((int) $id !== (int) $input['id']) {
return $listener->userVerificationFailed();
}
$validation = $this->validator->on('update')->bind(['roleID' => $id])->with($input);
if ($validation->fails()) {
return $listener->updateValidationFailed($validation, $id);
}
$role = $this->model->findOrFail($id);
try {
$this->saving($role, $input, 'update');
} catch (Exception $e) {
return $listener->updateFailed(['error' => $e->getMessage()]);
}
return $listener->updateSucceed($role);
} | php | {
"resource": ""
} |
q7171 | Role.destroy | train | public function destroy($listener, $id)
{
$role = $this->model->findOrFail($id);
try {
DB::transaction(function () use ($role) {
$role->delete();
});
} catch (Exception $e) {
return $listener->destroyFailed(['error' => $e->getMessage()]);
}
return $listener->destroySucceed($role);
} | php | {
"resource": ""
} |
q7172 | Role.saving | train | protected function saving(Eloquent $role, $input = [], $type = 'create')
{
$beforeEvent = ($type === 'create' ? 'creating' : 'updating');
$afterEvent = ($type === 'create' ? 'created' : 'updated');
$role->setAttribute('name', $input['name']);
$this->fireEvent($beforeEvent, [$role]);
$this->fireEvent('saving', [$role]);
DB::transaction(function () use ($role) {
$role->save();
});
$this->fireEvent($afterEvent, [$role]);
$this->fireEvent('saved', [$role]);
return true;
} | php | {
"resource": ""
} |
q7173 | StreamQueryResult.all | train | function all(): \React\Promise\PromiseInterface {
return \React\Promise\Stream\all($this)->then(function (array $rows) {
return (new \Plasma\QueryResult($this->affectedRows, $this->warningsCount, $this->insertID, $this->columns, $rows));
});
} | php | {
"resource": ""
} |
q7174 | StreamQueryResult.pause | train | function pause() {
$this->paused = true;
if($this->started && !$this->closed) {
$this->driver->pauseStreamConsumption();
}
} | php | {
"resource": ""
} |
q7175 | StreamQueryResult.resume | train | function resume() {
$this->paused = false;
if($this->started && !$this->closed) {
$this->driver->resumeStreamConsumption();
}
} | php | {
"resource": ""
} |
q7176 | StreamQueryResult.close | train | function close() {
if($this->closed) {
return;
}
$this->closed = true;
if($this->started && $this->paused) {
$this->driver->resumeStreamConsumption();
}
$this->emit('close');
$this->removeAllListeners();
} | php | {
"resource": ""
} |
q7177 | Authorization.edit | train | public function edit($listener, $metric)
{
$collection = [];
$instances = $this->acl->all();
$eloquent = null;
foreach ($instances as $name => $instance) {
$collection[$name] = (string) $this->getAuthorizationName($name);
$name === $metric && $eloquent = $instance;
}
if (is_null($eloquent)) {
return $listener->aclVerificationFailed();
}
$actions = $this->getAuthorizationActions($eloquent, $metric);
$roles = $this->getAuthorizationRoles($eloquent);
return $listener->indexSucceed(compact('actions', 'roles', 'eloquent', 'collection', 'metric'));
} | php | {
"resource": ""
} |
q7178 | Authorization.update | train | public function update($listener, array $input)
{
$metric = $input['metric'];
$acl = $this->acl->get($metric);
if (is_null($acl)) {
return $listener->aclVerificationFailed();
}
$roles = $acl->roles()->get();
$actions = $acl->actions()->get();
foreach ($roles as $roleKey => $roleName) {
foreach ($actions as $actionKey => $actionName) {
$value = ('yes' === Arr::get($input, "acl-{$roleKey}-{$actionKey}", 'no'));
$acl->allow($roleName, $actionName, $value);
}
}
return $listener->updateSucceed($metric);
} | php | {
"resource": ""
} |
q7179 | Authorization.sync | train | public function sync($listener, $vendor, $package = null)
{
$roles = [];
$name = $this->getExtension($vendor, $package)->get('name');
$acl = $this->acl->get($name);
if (is_null($acl)) {
return $listener->aclVerificationFailed();
}
foreach ($this->model->all() as $role) {
$roles[] = $role->name;
}
$acl->roles()->attach($roles);
$acl->sync();
return $listener->syncSucceed(new Fluent(compact('vendor', 'package', 'name')));
} | php | {
"resource": ""
} |
q7180 | Authorization.getAuthorizationActions | train | protected function getAuthorizationActions(AuthorizationContract $acl, $metric)
{
return collect($acl->actions()->get())->map(function ($slug) use ($metric) {
$key = "orchestra/foundation::acl.{$metric}.{$slug}";
$name = $this->translator->has($key) ? $this->translator->get($key) : Str::humanize($slug);
return compact('slug', 'name');
});
} | php | {
"resource": ""
} |
q7181 | Authorization.getAuthorizationRoles | train | protected function getAuthorizationRoles(AuthorizationContract $acl)
{
return collect($acl->roles()->get())->reject(function ($role) {
return in_array($role, ['guest']);
})->map(function ($slug) {
$name = Str::humanize($slug);
return compact('slug', 'name');
});
} | php | {
"resource": ""
} |
q7182 | VCard.download | train | function download()
{
if (!$this->card) {
$this->build();
}
if (!$this->filename) {
$this->filename = $this->data['display_name'];
}
$this->filename = str_replace(' ', '_', $this->filename);
header("Content-type: text/directory");
header("Content-Disposition: attachment; filename=" . $this->filename . ".vcf");
header("Pragma: public");
echo $this->card;
return true;
} | php | {
"resource": ""
} |
q7183 | AbstractTranslator.buildChoiceLookupList | train | protected function buildChoiceLookupList($choices)
{
$array = array();
foreach ($choices as $range => $choice) {
$range = explode(':', $range);
if (count($range) < 2) {
$range[] = '';
}
$array[] = (object) array(
'range' => (object) array(
'from' => $range[0],
'to' => $range[1],
),
'string' => $choice
);
}
return $array;
} | php | {
"resource": ""
} |
q7184 | AbstractTranslator.fetchChoice | train | protected function fetchChoice($choices, $index, $count)
{
$choice = $choices[$index];
// Set from number, if not set (notation ":X").
if (!$choice->range->from) {
if ($index > 0) {
$choice->range->from = ($choices[($index - 1)]->range->to + 1);
} else {
$choice->range->from = (-PHP_INT_MAX);
}
}
// Set to number, if not set (notation "X" or "X:").
if (!$choice->range->to) {
if ($index < ($count - 1)) {
$choice->range->to = ($choices[($index + 1)]->range->from - 1);
} else {
$choice->range->to = PHP_INT_MAX;
}
}
return $choice;
} | php | {
"resource": ""
} |
q7185 | DateTime.from | train | public static function from($time): self
{
if ($time instanceof DateTimeInterface) {
return new static($time->format('Y-m-d H:i:s'), $time->getTimezone());
} elseif (is_numeric($time)) {
return (new static('@' . $time))
->setTimezone(new DateTimeZone(date_default_timezone_get()));
} else {
return new static($time);
}
} | php | {
"resource": ""
} |
q7186 | Function_range.evaluate | train | public function evaluate(Context $context, $arity, $arguments) {
$rangeSize = intval($arguments[0]);
$result = array();
for ($i = 1; $i <= $rangeSize; ++ $i) {
$result []= $i;
}
return $result;
} | php | {
"resource": ""
} |
q7187 | soap_transport_http.sendHTTPS | train | function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies = NULL) {
return $this->send($data, $timeout, $response_timeout, $cookies);
} | php | {
"resource": ""
} |
q7188 | nusoap_parser.decodeSimple | train | function decodeSimple($value, $type, $typens) {
// TODO: use the namespace!
if ((!isset($type)) || $type == 'string' || $type == 'long' || $type == 'unsignedLong') {
return (string) $value;
}
if ($type == 'int' || $type == 'integer' || $type == 'short' || $type == 'byte') {
return (int) $value;
}
if ($type == 'float' || $type == 'double' || $type == 'decimal') {
return (double) $value;
}
if ($type == 'boolean') {
if (strtolower($value) == 'false' || strtolower($value) == 'f') {
return false;
}
return (boolean) $value;
}
if ($type == 'base64' || $type == 'base64Binary') {
$this->debug('Decode base64 value');
return base64_decode($value);
}
// obscure numeric types
if ($type == 'nonPositiveInteger' || $type == 'negativeInteger'
|| $type == 'nonNegativeInteger' || $type == 'positiveInteger'
|| $type == 'unsignedInt'
|| $type == 'unsignedShort' || $type == 'unsignedByte') {
return (int) $value;
}
// bogus: parser treats array with no elements as a simple type
if ($type == 'array') {
return array();
}
// everything else
return (string) $value;
} | php | {
"resource": ""
} |
q7189 | LocatorConfigurator.configure | train | public function configure(SimpleDoctrineMappingLocator $locator)
{
$path = $locator->getPaths()[0];
$resourcePathExploded = explode('/', $path);
$resourcePathRoot = array_shift($resourcePathExploded);
if (strpos($resourcePathRoot, '@') === 0) {
$mappingFileBundle = ltrim($resourcePathRoot, '@');
$bundle = $this->kernel->getBundle($mappingFileBundle);
if ($bundle instanceof BundleInterface) {
$resourcePathRoot = $bundle->getPath();
}
}
array_unshift($resourcePathExploded, $resourcePathRoot);
$path = implode('/', $resourcePathExploded);
if (!file_exists($path)) {
throw new ConfigurationInvalidException('Mapping file "' . $path . '" does not exist');
}
$locator->setPaths([$path]);
} | php | {
"resource": ""
} |
q7190 | Controller.getRoute | train | public function getRoute(): ?RouteInterface
{
if (!is_null($this->getApp())) {
return $this->getApp()->getService('routing')->getCurrentRoute();
}
return null;
} | php | {
"resource": ""
} |
q7191 | Controller.redirect | train | protected function redirect(string $url, int $httpResponseCode = 302): void
{
header('Location: ' . $url, true, $httpResponseCode);
exit;
} | php | {
"resource": ""
} |
q7192 | Controller.reload | train | protected function reload(array $get = [], bool $merge = false): void
{
$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
// Query
{
$query = [];
if ($merge) {
parse_str(parse_url($_SERVER["REQUEST_URI"], PHP_URL_QUERY), $query);
}
$query = array_merge($query, $get);
$queryString = http_build_query($query);
}
$this->redirect($path . (!empty($queryString) ? '?' . $queryString : ''));
} | php | {
"resource": ""
} |
q7193 | Controller.render | train | protected function render(string $name, array $variables = []): string
{
$templateEngine = $this->getApp()->getService('templating');
return $templateEngine->render($name, $variables);
} | php | {
"resource": ""
} |
q7194 | Controller.renderResponse | train | protected function renderResponse(string $name, array $variables = [], ResponseInterface $response = null): ResponseInterface
{
// Create new Response object if not given in parameter
if (is_null($response)) {
$response = new Response;
}
// Remove all headers
header_remove();
// Rendering
$rendering = $this->render($name, $variables);
// Get all headers defined in template engine and add to response
foreach (headers_list() as $header) {
$header = explode(':', $header, 2);
$response = $response->withAddedHeader($header[0], $header[1] ?? '');
}
// Get body of response
if ($response->getBody()->isWritable()) {
$response->getBody()->write($rendering);
} else {
$body = new Stream;
$body->write($rendering);
$response = $response->withBody($body);
}
return $response;
} | php | {
"resource": ""
} |
q7195 | GraphQueryImpl.getQueryParts | train | public function getQueryParts()
{
$this->queryParts = [
'graphs' => $this->extractGraphs($this->getQuery()),
'sub_type' => $this->determineSubType($this->getQuery()),
];
$this->unsetEmptyValues($this->queryParts);
return $this->queryParts;
} | php | {
"resource": ""
} |
q7196 | StringHelper.toPascalCase | train | public function toPascalCase(string $string): string
{
$string = Transliterator::urlize((string)$string);
$string = str_replace('-', '', ucwords($string, '-'));
return $string;
} | php | {
"resource": ""
} |
q7197 | StringHelper.convertCamelCase | train | public function convertCamelCase($string, $separator = '-'): string
{
$string = (string)$string;
$separator = (string)$separator;
return strtolower(
preg_replace(
'/([a-zA-Z])(?=[A-Z])/',
'$1' . $separator,
$string
)
);
} | php | {
"resource": ""
} |
q7198 | StringHelper.convertToString | train | public function convertToString($input, $separator = ' '): string
{
$separator = (string)$separator;
$string = is_array($input) ? implode($separator, $input) : (string)$input;
// Remove double space and trim the string
return trim(preg_replace('/(\s)+/', ' ', $string));
} | php | {
"resource": ""
} |
q7199 | UserCredentialSmsTokenLoginService.initialize | train | public function initialize() {
//revert to password only functionality if multi-factor flag is off
if ($this->_multiFactorFlag === false) {
parent::initialize();
return;
}
//verify that multi-factor stages is set
if (
!(isset($this->_multiFactorStages))
|| !(is_array($this->_multiFactorStages))
|| !(isset($this->_multiFactorStages['current']))
|| !(is_int($this->_multiFactorStages['current']))
|| !(isset($this->_multiFactorStages[1]))
|| !(is_array($this->_multiFactorStages[1]))
|| !(isset($this->keyLength))
) {
throw new UserCredentialException('The multi factor stages register is initialized with an an unknown state', 2100);
}
//get the current stage (1 or 2)
$currentStage = $this->_multiFactorStages['current'];
//bootstrap depends on which stage we are in
if ($currentStage == 1) {
$this->_multiFactorStages[1]['statuss'] = false;
parent::initialize();
return;
} elseif ($currentStage != 2) {
throw new UserCredentialException('The current stage of the multi factor auth process is in an unknown state', 2101);
}
//get the user TOTP profile
$userTotpProfile = $this->userTotpProfile;
//we are in stage 2, check that all items are in order
if (
!(is_array($userTotpProfile))
|| !(isset($userTotpProfile['enc_key']))
|| !(is_string($userTotpProfile['enc_key']))
|| !(isset($userTotpProfile['totp_timestamp']))
|| !($userTotpProfile['totp_timestamp'] instanceof \DateTime)
|| !(isset($userTotpProfile['totp_timelimit']))
|| !(is_int($userTotpProfile['totp_timelimit']))
|| !(isset($this->verificationHash))
|| !(is_string($this->verificationHash))
|| !(isset($this->oneTimeToken))
|| !(is_string($this->oneTimeToken))
|| !(isset($this->currentOneTimeToken))
|| !(is_string($this->currentOneTimeToken))
) {
throw new UserCredentialException('The user TOTP profile is not initialized properly', 2102);
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.