_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q253900 | Text.setExtraLanguagesOutdated | validation | private function setExtraLanguagesOutdated($name, $content)
{
foreach ($this->extraLangs as $lang) {
$this->getPageTexts($lang);
$this->contents[$lang][$name]['outdated'] = true;
if (!isset($this->contents[$lang][$name]['content'])) {
$this->contents[$lang][$name]['content'] = $content;
}
$this->writeTextsToFile($lang);
}
} | php | {
"resource": ""
} |
q253901 | Text.removeAll | validation | public function removeAll()
{
$fs = $this->env->getFileSystem();
$fs->deleteFile($this->baseDir . $this->pageName . '.js');
$fs->deleteFile($this->outdatedDir . $this->baseLang . '/' . $this->pageName . '.json');
foreach ($this->extraLangs as $language) {
$fs->deleteFile($this->baseDir . $language . '/' . $this->pageName . '.js');
$fs->deleteFile($this->outdatedDir . $language . '/' . $this->pageName . '.json');
}
} | php | {
"resource": ""
} |
q253902 | OpenPlatform.createAuthorizerApplication | validation | public function createAuthorizerApplication($appId, $refreshToken)
{
$this->fetch('authorizer', function ($authorizer) use ($appId, $refreshToken) {
$authorizer->setAppId($appId);
$authorizer->setRefreshToken($refreshToken);
});
return $this->fetch('app', function ($app) {
$app['access_token'] = $this->fetch('authorizer_access_token');
$app['oauth'] = $this->fetch('oauth');
$app['server'] = $this->fetch('server');
});
} | php | {
"resource": ""
} |
q253903 | PageCollectionBase.contributorDefined | validation | protected function contributorDefined()
{
if (null === $this->username && !$this->configurationHandler->isTheme()) {
$exception = array(
"message" => 'exception_contributor_not_defined',
"show_exception" => true,
);
throw new LogicException(json_encode($exception));
}
} | php | {
"resource": ""
} |
q253904 | Response.getMessage | validation | static public function getMessage($code = self::CODE_INTERNAL_SERVER_ERROR)
{
if (isset(self::$messages[$code])) {
return self::$messages[$code];
}
return self::$messages[self::CODE_INTERNAL_SERVER_ERROR];
} | php | {
"resource": ""
} |
q253905 | SimpleApplication.requirePackage | validation | public function requirePackage(string $package_class) : ApplicationInterface
{
if (!in_array(PackageInterface::class, class_implements($package_class))){
throw new PackageRequireException('Specified package does not implements PackageInterface: ' . $package_class, $package_class);
}
$module_list = call_user_func([$package_class, 'getModuleList']);
if (!is_array($module_list)){
throw new PackageRequireException('Failed to call getModuleList: ' . $package_class, $package_class);
}
$this->required_modules = array_merge($this->required_modules, $module_list);
return $this;
} | php | {
"resource": ""
} |
q253906 | SimpleApplication.install | validation | public function install() : ApplicationInterface
{
try{
// resolve module dependencies
$resolved_modules = (new ModuleDependencyResolver($this->required_modules))->resolve();
// install modules
$this->installModules($resolved_modules);
return $this;
}
catch(\Throwable $e)
{
throw new ApplicationInstallationException(__METHOD__ . ' failed: ' . $e->getMessage() , $e);
}
} | php | {
"resource": ""
} |
q253907 | BlockManagerEdit.edit | validation | public function edit($sourceDir, array $options, $username, $values)
{
$this->resolveOptions($options);
$this->init($sourceDir, $options, $username);
$this->createContributorDir($sourceDir, $options, $username);
$filename = sprintf('%s/blocks/%s.json', $this->getDirInUse(), $options["blockname"]);
$currentBlock = $options["baseBlock"] = JsonTools::jsonDecode(FilesystemTools::readFile($filename));
$values = $this->parseChildren($values);
$block = JsonTools::join($currentBlock, $values);
$encodedBlock = json_encode($block);
$blockClass = BlockFactory::getBlockClass($block["type"]);
$event = Dispatcher::dispatch(
BlockEvents::BLOCK_EDITING,
new BlockEditingEvent($this->serializer, $filename, $encodedBlock, $blockClass)
);
$blockContent = $event->getFileContent();
FilesystemTools::writeFile($filename, $blockContent);
Dispatcher::dispatch(
BlockEvents::BLOCK_EDITED,
new BlockEditedEvent($this->serializer, $filename, $encodedBlock, $blockClass)
);
DataLogger::log(
sprintf(
'Block "%s" has been edited on the "%s" slot on page "%s" for the "%s_%s" language',
$options["blockname"],
$options["slot"],
$options["page"],
$options["language"],
$options["country"]
)
);
} | php | {
"resource": ""
} |
q253908 | DateTimePicker.getInputSpecification | validation | public function getInputSpecification()
{
$datetimeElement = $this;
return array(
'name' => $this->getName(),
'required' => true,
'filters' => array(
array('name' => 'Zend\Filter\StringTrim'),
array(
'name' => 'Callback',
'options' => array(
'callback' => function ($value) use ($datetimeElement) {
if (!empty($value) && is_string($value)) {
return DateTime::createFromFormat($datetimeElement->getFormat(), $value);
}
return $value;
}
)
)
),
'validators' => $this->getValidators(),
);
} | php | {
"resource": ""
} |
q253909 | ModuleOptions.setCacheOptions | validation | public function setCacheOptions($cacheOptions)
{
if ($cacheOptions instanceof CacheOptionsInterface) {
$this->cacheOptions = $cacheOptions;
} elseif (is_array($cacheOptions)) {
$this->cacheOptions = new CacheOptions($cacheOptions);
} else {
throw new Exception\InvalidArgumentException(
sprintf(
'%s expects parameter 1 to be array or an instance of HtSettingsModule\Options\CacheOptionsInterface, %s provided instead',
__METHOD__,
is_object($cacheOptions) ? get_class($cacheOptions) : gettype($cacheOptions)
)
);
}
return $this;
} | php | {
"resource": ""
} |
q253910 | ModuleOptions.addNamespace | validation | public function addNamespace($namespaceOptions, $namespace = null)
{
if (!$namespaceOptions instanceof NamespaceOptionsInterface) {
if (is_array($namespaceOptions)) {
$namespaceOptions = new NamespaceOptions($namespaceOptions);
if ($namespace !== null) {
$namespaceOptions->setName($namespace);
}
} else {
throw new Exception\InvalidArgumentException(
sprintf(
'%s expects parameter 1 to be array or an instance of HtSettingsModule\Options\NamespaceOptionsInterface, %s provided instead',
__METHOD__,
is_object($namespaceOptions) ? get_class($namespaceOptions) : gettype($namespaceOptions)
)
);
}
} else {
if (!$namespaceOptions->getName() && $namespace) {
$namespaceOptions->setName($namespace);
}
}
if ($namespace === null) {
$namespace = $namespaceOptions->getName();
}
$this->namespaces[$namespace] = $namespaceOptions;
} | php | {
"resource": ""
} |
q253911 | StreamWrapper.stream_open | validation | public function stream_open($path)
{
$scheme = parse_url($path, PHP_URL_SCHEME);
if (substr($scheme, -10) === '-emulation') {
$scheme = substr($scheme, 0, -10);
}
$emulator = static::getEmulatorInstance($scheme, $path, $this->getContext());
if (!$emulator) {
return false;
}
$this->setEmulator($emulator);
$this->getEmulator()->setResponseStream($this->callEmulation($this->getEmulator()->getIncomingStream()));
$this->setResponse($this->getEmulator()->getOutgoingStream());
return true;
} | php | {
"resource": ""
} |
q253912 | StreamWrapper.getEmulatorInstance | validation | public static function getEmulatorInstance($scheme, $path, $context)
{
if (!isset(static::$emulators[$scheme])) {
throw new \InvalidArgumentException('No emulator found for scheme \'' . $scheme . '\'');
}
$emulator = static::$emulators[$scheme];
return new $emulator($path, $context);
} | php | {
"resource": ""
} |
q253913 | StreamWrapper.emulate | validation | public static function emulate($emulation, callable $assertionCallable = null)
{
if ((is_string($emulation)) && (class_exists($emulation))) {
$emulation = new $emulation($assertionCallable);
}
static::$emulation = $emulation;
} | php | {
"resource": ""
} |
q253914 | Module.setSourceFiles | validation | public function setSourceFiles($value)
{
foreach ($value as $key => $settings) {
if ($settings === false) {
$this->_sourceFiles[$key] = false;
continue;
}
if (!isset($settings['class'])) {
$settings['class'] = $this->sourceFileClass;
}
$settings['id'] = $key;
$this->_sourceFiles[$key] = Yii::createObject($settings);
}
} | php | {
"resource": ""
} |
q253915 | Module.getForeignModelConfig | validation | public function getForeignModelConfig($sourceFile, $modelName)
{
$config = ['class' => Model::className()];
if (isset($this->foreignModelsConfig[$modelName])) {
$config = array_merge($config, $this->foreignModelsConfig[$modelName]);
}
$config['modelName'] = $modelName;
$config['sourceFile'] = $sourceFile;
$config['interface'] = $this;
return $config;
} | php | {
"resource": ""
} |
q253916 | Module.getForeignModel | validation | public function getForeignModel($model)
{
$models = $this->foreignModels;
if (isset($models[$model])) {
return $models[$model];
}
return false;
} | php | {
"resource": ""
} |
q253917 | BlockManagerApprover.approve | validation | public function approve($sourceDir, array $options, $username)
{
$this->init($sourceDir, $options, $username);
$sourceFilename = sprintf('%s/blocks/%s.json', $this->contributorDir, $options['blockname']);
$targetFilename = sprintf('%s/blocks/%s.json', $this->productionDir, $options['blockname']);
Dispatcher::dispatch(
BlockEvents::BLOCK_APPROVING,
new BlockApprovingEvent($this->serializer, $sourceFilename, $targetFilename)
);
$blockValues = JsonTools::jsonDecode(FilesystemTools::readFile($sourceFilename));
$blockValues["history"] = array();
FilesystemTools::writeFile($targetFilename, json_encode($blockValues));
$slotDefinitionContribution = $this->getSlotDefinition($this->getContributorDir());
$this->saveSlotDefinition($this->productionDir, $slotDefinitionContribution);
Dispatcher::dispatch(
BlockEvents::BLOCK_APPROVED,
new BlockApprovedEvent($this->serializer, $sourceFilename, $targetFilename)
);
DataLogger::log(
sprintf(
'Block "%s" has been approved on the "%s" slot on page "%s" for the "%s_%s" language',
$options["blockname"],
$options["slot"],
$options["page"],
$options["language"],
$options["country"]
)
);
return $blockValues;
} | php | {
"resource": ""
} |
q253918 | BlockManagerApprover.approveRemoval | validation | public function approveRemoval($sourceDir, array $options, $username)
{
$this->init($sourceDir, $options, $username);
$targetFilename = sprintf('%s/blocks/%s.json', $this->productionDir, $options['blockname']);
if (!file_exists($targetFilename)) {
// @codeCoverageIgnoreStart
return;
// @codeCoverageIgnoreEnd
}
Dispatcher::dispatch(
BlockEvents::BLOCK_APPROVING_REMOVAL,
new BlockApprovingRemovalEvent($this->serializer, $targetFilename)
);
$this->filesystem->remove($targetFilename);
$slotDefinition = $this->getSlotDefinition($this->productionDir);
$blocks = $slotDefinition["blocks"];
$key = array_search($options['blockname'], $blocks);
unset($blocks[$key]);
$slotDefinition["blocks"] = $blocks;
$this->saveSlotDefinition($this->productionDir, $slotDefinition, $username);
Dispatcher::dispatch(
BlockEvents::BLOCK_APPROVED_REMOVAL,
new BlockApprovedRemovalEvent($this->serializer, $targetFilename)
);
DataLogger::log(
sprintf(
'Block "%s" has been approved for removal on the "%s" slot on page "%s" for the "%s_%s" language',
$options["blockname"],
$options["slot"],
$options["page"],
$options["language"],
$options["country"]
)
);
} | php | {
"resource": ""
} |
q253919 | Response.toJSON | validation | public function toJSON($pretty = false)
{
if ($pretty) {
return json_encode($this->scope->results, JSON_PRETTY_PRINT);
}
return json_encode($this->scope->results);
} | php | {
"resource": ""
} |
q253920 | BlockFactory.boot | validation | public static function boot(ConfigurationHandler $configurationHandler)
{
$pluginDirs = $configurationHandler->pluginFolders();
foreach ($pluginDirs as $pluginDir) {
self::$blocks += self::parse($pluginDir);
}
} | php | {
"resource": ""
} |
q253921 | ArgvInput.hasFlag | validation | public function hasFlag($name)
{
$option = $this->definition->getOption($name);
if (!$option->isFlag()) {
throw new \InvalidArgumentException(sprintf('The "--%s" option is not a flag.', $name));
}
return !empty($this->options[$name]);
} | php | {
"resource": ""
} |
q253922 | MessageBuilder.send | validation | public function send()
{
if (empty($this->message)) {
throw new RuntimeException('No message to send.');
}
$transformer = new Transformer();
if ($this->message instanceof RawMessage) {
$message = $this->message->get('content');
} else {
$content = $transformer->transform($this->message);
$message = [
'touser' => $this->to,
];
if ($this->account) {
$message['customservice'] = ['kf_account' => $this->account];
}
$message = array_merge($message, $content);
}
return $this->staff->send($message);
} | php | {
"resource": ""
} |
q253923 | FxpBlockExtension.registerProfilerConfiguration | validation | private function registerProfilerConfiguration(array $config, XmlFileLoader $loader)
{
if ($config['enabled'] && $config['collect'] && class_exists('Symfony\Component\Debug\Debug')) {
$loader->load('block_debug.xml');
$loader->load('collectors.xml');
}
} | php | {
"resource": ""
} |
q253924 | Matrix.process | validation | public function process()
{
$orderedTasks = $this->_tasks;
usort($orderedTasks, function($a, $b) {
return $a->duration() > $b->duration() ? 1 : -1;
});
$this->_ranking = $orderedTasks;
$matrix = [];
foreach($this->_ranking as $task1) {
$name1 = $task1->name();
$matrix[$name1] = [];
foreach($this->_ranking as $task2) {
$name2 = $task2->name();
$percent = intval(round($task1->duration() / $task2->duration() * 100));
$matrix[$name1][$name2] = $percent;
}
}
$this->_matrix = $matrix;
return $this;
} | php | {
"resource": ""
} |
q253925 | Web2All_Table_ObjectList.offsetSet | validation | public function offsetSet($offset, $value){
if (is_null($this->result)) {
$this->fetchData();
}
if (!$this->isFetched()) {
trigger_error('Web2All_Table_ObjectList::offsetSet: cannot set value on unitialized list',E_USER_NOTICE);
return false;
}
if (!$this->is_assoc && !is_numeric($value)) {
trigger_error('Web2All_Table_ObjectList::offsetSet: can only set numeric keys non assoc lists',E_USER_NOTICE);
return false;
}
if ($value instanceof $this->classname) {
$this->result[$offset]=$value;
}else{
trigger_error('Web2All_Table_ObjectList::offsetSet: can only add objects of type '.$this->classname.' to the list',E_USER_NOTICE);
return false;
}
} | php | {
"resource": ""
} |
q253926 | Web2All_Table_ObjectList.removeFromDB | validation | public function removeFromDB(){
if (is_null($this->result)) {
$this->fetchData();
}
if(count($this->result) > 0){
if(!$this->result[0] instanceof Web2All_Table_SaveObject){
throw new Exception("Web2All_Table_ObjectList->removeFromDB: Not a saveobject, you can't delete a non saveobject.");
}
foreach($this->result as $row){
$row->deleteFromDB();
}
}
} | php | {
"resource": ""
} |
q253927 | Inferrer.inferType | validation | public function inferType($value) {
if (is_string($value)) {
return new StringType();
} elseif (is_array($value)) {
return new ArrayType();
} elseif (is_object($value)) {
return $this->inferObjectType($value);
} elseif (is_integer($value)) {
return new IntegerType();
} elseif (is_bool($value)) {
return new BooleanType();
} elseif(is_null($value)) {
return new MixedType();
}
$e = new InferException('Typ konnte nicht geraten werden: '.Util::varInfo($value));
$e->value = $value;
throw $e;
} | php | {
"resource": ""
} |
q253928 | Configuration.init | validation | public function init($confPath, $useCache = true)
{
$this->confPath = $confPath;
if ($useCache) {
$cachedConfig = new PhpConfiguration();
$this->cache = $cachedConfig->get();
unset($cachedConfig);
}
} | php | {
"resource": ""
} |
q253929 | Configuration.load | validation | protected function load($namespace, $require = false)
{
// If cache is set.
if (isset($this->cache[$namespace])) {
return $this->cache[$namespace];
}
$file = $this->getConfigFile($namespace);
$configuration = null;
try {
$configFile = new YamlConfiguration($file);
$configuration = $configFile->get();
if (is_array($configuration) && !empty($configuration['inherits'])) {
$allConfiguration = [];
foreach ($configuration['inherits'] as $parentNamespace) {
$allConfiguration[] = $this->load($parentNamespace);
}
$allConfiguration[] = $configuration;
$configuration = $this->merge($allConfiguration);
unset($allConfiguration, $configuration['inherits']);
}
unset($configFile);
} catch (FileNotFoundException $e) {
if ($require) {
throw new FileNotFoundException('Could not find settings file for ' . $namespace);
}
}
return $this->cache[$namespace] = $configuration;
} | php | {
"resource": ""
} |
q253930 | Configuration.get | validation | public function get($namespace, $name, $default = null, $require = false)
{
$configuration = $this->load($namespace, $require);
return array_key_exists($name, $configuration) ? $configuration[$name] : $default;
} | php | {
"resource": ""
} |
q253931 | Configuration.merge | validation | protected function merge(array $configs)
{
$objects = array_filter($configs, 'is_object');
if (!empty($objects)) {
$listConfigs = [];
foreach ($configs as $config) {
if (!is_object($config)) {
throw new RuntimeException('Cannot merge object with other types');
}
$listConfigs[] = (array) $config;
}
$result = (object) $this->merge($listConfigs);
} else {
foreach ($configs as $config) {
foreach ($config as $key => $value) {
$existed = isset($result[$key]);
switch (true) {
case ($existed && (is_object($result[$key]) || is_object($value))):
case ($existed && (is_array($result[$key]) && is_array($value))):
$result[$key] = $this->merge(array($result[$key], $value));
break;
default:
$result[$key] = $value;
}
}
}
}
return $result;
} | php | {
"resource": ""
} |
q253932 | SpecReporter.outputError | validation | protected function outputError($errorNumber, $test, $exception)
{
$feature = null;
$scenario = null;
$testDescription = null;
$node = $test;
while ($node !== null) {
$class = get_class($node);
$description = str_replace(
"\n ",
"\n ",
$node->getDescription()
);
if ($description === '') {
$node = $node->getParent();
continue;
}
if ($class === 'Peridot\Core\Test') {
$testDescription = $description;
} elseif ($class === 'Peridot\Core\Suite') {
if (strpos($description, 'Feature:') === 0) {
$feature = $description;
} else {
$scenario = trim($description);
}
}
$node = $node->getParent();
}
if ($this->lastFeature !== $feature) {
$this->output->writeln(" " . $feature . "\n");
$this->lastFeature = $feature;
$this->lastScenario = null;
}
if ($this->lastScenario !== $scenario) {
$this->output->writeln(" " . $scenario . "\n");
$this->lastScenario = $scenario;
}
$this->output->writeln(
$this->color(
'error',
sprintf(" %d) %s", $errorNumber, $testDescription)
)
);
$message = sprintf(
" %s",
str_replace("\n", "\n ", $exception->getMessage())
);
$this->output->writeln($this->color('pending', $message));
$class = method_exists($exception, 'getClass') ?
$exception->getClass() :
get_class($exception);
$trace = method_exists($exception, 'getTrueTrace') ?
$exception->getTrueTrace() :
$exception->getTrace();
array_unshift($trace, [
'function' => $class . ' thrown',
'file' => $exception->getFile(),
'line' => $exception->getLine()
]);
$this->outputTrace($trace);
} | php | {
"resource": ""
} |
q253933 | ThemeSlotsGenerator.synchronize | validation | public function synchronize(Page $page, array $pages)
{
if (!$this->configurationHandler->isTheme()) {
return;
}
foreach ($pages as $pageValues) {
$tokens = explode("_", $pageValues["seo"][0]["language"]);
$pageOptions = array(
'page' => $pageValues["name"],
'language' => $tokens[0],
'country' => $tokens[1],
);
$page->render($this->configurationHandler->siteDir(), $pageOptions);
$this->saveTemplateSlots($page->getPageSlots(), $pageValues["template"]);
}
$this->saveTemplateSlots($page->getCommonSlots(), 'base');
} | php | {
"resource": ""
} |
q253934 | ThemeSlotsGenerator.generate | validation | public function generate()
{
$templates = array_merge(array_keys($this->templates["base"]), array_keys($this->templates["template"]));
foreach($templates as $template) {
$templateDir = $this->themeDir . '/' . $template;
if (!is_dir($templateDir)) {
continue;
}
$finder = new Finder();
$files = $finder->files()->depth(0)->in($templateDir);
foreach ($files as $file) {
$file = (string)$file;
$slotName = basename($file, '.json');
$json = FilesystemTools::readFile($file);
$slot = json_decode($json, true);
$blocks = array();
if (array_key_exists("blocks", $slot)) {
$blocks = $slot["blocks"];
}
$slotManager = $this->slotsManagerFactory->createSlotManager($slot["repeat"]);
$slotManager->addSlot($slotName, $blocks);
}
}
} | php | {
"resource": ""
} |
q253935 | Configure.addOption | validation | public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null) : self
{
$this->cmd->addOption($name, $shortcut, $mode, $description, $default);
return $this;
} | php | {
"resource": ""
} |
q253936 | Builder.getVendorDir | validation | static function getVendorDir( $vendorPrefix = 'vendor' )
{
if( is_dir( __DIR__ . '/../../../composer' ) && is_file( __DIR__ . '/../../../autoload.php' ) )
{
return realpath( __DIR__ . '/../../..' );
}
if( is_dir( __DIR__ . "/../$vendorPrefix/composer" ) && is_file( __DIR__ . "/../$vendorPrefix/autoload.php" ) )
{
return realpath( __DIR__ . "/../$vendorPrefix" );
}
return false;
} | php | {
"resource": ""
} |
q253937 | Builder.getAvailableExtNames | validation | static function getAvailableExtNames()
{
$files = pakeFinder::type( 'file' )->name( 'options-*.yaml' )->not_name( 'options-sample.yaml' )->not_name( 'options-user.yaml' )->maxdepth( 0 )->in( self::getOptionsDir() );
foreach ( $files as $i => $file )
{
$files[$i] = substr( basename( $file ), 8, -5 );
}
return $files;
} | php | {
"resource": ""
} |
q253938 | Builder.getOpts | validation | static function getOpts( $extname='', $version='', $cliopts = array() )
{
self::setConfigDir( $cliopts );
if ( $version == '' && self::isValidVersion( $extname ) )
{
// lazy user
$version = $extname;
$extname = '';
}
if ( $version != '' && !self::isValidVersion( $version ) )
{
throw new PakeException( "'$version' is not a valid version number" );
}
if ( $extname == '' )
{
$extname = self::getDefaultExtName();
}
/// @bug we cache the options gotten from disk, but what if this function is invoked multiple times with different cli options?
if ( !isset( self::$options[$extname] ) || !is_array( self::$options[$extname] ) )
{
// custom config file
if ( isset( $cliopts['config-file'] ) )
{
$cfgfile = $cliopts['config-file'];
}
else
{
$cfgfile = self::getOptionsDir() . "/options-$extname.yaml";
}
// user-local config file
if ( isset( $cliopts['user-config-file'] ) )
{
$usercfgfile = $cliopts['user-config-file'];
if ( !is_file( $cliopts['user-config-file'] ) )
{
throw new PakeException( "Could not find user-configuration-file {$cliopts['user-config-file']}" );
}
}
else
{
$usercfgfile = self::getOptionsDir() . "/options-user.yaml";
}
// command-line config options
foreach( $cliopts as $opt => $val )
{
if ( substr( $opt, 0, 7 ) == 'option.')
{
unset( $cliopts[$opt] );
// transform dotted notation in array structure
$work = array_reverse( explode( '.', substr( $opt, 7 ) ) );
$built = array( array_shift( $work ) => $val );
foreach( $work as $key )
{
$built = array( $key=> $built );
}
self::recursivemerge( $cliopts, $built );
}
}
self::loadConfiguration( $cfgfile, $extname, $version, $usercfgfile, $cliopts );
}
pake_echo( "Building extension $extname ( " . self::$options[$extname]['extension']['name'] . " ) version " .
self::$options[$extname]['version']['alias'] .
self::$options[$extname]['releasenr']['separator'] .
self::$options[$extname]['version']['release'] );
return self::$options[$extname];
} | php | {
"resource": ""
} |
q253939 | Builder.archiveDir | validation | static function archiveDir( $sourcedir, $archivefile, $no_top_dir=false )
{
// please tar cmd on win - OH MY!
$archivefile = str_replace( '\\', '/', $archivefile );
$sourcedir = str_replace( '\\', '/', realpath( $sourcedir ) );
if( $no_top_dir )
{
$srcdir = '.';
$workdir = $sourcedir;
}
else
{
$srcdir = basename( $sourcedir );
$workdir = dirname( $sourcedir );
}
$archivedir = dirname( $archivefile );
$extra = '';
$tar = self::getTool( 'tar' );
if ( substr( $archivefile, -7 ) == '.tar.gz' || substr( $archivefile, -4 ) == '.tgz' )
{
$cmd = "$tar -z -cvf";
$extra = "-C " . escapeshellarg( $workdir );
$workdir = $archivedir;
$archivefile = basename( $archivefile );
}
else if ( substr( $archivefile, -8 ) == '.tar.bz2' )
{
$cmd = "$tar -j -cvf";
$extra = "-C " . escapeshellarg( $workdir );
$workdir = $archivedir;
$archivefile = basename( $archivefile );
}
else if ( substr( $archivefile, -4 ) == '.tar' )
{
$cmd = "$tar -cvf";
$extra = "-C " . escapeshellarg( $workdir );
$workdir = $archivedir;
$archivefile = basename( $archivefile );
}
else if ( substr( $archivefile, -4 ) == '.zip' )
{
$zip = self::getTool( 'zip' );
$cmd = "$zip -9 -r";
}
else
{
throw new pakeException( "Can not determine archive type from filename: $archivefile" );
}
pake_sh( self::getCdCmd( $workdir ) . " && $cmd $archivefile $extra $srcdir" );
pake_echo_action( 'file+', $archivefile );
} | php | {
"resource": ""
} |
q253940 | Builder.pake_antpattern | validation | static function pake_antpattern( $files, $rootdir )
{
$results = array();
foreach( $files as $file )
{
//echo " Beginning with $file in dir $rootdir\n";
// safety measure: try to avoid multiple scans
$file = str_replace( '/**/**/', '/**/', $file );
$type = 'any';
// if user set '/ 'as last char: we look for directories only
if ( substr( $file, -1 ) == '/' )
{
$type = 'dir';
$file = substr( $file, 0, -1 );
}
// managing 'any subdir or file' as last item: trick!
if ( strlen( $file ) >= 3 && substr( $file, -3 ) == '/**' )
{
$file .= '/*';
}
$dir = dirname( $file );
$file = basename( $file );
if ( strpos( $dir, '**' ) !== false )
{
$split = explode( '/', $dir );
$path = '';
foreach( $split as $i => $part )
{
if ( $part != '**' )
{
$path .= "/$part";
}
else
{
//echo " Looking for subdirs in dir $rootdir{$path}\n";
$newfile = implode( '/', array_slice( $split, $i + 1 ) ) . "/$file" . ( $type == 'dir'? '/' : '' );
$dirs = pakeFinder::type( 'dir' )->in( $rootdir . $path );
// also cater for the case '** matches 0 subdirs'
$dirs[] = $rootdir . $path;
foreach( $dirs as $newdir )
{
//echo " Iterating in $newdir, looking for $newfile\n";
$found = self::pake_antpattern( array( $newfile ), $newdir );
$results = array_merge( $results, $found );
}
break;
}
}
}
else
{
//echo " Looking for $type $file in dir $rootdir/$dir\n";
$found = pakeFinder::type( $type )->name( $file )->maxdepth( 0 )->in( $rootdir . '/' . $dir );
//echo " Found: " . count( $found ) . "\n";
$results = array_merge( $results, $found );
}
}
return $results;
} | php | {
"resource": ""
} |
q253941 | CacheFactory.createServiceWithName | validation | public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
$config = $serviceLocator->get('config');
if (isset($config['rznviewcomponent']['cache_adapter']))
{
$config = $config['rznviewcomponent']['cache_adapter'];
}
else
$config = array(
'name' => 'filesystem',
'options' => array(
'ttl' => 3600,
'dirLevel' => 2,
'file_locking' => false,
'cacheDir' => 'data/cache',
'dirPermission' => 0755,
'filePermission' => 0666,
),
);
return \Zend\Cache\StorageFactory::factory(
array(
'adapter' => $config,
'plugins' => array('serializer'),
)
);
} | php | {
"resource": ""
} |
q253942 | CkEditor.setEditorConfig | validation | public function setEditorConfig($config)
{
if ($config instanceof Traversable) {
$config = ArrayUtils::iteratorToArray($config);
}
if (!is_array($config)) {
throw new InvalidArgumentException(
'The options parameter must be an array or a Traversable'
);
}
$this->editorConfig = $config;
return $this;
} | php | {
"resource": ""
} |
q253943 | ContainerBase.get | validation | public function get($id)
{
if (isset($this->singletons[$id])) {
return $this->singletons[$id];
}
$methodName = 'get' . Util::mapIdToCamelCase($id);
if (method_exists($this, $methodName)) {
return $this->$methodName();
}
throw new \InvalidArgumentException("Unknown service '$id' in container '" . get_called_class() . "'");
} | php | {
"resource": ""
} |
q253944 | PublishPageController.publishAction | validation | public function publishAction(Request $request, Application $app)
{
$options = array(
"request" => $request,
"page_manager" => $app["red_kite_cms.page_manager"],
"username" => $this->fetchUsername($app["security"], $app["red_kite_cms.configuration_handler"]),
);
return parent::publish($options);
} | php | {
"resource": ""
} |
q253945 | Page.getTitleAttribute | validation | public function getTitleAttribute($value)
{
if ($value === null) {
$value = '';
}
if (getenv("BYPASS_HOOKS") != true) {
global $hooks, $codes;
return $hooks->apply_filters("TCT-Core-Main-Model-Page-Title", $codes->do_shortcode($value));
} else {
return $value;
}
} | php | {
"resource": ""
} |
q253946 | Page.getContentAttribute | validation | public function getContentAttribute($value)
{
if ($value === null) {
$value = '';
}
if (getenv("BYPASS_HOOKS") != true) {
global $hooks, $codes;
return markdown_interpreter($hooks->apply_filters("TCT-Core-Main-Model-Page-Content", $codes->do_shortcode($value)));
} else {
return $value;
}
} | php | {
"resource": ""
} |
q253947 | Service.getAllCommands | validation | public static function getAllCommands(): array
{
/* Get All Commands */
$commands = [];
foreach (get_declared_classes() as $class) {
if (is_subclass_of($class, 'Senhung\CLI\Command')) {
$commandObject = new $class;
$command = $commandObject->getCommand();
$commands[$command] = $class;
}
}
return $commands;
} | php | {
"resource": ""
} |
q253948 | Service.parseSignature | validation | public static function parseSignature(string $signature): array
{
/* Parse Signature to Array */
$signature = explode(' ', trim($signature));
/* Initialize */
$command = trim($signature[0]);
$arguments = [];
$options = [];
/* Check Each Word */
foreach ($signature as $word) {
$type = self::determineTypeOfWord($word);
/* Option */
if ($type == self::OPTION_TYPE) {
list($key, $defaultValue) = self::parse($word);
$options[$key] = $defaultValue;
}
/* Argument */
elseif ($type == self::ARGUMENT_TYPE) {
list($key, $defaultValue) = self::parse($word);
$arguments[$key] = $defaultValue;
}
}
return [$command, $arguments, $options];
} | php | {
"resource": ""
} |
q253949 | Service.runCommand | validation | public static function runCommand(string $command, array $arguments = null, array $options = null): void
{
$commandObject = new $command($arguments, $options);
$commandObject->update($arguments, $options);
$commandObject->handle();
} | php | {
"resource": ""
} |
q253950 | Service.parse | validation | public static function parse(string $word): array
{
$word = ltrim(rtrim(trim($word), '}'), '{');
/* Having Default Value */
if ($separatorPosition = strpos($word, '=')) {
$key = substr($word, 0, $separatorPosition);
$defaultValue = substr($word, $separatorPosition + 1);
return [$key, $defaultValue];
}
return [$word, null];
} | php | {
"resource": ""
} |
q253951 | Container.make | validation | public function make($instance, $parameters = [])
{
return $this->resolve($instance, is_array($parameters) ? $parameters
: array_slice(func_get_args(), 1));
} | php | {
"resource": ""
} |
q253952 | Container.register | validation | public function register($alias, $abstract)
{
if (!is_string($alias) || !is_string($abstract)) {
throw new \InvalidArgumentException(
sprintf("Parameter 1 and 2 of %s must be a string.", __METHOD__)
);
}
if (!isset($this->aliases[$alias])) {
$this->aliases[$alias] = $this->make($abstract);
}
return $this;
} | php | {
"resource": ""
} |
q253953 | Container.getResolvedConcreteFlag | validation | public function getResolvedConcreteFlag($abstract)
{
if (!$this->hasResolvedConcrete($abstract)) {
throw Internal\Exception\ReflectionExceptionFactory::invalidArgument(
sprintf(
"Parameter 1 of %s must be an abstract class name which exists in resolved concrete stack.",
__METHOD__
)
);
}
return explode('|', $this->resolved[$abstract]['flag']);
} | php | {
"resource": ""
} |
q253954 | Container.resolve | validation | protected function resolve($instance, $parameters = [])
{
// If the current abstract is an interface,
// just return the concrete implementation to the callee.
if ($this->isInterface($instance)) {
return $this->getConcreteFromInterface($instance);
}
// If the current abstract type being managed as a singleton,
// just return it to the caller instead of reinstantiating it.
try {
return $this->getResolvedSingleton($instance);
} catch (\Exception $e) {
}
$concrete = $this->getConcrete($instance);
if (!is_null($concrete)) {
$object = $this->build($instance,
$concrete instanceof \Closure ? $concrete($this) : $concrete);
if ($this->isShared($instance)) {
$this->markAsResolved($instance, $object, 'singleton');
} else {
$this->markAsResolved($instance, $object);
}
} else {
$object = $this->build($instance, $parameters);
}
return $object;
} | php | {
"resource": ""
} |
q253955 | Container.resolveMethodParameters | validation | protected function resolveMethodParameters($params = [])
{
if (!is_array($params)) {
throw new \InvalidArgumentException(
sprintf("Parameter 1 of %s must be an array.", __METHOD__)
);
}
foreach ($params as $key => $value) {
if ($value instanceof \ReflectionParameter) {
$class = $value->getClass();
if ($class instanceof \ReflectionClass) {
if ($class->isInterface()) {
$params[$key] = $this->getConcreteFromInterface($class->getName());
} else {
$params[$key] = $this->circularDependencyResolver($class->getName());
}
} else {
$params[$key] = ($value->isDefaultValueAvailable()
? $value->getDefaultValue() : null);
}
} else {
if (is_string($value) && class_exists($value)) {
$params[$key] = $this->circularDependencyResolver($value);
} elseif ($value instanceof \Closure) {
$params[$key] = $value($this);
} else {
$params[$key] = $value;
}
}
}
return $params;
} | php | {
"resource": ""
} |
q253956 | Container.circularDependencyResolver | validation | protected function circularDependencyResolver($class)
{
if (!is_string($class) && !class_exists($class)) {
throw Internal\Exception\ReflectionExceptionFactory::invalidArgument(
sprintf("Parameter 1 of %s must be a string of valid class name.", __METHOD__)
);
}
$reflector = Internal\ReflectionClassFactory::create($class);
if (!$this->hasConstructor($reflector)) {
return $this->resolveInstanceWithoutConstructor($reflector);
} else {
$param = $this->getMethodParameters($reflector, '__construct');
if (empty($param)) {
return $reflector->newInstance();
} else {
foreach ($param as $key => $value) {
$class = $value->getClass();
if ($class instanceof \ReflectionClass) {
if ($class->isInterface()) {
$param[$key] = $this->getConcreteFromInterface($class->getName());
} else {
$param[$key] = $this->circularDependencyResolver($class->getName());
}
}
}
return $reflector->newInstanceArgs($param);
}
}
} | php | {
"resource": ""
} |
q253957 | Container.getConcreteFromInterface | validation | protected function getConcreteFromInterface($interface)
{
if (!$this->isAbstractExists($interface)) {
throw Internal\Exception\ReflectionExceptionFactory::runtime(
sprintf("%s has no concrete implementation in the class binding stack.", $interface)
);
}
try {
return $this->getResolvedSingleton($interface);
} catch (\Exception $e) {
}
$concrete = $this->bindings[$interface]['concrete'];
$object = $concrete instanceof \Closure ? $concrete($this) : $this->build($concrete);
if ($this->isShared($interface)) {
$this->markAsResolved($interface, $object, 'singleton');
} else {
$this->markAsResolved($interface, $object);
}
return $object;
} | php | {
"resource": ""
} |
q253958 | Container.getMethodParameters | validation | protected function getMethodParameters(Internal\ReflectionClassFactory $refl, $method)
{
return ($refl->hasMethod($method) ? $refl->getMethod($method)->getParameters() : null);
} | php | {
"resource": ""
} |
q253959 | Container.markAsResolved | validation | protected function markAsResolved($abstract, $resolvedInstance, $flag = [])
{
if (!is_array($flag)) {
$flag = array_slice(func_get_args(), 2);
}
if ($this->isAbstractExists($abstract)) {
$this->resolved[$abstract] = [
'concrete' => $resolvedInstance,
'resolved' => true,
'flag' => join('|', $flag)
];
}
} | php | {
"resource": ""
} |
q253960 | Container.bind | validation | public function bind($abstract, $concrete = null, $shared = false)
{
if (is_null($concrete)) {
$concrete = $abstract;
}
if (!($concrete instanceof \Closure)) {
$concrete = $this->turnIntoResolvableClosure($abstract, $concrete);
}
$this->bindings[$abstract] = compact('concrete', 'shared');
} | php | {
"resource": ""
} |
q253961 | Container.callInstance | validation | public function callInstance($instance, $args = [])
{
$args = (is_array($args) ? $args : array_slice(func_get_args(), 1));
$current = $this->make($instance);
return call_user_func_array($current, $args);
} | php | {
"resource": ""
} |
q253962 | Container.isShared | validation | public function isShared($abstract)
{
if (!isset($this->bindings[$abstract])) {
throw Internal\Exception\ReflectionExceptionFactory::invalidArgument(
sprintf("Parameter 1 of %s must be valid keys in binding container stack.", __METHOD__)
);
}
return ($this->bindings[$abstract]['shared'] ? true : false);
} | php | {
"resource": ""
} |
q253963 | Container.turnIntoResolvableClosure | validation | protected function turnIntoResolvableClosure($abstract, $concrete)
{
return function (Container $container, $parameters = []) use ($abstract, $concrete) {
return ($abstract == $concrete ? $container->resolve($abstract)
: $container->resolve($concrete, $parameters));
};
} | php | {
"resource": ""
} |
q253964 | SourceFileLine.getContent | validation | public function getContent()
{
if (!isset($this->_content)) {
$this->_content = $this->sourceFile->readLine($this->lineNumber);
}
return $this->_content;
} | php | {
"resource": ""
} |
q253965 | Scope.resetSelf | validation | public function resetSelf()
{
$this->where = '';
$this->select = '*';
$this->limit = 20;
$this->offset = 0;
$this->orderBy = array();
$this->groupBy = array();
$this->prepend = '';
$this->listWordsField = null;
$this->alternativesField = null;
$this->join = null;
} | php | {
"resource": ""
} |
q253966 | Formatter.format | validation | public function format($event)
{
$output = $this->format;
if (array_key_exists('extra', $event) === true)
{
$this->formatExtra($event, $event['extra']);
$event['message'] = 'Missing Key:';
}
else
{
$event['extra'] = [];
}
foreach ($event as $name => $value)
{
if (is_array($value) === true && count($value) === 0)
{
$value = '';
}
else
{
$value = $this->normalize($value);
}
$output = str_replace('%' . $name . '%', $value, $output);
}
return trim($output);
} | php | {
"resource": ""
} |
q253967 | ContentMapper.getContent | validation | public function getContent(array $contentData)
{
// check if all mandatory fields are present
foreach ($this->mandatoryFields as $mandatoryField) {
if (!array_key_exists($mandatoryField, $contentData)) {
throw new ContentException("The field '$mandatoryField' is missing in the given content data");
}
}
// try to create a content model from the available data
try {
// title
$title = "";
if (isset($contentData[self::FIELD_TITLE])) {
$title = $contentData[self::FIELD_TITLE];
}
// summary
$summary = "";
if (isset($contentData[self::FIELD_SUMMARY])) {
$summary = $contentData[self::FIELD_SUMMARY];
}
// description
$description = "";
if (isset($contentData[self::FIELD_DESCRIPTION])) {
$description = $contentData[self::FIELD_DESCRIPTION];
}
$content = new Content($title, $summary, $description);
return $content;
} catch (\Exception $contentException) {
throw new ContentException(sprintf("Failed to create a content model from the given data: %s",
$contentException->getMessage()), $contentException);
}
} | php | {
"resource": ""
} |
q253968 | AbstractFormField.getValueMappedToTemplate | validation | public function getValueMappedToTemplate()
{
if ($this->submitted) {
return $this->submittedValue;
}
if ($this->mapper) {
return $this->mapper->mapToFrom($this->getValue());
}
return $this->getValue();
} | php | {
"resource": ""
} |
q253969 | AbstractFormField.expectsOutcome | validation | public function expectsOutcome(
IOutcomeRule $rule,
IOutcomeRule $rule2 = null,
IOutcomeRule $rule3 = null,
IOutcomeRule $rule4 = null,
IOutcomeRule $rule5 = null,
IOutcomeRule $rule6 = null,
IOutcomeRule $rule7 = null,
IOutcomeRule $rule8 = null,
IOutcomeRule $rule9 = null,
IOutcomeRule $rule10 = null
)
{
foreach (func_get_args() as $arg) {
if ($arg instanceof IInputRule) {
$this->outcomeRules[] = $arg;
}
}
return $this;
} | php | {
"resource": ""
} |
q253970 | API.optionsMap | validation | public function optionsMap(): array
{
$routes_list = $this->router->getRoutes();
$final_routes = $modified_routes = [];
foreach ($routes_list as $route) {
if (isset($modified_routes[$route[1]]) === false) {
$modified_routes[$route[1]] = [];
}
$modified_routes[$route[1]][] = $route[0];
}
foreach ($modified_routes as $route => $method) {
$final_routes[] = ['OPTIONS', $route, function () use ($method) {
return [
"headers" => [
[
'X-PHP-Response-Code: 200',
true,
200
],
[
'Allow: ' . implode(',', $method)
]
],
"response" => ''
];
}];
}
return $final_routes;
} | php | {
"resource": ""
} |
q253971 | SDIS62_View_Helper_Navigation_BootstrapBreadcrumbs.renderStraight | validation | public function renderStraight(Zend_Navigation_Container $container = null)
{
if ($container === null)
{
$container = $this->getContainer();
}
// find deepest active
if (!$active = $this->findActive($container))
{
return '';
}
$active = $active['page'];
// put the deepest active page last in breadcrumbs
if ($this->getLinkLast())
{
$html = '<li>' . $this->htmlify($active) . '</li>';
}
else
{
$html = $active->getLabel();
if ($this->getUseTranslator() && $t = $this->getTranslator())
{
$html = $t->translate($html);
}
$html = '<li class="active">' . $this->view->escape($html) . '</li>';
}
// walk back to root
while (($parent = $active->getParent()) != null)
{
if ($parent instanceof Zend_Navigation_Page)
{
// prepend crumb to html
$html = '<li>' . $this->htmlify($parent) . ' <span class="divider">' .
$this->getSeparator() . '</span></li>' . PHP_EOL . $html;
}
if ($parent === $container)
{
// at the root of the given container
break;
}
$active = $parent;
}
return strlen($html) ? $this->getIndent() . '<ul class="breadcrumb">' . $html . '</ul>' : '';
} | php | {
"resource": ""
} |
q253972 | DashboardController.getTasks | validation | protected function getTasks()
{
$tasks = [];
$tasks['flush-file-cache'] = [];
$tasks['flush-file-cache']['title'] = 'Flush File Cache';
$tasks['flush-file-cache']['description'] = 'Clear the file cache in Cascade';
$tasks['flush-file-cache']['run'] = function () {
Yii::$app->fileCache->flush();
Yii::$app->response->content = 'File cache was flushed!';
Yii::$app->response->taskOptions = ['state' => 'success', 'title' => 'Success'];
};
$tasks['flush-cache'] = [];
$tasks['flush-cache']['title'] = 'Flush Memory Cache';
$tasks['flush-cache']['description'] = 'Clear the memory cache in Cascade';
$tasks['flush-cache']['run'] = function () {
Yii::$app->cache->flush();
Yii::$app->response->content = 'Memory cache was flushed!';
Yii::$app->response->taskOptions = ['state' => 'success', 'title' => 'Success'];
};
return $tasks;
} | php | {
"resource": ""
} |
q253973 | Handler.handle | validation | public function handle($signal) {
if (isset($this->_bySignal[$signal])) {
/** @var Listener $reg */
foreach ($this->_bySignal[$signal] as $reg) {
$reg->interrupt = $signal;
}
} else {
return SIG_DFL;
}
} | php | {
"resource": ""
} |
q253974 | Handler.register | validation | public function register(array $signals, $callableArray = null) {
foreach ($signals as $signal) {
if (!in_array($signal, $this->_signals, true)) {
$signalName = static::getSignalName($signal);
throw new InvalidArgumentException("Signal [{$signalName}] is not supported. Use setSignals() to add support.", $signal);
}
}
$reg = new Listener($signals);
$reg->setNotification($callableArray);
$this->_byId[$reg->id] = $reg;
foreach ($signals as $signal) {
$this->_bySignal[$signal][$reg->id] = $reg;
}
return $reg;
} | php | {
"resource": ""
} |
q253975 | Handler.unregister | validation | public function unregister(Listener $register) {
$id = $register->id;
$success = false;
if (isset($this->_byId[$id])) {
unset($this->_byId[$id]);
$success = true;
}
foreach ($this->_bySignal as $signal => $reg) {
if (isset($reg[$id])) {
unset($this->_bySignal[$signal][$id]);
}
}
return $success;
} | php | {
"resource": ""
} |
q253976 | EloquentTitleIntrospector.setKeyTitle | validation | public function setKeyTitle($class, $column, $title)
{
$class = ltrim($this->getClassName($class),'\\');
$this->manualKeyTitles[$class.'|'.$column] = $title;
return $this;
} | php | {
"resource": ""
} |
q253977 | EloquentTitleIntrospector.mapModelToLangName | validation | public function mapModelToLangName($modelName, $langName)
{
$modelName = $this->getClassName($modelName);
$this->modelToLangName[$modelName] = $langName;
} | php | {
"resource": ""
} |
q253978 | BaseBlock.translate | validation | protected function translate()
{
$translatorOptions = $this->getTranslatorOptions();
if (empty($translatorOptions) && !array_key_exists("fields", $translatorOptions)) {
return;
}
$params = array();
if (array_key_exists("params", $translatorOptions)) {
$params = $translatorOptions["params"];
}
$domain = "RedKiteCms";
if (array_key_exists("domain", $translatorOptions)) {
$domain = $translatorOptions["domain"];
}
foreach ($translatorOptions["fields"] as $field) {
$field = ucfirst($field);
$method = 'get' . $field;
$value = Translator::translate($this->$method(), $params, $domain);
$method = 'set' . $field;
$this->$method($value);
}
} | php | {
"resource": ""
} |
q253979 | FormField.addClass | validation | public function addClass($name){
$classParts=explode(' ',$this->tags['class']);
foreach($classParts as $part){
if($name==$part)
return;
}
$this->tags['class'].=' '.$name;
$this->tags['class']=trim($this->tags['class']);
} | php | {
"resource": ""
} |
q253980 | FormField.removeClass | validation | public function removeClass($name){
$classParts=explode(' ',$this->tags['class']);
$className='';
foreach($classParts as $part){
if($name!=$part){
$className.=' '.$part;
}
}
$this->tags['class']=trim($className);
} | php | {
"resource": ""
} |
q253981 | FormField.setRequired | validation | public function setRequired($flag){
$this->tags['required']=$flag;
if($this->validator){
$this->validator->setOption('empty',!$flag);
}
} | php | {
"resource": ""
} |
q253982 | FormField.getTag | validation | public function getTag($name){
if(!isset($this->tags[$name])){
throw new AttributeNotFoundException($name);
}
return $this->tags[$name];
} | php | {
"resource": ""
} |
q253983 | RedisCluster.removeById | validation | public function removeById($connectionID)
{
if (isset($this->pool[$connectionID])) {
$this->slotmap->reset();
$this->slots = array_diff($this->slots, array($connectionID));
unset($this->pool[$connectionID]);
return true;
}
return false;
} | php | {
"resource": ""
} |
q253984 | RedisCluster.buildSlotMap | validation | public function buildSlotMap()
{
$this->slotmap->reset();
foreach ($this->pool as $connectionID => $connection) {
$parameters = $connection->getParameters();
if (!isset($parameters->slots)) {
continue;
}
foreach (explode(',', $parameters->slots) as $slotRange) {
$slots = explode('-', $slotRange, 2);
if (!isset($slots[1])) {
$slots[1] = $slots[0];
}
$this->slotmap->setSlots($slots[0], $slots[1], $connectionID);
}
}
} | php | {
"resource": ""
} |
q253985 | RedisCluster.askSlotMap | validation | public function askSlotMap(NodeConnectionInterface $connection = null)
{
if (!$connection && !$connection = $this->getRandomConnection()) {
return;
}
$this->slotmap->reset();
$response = $this->queryClusterNodeForSlotMap($connection);
foreach ($response as $slots) {
// We only support master servers for now, so we ignore subsequent
// elements in the $slots array identifying slaves.
list($start, $end, $master) = $slots;
if ($master[0] === '') {
$this->slotmap->setSlots($start, $end, (string) $connection);
} else {
$this->slotmap->setSlots($start, $end, "{$master[0]}:{$master[1]}");
}
}
} | php | {
"resource": ""
} |
q253986 | RedisCluster.move | validation | protected function move(NodeConnectionInterface $connection, $slot)
{
$this->pool[(string) $connection] = $connection;
$this->slots[(int) $slot] = $connection;
$this->slotmap[(int) $slot] = $connection;
} | php | {
"resource": ""
} |
q253987 | RedisCluster.onMovedResponse | validation | protected function onMovedResponse(CommandInterface $command, $details)
{
list($slot, $connectionID) = explode(' ', $details, 2);
if (!$connection = $this->getConnectionById($connectionID)) {
$connection = $this->createConnection($connectionID);
}
if ($this->useClusterSlots) {
$this->askSlotMap($connection);
}
$this->move($connection, $slot);
$response = $this->executeCommand($command);
return $response;
} | php | {
"resource": ""
} |
q253988 | Time.getInputSpecification | validation | public function getInputSpecification()
{
$dateValidator = $this->getDateValidator();
$dateValidatorName = get_class($dateValidator);
return [
'name' => $this->getName(),
'required' => true,
'filters' => [
Filter\StringTrim::class => [
'name' => Filter\StringTrim::class
],
Filter\StripNewlines::class => [
'name' => Filter\StripNewlines::class
],
Filter\StripTags::class => [
'name' => Filter\StripTags::class
],
TimeToDateTime::class => [
'name' => TimeToDateTime::class,
'options' => [
'time_format' => $this->getFormat()
]
]
],
'validators' => [
$dateValidatorName => $dateValidator
]
];
} | php | {
"resource": ""
} |
q253989 | InputField.setPattern | validation | public function setPattern($pattern){
$this->setTag('pattern',$pattern);
if($this->getValidator()){
$this->getValidator()->setOption('pattern',$pattern);
}
} | php | {
"resource": ""
} |
q253990 | SKU.validateSKU | validation | private function validateSKU(string $sku)
{
if (strlen($sku) == 0) {
throw new SKUException("A SKU cannot be empty");
}
// check for white-space
$containsWhitespace = preg_match($this->whiteSpacePattern, $sku) == 1;
if ($containsWhitespace) {
throw new SKUException(sprintf("A SKU cannot contain white space characters: \"%s\"", $sku));
}
// uppercase
$containsUppercaseCharacters = preg_match($this->uppercaseCharactersPattern, $sku) == 1;
if ($containsUppercaseCharacters) {
throw new SKUException(sprintf("A SKU cannot contain uppercase characters: \"%s\"", $sku));
}
// check for invalid characters
$containsInvalidCharacters = preg_match($this->invalidCharactersPattern, $sku) == 1;
if ($containsInvalidCharacters) {
throw new SKUException(sprintf("The SKU \"%s\" contains invalid characters. A SKU can only contain the following characters: a-z, 0-9 and -",
$sku));
}
// check prefix
$prefixMatches = [];
$prefixContainsInvalidCharacters = preg_match($this->invalidPrefixCharacters, $sku, $prefixMatches) == 1;
if ($prefixContainsInvalidCharacters) {
throw new SKUException(sprintf("A SKU cannot start with the given characters: \"%s\"",
implode("", $prefixMatches)));
}
// check suffix
$suffixMatches = [];
$suffixContainsInvalidCharacters = preg_match($this->invalidSuffixCharacters, $sku, $suffixMatches) == 1;
if ($suffixContainsInvalidCharacters) {
throw new SKUException(sprintf("A SKU cannot end with the given characters: \"%s\"",
implode("", $suffixMatches)));
}
// check minimum length
if (strlen($sku) < $this->minLength) {
throw new SKUException(sprintf("The given SKU \"%s\" is too short. The minimum length for a SKU is: %s",
$sku, $this->minLength));
}
// check maximum length
if (strlen($sku) > $this->maxLength) {
throw new SKUException(sprintf("The given SKU \"%s\" is too long (%s character). The maximum length for a SKU is: %s",
strlen($sku), $sku, $this->maxLength));
}
} | php | {
"resource": ""
} |
q253991 | UserAlias.getUserAlias4User | validation | public function getUserAlias4User(UserInterface $user)
{
if (!isset($this->userAliasCache[$user->getUsername()])) {
$userAliasEntityTmp = $this->getUserAliasEntity4User($user);
// workaround for the isset check, null would be false, so we have to set false=)
if (!$userAliasEntityTmp) {
$userAliasEntityTmp = false;
}
$this->userAliasCache[$user->getUsername()] = $userAliasEntityTmp;
}
$userAliasEntity = $this->userAliasCache[$user->getUsername()];
if ($userAliasEntity) {
$result = $userAliasEntity->getCharName();
} else {
$result = $user->getUsername();
}
return $result;
} | php | {
"resource": ""
} |
q253992 | Mailer.sendWelcomeMessage | validation | public function sendWelcomeMessage(User $user, Token $token = null)
{
return $this->sendMessage($user->email,
$this->welcomeSubject,
'welcome',
['user' => $user, 'token' => $token]
);
} | php | {
"resource": ""
} |
q253993 | Mailer.sendConfirmationMessage | validation | public function sendConfirmationMessage(User $user, Token $token)
{
return $this->sendMessage($user->email,
$this->confirmationSubject,
'confirmation',
['user' => $user, 'token' => $token]
);
} | php | {
"resource": ""
} |
q253994 | Mailer.sendRecoveryMessage | validation | public function sendRecoveryMessage(User $user, Token $token)
{
return $this->sendMessage($user->email,
$this->recoverySubject,
'recovery',
['user' => $user, 'token' => $token]
);
} | php | {
"resource": ""
} |
q253995 | Curl.prepareRequest | validation | protected function prepareRequest()
{
// Set data for GET queries
if ($this->method === static::GET && !empty($this->data)) {
$url = trim($this->url, '/') . '?';
$url .= http_build_query($this->data);
} else {
$url = $this->url;
}
// Set options
$options = array(
CURLOPT_URL => $url,
CURLOPT_POST => $this->method === static::POST,
CURLOPT_HEADER => true,
CURLOPT_NOBODY => $this->method === static::HEAD,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => $this->userAgent,
CURLOPT_SSL_VERIFYPEER => false
);
if (!in_array($this->method, [static::GET, static::HEAD, static::POST])) {
$options[CURLOPT_CUSTOMREQUEST] = $this->method;
}
// Set data for not GET queries
if (!empty($this->data) && $this->method !== static::GET) {
$options[CURLOPT_POSTFIELDS] = http_build_query($this->data);
}
// Set headers if needed
if (!empty($this->headers)) {
$headersToSend = [];
foreach ($this->headers as $key => $value) {
$headersToSend[] = "{$key}: {$value}";
}
$options[CURLOPT_HTTPHEADER] = $headersToSend;
}
// Set cookies if needed
if (!empty($this->cookies)) {
$cookiesToSend = [];
foreach ($this->cookies as $key => $value) {
$cookiesToSend[] = "{$key}={$value}";
}
$options[CURLOPT_COOKIE] = implode('; ', $cookiesToSend);
}
curl_setopt_array($this->resource, $options);
} | php | {
"resource": ""
} |
q253996 | Curl.parseResponse | validation | protected function parseResponse()
{
if (isset($this->response)) {
list($responseParts['headersString'], $responseParts['body']) = explode("\r\n\r\n", $this->response, 2);
$responseParts['body'] = htmlspecialchars($responseParts['body']);
$headers = explode("\r\n", $responseParts['headersString']);
$cookies = [];
if (preg_match_all('/Set-Cookie: (.*?)=(.*?)(\n|;)/i', $responseParts['headersString'], $matches)) {
if (!empty($matches)) {
foreach ($matches[1] as $key => $value) {
$cookies[$value] = $matches[2][$key];
}
$responseParts['cookies'] = $cookies;
}
}
unset($responseParts['headersString']);
$first = true;
foreach ($headers as $header) {
if ($first) {
list($responseParts['protocol'], $responseParts['statusCode']) = explode(' ', $header, 2);
$first = false;
} else {
$tmp = (explode(': ', $header));
if ($tmp[0] === 'Set-Cookie') {
continue;
} else {
$responseParts['headersArray'][$tmp[0]] = $tmp[1];
}
}
}
return $responseParts;
} else {
return null;
}
} | php | {
"resource": ""
} |
q253997 | CreateFieldsOnGroupCommand.deleteFieldsForCFGroup | validation | protected function deleteFieldsForCFGroup($customFieldsGroup)
{
$em = $this->getContainer()
->get('doctrine.orm.default_entity_manager');
foreach ($customFieldsGroup->getCustomFields() as $field) {
$em->remove($field);
}
} | php | {
"resource": ""
} |
q253998 | Benri_Controller_Plugin_RequireUserAgentHeader.routeStartup | validation | public function routeStartup(Zend_Controller_Request_Abstract $request)
{
if (!$request->getHeader('User-Agent')) {
$this
->getResponse()
->setHttpResponseCode(403)
->setHeader('Content-Type', 'text/plain; charset=utf-8')
->setBody(implode("\n", self::$_errMessage))
->sendResponse();
exit(403);
}
} | php | {
"resource": ""
} |
q253999 | MediaLink.getNew | validation | public static function getNew() {
//Get the default properties;
$class = new MediaLink;
$medialink = get_class_vars(get_class($class));
//Reset this class!
foreach ($medialink as $name => $default):
$class::set($name, null);
$class::set("objectType", "medialink");
endforeach;
return $class;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.