_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q7000
Slim.get
train
protected function get($place, $args=array()){ $sep = isset($args['seperator']) ? $args['seperator'] : ' '; $content = ''; if(isset($this->content[$place])){ foreach($this->content[$place] as $item){ if($this->options['debug']===true){ $content.='<!--Skinny:Place: '.$place.'-->'; } switch($item['type']){ case 'hook': //method will be called with two arrays as arguments //the first is the args passed to this method (ie. in a template call to $this->insert() ) //the second are the args passed when the hook was bound $content .= call_user_method_array($item['hook'][0], $item['hook'][1], array($args, $item['arguments'])); break; case 'html': $content .= $sep . (string) $item['html']; break; case 'template': $content .= $this->render($item['template'], $item['params']); break; } } } //content from #movetoskin and #skintemplate /*if( Skinny::hasContent($place) ){ foreach(Skinny::getContent($place) as $item){ //pre-rendered html from #movetoskin if(isset($item['html'])){ if($this->options['debug']===true){ $content.='<!--Skinny:MoveToSkin: '.$template.'-->'; } $content .= $sep . $item['html']; } else //a template name to render if(isset($item['template'])){ if($this->options['debug']===true){ $content.='<!--Skinny:Template (via #skintemplate): '.$item['template'].'-->'; } $content .= $this->render( $item['template'], $item['params'] ); } } }*/ return $content; }
php
{ "resource": "" }
q7001
Application.configureIO
train
protected function configureIO() { if ($this->consoleInput->hasParameterOption(['--ansi'], true)) { $this->consoleOutput->setDecorated(true); } elseif ($this->consoleInput->hasParameterOption(['--no-ansi'], true)) { $this->consoleOutput->setDecorated(false); } if ($this->consoleInput->hasParameterOption(['--no-interaction', '-n'], true)) { $this->consoleInput->setInteractive(false); } if ($this->consoleInput->hasParameterOption(['--quiet', '-q'], true)) { $this->consoleOutput->setVerbosity(OutputInterface::VERBOSITY_QUIET); $this->consoleInput->setInteractive(false); } else { if ($this->consoleInput->hasParameterOption('-vvv', true) || $this->consoleInput->hasParameterOption('--verbose=3', true) || $this->consoleInput->getParameterOption('--verbose', false, true) === 3 ) { $this->consoleOutput->setVerbosity(OutputInterface::VERBOSITY_DEBUG); } elseif ($this->consoleInput->hasParameterOption('-vv', true) || $this->consoleInput->hasParameterOption('--verbose=2', true) || $this->consoleInput->getParameterOption('--verbose', false, true) === 2 ) { $this->consoleOutput->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE); } elseif ($this->consoleInput->hasParameterOption('-v', true) || $this->consoleInput->hasParameterOption('--verbose=1', true) || $this->consoleInput->hasParameterOption('--verbose', true) || $this->consoleInput->getParameterOption('--verbose', false, true) ) { $this->consoleOutput->setVerbosity(OutputInterface::VERBOSITY_VERBOSE); } } }
php
{ "resource": "" }
q7002
Application.findNamespace
train
public function findNamespace(string $namespace): string { $allNamespaces = $this->getNamespaces(); $expr = preg_replace_callback( '{([^:]+|)}', function ($matches) { return preg_quote($matches[1]) . '[^:]*'; }, $namespace ); $namespaces = preg_grep('{^' . $expr . '}', $allNamespaces); if (empty($namespaces)) { throw new NamespaceNotFoundException(sprintf('There are no commands defined in the "%s" namespace.', $namespace)); } $exact = \in_array($namespace, $namespaces, true); if (\count($namespaces) > 1 && !$exact) { throw new NamespaceNotFoundException(sprintf('The namespace "%s" is ambiguous.', $namespace)); } return $exact ? $namespace : reset($namespaces); }
php
{ "resource": "" }
q7003
Application.getAllCommands
train
public function getAllCommands(string $namespace = ''): array { $this->initCommands(); if ($namespace === '') { $commands = $this->commands; if (!$this->commandLoader) { return $commands; } foreach ($this->commandLoader->getNames() as $name) { if (!isset($commands[$name])) { $commands[$name] = $this->getCommand($name); } } return $commands; } $commands = []; foreach ($this->commands as $name => $command) { if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) { $commands[$name] = $command; } } if ($this->commandLoader) { foreach ($this->commandLoader->getNames() as $name) { if (!isset($commands[$name]) && $namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) { $commands[$name] = $this->getCommand($name); } } } return $commands; }
php
{ "resource": "" }
q7004
Application.getDefaultInputDefinition
train
protected function getDefaultInputDefinition(): InputDefinition { return new InputDefinition( [ new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'), new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display the help information'), new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Flag indicating that all output should be silenced'), new InputOption( '--verbose', '-v|vv|vvv', InputOption::VALUE_NONE, 'Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug' ), new InputOption('--ansi', '', InputOption::VALUE_NONE, 'Force ANSI output'), new InputOption('--no-ansi', '', InputOption::VALUE_NONE, 'Disable ANSI output'), new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Flag to disable interacting with the user'), ] ); }
php
{ "resource": "" }
q7005
Application.getHelperSet
train
public function getHelperSet(): HelperSet { if (!$this->helperSet) { $this->helperSet = $this->getDefaultHelperSet(); } return $this->helperSet; }
php
{ "resource": "" }
q7006
Application.getLongVersion
train
public function getLongVersion(): string { $name = $this->getName(); if ($name === '') { $name = 'Joomla Console Application'; } if ($this->getVersion() !== '') { return sprintf('%s <info>%s</info>', $name, $this->getVersion()); } return $name; }
php
{ "resource": "" }
q7007
Application.hasCommand
train
public function hasCommand(string $name): bool { $this->initCommands(); // If command is already registered, we're good if (isset($this->commands[$name])) { return true; } // If there is no loader, we can't look for a command there if (!$this->commandLoader) { return false; } return $this->commandLoader->has($name); }
php
{ "resource": "" }
q7008
Application.initCommands
train
private function initCommands() { if ($this->initialised) { return; } $this->initialised = true; foreach ($this->getDefaultCommands() as $command) { $this->addCommand($command); } }
php
{ "resource": "" }
q7009
Role.extendCreate
train
protected function extendCreate(ValidatorResolver $validator) { $name = Keyword::make($validator->getData()['name']); $validator->after(function (ValidatorResolver $v) use ($name) { if ($this->isRoleNameAlreadyUsed($name)) { $v->errors()->add('name', trans('orchestra/control::response.roles.reserved-word')); } }); }
php
{ "resource": "" }
q7010
Role.extendUpdate
train
protected function extendUpdate(ValidatorResolver $validator) { $name = Keyword::make($validator->getData()['name']); $validator->after(function (ValidatorResolver $v) use ($name) { if ($this->isRoleNameGuest($name)) { $v->errors()->add('name', trans('orchestra/control::response.roles.reserved-word')); } }); }
php
{ "resource": "" }
q7011
Role.isRoleNameAlreadyUsed
train
protected function isRoleNameAlreadyUsed(Keyword $name): bool { $roles = Foundation::acl()->roles()->get(); return $name->searchIn($roles) !== false; }
php
{ "resource": "" }
q7012
ReportExtension.decorateSubreportsDataSource
train
protected function decorateSubreportsDataSource(): void { $builder = $this->getContainerBuilder(); $subreports = $builder->findByTag(self::TAG_CACHE); foreach ($subreports as $service => $tag) { $serviceDef = $builder->getDefinition($service); // Validate datasource class if (!is_subclass_of((string) $serviceDef->getType(), DataSource::class)) { throw new AssertionException(sprintf( 'Please use tag "%s" only on datasource (object %s found in %s).', self::TAG_CACHE, $serviceDef->getType(), $service )); } // If cache.key is not provided, pick subreport name (fullname) if (!isset($tag['key'])) $tag['key'] = $serviceDef->getTag(self::TAG_SUBREPORT_DATASOURCE); // Validate cache scheme $this->validateConfig($this->scheme['tags'][self::TAG_CACHE], $tag, sprintf('%s', self::TAG_CACHE)); // Wrap factory to cache $wrappedDef = $builder->addDefinition(sprintf('%s_cached', $service), $serviceDef); // Remove definition $builder->removeDefinition($service); // Add cached defition of datasource with wrapped original datasource $builder->addDefinition($service) ->setFactory(CachedDataSource::class, [1 => $wrappedDef]) ->addSetup('setKey', [$tag['key']]) ->addSetup('setExpiration', [$tag['expiration']]) ->addTag(self::TAG_SUBREPORT_DATASOURCE, $wrappedDef->getTag(self::TAG_SUBREPORT_DATASOURCE)); // Append cache tags to subreport introspection $subreportDef = $builder->getDefinition($wrappedDef->getTag(self::TAG_SUBREPORT_DATASOURCE)); $introspection = $subreportDef->getTag(self::TAG_INTROSPECTION); $introspection['cache'] = ['datasource' => $tag]; $subreportDef->addTag(self::TAG_INTROSPECTION, $introspection); } }
php
{ "resource": "" }
q7013
ViewElement.evaluate
train
public function evaluate(Context $context, $expression) { if(is_numeric($expression)) { $expression = (string)$expression; } if(! isset($context->view->lexers[$expression]) ) { $lexer = new Lexer($expression); $context->view->lexers[$expression] = & $lexer; $lexer->parse($context); } else { $lexer = & $context->view->lexers[$expression]; } $result = $lexer->evaluate($context); return $result; }
php
{ "resource": "" }
q7014
Html.el
train
public static function el($name = NULL, $attrs = NULL) { $el = new static; $parts = explode(' ', (string)$name, 2); $el->setName($parts[0]); if (is_array($attrs)) { $el->attrs = $attrs; } elseif ($attrs !== NULL) { $el->setText($attrs); } if (isset($parts[1])) { $matches = preg_match_all('#([a-z0-9:-]+)(?:=(["\'])?(.*?)(?(2)\\2|\s))?#i', $parts[1] . ' ', $matches, PREG_SET_ORDER); foreach ($matches as $m) { $el->attrs[$m[1]] = isset($m[3]) ? $m[3] : TRUE; } } return $el; }
php
{ "resource": "" }
q7015
Html.setName
train
public function setName($name, $isEmpty = NULL) { if ($name !== NULL && !is_string($name)) { throw new InvalidArgumentException(sprintf('Name must be string or NULL, %s given.', gettype($name))); } $this->name = $name; $this->isEmpty = $isEmpty === NULL ? isset(static::$emptyElements[$name]) : (bool)$isEmpty; return $this; }
php
{ "resource": "" }
q7016
Html.appendAttribute
train
public function appendAttribute($name, $value, $option = TRUE) { if (is_array($value)) { $prev = isset($this->attrs[$name]) ? (array)$this->attrs[$name] : []; $this->attrs[$name] = $value + $prev; } elseif ((string)$value === '') { $tmp = &$this->attrs[$name]; // appending empty value? -> ignore, but ensure it exists } elseif (!isset($this->attrs[$name]) || is_array($this->attrs[$name])) { // needs array $this->attrs[$name][$value] = $option; } else { $this->attrs[$name] = [$this->attrs[$name] => TRUE, $value => $option]; } return $this; }
php
{ "resource": "" }
q7017
Html.getAttribute
train
public function getAttribute($name) { return isset($this->attrs[$name]) ? $this->attrs[$name] : NULL; }
php
{ "resource": "" }
q7018
Html.href
train
public function href($path, $query = NULL) { if ($query) { $query = http_build_query($query, '', '&'); if ($query !== '') { $path .= '?' . $query; } } $this->attrs['href'] = $path; return $this; }
php
{ "resource": "" }
q7019
Html.setHtml
train
public function setHtml($html) { if (is_array($html)) { throw new InvalidArgumentException(sprintf('Textual content must be a scalar, %s given.', gettype($html))); } $this->removeChildren(); $this->children[] = (string)$html; return $this; }
php
{ "resource": "" }
q7020
Html.getHtml
train
public function getHtml() { $s = ''; foreach ($this->children as $child) { if (is_object($child)) { $s .= $child->render(); } else { $s .= $child; } } return $s; }
php
{ "resource": "" }
q7021
Html.setText
train
public function setText($text) { if (!is_array($text) && !$text instanceof self) { $text = htmlspecialchars((string)$text, ENT_NOQUOTES, 'UTF-8'); } return $this->setHtml($text); }
php
{ "resource": "" }
q7022
Html.create
train
public function create($name, $attrs = NULL) { $this->insert(NULL, $child = static::el($name, $attrs)); return $child; }
php
{ "resource": "" }
q7023
Html.insert
train
public function insert($index, $child, $replace = FALSE) { if ($child instanceof self || is_scalar($child)) { if ($index === NULL) { // append $this->children[] = $child; } else { // insert or replace array_splice($this->children, (int)$index, $replace ? 1 : 0, [$child]); } } else { throw new InvalidArgumentException(sprintf('Child node must be scalar or Html object, %s given.', is_object($child) ? get_class($child) : gettype($child))); } return $this; }
php
{ "resource": "" }
q7024
Html.render
train
public function render($indent = NULL) { $s = $this->startTag(); if (!$this->isEmpty) { // add content if ($indent !== NULL) { $indent++; } foreach ($this->children as $child) { if (is_object($child)) { $s .= $child->render($indent); } else { $s .= $child; } } // add end tag $s .= $this->endTag(); } if ($indent !== NULL) { return "\n" . str_repeat("\t", $indent - 1) . $s . "\n" . str_repeat("\t", max(0, $indent - 2)); } return $s; }
php
{ "resource": "" }
q7025
Html.startTag
train
public function startTag() { if ($this->name) { return '<' . $this->name . $this->attributes() . (static::$xhtml && $this->isEmpty ? ' />' : '>'); } else { return ''; } }
php
{ "resource": "" }
q7026
Html.attributes
train
public function attributes() { if (!is_array($this->attrs)) { return ''; } $s = ''; $attrs = $this->attrs; foreach ($attrs as $key => $value) { if ($value === NULL || $value === FALSE) { continue; } elseif ($value === TRUE) { if (static::$xhtml) { $s .= ' ' . $key . '="' . $key . '"'; } else { $s .= ' ' . $key; } continue; } elseif (is_array($value)) { if (strncmp($key, 'data-', 5) === 0) { $value = json_encode($value); } else { $tmp = NULL; foreach ($value as $k => $v) { if ($v != NULL) { // intentionally ==, skip NULLs & empty string // composite 'style' vs. 'others' $tmp[] = $v === TRUE ? $k : (is_string($k) ? $k . ':' . $v : $v); } } if ($tmp === NULL) { continue; } $value = implode($key === 'style' || !strncmp($key, 'on', 2) ? ';' : ' ', $tmp); } } elseif (is_float($value)) { $value = rtrim(rtrim(number_format($value, 10, '.', ''), '0'), '.'); } else { $value = (string)$value; } $q = strpos($value, '"') === FALSE ? '"' : "'"; $s .= ' ' . $key . '=' . $q . str_replace( ['&', $q, '<'], ['&amp;', $q === '"' ? '&quot;' : '&#39;', self::$xhtml ? '&lt;' : '<'], $value ) . (strpos($value, '`') !== FALSE && strpbrk($value, ' <>"\'') === FALSE ? ' ' : '') . $q; } $s = str_replace('@', '&#64;', $s); return $s; }
php
{ "resource": "" }
q7027
Request.request
train
protected function request($method, $endpoint, $options = []) { return $this->unwrapResponse($this->getHttpClient($this->getBaseOptions())->{$method}($endpoint, $options)); }
php
{ "resource": "" }
q7028
SubscriptionManager.subscribe
train
public function subscribe($id, string $channel, $args, Request $request, \DateTime $expireAt = null): void { $this->convertNodes($args); $this->pubSubHandler->sub( $channel, $id, [ 'channel' => $channel, 'arguments' => $args, 'request' => $request, ], $expireAt ); }
php
{ "resource": "" }
q7029
SubscriptionManager.convertNodes
train
private function convertNodes(array &$data): void { array_walk_recursive( $data, function (&$value) { if ($value instanceof NodeInterface) { $value = IDEncoder::encode($value); } } ); }
php
{ "resource": "" }
q7030
SubscriptionManager.sendRequest
train
private function sendRequest(Request $originRequest, SubscriptionMessage $message, OutputInterface $output, bool $debug = false): void { $host = $originRequest->getHost(); $port = $originRequest->getPort(); $path = $originRequest->getPathInfo(); $handle = fsockopen($originRequest->isSecure() ? 'ssl://'.$host : $host, $port, $errno, $errstr, 10); $signer = new Sha256(); $subscriptionToken = (new Builder())->setId($message->getId()) ->set('data', serialize($message->getData())) ->setIssuedAt(time()) ->setNotBefore(time() + 60) ->setExpiration(time() + 60) ->sign($signer, $this->secret) ->getToken(); $body = $originRequest->getContent(); $length = strlen($body); $out = "POST $path HTTP/1.1\r\n"; $out .= "Host: $host\r\n"; $auth = $originRequest->headers->get('Authorization'); $out .= "Authorization: $auth\r\n"; $out .= "Subscription: $subscriptionToken\r\n"; $out .= "Content-Length: $length\r\n"; $out .= "Content-Type: application/json\r\n"; $out .= "Connection: Close\r\n\r\n"; $out .= $body; fwrite($handle, $out); if ($debug) { /// in debug mode wait for response $output->writeln(sprintf('[DEBUG] Getting response for subscription %s', $message->getId())); while (true) { $buffer = fgets($handle); if (!$buffer) { break; } $output->write($buffer); } } fclose($handle); }
php
{ "resource": "" }
q7031
TextDescriptor.describe
train
public function describe(OutputInterface $output, $object, array $options = []) { $this->output = $output; switch (true) { case $object instanceof Application: $this->describeJoomlaApplication($object, $options); break; case $object instanceof AbstractCommand: $this->describeConsoleCommand($object, $options); break; default: parent::describe($output, $object, $options); } }
php
{ "resource": "" }
q7032
TextDescriptor.describeConsoleCommand
train
private function describeConsoleCommand(AbstractCommand $command, array $options) { $command->getSynopsis(true); $command->getSynopsis(false); $command->mergeApplicationDefinition(false); $this->writeText('<comment>Usage:</comment>', $options); foreach (array_merge([$command->getSynopsis(true)], $command->getAliases()) as $usage) { $this->writeText("\n"); $this->writeText(' ' . $usage, $options); } $this->writeText("\n"); $definition = $command->getDefinition(); if ($definition->getOptions() || $definition->getArguments()) { $this->writeText("\n"); $this->describeInputDefinition($definition, $options); $this->writeText("\n"); } if ($help = $command->getProcessedHelp()) { $this->writeText("\n"); $this->writeText('<comment>Help:</comment>', $options); $this->writeText("\n"); $this->writeText(' ' . str_replace("\n", "\n ", $help), $options); $this->writeText("\n"); } }
php
{ "resource": "" }
q7033
TextDescriptor.describeJoomlaApplication
train
private function describeJoomlaApplication(Application $app, array $options) { $describedNamespace = $options['namespace'] ?? ''; $description = new ApplicationDescription($app, $describedNamespace); $version = $app->getLongVersion(); if ($version !== '') { $this->writeText("$version\n\n", $options); } $this->writeText("<comment>Usage:</comment>\n"); $this->writeText(" command [options] [arguments]\n\n"); $this->describeInputDefinition(new InputDefinition($app->getDefinition()->getOptions()), $options); $this->writeText("\n"); $this->writeText("\n"); $commands = $description->getCommands(); $namespaces = $description->getNamespaces(); if ($describedNamespace && $namespaces) { // Ensure all aliased commands are included when describing a specific namespace $describedNamespaceInfo = reset($namespaces); foreach ($describedNamespaceInfo['commands'] as $name) { $commands[$name] = $description->getCommand($name); } } $width = $this->getColumnWidth( \call_user_func_array( 'array_merge', array_map( function ($namespace) use ($commands) { return array_intersect($namespace['commands'], array_keys($commands)); }, $namespaces ) ) ); if ($describedNamespace) { $this->writeText(sprintf('<comment>Available commands for the "%s" namespace:</comment>', $describedNamespace), $options); } else { $this->writeText('<comment>Available commands:</comment>', $options); } foreach ($namespaces as $namespace) { $namespace['commands'] = array_filter( $namespace['commands'], function ($name) use ($commands) { return isset($commands[$name]); } ); if (!$namespace['commands']) { continue; } if (!$describedNamespace && $namespace['id'] !== ApplicationDescription::GLOBAL_NAMESPACE) { $this->writeText("\n"); $this->writeText(' <comment>' . $namespace['id'] . '</comment>', $options); } foreach ($namespace['commands'] as $name) { $this->writeText("\n"); $spacingWidth = $width - StringHelper::strlen($name); $command = $commands[$name]; $commandAliases = $name === $command->getName() ? $this->getCommandAliasesText($command) : ''; $this->writeText( sprintf( ' <info>%s</info>%s%s', $name, str_repeat(' ', $spacingWidth), $commandAliases . $command->getDescription() ), $options ); } } $this->writeText("\n"); }
php
{ "resource": "" }
q7034
TextDescriptor.getColumnWidth
train
private function getColumnWidth(array $commands): int { $widths = []; foreach ($commands as $command) { if ($command instanceof AbstractCommand) { $widths[] = StringHelper::strlen($command->getName()); foreach ($command->getAliases() as $alias) { $widths[] = StringHelper::strlen($alias); } } else { $widths[] = StringHelper::strlen($command); } } return $widths ? max($widths) + 2 : 0; }
php
{ "resource": "" }
q7035
TokensTable.findValidToken
train
public function findValidToken(Query $query, array $options) { $options += [ 'token' => null, 'expires >' => new DateTimeImmutable(), 'status' => false ]; return $query->where($options); }
php
{ "resource": "" }
q7036
TokensTable.setStatus
train
public function setStatus($id, $status) { if (!is_numeric($status)) { throw new Exception('Status argument must be an integer'); } $entity = $this->findById($id)->firstOrFail(); $entity->status = $status; $this->save($entity); return $entity; }
php
{ "resource": "" }
q7037
ThemesController.activate
train
public function activate(Processor $processor, $type, $id) { return $processor->activate($this, $type, $id); }
php
{ "resource": "" }
q7038
ThemesController.themeHasActivated
train
public function themeHasActivated($type, $id) { $message = \trans('orchestra/control::response.themes.update', [ 'type' => Str::title($type), ]); return $this->redirectWithMessage( \handles("orchestra::control/themes/{$type}"), $message ); }
php
{ "resource": "" }
q7039
TagFigDictionary.fig_dictionary
train
private function fig_dictionary(Context $context) { //If a @source attribute is specified, //it means that when the target (view's language) is the same as @source, //then don't bother loading dictionary file, nor translating: just render the tag's children. $file = $this->dicFile; $filename = $context->view->getTranslationPath() . '/' . $context->view->getLanguage() . '/' . $file; $dictionary = new Dictionary($filename, $this->source); if ( ($context->view->getLanguage() == '') || ($this->source == $context->view->getLanguage()) ) { // If the current View does not specify a Language, // or if the dictionary to load is same language as View, // let's not care about i18n. // We will activate i18n only if the dictionary explicitly specifies a source, // which means that we cannot simply rely on contents of the fig:trans tags. // However, we still need to hook the Dictionary object as a placeholder, // so that subsequent trans tag for the given dic name and source will // simply render their contents. $context->addDictionary($dictionary, $this->dicName); return ''; } //TODO: Please optimize here: cache the realpath of the loaded dictionaries, //so as not to re-load an already loaded dictionary in same View hierarchy. try { //Determine whether this dictionary was pre-compiled: if($context->view->getCachePath()) { $tmpFile = $context->getView()->getCachePath() . '/' . 'Dictionary' . '/' . $context->getView()->getLanguage() . '/' . $file . '.php'; //If the tmp file already exists, if(file_exists($tmpFile)) { //but is older than the source file, if(file_exists($filename) && (filemtime($tmpFile) < filemtime($filename)) ) { Dictionary::compile($filename, $tmpFile); } } else { Dictionary::compile($filename, $tmpFile); } $dictionary->restore($tmpFile); } //If we don't even have a temp folder specified, load the dictionary for the first time. else { $dictionary->load(); } } catch(FileNotFoundException $ex) { throw new FileNotFoundException('Translation file not found: file=' . $filename . ', language=' . $context->view->getLanguage() . ', source=' . $context->getFilename(), $context->getFilename() ); } //Hook the dictionary to the current file. //(in fact this will bubble up the message as high as possible, ie: //to the highest parent which does not bear a dictionary of same name) $context->addDictionary($dictionary, $this->dicName); return ''; }
php
{ "resource": "" }
q7040
Json.decode
train
public static function decode($json, $assoc = false) { if ($json instanceof Response) { return json_decode($json->getContent(), $assoc); } return json_decode($json, $assoc); }
php
{ "resource": "" }
q7041
ConfigurationValidator.validate
train
public function validate($data) { $this->validator->reset(); $this->validator->check($data, $this->schema()); if (!$this->validator->isValid()) { throw new InvalidConfigurationException( $this->validator->getErrors() ); } }
php
{ "resource": "" }
q7042
ClassUtils.applyNamingConvention
train
public static function applyNamingConvention(string $namespace, string $path, ?string $node, string $name, ?string $suffix = null) { if (null === $node) { return sprintf('%s\%s\%s%s', $namespace, $path, ucfirst($name), $suffix); } return sprintf('%s\%s\%s\%s%s', $namespace, $path, $node, ucfirst($name), $suffix); }
php
{ "resource": "" }
q7043
Skinny.insertTemplatePF
train
public static function insertTemplatePF ($parser, $template, $spot=''){ //process additional arguments into a usable array $params = array(); //sanitize the template name $template = preg_replace('/[^A-Za-z0-9_\-]/', '_', $template); //this will be stripped out, assuming the skin is based on Skinny.template return '<p>ADDTEMPLATE('.$spot.'):'.$template.':ETALPMETDDA</p>'; }
php
{ "resource": "" }
q7044
Skinny.getSkin
train
public static function getSkin($context, &$skin){ //there's probably a better way to check for this... if(!isset($_GET['useskin'])){ $key = $GLOBALS['wgDefaultSkin']; if( self::$pageSkin ){ $key = new self::$pageSkin; } $key = \Skin::normalizeKey( $key ); $skinNames = \Skin::getSkinNames(); $skinName = $skinNames[$key]; $className = "\Skin{$skinName}"; if (class_exists($className)) { $skin = new $className(); if (isset(self::$skinLayout) && method_exists($skin, 'setLayout')) { $skin->setLayout(self::$skinLayout); } } } self::$skin = $skin; return true; }
php
{ "resource": "" }
q7045
Role.table
train
public function table($model) { return $this->table->of('control.roles', function (TableGrid $table) use ($model) { // attach Model and set pagination option to true. $table->with($model)->paginate(true); $table->sortable(); $table->searchable(['name']); $table->layout('orchestra/foundation::components.table'); // Add columns. $table->column(trans('orchestra/foundation::label.name'), 'name'); }); }
php
{ "resource": "" }
q7046
Role.addEditButton
train
protected function addEditButton(Eloquent $role) { $link = handles("orchestra::control/roles/{$role->id}/edit"); $text = trans('orchestra/foundation::label.edit'); $attributes = ['class' => 'btn btn-xs btn-label btn-warning']; return app('html')->link($link, $text, $attributes); }
php
{ "resource": "" }
q7047
Role.form
train
public function form(Eloquent $model) { return $this->form->of('control.roles', function (FormGrid $form) use ($model) { $form->resource($this, 'orchestra::control/roles', $model); $form->hidden('id'); $form->fieldset(function (Fieldset $fieldset) { $fieldset->control('input:text', 'name') ->label(trans('orchestra/control::label.name')); }); }); }
php
{ "resource": "" }
q7048
VCardReader.SaveFile
train
public function SaveFile($Key, $Index = 0, $TargetPath = '') { if (!isset($this->Data[$Key])) { return false; } if (!isset($this->Data[$Key][$Index])) { return false; } // Returing false if it is an image URL if (stripos($this->Data[$Key][$Index]['Value'], 'uri:') === 0) { return false; } if (is_writable($TargetPath) || (!file_exists($TargetPath) && is_writable(dirname($TargetPath)))) { $RawContent = $this->Data[$Key][$Index]['Value']; if (isset($this->Data[$Key][$Index]['Encoding']) && $this->Data[$Key][$Index]['Encoding'] == 'b') { $RawContent = base64_decode($RawContent); } $Status = file_put_contents($TargetPath, $RawContent); return (bool)$Status; } else { throw new Exception('vCard: Cannot save file ('.$Key.'), target path not writable ('.$TargetPath.')'); } return false; }
php
{ "resource": "" }
q7049
VCardReader.ParseStructuredValue
train
private static function ParseStructuredValue($Text, $Key) { $Text = array_map('trim', explode(';', $Text)); $Result = array(); $Ctr = 0; foreach (self::$Spec_StructuredElements[$Key] as $Index => $StructurePart) { $Result[$StructurePart] = isset($Text[$Index]) ? $Text[$Index] : null; } return $Result; }
php
{ "resource": "" }
q7050
RawReportFormat.prepareReport
train
public static function prepareReport(Report $report) { $contents = Report::getReportFileContents($report->getFullPath()); $report->content = $contents; return $report; }
php
{ "resource": "" }
q7051
Client.call
train
public function call(string $method, array $arguments): ResponseInterface { try { return $this->__soapCall($method, $arguments, null, $this->getHeader()); } catch (\Exception $e) { $exception = new ClientException($e->getMessage(), $e->getCode(), $e); if ($this->debug) { $exception->request = ClientException::formatXml($this->__getLastRequest()); $exception->response = ClientException::formatXml($this->__getLastResponse()); } throw $exception; } }
php
{ "resource": "" }
q7052
Client.getHeader
train
protected function getHeader(): \SoapHeader { if ($this->header) { return $this->header; } return $this->header = new \SoapHeader(static::NAMESPACE, 'UserCredentials', [ 'userid' => $this->login, 'password' => $this->password, ]); }
php
{ "resource": "" }
q7053
Clock.read
train
public function read(): ?TimePoint { try { $datetime = new DateTime($this->current, $this->timezone); } catch (BaseException $e) { return null; } return $this->fromDateTime($datetime); }
php
{ "resource": "" }
q7054
Clock.fromString
train
public function fromString($input, $format = null): ?TimePoint { if ($format === null) { $formats = [ 'Y-m-d\TH:i:sP', // RFC 3339 'Y-m-d\TH:i:s.uP', // RFC 3339 with fractional seconds 'Y-m-d\TH:i:sO', // ISO 8601 'Y-m-d\TH:i:s.uO', // ISO 8601 with fractional seconds and period 'Y-m-d\TH:i:s,uO', // ISO 8601 with fractional seconds and comma 'Y-m-d\TH:iO', // ISO 8601 with no seconds ]; do { $datetime = DateTime::createFromFormat(array_shift($formats), $input, $this->timezone); } while (!$datetime instanceof DateTime && count($formats) > 0); } else { $datetime = DateTime::createFromFormat($format, $input, $this->timezone); } return ($datetime instanceof DateTime) ? $this->fromDateTime($datetime) : null; }
php
{ "resource": "" }
q7055
Clock.inRange
train
public function inRange(TimePoint $expiration, TimePoint $creation = null, $skew = null): bool { $now = $this->read(); if ($skew !== null) { if ($creation instanceof TimePoint) { $creation = $creation->modify(sprintf('-%s', $skew)); } $expiration = $expiration->modify(sprintf('+%s', $skew)); } return $now->compare($expiration) !== 1 && (!$creation instanceof TimePoint || $now->compare($creation) !== -1); }
php
{ "resource": "" }
q7056
UsersTable.validateActivationKey
train
public function validateActivationKey($email, $activationKey) { $query = $this->findByEmailAndActivationKey($email, $activationKey); if ($query->Count() > 0) { return true; } return false; }
php
{ "resource": "" }
q7057
UsersTable.activateUser
train
public function activateUser($email, $activationKey) { if ($this->validateActivationKey($email, $activationKey)) { $user = $this->findByEmailAndActivationKey($email, $activationKey)->first(); if ($user->active == 0) { $user->active = 1; $user->activation_key = null; if ($this->save($user)) { return true; } } } return false; }
php
{ "resource": "" }
q7058
FunctionFactory.lookup
train
public final function lookup($funcName) { if(isset(self::$functions[$funcName])) { return self::$functions[$funcName]; } //The assign-and-return is acceptable because isset(null) returns false. return (self::$functions[$funcName] = $this->create($funcName)); }
php
{ "resource": "" }
q7059
ControlledError.create
train
public static function create($code, $message = null, $category = null) { return new class($message, $code, $category) extends ControlledError { /** * @var string */ protected $category; /** * @param string $message * @param string $code * @param null $category */ public function __construct($message, $code, $category = null) { if ($category) { $this->category = $category; } parent:: __construct($message, $code); } /** * @return string */ public function getCategory(): string { return $this->category ?? parent::getCategory(); } }; }
php
{ "resource": "" }
q7060
ViewElementTag.parseAttributes
train
protected function parseAttributes($figNamespace, array $attributes) { // A fig:call attribute on a tag, indicates that all the other attributes // are arguments for the macro. They all are considered as expressions, // and therefore there is no need to search for adhoc inside. if (! $this->figCall) { foreach ($attributes as $name => $value) { // Process the non-fig attributes only if (strpos($name, $figNamespace) === 0) { continue; } // Search for inline conditional attributes if (preg_match('/\|(.+)\|(.+)\|$/', $value, $matches)) { $attributes[$name] = new InlineCondAttr($matches[1], $matches[2]); //Element can no longer be squashed in optimizations, because it carries // an active runtime piece. $this->isDirective = true; continue; } // Search for adhocs if (preg_match_all('/\{([^\{]+)\}/', $value, $matches, PREG_OFFSET_CAPTURE)) { $parts = []; $previousPosition = 0; $nMatches = count($matches[0]); for($i = 0; $i < $nMatches; ++ $i) { $expression = $matches[1][$i][0]; $position = $matches[1][$i][1]; if ($position > $previousPosition + 1) { // +1 because we exclude the leading { $parts []= substr($value, $previousPosition, $position - 1 - $previousPosition); } $parts []= new AdHoc($expression); // Mark the current tag as being an active cell in the template, // as opposed to a stupid static string with no logic. $this->isDirective = true; // +1 because we contiunue past the trailing } $previousPosition = $position + strlen($expression) + 1; } // And finish with the trailing static part, past the last } if ($previousPosition < strlen($value)) { $parts []= substr($value, $previousPosition); } // At this stage, $parts is an index array of pieces, // each piece is either a scalar string, or an instance of AdHoc. // If there is only one part, let's simplify the array if (count($parts) == 1) { $parts = $parts[0]; } // $parts can safely replace the origin value in $attributes, // because the serializing and rendering engine are aware. $attributes[$name] = $parts; } } } $this->attributes = $attributes; }
php
{ "resource": "" }
q7061
ViewElementTag.buildXMLAttributesString
train
private function buildXMLAttributesString(Context $context) { $result = ''; $matches = null; $attributes = $this->attributes; $runtimeAttributes = $context->getRuntimeAttributes(); foreach($runtimeAttributes as $attributeName=>$runtimeAttr) { $attributes[$attributeName] = $runtimeAttr; } foreach($attributes as $attribute=>$value) { if( ! $context->view->isFigPrefix($attribute)) { // a flag attribute is to be processed differently because // it isn't a key=value pair. if ($value instanceof Flag) { // Flag attribute: there is no value. We print only the name of the flag. $result .= " $attribute"; } else { // We're potentially in presence of: // - a plain scalar // - an AdHoc instance // - an array of the above. // - an inline conditional attribute: InlineCondAttr if ($value instanceof InlineCondAttr) { /** @var InlineCondAttr $inlineCondAttr */ $inlineCondAttr = $value; if ($this->evaluate($context, $inlineCondAttr->cond)) { $value = $this->evaluate($context, $inlineCondAttr->val); } else { continue; } } if (! is_array($value)) { $value = [$value]; } $combined = ''; foreach ($value as $part) { if ($part instanceof AdHoc) { $evaluatedValue = $this->evaluate($context, $part->string); if($evaluatedValue instanceof ViewElement) { $evaluatedValue = $evaluatedValue->render($context); } if(is_array($evaluatedValue)) { if(empty($evaluatedValue)) { $evaluatedValue = ''; } else { $message = 'Adhoc {' . $part->string . '} of attribute ' . $attribute . ' in tag "' . $this->name . '" evaluated to array.'; throw new TagRenderingException($this->getTagName(), $this->getLineNumber(), $message); } } else if (is_object($evaluatedValue) && ($evaluatedValue instanceof \DOMNode)) { // Treat the special case of DOMNode descendants, // for which we can evalute the text contents $evaluatedValue = $evaluatedValue->nodeValue; } //The outcome of the evaluatedValue, coming from DB or other, might contain non-standard HTML characters. //We assume that the FIG library targets HTML rendering. //Therefore, let's have the outcome comply with HTML. if(is_object($evaluatedValue)) { //TODO: Log some warning! $evaluatedValue = '### Object of class: ' . get_class($evaluatedValue) . ' ###'; } else { $evaluatedValue = htmlspecialchars($evaluatedValue); } $part = $evaluatedValue; } // Append to what we had already (and if $part was a string in the first place, // we use its direct value; $combined .= $part; } $value = $combined; $result .= " $attribute=\"$value\""; } } } return $result; }
php
{ "resource": "" }
q7062
ViewElementTag.evalAttribute
train
protected function evalAttribute(Context $context, $name) { $expression = $this->getAttribute($name, false); if($expression) { return $this->evaluate($context, $expression); } return false; }
php
{ "resource": "" }
q7063
ViewElementTag.applyOutputFilter
train
private function applyOutputFilter(Context $context, $buffer) { //TODO: Currently the filtering works only on non-slot tags. //If applied on a slot tag, the transform is made on the special placeholder /==SLOT=.../ //rather than the future contents of the slot. if($this->figFilter) { $filterClass = $this->figFilter; $filter = $this->instantiateFilter($context, $filterClass); $buffer = $filter->transform($buffer); } return $buffer; }
php
{ "resource": "" }
q7064
ViewElementTag.replaceLastChild_cdata
train
private function replaceLastChild_cdata(ViewElementCData $cdata) { $n = count($this->children); if ( ($n > 1) && ($this->children[$n - 2] instanceof ViewElementCData) ) { // Group the last-but-one cdata with this new cdata $this->children[$n - 2]->outputBuffer .= $cdata->outputBuffer; // and chop the final element off the children array. array_pop($this->children); } else { $cdata->parent = $this; $this->children[$n - 1] = $cdata; } }
php
{ "resource": "" }
q7065
ApplicationDescription.inspectApplication
train
private function inspectApplication() { $this->commands = []; $this->namespaces = []; $all = $this->application->getAllCommands($this->namespace ? $this->application->findNamespace($this->namespace) : ''); foreach ($this->sortCommands($all) as $namespace => $commands) { $names = []; /** @var AbstractCommand $command */ foreach ($commands as $name => $command) { if (!$command->getName() || (!$this->showHidden && $command->isHidden())) { continue; } if ($command->getName() === $name) { $this->commands[$name] = $command; } else { $this->aliases[$name] = $command; } $names[] = $name; } $this->namespaces[$namespace] = ['id' => $namespace, 'commands' => $names]; } }
php
{ "resource": "" }
q7066
ApplicationDescription.sortCommands
train
private function sortCommands(array $commands): array { $namespacedCommands = []; $globalCommands = []; foreach ($commands as $name => $command) { $key = $this->extractNamespace($name, 1); if (!$key) { $globalCommands[self::GLOBAL_NAMESPACE][$name] = $command; } else { $namespacedCommands[$key][$name] = $command; } } ksort($namespacedCommands); $namespacedCommands = array_merge($globalCommands, $namespacedCommands); foreach ($namespacedCommands as &$commandsSet) { ksort($commandsSet); } // Unset reference to keep scope clear unset($commandsSet); return $namespacedCommands; }
php
{ "resource": "" }
q7067
PluginConfigAnnotation.getConfig
train
public function getConfig(): array { $ref = new \ReflectionClass(get_class($this)); $properties = $ref->getProperties(); $config = []; //set default values foreach ($properties as $property) { $value = $property->getValue($this); if (null !== $value) { $config[Inflector::tableize($property->getName())] = $property->getValue($this); } } return $config; }
php
{ "resource": "" }
q7068
Shipment.getTrackingUrl
train
public function getTrackingUrl() { if (!isset($this->parcelnumber)) { throw new RuntimeException("Shipment has no parcel number."); } return sprintf(Api::TRACKING_URL, $this->parcelnumber); }
php
{ "resource": "" }
q7069
SolrQueryBuilder.addFilter
train
public function addFilter($query, $value = null) { if ($value) { $query = "$query:$value"; } $this->filters[$query] = $query; return $this; }
php
{ "resource": "" }
q7070
SolrQueryBuilder.removeFilter
train
public function removeFilter($query, $value = null) { if ($value) { $query = "$query:$value"; } unset($this->filters[$query]); return $this; }
php
{ "resource": "" }
q7071
SolrQueryBuilder.restrictNearPoint
train
public function restrictNearPoint($point, $field, $radius) { $this->addFilter("{!geofilt}"); $this->params['sfield'] = $field; $this->params['pt'] = $point; $this->params['d'] = $radius; return $this; }
php
{ "resource": "" }
q7072
Router.toRoute
train
public function toRoute($name, array $args = [], $code = 307) { $to = $this->getRoute($name, $args); header("location: {$to}", true, $code); exit; }
php
{ "resource": "" }
q7073
Router.crud
train
public function crud($pattern, $callback, array $params = []) { if (!is_string($callback)) { throw new \Exception('Crud callbacks must be a string to a controller class'); } if (!empty($params['name'])) { $name = $params['name']; } $pattern = rtrim($pattern, '/'); $params['name'] = $name ? $name . '.create' : null; $this->post("{$pattern}", "{$callback}@create", $params); $params['name'] = $name ? $name . '.one' : null; $this->get("{$pattern}/(:any)", "{$callback}@one", $params); $params['name'] = $name ? $name . '.many' : null; $this->get("{$pattern}", "{$callback}@many", $params); $params['name'] = $name ? $name . '.update' : null; $this->put("{$pattern}/(:any)", "{$callback}@update", $params); $params['name'] = $name ? $name . '.delete' : null; $this->delete("{$pattern}/(:any)", "{$callback}@delete", $params); return $this; }
php
{ "resource": "" }
q7074
Router.group
train
public function group(array $params, $callback) { $prefix = trim($this->getParam($params, 'prefix'), '/'); $before = $this->getParam($params, 'before'); $after = $this->getParam($params, 'after'); if ($prefix) { $this->prefixes[] = $prefix; $this->prefix = '/' . trim(implode('/', $this->prefixes), '/'); } if ($before) { $this->befores[] = $before; $this->before = explode('|', implode('|', $this->befores)); } if ($after) { $this->afters[] = $after; $this->after = explode('|', implode('|', $this->afters)); } call_user_func_array($callback, [$this]); if ($prefix) { array_pop($this->prefixes); $this->prefix = $this->prefixes ? '/' . trim(implode('/', $this->prefixes), '/') : null; } if ($before) { array_pop($this->befores); $this->before = explode('|', implode('|', $this->befores)); } if ($after) { array_pop($this->afters); $this->after = explode('|', implode('|', $this->afters)); } return $this; }
php
{ "resource": "" }
q7075
Router.getMatch
train
public function getMatch($method = null, $path = null) { $method = $method ?: $this->getRequestMethod(); $path = $path ?: $this->getRequestPath(); $method = strtoupper($method); $methodNotAllowed = null; foreach ($this->routes as $pattern => $methods) { preg_match($this->regexifyPattern($pattern), $path, $matches); if ($matches) { $r = $this->getRouteObject($pattern, $method); if (!$r) { // We found a match but with the wrong method $methodNotAllowed = true; continue; } $r->method = strtoupper($method); $r->args = $this->getMatchArgs($matches); return $r; } } if ($methodNotAllowed) { if ($this->methodNotAllowed) { return (object)[ 'before' => [], 'after' => [], 'args' => [], 'callback' => &$this->methodNotAllowed, ]; } throw new MethodNotAllowedException; } if ($this->notFound) { return (object)[ 'before' => [], 'after' => [], 'args' => [], 'callback' => &$this->notFound, ]; } throw new NotFoundException; }
php
{ "resource": "" }
q7076
Router.dispatch
train
public function dispatch($method = null, $path = null) { $match = $this->getMatch($method, $path); foreach ($match->before as $filter) { if (empty($filter)) { continue; } $response = $this->executeCallback($this->getFilterCallback($filter), $match->args, true); if (!is_null($response)) { return $response; } } $routeResponse = $this->executeCallback($match->callback, $match->args); foreach ($match->after as $filter) { if (empty($filter)) { continue; } array_unshift($match->args, $routeResponse); $response = $this->executeCallback($this->getFilterCallback($filter), $match->args, true); if (!is_null($response)) { return $response; } } return $routeResponse; }
php
{ "resource": "" }
q7077
Router.executeCallback
train
public function executeCallback($cb, array $args = [], $filter = false) { if ($cb instanceof Closure) { return call_user_func_array($cb, $args); } if (is_string($cb) && strpos($cb, "@") !== false) { $cb = explode('@', $cb); } if (is_array($cb) && count($cb) == 2) { if (!is_object($cb[0])) { $cb = $this->resolveCallback($cb); } if (isset($cb[0], $cb[1]) && is_object($cb[0]) && !method_exists($cb[0], $cb[1])) { $name = get_class($cb[0]); throw new ControllerNotFoundException("Controller '{$name}->{$cb[1]}' not found"); } return call_user_func_array($cb, $args); } if (is_string($cb) && strpos($cb, "::") !== false) { return call_user_func_array($cb, $args); } throw new Exception('Invalid callback'); }
php
{ "resource": "" }
q7078
Router.getRoute
train
public function getRoute($name, array $args = []) { if (!isset($this->names[$name])) { return null; } $route = $this->callbacks[$this->names[$name]]; if (strpos($route->pattern, '(') === false) { // If we don't have any route parameters, just return the pattern // straight off. No need for any regex stuff. return $route->pattern; } // Convert all placeholders to %o = optional and %r = required $from = ['/(\([^\/]+[\)]+[\?])/', '/(\([^\/]+\))/']; $to = ['%o', '%r']; $pattern = preg_replace($from, $to, $route->pattern); $frags = explode('/', trim($pattern, '/')); $url = []; // Loop thru the pattern fragments and insert the arguments foreach ($frags as $frag) { if ($frag == '%r') { if (!$args) { // A required parameter, but no more arguments. throw new Exception('Missing route parameters'); } $url[] = array_shift($args); continue; } if ($frag == "%o") { if (!$args) { // No argument for the optional parameter, // just continue the iteration. continue; } $url[] = array_shift($args); continue; } $url[] = $frag; } return '/' . implode('/', $url); }
php
{ "resource": "" }
q7079
Router.regexifyPattern
train
protected function regexifyPattern($pattern) { preg_match_all('/(\/?)\(:([^)]*)\)(\??)/', $pattern, $regExPatterns, PREG_SET_ORDER, 0); $pattern = preg_quote($pattern, '/'); foreach ($regExPatterns as $regExPattern) { if (!empty($regExPattern[2]) && key_exists($regExPattern[2], $this->patterns)) { $replacement = sprintf( '(%s%s)%s', empty($regExPattern[1]) ? '' : '\/', $this->patterns[$regExPattern[2]], $regExPattern[3] ); $pattern = str_replace(preg_quote($regExPattern[0], '/'), $replacement, $pattern); } } return "/^$pattern$/"; }
php
{ "resource": "" }
q7080
Router.getRouteObject
train
protected function getRouteObject($pattern, $method) { foreach (['REDIRECT', $method, 'ANY'] as $verb) { if (array_key_exists($verb, $this->routes[$pattern])) { $index = $this->routes[$pattern][$verb]; return $this->callbacks[$index]; } } return false; }
php
{ "resource": "" }
q7081
Router.getMatchArgs
train
protected function getMatchArgs(array $match) { // Remove the first element, the matching regex array_shift($match); // Iterate through the arguments and remove any unwanted slashes foreach ($match as &$arg) { $arg = trim($arg, '/'); } return $match; }
php
{ "resource": "" }
q7082
Router.storeRoute
train
protected function storeRoute(array $methods, array $route) { $this->callbacks[] = (object)$route; $index = count($this->callbacks) - 1; if (!isset($this->routes[$route['pattern']])) { $this->routes[$route['pattern']] = []; } if ($route['name']) { $this->names[$route['name']] = $index; } foreach ($methods as $method) { $this->routes[$route['pattern']][strtoupper($method)] = $index; } }
php
{ "resource": "" }
q7083
Log.interpolate
train
protected function interpolate($message, $context = array()) { $replace = array(); foreach ($context as $key => $value) { $replace['{' . $key . '}'] = $value; } return strtr($message, $replace); }
php
{ "resource": "" }
q7084
CRUDExtensionResolverPlugin.resolveInterfaceExtension
train
protected function resolveInterfaceExtension(InterfaceDefinition $definition, Endpoint $endpoint): void { $bundleNamespace = ClassUtils::relatedBundleNamespace($definition->getClass()); $extensionClass = ClassUtils::applyNamingConvention($bundleNamespace, 'Extension', null, $definition->getName().'Extension'); if (class_exists($extensionClass)) { foreach ($definition->getImplementors() as $implementor) { $definition->addExtension($extensionClass); $object = $endpoint->getType($implementor); if ($object instanceof HasExtensionsInterface) { $object->addExtension($extensionClass); } } } }
php
{ "resource": "" }
q7085
CRUDExtensionResolverPlugin.resolveObjectRealInterfaceExtensions
train
protected function resolveObjectRealInterfaceExtensions(ClassAwareDefinitionInterface $definition): void { $class = $definition->getClass(); if (class_exists($class)) { $refClass = new \ReflectionClass($definition->getClass()); if ($interfaces = $refClass->getInterfaceNames()) { foreach ($interfaces as $interface) { $bundleNamespace = ClassUtils::relatedBundleNamespace($interface); if (preg_match('/(\w+)Interface?$/', $interface, $matches)) { $extensionClass = ClassUtils::applyNamingConvention($bundleNamespace, 'Extension', null, $matches[1].'Extension'); if (class_exists($extensionClass)) { if ($definition instanceof HasExtensionsInterface) { $definition->addExtension($extensionClass); } } } } } } }
php
{ "resource": "" }
q7086
Apache_Solr_Service.getHttpTransport
train
public function getHttpTransport() { // lazy load a default if one has not be set if ($this->_httpTransport === false) { require_once(dirname(__FILE__) . '/HttpTransport/FileGetContents.php'); $this->_httpTransport = new Apache_Solr_HttpTransport_FileGetContents(); } return $this->_httpTransport; }
php
{ "resource": "" }
q7087
TranslatorChain.add
train
public function add(TranslatorInterface $translator) { $hash = spl_object_hash($translator); $this->translators[$hash] = $translator; return $this; }
php
{ "resource": "" }
q7088
TranslatorChain.remove
train
public function remove(TranslatorInterface $translator) { $hash = spl_object_hash($translator); unset($this->translators[$hash]); return $this; }
php
{ "resource": "" }
q7089
View.loadFile
train
public function loadFile($filename) { $this->filename = $filename; // If a cache directory was specified, // try to load from it if ($this->cachePath) { if (! $this->templatesRoot) { $this->templatesRoot = dirname($filename); } $cacheFile = $this->makeCacheFilename($this->cachePath, $this->templatesRoot, $this->filename); if ( file_exists($cacheFile) && (! file_exists($this->filename) || (filemtime($this->filename) < filemtime($cacheFile)) ) ) { $this->loadFromSerialized(file_get_contents($cacheFile)); return; } } if(file_exists($filename)) { $this->source = file_get_contents($filename); } else { $message = "File not found: $filename"; throw new FileNotFoundException($message, $filename); } }
php
{ "resource": "" }
q7090
View.parse
train
public function parse() { if($this->bParsed) { return; } if ($this->replacements) { // We cannot rely of html_entity_decode, // because it would replace &amp; and &lt; as well, // whereas we need to keep them unmodified. // We must do it manually, with a modified hardcopy // of PHP 5.4+ 's get_html_translation_table(ENT_XHTML) $this->source = XMLEntityTransformer::replace($this->source); } $this->xmlParser = xml_parser_create('UTF-8'); xml_parser_set_option($this->xmlParser, XML_OPTION_CASE_FOLDING, false); xml_set_object($this->xmlParser, $this); xml_set_element_handler($this->xmlParser, 'openTagHandler', 'closeTagHandler'); xml_set_character_data_handler($this->xmlParser,'cdataHandler'); //Prepare the detection of the very first tag, in order to compute //the offset in XML string as regarded by the parser. $this->firstOpening = true; try { $bSuccess = xml_parse($this->xmlParser, $this->source); } catch (RequiredAttributeException $ex) { throw $ex->setFile($this->filename); } if ($bSuccess) { $errMsg = ''; $lineNumber = 0; } else { $errMsg = xml_error_string(xml_get_error_code($this->xmlParser)); $lineNumber = xml_get_current_line_number($this->xmlParser); if(count($this->stack)) { $lastElement = $this->stack[count($this->stack) - 1]; if($lastElement instanceof ViewElementTag) { $errMsg .= '. Last element: ' . $lastElement->getTagName() . '(' . $lineNumber . ')'; } } } xml_parser_free($this->xmlParser); $this->bParsed = $bSuccess; if(! $bSuccess ) { throw new XMLParsingException( $errMsg, $lineNumber); } // Store a serialized version of the parsed tree, if successfully parsed, // and if we've got a cache path. if ( ($this->cachePath) && ($this->filename !== null) && (! $this->unserialized) ) { $cacheFile = $this->makeCacheFilename($this->cachePath, $this->templatesRoot, $this->filename, true); file_put_contents($cacheFile, serialize($this)); } }
php
{ "resource": "" }
q7091
View.makeCacheFilename
train
private function makeCacheFilename($cachePath, $templatesRoot, $filename, $mkdir = false) { // If the template filename is relative (ie. not starting by / and not specifying a scheme) // then we first prefis it with the current working directory. And then we continue as if // absolute. if ( (substr($filename, 0, 1) != '/') && ! parse_url($filename, PHP_URL_SCHEME)) { $filename = getcwd() . '/' . $filename; } $cacheFile = str_replace($templatesRoot, $cachePath . '/figs', $filename) . '.fig'; if ($mkdir) { // Create the intermediary folders if not exist. $intermed = dirname($cacheFile); if (! file_exists($intermed)) { // In case of permission problems, or file already exists (and is not a directory), // the regular PHP warnings will be issued. mkdir($intermed, 0700, true); } } return $cacheFile; }
php
{ "resource": "" }
q7092
View.render
train
public function render() { if(! $this->bParsed) { $this->parse(); } if (! $this->rootNode) { throw new XMLParsingException('No template file loaded', 0); } $context = new Context($this); // DOCTYPE // The doctype is necessarily on the root tag, declared as an attribute, example: // fig:doctype="html" // However, it can be on the root node of an included template (when using the reverse plug/slot pattern) if ($this->rootNode instanceof ViewElementTag) { $context->setDoctype($this->rootNode->getAttribute($this->figNamespace . 'doctype')); } try { $result = $this->rootNode->render($context); } catch (RequiredAttributeException $ex) { throw $ex->setFile($context->getFilename()); } catch (TagRenderingException $ex) { throw new RenderingException($ex->getTag(), $context->getFilename(), $ex->getLine(), $ex->getMessage(), $ex); } catch (FeedClassNotFoundException $ex) { throw $ex->setFile($context->getFilename()); } $result = $this->plugIntoSlots($context, $result); // Take care of the doctype at top of output if ($context->getDoctype()) { $result = '<!doctype ' . $context->getDoctype() . '>' . "\n" . $result; } return $result; }
php
{ "resource": "" }
q7093
View.setCachePath
train
public function setCachePath($path, $templatesRoot = null) { // Suppress the trailing slash $this->cachePath = preg_replace('#/+$#', '', $path); $this->templatesRoot = preg_replace('#/+$#', '', $templatesRoot); }
php
{ "resource": "" }
q7094
View.cdataHandler
train
private function cdataHandler($xmlParser, $cdata) { //Last element in stack = parent element of the CDATA. $currentElement = $this->stack[count($this->stack)-1]; $currentElement->appendCDataChild($cdata); // hhvm invokes several cdata chunks if they contain \n $this->previousCData .= $cdata; }
php
{ "resource": "" }
q7095
Feed.getParameter
train
public function getParameter($paramName) { if(isset($this->params[$paramName])) { return $this->params[$paramName]; } return null; }
php
{ "resource": "" }
q7096
BaseGateway.getState
train
protected function getState($key) { if (!Yii::$app->has('session')) { return null; } /* @var \yii\web\Session $session */ $session = Yii::$app->get('session'); $key = $this->getStateKeyPrefix() . $key; $value = $session->get($key); return $value; }
php
{ "resource": "" }
q7097
BaseGateway.removeState
train
protected function removeState($key) { if (!Yii::$app->has('session')) { return true; } /* @var \yii\web\Session $session */ $session = Yii::$app->get('session'); $key = $this->getStateKeyPrefix() . $key; $session->remove($key); return true; }
php
{ "resource": "" }
q7098
CashAddress.pubKeyHashFromKey
train
public static function pubKeyHashFromKey($prefix, $publicKey) { $length = strlen($publicKey); if ($length === 33) { if ($publicKey[0] !== "\x02" && $publicKey[0] !== "\x03") { throw new CashAddressException("Invalid public key"); } } else if ($length === 65) { if ($publicKey[0] !== "\x04") { throw new CashAddressException("Invalid public key"); } } else { throw new CashAddressException("Invalid public key"); } return self::pubKeyHash($prefix, hash('ripemd160', hash('sha256', $publicKey, true), true)); }
php
{ "resource": "" }
q7099
Utility.replaceParameters
train
static function replaceParameters(array $paramsInfo, array $params): array { if(\count($params) !== \count($paramsInfo)) { throw new \Plasma\Exception('Insufficient amount of parameters passed, expected '.\count($paramsInfo).', got '.\count($params)); } $realParams = array(); $pos = (\array_key_exists(0, $params) ? 0 : 1); foreach($paramsInfo as $param) { $key = ($param[0] === ':' ? $param : ($pos++)); if(!\array_key_exists($key, $params)) { throw new \Plasma\Exception('Missing parameter with key "'.$key.'"'); } $realParams[] = $params[$key]; } return $realParams; }
php
{ "resource": "" }