_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
33
8k
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; } } }
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); }
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 . '}',
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); }
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
php
{ "resource": "" }
q7005
Application.getHelperSet
train
public function getHelperSet(): HelperSet { if (!$this->helperSet)
php
{ "resource": "" }
q7006
Application.getLongVersion
train
public function getLongVersion(): string { $name = $this->getName(); if ($name === '') { $name = 'Joomla Console Application'; } if ($this->getVersion() !== '') {
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
php
{ "resource": "" }
q7008
Application.initCommands
train
private function initCommands() { if ($this->initialised) { return; }
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)) {
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)) {
php
{ "resource": "" }
q7011
Role.isRoleNameAlreadyUsed
train
protected function isRoleNameAlreadyUsed(Keyword $name): bool { $roles = Foundation::acl()->roles()->get();
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])
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;
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])) {
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;
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
php
{ "resource": "" }
q7017
Html.getAttribute
train
public function getAttribute($name) { return
php
{ "resource": "" }
q7018
Html.href
train
public function href($path, $query = NULL) { if ($query) { $query = http_build_query($query, '', '&'); if ($query !== '') { $path .= '?' .
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)));
php
{ "resource": "" }
q7020
Html.getHtml
train
public function getHtml() { $s = ''; foreach ($this->children as $child) { if (is_object($child)) {
php
{ "resource": "" }
q7021
Html.setText
train
public function setText($text) { if (!is_array($text) && !$text instanceof
php
{ "resource": "" }
q7022
Html.create
train
public function create($name, $attrs = NULL) { $this->insert(NULL, $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]);
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; }
php
{ "resource": "" }
q7025
Html.startTag
train
public function startTag() { if ($this->name) { return '<' . $this->name . $this->attributes() . (static::$xhtml
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 &
php
{ "resource": "" }
q7027
Request.request
train
protected function request($method, $endpoint, $options = []) { return
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(
php
{ "resource": "" }
q7029
SubscriptionManager.convertNodes
train
private function convertNodes(array &$data): void { array_walk_recursive( $data, function (&$value) { if ($value instanceof NodeInterface) {
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";
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
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,
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) {
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) {
php
{ "resource": "" }
q7035
TokensTable.findValidToken
train
public function findValidToken(Query $query, array $options) { $options += [ 'token' => null, 'expires >' => new
php
{ "resource": "" }
q7036
TokensTable.setStatus
train
public function setStatus($id, $status) { if (!is_numeric($status)) { throw new Exception('Status argument must be an integer'); }
php
{ "resource": "" }
q7037
ThemesController.activate
train
public function activate(Processor $processor, $type, $id)
php
{ "resource": "" }
q7038
ThemesController.themeHasActivated
train
public function themeHasActivated($type, $id) { $message = \trans('orchestra/control::response.themes.update', [
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); }
php
{ "resource": "" }
q7040
Json.decode
train
public static function decode($json, $assoc = false) { if ($json instanceof Response) {
php
{ "resource": "" }
q7041
ConfigurationValidator.validate
train
public function validate($data) { $this->validator->reset(); $this->validator->check($data, $this->schema()); if (!$this->validator->isValid()) {
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
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
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}";
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']);
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'
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) {
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)
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) {
php
{ "resource": "" }
q7050
RawReportFormat.prepareReport
train
public static function prepareReport(Report $report) { $contents = Report::getReportFileContents($report->getFullPath());
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) {
php
{ "resource": "" }
q7052
Client.getHeader
train
protected function getHeader(): \SoapHeader { if ($this->header) { return $this->header; } return $this->header = new \SoapHeader(static::NAMESPACE, 'UserCredentials', [
php
{ "resource": "" }
q7053
Clock.read
train
public function read(): ?TimePoint { try { $datetime = new DateTime($this->current, $this->timezone); } catch (BaseException $e) {
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
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)); }
php
{ "resource": "" }
q7056
UsersTable.validateActivationKey
train
public function validateActivationKey($email, $activationKey) { $query = $this->findByEmailAndActivationKey($email, $activationKey);
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 =
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
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 *
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
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,
php
{ "resource": "" }
q7062
ViewElementTag.evalAttribute
train
protected function evalAttribute(Context $context, $name) { $expression = $this->getAttribute($name, false); if($expression) { return
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) {
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
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())) {
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 =
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);
php
{ "resource": "" }
q7068
Shipment.getTrackingUrl
train
public function getTrackingUrl() { if (!isset($this->parcelnumber)) { throw new
php
{ "resource": "" }
q7069
SolrQueryBuilder.addFilter
train
public function addFilter($query, $value = null) { if ($value) { $query = "$query:$value";
php
{ "resource": "" }
q7070
SolrQueryBuilder.removeFilter
train
public function removeFilter($query, $value = null) { if ($value) { $query = "$query:$value";
php
{ "resource": "" }
q7071
SolrQueryBuilder.restrictNearPoint
train
public function restrictNearPoint($point, $field, $radius) { $this->addFilter("{!geofilt}"); $this->params['sfield'] = $field;
php
{ "resource": "" }
q7072
Router.toRoute
train
public function toRoute($name, array $args = [], $code = 307) {
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);
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)); }
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) {
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) {
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]);
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.
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]) ? '' : '\/',
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])) {
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
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'])
php
{ "resource": "" }
q7083
Log.interpolate
train
protected function interpolate($message, $context = array()) { $replace = array(); foreach ($context as $key => $value) {
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) {
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');
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');
php
{ "resource": "" }
q7087
TranslatorChain.add
train
public function add(TranslatorInterface $translator) { $hash = spl_object_hash($translator);
php
{ "resource": "" }
q7088
TranslatorChain.remove
train
public function remove(TranslatorInterface $translator) { $hash = spl_object_hash($translator);
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);
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];
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
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()); }
php
{ "resource": "" }
q7093
View.setCachePath
train
public function setCachePath($path, $templatesRoot = null) { // Suppress the trailing slash $this->cachePath = preg_replace('#/+$#', '', $path);
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); //
php
{ "resource": "" }
q7095
Feed.getParameter
train
public function getParameter($paramName) { if(isset($this->params[$paramName]))
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');
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');
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");
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++));
php
{ "resource": "" }