_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q10600 | ChartIterator.getScripts | train | public function getScripts()
{
$retVal = '';
while ( $this->scripts->valid() ) {
$retVal .= "<script type='text/javascript'>\n{$this->scripts->get()}\n</script>\n";
$this->scripts->next();
}
return $retVal;
} | php | {
"resource": ""
} |
q10601 | ChartIterator.getLibraries | train | public function getLibraries()
{
$config = \Altamira\Config::getInstance();
$libraryToPath = array(
\Altamira\JsWriter\Flot::LIBRARY => $config['js.flotlib'],
\Altamira\JsWriter\JqPlot::LIBRARY => $config['js.jqplotlib']
);
$libraryKeys = array_unique( array_keys( $this->libraries ) );
$libraryPaths = array();
foreach ($libraryKeys as $key) {
$libraryPaths[] = $libraryToPath[$key];
}
return $libraryPaths;
} | php | {
"resource": ""
} |
q10602 | ChartIterator.renderCss | train | public function renderCss()
{
$config = \Altamira\Config::getInstance();
foreach ( $this->libraries as $library => $junk ) {
switch( $library ) {
case \Altamira\JsWriter\Flot::LIBRARY:
break;
case \Altamira\JsWriter\JqPlot::LIBRARY:
default:
$cssPath = $config['css.jqplotpath'];
}
}
if ( isset( $cssPath ) ) {
echo "<link rel='stylesheet' type='text/css' href='{$cssPath}'></link>";
}
return $this;
} | php | {
"resource": ""
} |
q10603 | InstallerController.getForm | train | protected function getForm($configPath)
{
$form = null;
$melisConfig = $this->serviceLocator->get('MelisInstallerConfig');
$formConfig = $melisConfig->getItem($configPath);
if ($formConfig) {
$factory = new \Zend\Form\Factory();
$formElements = $this->getServiceLocator()->get('FormElementManager');
$factory->setFormElementManager($formElements);
$form = $factory->createForm($formConfig);
}
return $form;
} | php | {
"resource": ""
} |
q10604 | InstallerController.systemConfigurationChecker | train | protected function systemConfigurationChecker()
{
$response = [];
$data = [];
$errors = [];
$dataExt = [];
$dataVar = [];
$checkDataExt = 0;
$success = 0;
$translator = $this->getServiceLocator()->get('translator');
$installHelper = $this->getServiceLocator()->get('InstallerHelper');
$installHelper->setRequiredExtensions([
'openssl',
'json',
'pdo_mysql',
'intl',
]);
foreach ($installHelper->getRequiredExtensions() as $ext) {
if (in_array($ext, $installHelper->getPhpExtensions())) {
$dataExt[$ext] = $installHelper->isExtensionsExists($ext);
} else {
$dataExt[$ext] = sprintf($translator->translate('tr_melis_installer_step_1_0_extension_not_loaded'), $ext);
}
}
$dataVar = $installHelper->checkEnvironmentVariables();
// checks if all PHP configuration is fine
if (!empty($dataExt)) {
foreach ($dataExt as $ext => $status) {
if ((int) $status === 1) {
$checkDataExt = 1;
} else {
$checkDataExt = 0;
}
}
}
if (!empty($dataVar)) {
foreach ($dataVar as $var => $value) {
$currentVal = trim($value);
if (is_null($currentVal)) {
$dataVar[$var] = sprintf($translator->translate('tr_melis_installer_step_1_0_php_variable_not_set'), $var);
array_push($errors, sprintf($translator->translate('tr_melis_installer_step_1_0_php_variable_not_set'), $var));
} elseif ($currentVal || $currentVal == '0' || $currentVal == '-1') {
$dataVar[$var] = 1;
}
}
} else {
array_push($errors, $translator->translate('tr_melis_installer_step_1_0_php_requied_variables_empty'));
}
// last checking
if (empty($errors) && $checkDataExt === 1) {
$success = 1;
}
$response = [
'success' => $success,
'errors' => $errors,
'data' => [
'extensions' => $dataExt,
'variables' => $dataVar,
],
];
return $response;
} | php | {
"resource": ""
} |
q10605 | InstallerController.vHostSetupChecker | train | protected function vHostSetupChecker()
{
$translator = $this->getServiceLocator()->get('translator');
$success = 0;
$error = [];
$platform = null;
$module = null;
if (!empty(getenv('MELIS_PLATFORM'))) {
$platform = getenv('MELIS_PLATFORM');
} else {
$error['platform'] = $translator->translate('tr_melis_installer_step_1_1_no_paltform_declared');
}
if (!empty(getenv('MELIS_MODULE'))) {
$module = getenv('MELIS_MODULE');
} else {
$error['module'] = $translator->translate('tr_melis_installer_step_1_1_no_module_declared');
}
if (empty($error)) {
$success = 1;
}
$response = [
'success' => $success,
'errors' => $error,
'data' => [
'platform' => $platform,
'module' => $module,
],
];
return $response;
} | php | {
"resource": ""
} |
q10606 | InstallerController.checkDirectoryRights | train | protected function checkDirectoryRights()
{
$translator = $this->getServiceLocator()->get('translator');
$installHelper = $this->getServiceLocator()->get('InstallerHelper');
$configDir = $installHelper->getDir('config');
$module = $this->getModuleSvc()->getAllModules();
$success = 0;
$errors = [];
$data = [];
for ($x = 0; $x < count($configDir); $x++) {
$configDir[$x] = 'config/' . $configDir[$x];
}
array_push($configDir, 'config');
/**
* Add config platform, MelisSites and public dir to check permission
*/
array_push($configDir, 'config/autoload/platforms/');
array_push($configDir, 'module/MelisModuleConfig/');
array_push($configDir, 'module/MelisModuleConfig/languages');
array_push($configDir, 'module/MelisModuleConfig/config');
array_push($configDir, 'module/MelisSites/');
array_push($configDir, 'dbdeploy/');
array_push($configDir, 'dbdeploy/data');
array_push($configDir, 'public/');
array_push($configDir, 'cache/');
array_push($configDir, 'test/');
for ($x = 0; $x < count($module); $x++) {
$module[$x] = $this->getModuleSvc()->getModulePath($module[$x], false) . '/config';
}
$dirs = array_merge($configDir, $module);
$results = [];
foreach ($dirs as $dir) {
if (file_exists($dir)) {
if ($installHelper->isDirWritable($dir)) {
$results[$dir] = 1;
} else {
$results[$dir] = sprintf($translator->translate('tr_melis_installer_step_1_2_dir_not_writable'), $dir);
array_push($errors, sprintf($translator->translate('tr_melis_installer_step_1_2_dir_not_writable'), $dir));
}
}
}
if (empty($errors)) {
$success = 1;
}
$response = [
'success' => $success,
'errors' => $errors,
'data' => $results,
];
return $response;
} | php | {
"resource": ""
} |
q10607 | InstallerController.getEnvironments | train | protected function getEnvironments()
{
$env = [];
$container = new Container('melisinstaller');
if (isset($container['environments']) && isset($container['environments']['new'])) {
$env = $container['environments']['new'];
}
return $env;
} | php | {
"resource": ""
} |
q10608 | InstallerController.getCurrentPlatform | train | protected function getCurrentPlatform()
{
$env = [];
$container = new Container('melisinstaller');
if (isset($container['environments']) && isset($container['environments']['default_environment'])) {
$env = $container['environments']['default_environment'];
}
return $env;
} | php | {
"resource": ""
} |
q10609 | InstallerController.checkSysConfigAction | train | public function checkSysConfigAction()
{
$success = 0;
$errors = [];
if ($this->getRequest()->isXmlHttpRequest()) {
$response = $this->systemConfigurationChecker();
$success = $response['success'];
$errors = $response['errors'];
// add status to session
$container = new Container('melisinstaller');
$container['steps'][$this->steps[0]] = ['page' => 1, 'success' => $success];
}
return new JsonModel([
'success' => $success,
'errors' => $errors,
]);
} | php | {
"resource": ""
} |
q10610 | InstallerController.checkVhostSetupAction | train | public function checkVhostSetupAction()
{
$success = 0;
$errors = [];
if ($this->getRequest()->isXmlHttpRequest()) {
$response = $this->vHostSetupChecker();
$success = $response['success'];
$errors = $response['errors'];
// add status to session
$container = new Container('melisinstaller');
$container['steps'][$this->steps[1]] = ['page' => 2, 'success' => $success];
}
return new JsonModel([
'success' => $success,
'errors' => $errors,
]);
} | php | {
"resource": ""
} |
q10611 | InstallerController.checkFileSystemRightsAction | train | public function checkFileSystemRightsAction()
{
$success = 0;
$errors = [];
if ($this->getRequest()->isXmlHttpRequest()) {
$response = $this->checkDirectoryRights();
$success = $response['success'];
$errors = $response['errors'];
// add status to session
$container = new Container('melisinstaller');
$container['steps'][$this->steps[2]] = ['page' => 3, 'success' => $success];
}
return new JsonModel([
'success' => $success,
'errors' => $errors,
]);
} | php | {
"resource": ""
} |
q10612 | InstallerController.rollBackAction | train | public function rollBackAction()
{
$success = 0;
$errors = [];
$installHelper = $this->getServiceLocator()->get('InstallerHelper');
$container = new Container('melisinstaller');
if (!empty($container->getArrayCopy()) && in_array(array_keys($container['steps']), [$this->steps])) {
$tablesInstalled = isset($container['db_install_tables']) ? $container['db_install_tables'] : [];
$siteModule = 'module/MelisSites/' . $container['cms_data']['website_module'] . '/';
$dbConfigFile = 'config/autoload/platforms/' . $installHelper->getMelisPlatform() . '.php';
$config = include($dbConfigFile);
// drop table
$installHelper->setDbAdapter($config['db']);
foreach ($tablesInstalled as $table) {
if ($installHelper->isDbTableExists($table)) {
$installHelper->executeRawQuery("DROP TABLE " . trim($table));
}
}
// delete site module
if (file_exists($siteModule)) {
unlink($siteModule);
}
//delete db config file
if (file_exists($dbConfigFile)) {
unlink($dbConfigFile);
}
// clear session
$container->getManager()->destroy();
$success = 1;
}
return new JsonModel([
'success' => $success,
]);
} | php | {
"resource": ""
} |
q10613 | InstallerController.hasMelisCmsModule | train | protected function hasMelisCmsModule()
{
$modulesSvc = $this->getServiceLocator()->get('MelisAssetManagerModulesService');
$modules = $modulesSvc->getAllModules();
$path = $modulesSvc->getModulePath('MelisCms');
$isExists = 0;
if (file_exists($path)) {
$isExists = 1;
}
return $isExists;
} | php | {
"resource": ""
} |
q10614 | TextListField.build | train | public function build(ConfigInterface $config, $width, ManialinkInterface $manialink, ManialinkFactory $manialinkFactory): Renderable
{
$input = $this
->uiFactory
->createInput($config->getPath(), '')
->setWidth($width * 0.66);
$addButton = $this->uiFactory
->createButton('Add')
->setWidth($width * 0.33)
->setAction(
$this->actionFactory->createManialinkAction(
$manialink,
function (ManialinkInterface $manialink, $login, $entries, $args) use ($manialinkFactory) {
/** @var TextListConfig $config */
$config = $args['config'];
if (!empty($entries[$config->getPath()])) {
$config->add(trim($entries[$config->getPath()]));
$manialinkFactory->update($manialink->getUserGroup());
}
},
['config' => $config]
)
);
$elements = [$this->uiFactory->createLayoutLine(0,0, [$input, $addButton])];
foreach ($config->get() as $element) {
$elements[] = $this->getElementLine($config, $manialink, $element, $width, $manialinkFactory);
}
return $this->uiFactory->createLayoutRow(0, 0, $elements, 0.5);
} | php | {
"resource": ""
} |
q10615 | TextListField.getElementLine | train | protected function getElementLine($config, $manialink, $element, $width, $manialinkFactory)
{
$label = $this->uiFactory
->createLabel($this->getElementName($element))
->setX(2)
->setWidth($width * 0.66);
$delButton = $this->uiFactory
->createButton('Remove')
->setWidth($width * 0.33)
->setAction(
$this->actionFactory->createManialinkAction(
$manialink,
function (ManialinkInterface $manialink, $login, $entries, $args) use ($manialinkFactory) {
/** @var TextListConfig $config */
$config = $args['config'];
$config->remove($args['element']);
$manialinkFactory->update($manialink->getUserGroup());
},
['config' => $config, 'element' => $element]
)
);
return $this->uiFactory->createLayoutLine(0,0, [$label, $delButton]);
} | php | {
"resource": ""
} |
q10616 | ActionButtons.renderActions | train | private function renderActions()
{
$this->beginButtonGroup();
foreach ($this->visibleActions as $action) {
$label = ArrayHelper::getValue($action, $this->actionLabelProperty, '');
$url = ArrayHelper::getValue($action, $this->actionUrlProperty, null);
$options = ArrayHelper::getValue($action, $this->actionOptionsProperty, []);
// Use $this->buttonClasses as base classes, then override with any classes specified in options
$actionClasses = ArrayHelper::getValue($options, 'class', []);
$options['class'] = $this->linkClasses;
Html::addCssClass($options, $actionClasses);
echo Html::a($label, $url, $options);
}
$this->endButtonGroup();
} | php | {
"resource": ""
} |
q10617 | ActionButtons.renderActionButton | train | private function renderActionButton()
{
$actionButtonOptions = $this->actionButtonOptions;
Html::addCssClass($actionButtonOptions, $this->linkClasses);
$this->beginButtonGroup();
echo Html::button($this->actionsButtonLabel . $this->caretHtml, $actionButtonOptions);
echo Html::beginTag('ul', ['class' => 'dropdown-menu dropdown-menu-right']);
foreach ($this->visibleActions as $action) {
$label = ArrayHelper::getValue($action, $this->actionLabelProperty, '');
$url = ArrayHelper::getValue($action, $this->actionUrlProperty, null);
$options = ArrayHelper::getValue($action, $this->actionOptionsProperty, []);
echo Html::tag('li', Html::a($label, $url, $options));
}
echo Html::endTag('ul');
$this->endButtonGroup();
} | php | {
"resource": ""
} |
q10618 | File.copy | train | public function copy(string $destination, $overwrite = false) : bool
{
$copied = false;
if ($this->isFile()) {
$exists = file_exists($destination);
if (!$exists || ($exists && $overwrite)) {
$copied = copy($this->realPath, $destination);
}
}
return $copied;
} | php | {
"resource": ""
} |
q10619 | File.delete | train | public function delete() : bool
{
$removed = null;
if ($this->isDirectory()) {
$removed = rmdir($this->realPath);
} else {
$removed = unlink($this->realPath);
}
return $removed;
} | php | {
"resource": ""
} |
q10620 | File.getSize | train | public function getSize() : int
{
$size = -1;
if ($this->isFile()) {
$size = filesize($this->realPath);
}
return $size;
} | php | {
"resource": ""
} |
q10621 | File.read | train | public function read()
{
$contents = false;
if ($this->isFile() && $this->isReadable()) {
$contents = file_get_contents($this->realPath);
}
return $contents;
} | php | {
"resource": ""
} |
q10622 | File.rename | train | public function rename(string $newName) : bool
{
$renamed = rename($this->realPath, $newName);
if ($renamed) {
$this->realPath = realpath($newName);
}
return $renamed;
} | php | {
"resource": ""
} |
q10623 | AutoLoad.autoLoad_XmlnukeFramework | train | protected function autoLoad_XmlnukeFramework($className)
{
foreach (AutoLoad::$_folders[AutoLoad::FRAMEWORK_XMLNUKE] as $prefix)
{
// PSR-0 Classes
// convert namespace to full file path
$class = PHPXMLNUKEDIR . $prefix . str_replace('\\', '/', $className);
$class = (
file_exists("$class.php")
? "$class.php"
: (
file_exists("$class.class.php")
? "$class.class.php"
: null
)
);
if (!empty($class) && \Xmlnuke\Util\FileUtil::isReadable($class))
{
require_once($class);
break;
}
}
} | php | {
"resource": ""
} |
q10624 | AutoLoad.autoLoad_UserProjects | train | protected function autoLoad_UserProjects($className)
{
$class = str_replace('\\', '/', ($className[0] == '\\' ? substr($className, 1) : $className));
foreach (AutoLoad::$_folders[AutoLoad::USER_PROJECTS] as $libName => $libDir)
{
$file = $libDir . '/' . $class;
$file = (
file_exists("$file.php")
? "$file.php"
: (
file_exists("$file.class.php")
? "$file.class.php"
: null
)
);
if (!empty($file) && \Xmlnuke\Util\FileUtil::isReadable($file))
{
require_once $file;
return;
}
}
return;
} | php | {
"resource": ""
} |
q10625 | PaymentProcessor.createPayment | train | public function createPayment($gateway)
{
if (!GatewayInfo::isSupported($gateway)) {
user_error(_t(
"PaymentProcessor.INVALID_GATEWAY",
"`{gateway}` is not supported.",
null,
array('gateway' => (string)$gateway)
), E_USER_ERROR);
}
// Create a payment
$this->payment = Payment::create()->init(
$gateway,
$this->reservation->Total,
self::config()->get('currency')
);
// Set a reference to the reservation
$this->payment->ReservationID = $this->reservation->ID;
return $this->payment;
} | php | {
"resource": ""
} |
q10626 | PaymentProcessor.createServiceFactory | train | public function createServiceFactory()
{
$factory = ServiceFactory::create();
$service = $factory->getService($this->payment, ServiceFactory::INTENT_PAYMENT);
try {
$serviceResponse = $service->initiate($this->getGatewayData());
} catch (Exception $ex) {
// error out when an exception occurs
user_error($ex->getMessage(), E_USER_WARNING);
return null;
}
return $serviceResponse;
} | php | {
"resource": ""
} |
q10627 | SfdcResultHydrator.doHydrateList | train | public function doHydrateList(array $list, $parentKey = null)
{
$retVal = parent::doHydrateList($list, $parentKey);
if('Id' === $parentKey)
{
if($retVal->count() > 0)
{
return $retVal->get(0);
}
return null;
}
return $retVal;
} | php | {
"resource": ""
} |
q10628 | Collection.remove | train | public function remove($key, $remove = true)
{
if ($remove && $this->has($key, self::HAS_EXISTS)) {
$key = $this->normalizeKey($key);
unset($this->data[$key]);
}
return $this;
} | php | {
"resource": ""
} |
q10629 | Collection.removeEmpty | train | public function removeEmpty($considerEmpty = [''])
{
foreach ($this->all() as $key => $value) {
if (!is_scalar($value) && !is_null($value)) {
continue;
}
foreach ($considerEmpty as $empty) {
if ($value === $empty) {
$this->remove($key);
break;
}
}
}
return $this;
} | php | {
"resource": ""
} |
q10630 | Collection.sort | train | public function sort($sortBy = self::SORT_BY_KEYS_ASC, $sortFlags = SORT_REGULAR)
{
/** @noinspection SpellCheckingInspection */
$sortFunctions = [
self::SORT_BY_KEYS_ASC => 'ksort',
self::SORT_BY_KEYS_DESC => 'krsort',
self::SORT_BY_VALUES_ASC => 'asort',
self::SORT_BY_VALUES_DESC => 'arsort',
];
if (!isset($sortFunctions[$sortBy])) {
throw new InvalidArgumentException("SortBy {$sortBy} not supported");
}
$function = $sortFunctions[$sortBy];
$function($this->data, $sortFlags);
return $this;
} | php | {
"resource": ""
} |
q10631 | XSLTheme.generateList | train | private function generateList($caption, $paragraph, $filelist, $xslUsed, $xsl)
{
$paragraph->addXmlnukeObject(new XmlnukeText($caption,true));
$listCollection = new XmlListCollection(XmlListType::UnorderedList );
$paragraph->addXmlnukeObject($listCollection);
foreach($filelist as $file)
{
$xslname = FileUtil::ExtractFileName($file);
$xslname = $xsl->removeLanguage($xslname);
if(!in_array ($xslname, $xslUsed))
{
$objectList = new XmlnukeSpanCollection();
$listCollection->addXmlnukeObject($objectList);
$xslUsed[] = $xslname;
if ($xslname == "index")
{
$anchor = new XmlAnchorCollection("engine:xmlnuke?xml=index&xsl=index");
$anchor->addXmlnukeObject(new XmlnukeText($xslname,true));
$objectList->addXmlnukeObject($anchor);
}
else
{
$anchor = new XmlAnchorCollection("module:Xmlnuke.XSLTheme?xsl=" . $xslname);
$anchor->addXmlnukeObject(new XmlnukeText($xslname,true));
$objectList->addXmlnukeObject($anchor);
}
}
}
} | php | {
"resource": ""
} |
q10632 | PathTranslator.translate | train | function translate($path)
{
if(static::isWindowsOS())
{
if(preg_match('%^([A-Z]):(.*)%', $path, $matches))
{
// $path contains something like 'C:' at the start,
// so it's an absolute path from the root.
$drive = $matches[1];
$file = $matches[2];
$unixFile = str_replace('\\', '/', $file);
if(static::isWindowsMsys())
{
$path = '/' . strtolower($drive) . $unixFile;
}
else if(static::isWindowsCygwin())
{
$path = '/cygdrive/' . strtolower($drive) . $unixFile;
}
}
else
{
// $path does not look like 'C:' so we assume it to be relative
if(static::isWindowsMsys() || static::isWindowsCygwin())
$path = str_replace('\\', '/', $path);;
}
}
return $path;
} | php | {
"resource": ""
} |
q10633 | DebugExtension.definition | train | private function definition(ContainerBuilder $container, $class, $tag, array $arguments = [])
{
$definition = new Definition(strtr(__NAMESPACE__, ['ServiceContainer' => $class]), $arguments);
return $container
->setDefinition($tag . '.' . self::id($class), $definition)
->addTag($tag);
} | php | {
"resource": ""
} |
q10634 | Container.invoke | train | public function invoke(
$obj,
string $method,
array $params = []
) {
if (is_string($obj)) {
//Attempt to retrieve object from
//the container.
$obj = $this->get($obj);
} elseif (!is_object($obj)) {
//Not a valid argument.
throw new \Exception('Invalid object');
}
$map = $this->generateArgumentsMap(
$obj,
$method,
$params
);
$mapParams = $this->getParamsFromMap($map);
return $obj->$method(...$mapParams);
} | php | {
"resource": ""
} |
q10635 | Container.build | train | private function build(string $name)
{
$instance = null;
$map = $this->map[$name];
if (is_array($map)) {
$params = $this->getParamsFromMap($map);
$instance = new $name(...$params);
} elseif ($map instanceof \Closure) {
$instance = $map($this);
} elseif (is_object($map)) {
$instance = $map;
} elseif (is_string($map)) {
$instance = $this->get($map);
} else {
throw new \Exception('Invalid map');
}
return $instance;
} | php | {
"resource": ""
} |
q10636 | Collections.sort | train | public static function sort(ArrayList &$list, Comparator $comparator)
{
$array = $list->toArray();
usort($array, [$comparator, "compare"]);
$list->replace($array);
return $list;
} | php | {
"resource": ""
} |
q10637 | Config.getPluginPath | train | public function getPluginPath( $library )
{
switch ( $library ) {
case \Altamira\JsWriter\Flot::LIBRARY:
return $this['js.flotpluginpath'];
case \Altamira\JsWriter\JqPlot::LIBRARY:
return $this['js.jqplotpluginpath'];
}
} | php | {
"resource": ""
} |
q10638 | Dispatcher.reset | train | public function reset(Map $map)
{
$this->pluginManager->reset($map);
$this->dataProviderManager->reset($this->pluginManager, $map);
} | php | {
"resource": ""
} |
q10639 | EventSynchronizer.prepareEntriesToDeliver | train | private function prepareEntriesToDeliver(array $entries)
{
$binaryAttributes = ['objectguid', 'objectsid'];
foreach ($entries as $key => &$entry) {
foreach ($binaryAttributes as $binaryAttribute) {
if (array_key_exists($binaryAttribute, $entry)) {
if (is_array($entry[$binaryAttribute])) {
foreach ($entry[$binaryAttribute] as &$value) {
$value = bin2hex($value);
}
} else {
$entry[$binaryAttribute] = bin2hex($entry[$binaryAttribute]);
}
}
}
}
return $entries;
} | php | {
"resource": ""
} |
q10640 | Consumer.consume | train | public function consume($url, Provider $provider = null, $format = self::FORMAT_DEFAULT)
{
if ($this->requestParameters instanceof RequestParameters) {
$cacheKey = sha1($url . json_encode($this->requestParameters->toArray()));
} else {
$cacheKey = sha1($url);
}
// Check if the resource is cached
if ($this->resourceCache->has($cacheKey)) {
return $this->resourceCache->get($cacheKey);
}
try {
// Try to find a provider matching the supplied URL if no one has been supplied.
if (!$provider) {
$provider = $this->findProviderForUrl($url);
}
if ($provider instanceof Provider) {
// If a provider was supplied or we found one, store the endpoint URL.
$endPoint = $provider->getEndpoint();
} else {
// If no provider was found, try to discover the endpoint URL.
$discover = new Discoverer();
$endPoint = $discover->getEndpointForUrl($url);
}
$requestUrl = $this->buildOEmbedRequestUrl($url, $endPoint, $format);
$content = $this->browser->getContent($requestUrl);
$methodName = 'process' . ucfirst(strtolower($format)) . 'Response';
$resource = $this->$methodName($content);
// Save the resource in cache
$this->resourceCache->set($cacheKey, $resource);
} catch (Exception $exception) {
$this->systemLogger->logException($exception);
$resource = null;
}
return $this->postProcessResource($resource);
} | php | {
"resource": ""
} |
q10641 | Consumer.buildOEmbedRequestUrl | train | protected function buildOEmbedRequestUrl($resource, $endPoint, $format = self::FORMAT_DEFAULT)
{
$parameters = [
'url' => $resource,
'format' => $format,
'version' => self::VERSION
];
if ($this->getRequestParameters() !== null) {
$parameters = Arrays::arrayMergeRecursiveOverrule($this->getRequestParameters()->toArray(), $parameters);
}
$urlParams = http_build_query($parameters, '', '&');
$url = $endPoint . ((strpos($endPoint, '?') !== false) ? '&' : '?') . $urlParams;
return $url;
} | php | {
"resource": ""
} |
q10642 | Consumer.findProviderForUrl | train | protected function findProviderForUrl($url)
{
foreach ($this->providers as $provider) {
if ($provider->match($url)) {
return $provider;
}
}
return null;
} | php | {
"resource": ""
} |
q10643 | Radio._checkSelected | train | protected function _checkSelected(array $options, $selectedVal)
{
if (!empty($selectedVal) && !Arr::key($selectedVal, $options)) {
$selectedVal = self::KEY_NO_EXITS_VAL;
$options = array_merge(array(self::KEY_NO_EXITS_VAL => $this->_translate('No exits')), $options);
}
return array($options, $selectedVal);
} | php | {
"resource": ""
} |
q10644 | AdapterTrait.getNewSandBox | train | public function getNewSandBox(callable $action)
{
$errorHandler = $this->getOption('error_reporting');
if ($errorHandler !== null && !is_callable($errorHandler)) {
$errorReporting = $errorHandler;
$errorHandler = function ($number, $message, $file, $line) use ($errorReporting) {
if ($errorReporting & $number) {
throw new ErrorException($message, 0, $number, $file, $line);
}
return true;
};
}
return new SandBox($action, $errorHandler);
} | php | {
"resource": ""
} |
q10645 | AdapterTrait.getSandboxCall | train | private function getSandboxCall(&$source, $method, $path, $input, callable $getSource, array $parameters)
{
return $this->getNewSandBox(function () use (&$source, $method, $path, $input, $getSource, $parameters) {
$adapter = $this->getAdapter();
$cacheEnabled = (
$adapter->hasOption('cache_dir') && $adapter->getOption('cache_dir') ||
$this->hasOption('cache_dir') && $this->getOption('cache_dir')
);
if ($cacheEnabled) {
$this->expectCacheAdapter();
$adapter = $this->getAdapter();
$display = function () use ($adapter, $path, $input, $getSource, $parameters) {
/* @var CacheInterface $adapter */
$adapter->displayCached($path, $input, $getSource, $parameters);
};
return in_array($method, ['display', 'displayFile'])
? $display()
: $adapter->captureBuffer($display);
}
$source = $getSource($path, $input);
return $adapter->$method(
$source,
$parameters
);
});
} | php | {
"resource": ""
} |
q10646 | DirectAdmin.send | train | private function send(string $method, string $command, array $options = []): array
{
$result = $this->client->da_request($method, self::CMD_PREFIX . $command, $options);
return $result;
} | php | {
"resource": ""
} |
q10647 | Select._checkNoSelected | train | protected function _checkNoSelected(array $options, array $selected, $isMultiply = false)
{
if ($isMultiply === 'multiple') {
return array($options, $selected);
}
$_selected = array_pop($selected);
if (!Arr::key($_selected, $options) && !empty($selected)) {
$options = array_merge(array($_selected => $this->_translate('--No selected--')), $options);
}
return array($options, array($_selected));
} | php | {
"resource": ""
} |
q10648 | Select._createGroup | train | protected function _createGroup($key, array $gOptions, array $selected, array $options)
{
$label = (is_int($key)) ? sprintf($this->_translate('Select group %s'), $key) : $key;
$output = array(
'<optgroup label="' . $this->_translate($label) . '">'
);
foreach ($gOptions as $value => $label) {
if (Arr::key($value, $options)) {
continue;
}
$classes = implode(' ', array(
$this->_jbSrt('option'),
$this->_jbSrt('option-' . Str::slug($label)),
));
$isSelected = $this->_isSelected($value, $selected);
$output[] = $this->_option($value, $isSelected, $classes, $label);
}
$output[] = '</optgroup>';
return implode(PHP_EOL, $output);
} | php | {
"resource": ""
} |
q10649 | Select._getOptions | train | protected function _getOptions(array $options, array $selected = array(), $isMultiple = false)
{
$output = array();
list($options, $_selected) = $this->_checkNoSelected($options, $selected, $isMultiple);
foreach ($options as $key => $data) {
$label = $data;
$value = $key;
$classes = implode(' ', array(
$this->_jbSrt('option'),
$this->_jbSrt('option-' . Str::slug($value, true)),
));
$isSelected = $this->_isSelected($value, $_selected);
if (is_array($data)) {
$output[] = $this->_createGroup($key, $data, $_selected, $options);
} else {
$output[] = $this->_option($value, $isSelected, $classes, $label);
}
}
return implode(PHP_EOL, $output);
} | php | {
"resource": ""
} |
q10650 | Select._option | train | protected function _option($value, $selected = false, $class = '', $label = '')
{
if ($selected === true) {
$selected = ' selected="selected"';
}
$option = '<option value="' . $value . '" class="' . $class . '"' . $selected .'>' .
$this->_translate($label) .
'</option>';
return $option;
} | php | {
"resource": ""
} |
q10651 | FileAdapter.cache | train | public function cache($path, $input, callable $rendered, &$success = null)
{
$cacheFolder = $this->getCacheDirectory();
$destination = $path;
if (!$this->isCacheUpToDate($destination, $input)) {
if (!is_writable($cacheFolder)) {
throw new RuntimeException(sprintf('Cache directory must be writable. "%s" is not.', $cacheFolder), 6);
}
$compiler = $this->getRenderer()->getCompiler();
$fullPath = $compiler->locate($path) ?: $path;
$output = $rendered($fullPath, $input);
$importsPaths = $compiler->getImportPaths($fullPath);
$success = $this->cacheFileContents(
$destination,
$output,
$importsPaths
);
}
return $destination;
} | php | {
"resource": ""
} |
q10652 | FileAdapter.displayCached | train | public function displayCached($path, $input, callable $rendered, array $variables, &$success = null)
{
$__pug_parameters = $variables;
$__pug_path = $this->cache($path, $input, $rendered, $success);
call_user_func(function () use ($__pug_path, $__pug_parameters) {
extract($__pug_parameters);
include $__pug_path;
});
} | php | {
"resource": ""
} |
q10653 | FileAdapter.cacheFileIfChanged | train | public function cacheFileIfChanged($path)
{
$outputFile = $path;
if (!$this->isCacheUpToDate($outputFile)) {
$compiler = $this->getRenderer()->getCompiler();
return $this->cacheFileContents(
$outputFile,
$compiler->compileFile($path),
$compiler->getCurrentImportPaths()
);
}
return true;
} | php | {
"resource": ""
} |
q10654 | FileAdapter.cacheDirectory | train | public function cacheDirectory($directory)
{
$success = 0;
$errors = 0;
$errorDetails = [];
$renderer = $this->getRenderer();
$events = $renderer->getCompiler()->getEventListeners();
foreach ($renderer->scanDirectory($directory) as $inputFile) {
$renderer->initCompiler();
$compiler = $renderer->getCompiler();
$compiler->mergeEventListeners($events);
$path = $inputFile;
$this->isCacheUpToDate($path);
$sandBox = $this->getRenderer()->getNewSandBox(function () use (&$success, $compiler, $path, $inputFile) {
$this->cacheFileContents($path, $compiler->compileFile($inputFile), $compiler->getCurrentImportPaths());
$success++;
});
$error = $sandBox->getThrowable();
if ($error) {
$errors++;
$errorDetails[] = compact(['directory', 'inputFile', 'path', 'error']);
}
}
return [$success, $errors, $errorDetails];
} | php | {
"resource": ""
} |
q10655 | FileAdapter.isCacheUpToDate | train | private function isCacheUpToDate(&$path, $input = null)
{
if (!$input) {
$compiler = $this->getRenderer()->getCompiler();
$input = $compiler->resolve($path);
$path = $this->getCachePath(
($this->getOption('keep_base_name') ? basename($path) : '').
$this->hashPrint($input)
);
// If up_to_date_check never refresh the cache
if (!$this->getOption('up_to_date_check')) {
return true;
}
// If there is no cache file, create it
if (!file_exists($path)) {
return false;
}
// Else check the main input path and all imported paths in the template
return !$this->hasExpiredImport($input, $path);
}
$path = $this->getCachePath($this->hashPrint($input));
// Do not re-parse file if the same hash exists
return file_exists($path);
} | php | {
"resource": ""
} |
q10656 | XmlnukePoll.getPollConfig | train | protected function getPollConfig()
{
$pollfile = new AnydatasetFilenameProcessor("_poll");
$anyconfig = new AnyDataset($pollfile->FullQualifiedNameAndPath());
$it = $anyconfig->getIterator();
if ($it->hasNext())
{
$sr = $it->moveNext();
$this->_isdb = $sr->getField("dbname") != "-anydata-";
$this->_connection = $sr->getField("dbname");
$this->_tblanswer = $sr->getField("tbl_answer");
$this->_tblpoll = $sr->getField("tbl_poll");
$this->_tbllastip = $sr->getField("tbl_lastip");
}
else
{
$this->_error = true;
}
} | php | {
"resource": ""
} |
q10657 | XmlnukePoll.getAnyData | train | protected function getAnyData()
{
$filepoll = new AnydatasetFilenameProcessor("poll_list");
$this->_anyPoll = new AnyDataset($filepoll->FullQualifiedNameAndPath());
$fileanswer = new AnydatasetFilenameProcessor("poll_" . $this->_poll . "_" . $this->_lang);
$this->_anyAnswer = new AnyDataset($fileanswer->FullQualifiedNameAndPath());
} | php | {
"resource": ""
} |
q10658 | ToursController.steps | train | public function steps() {
Configure::write('debug', 0);
if (!$this->request->is('ajax') || !$this->request->is('post') ||
!$this->RequestHandler->prefers('json')) {
throw new BadRequestException();
}
$data = $this->ConfigTheme->getStepsConfigTourApp();
$this->set(compact('data'));
$this->set('_serialize', 'data');
} | php | {
"resource": ""
} |
q10659 | FirePHPHandler.write | train | protected function write(array $record)
{
if (!self::$sendHeaders) {
return;
}
// WildFire-specific headers must be sent prior to any messages
if (!self::$initialized) {
self::$initialized = true;
self::$sendHeaders = $this->headersAccepted();
if (!self::$sendHeaders) {
return;
}
foreach ($this->getInitHeaders() as $header => $content) {
$this->sendHeader($header, $content);
}
}
$header = $this->createRecordHeader($record);
if (trim(current($header)) !== '') {
$this->sendHeader(key($header), current($header));
}
} | php | {
"resource": ""
} |
q10660 | GuiHandler.displayManialinks | train | protected function displayManialinks()
{
$size = 0;
foreach ($this->getManialinksToDisplay() as $mlData) {
$currentSize = $size;
$size += strlen($mlData['ml']);
if ($currentSize != 0 && $size > $this->charLimit) {
$this->executeMultiCall();
$size = strlen($mlData['ml']);
}
$logins = array_filter($mlData['logins'], function ($value) {
return $value != '';
});
if (!empty($logins)) {
$this->factory->getConnection()->sendDisplayManialinkPage(
$mlData['logins'],
$mlData['ml'],
$mlData['timeout'],
false,
true
);
}
}
if ($size > 0) {
$this->executeMultiCall();
}
// Reset the queues.
$this->displayQueu = [];
$this->individualQueu = [];
$this->hideQueu = [];
$this->hideIndividualQueu = [];
$this->disconnectedLogins = [];
} | php | {
"resource": ""
} |
q10661 | GuiHandler.executeMultiCall | train | protected function executeMultiCall()
{
try {
$this->factory->getConnection()->executeMulticall();
} catch (\Exception $e) {
$this->logger->error("Couldn't deliver all manialinks : ".$e->getMessage(), ['exception' => $e]);
$this->console->writeln('$F00ERROR - Couldn\'t deliver all manialinks : '.$e->getMessage());
}
} | php | {
"resource": ""
} |
q10662 | GuiHandler.getManialinksToDisplay | train | protected function getManialinksToDisplay()
{
foreach ($this->displayQueu as $groupName => $manialinks) {
foreach ($manialinks as $factoryId => $manialink) {
$logins = $manialink->getUserGroup()->getLogins();
$this->displayeds[$groupName][$factoryId] = $manialink;
if (!empty($logins)) {
yield ['logins' => $logins, 'ml' => $manialink->getXml(), "timeout" => $manialink->getTimeout()];
}
}
}
foreach ($this->individualQueu as $manialinks) {
// Fetch all logins
$logins = [];
$lastManialink = null;
foreach ($manialinks as $login => $manialink) {
$logins[] = $login;
$lastManialink = $manialink;
}
if ($lastManialink) {
$xml = $manialink->getXml();
yield ['logins' => $logins, 'ml' => $xml, "timeout" => $manialink->getTimeout()];
}
}
foreach ($this->hideQueu as $manialinks) {
foreach ($manialinks as $manialink) {
$id = $manialink->getId();
$manialink->destroy();
$logins = $manialink->getUserGroup()->getLogins();
$logins = array_diff($logins, $this->disconnectedLogins);
if (!empty($logins)) {
yield ['logins' => $logins, 'ml' => '<manialink id="'.$id.'" />', "timeout" => 0];
}
}
}
foreach ($this->hideIndividualQueu as $id => $manialinks) {
// Fetch all logins.
$logins = [];
$lastManialink = null;
foreach ($manialinks as $login => $manialink) {
if (!in_array($login, $this->disconnectedLogins)) {
$logins[] = $login;
$lastManialink = $manialink;
}
}
if ($lastManialink) {
// Manialink is not destroyed just not shown at a particular user that left the group.
yield ['logins' => $logins, 'ml' => '<manialink id="'.$lastManialink->getId().'" />', "timeout" => 0];
}
}
} | php | {
"resource": ""
} |
q10663 | Button.render | train | public function render($name = '', $content = '', array $attrs = array(), $type = 'submit')
{
$attrs = array_merge(array('text' => null, 'name' => $name), $attrs);
$attrs = $this->_getBtnClasses($attrs);
$attrs['type'] = $type;
if (Arr::key('icon', $attrs)) {
$content = '<i class="' . $this->_icon . '-' . $attrs['icon'] . '"></i> ' . $this->_translate($content);
unset($attrs['icon']);
}
return '<button ' . $this->buildAttrs($attrs) . '>' . $content . '</button>';
} | php | {
"resource": ""
} |
q10664 | Search.CreatePage | train | public function CreatePage()
{
$myWords = $this->WordCollection();
$this->_titlePage = $myWords->Value("TITLE", $this->_context->get("SERVER_NAME") );
$this->_abstractPage = $myWords->Value("ABSTRACT", $this->_context->get("SERVER_NAME") );
$this->_document = new XmlnukeDocument($this->_titlePage, $this->_abstractPage);
$this->txtSearch = $this->_context->get("txtSearch");
if ($this->txtSearch != "")
{
$this->Form();
$doc = $this->Find();
}
else
{
$this->Form();
}
return $this->_document->generatePage();
} | php | {
"resource": ""
} |
q10665 | MapListDataProvider.updateMapList | train | protected function updateMapList()
{
$start = 0;
do {
try {
$maps = $this->factory->getConnection()->getMapList(self::BATCH_SIZE, $start);
} catch (IndexOutOfBoundException $e) {
// This is normal error when we we are trying to find all maps and we are out of bounds.
return;
} catch (NextMapException $ex) {
// this is if no maps defined
return;
}
if (!empty($maps)) {
foreach ($maps as $map) {
$this->mapStorage->addMap($map);
}
}
$start += self::BATCH_SIZE;
} while (count($maps) == self::BATCH_SIZE);
} | php | {
"resource": ""
} |
q10666 | MapListDataProvider.onMapListModified | train | public function onMapListModified($curMapIndex, $nextMapIndex, $isListModified)
{
if ($isListModified) {
$oldMaps = $this->mapStorage->getMaps();
$this->mapStorage->resetMapData();
$this->updateMapList();
// We will dispatch even only when list is modified. If not we dispatch specific events.
$this->dispatch(__FUNCTION__, [$oldMaps, $curMapIndex, $nextMapIndex, $isListModified]);
}
try {
$currentMap = $this->factory->getConnection()->getCurrentMapInfo(); // sync better
} catch (\Exception $e) {
// fallback to use map storage
$currentMap = $this->mapStorage->getMapByIndex($curMapIndex);
} // current map can be false if map by index is not found..
if ($currentMap) {
if ($this->mapStorage->getCurrentMap()->uId != $currentMap->uId) {
$previousMap = $this->mapStorage->getCurrentMap();
$this->mapStorage->setCurrentMap($currentMap);
$this->dispatch('onExpansionMapChange', [$currentMap, $previousMap]);
}
}
try {
$nextMap = $this->factory->getConnection()->getNextMapInfo(); // sync better
} catch (\Exception $e) {
// fallback to use map storage
$nextMap = $this->mapStorage->getMapByIndex($nextMapIndex);
}
// next map can be false if map by index is not found..
if ($nextMap) {
if ($this->mapStorage->getNextMap()->uId != $nextMap->uId) {
$previousNextMap = $this->mapStorage->getNextMap();
$this->mapStorage->setNextMap($nextMap);
$this->dispatch('onExpansionNextMapChange', [$nextMap, $previousNextMap]);
}
}
} | php | {
"resource": ""
} |
q10667 | PopulateTimeZonesTask.rebuildTitles | train | protected function rebuildTitles()
{
// Update the Title field in the dataobjects. This saves the time to build the title dynamically each time.
foreach (TimeZoneData::get() as $tz) {
$newTitle = $tz->prepareTitle();
if ($newTitle != $tz->Title) {
$tz->Title = $newTitle;
$tz->write();
}
}
} | php | {
"resource": ""
} |
q10668 | PopulateTimeZonesTask.message | train | protected function message($text)
{
if (Controller::curr() instanceof DatabaseAdmin) {
DB::alteration_message($text, 'obsolete');
} else {
Debug::message($text);
}
} | php | {
"resource": ""
} |
q10669 | EventsController.ssecfg | train | public function ssecfg() {
Configure::write('debug', 0);
if (!$this->request->is('ajax') || !$this->request->is('post') ||
!$this->RequestHandler->prefers('json')) {
throw new BadRequestException();
}
$data = $this->ConfigTheme->getSseConfig();
$this->set(compact('data'));
$this->set('_serialize', 'data');
} | php | {
"resource": ""
} |
q10670 | EventsController.tasks | train | public function tasks() {
$this->response->disableCache();
Configure::write('debug', 0);
if (!$this->request->is('ajax') || !$this->request->is('post') ||
!$this->RequestHandler->prefers('json')) {
throw new BadRequestException();
}
$data = [
'result' => false,
'tasks' => []
];
$delete = (bool)$this->request->data('delete');
if ($delete) {
$tasks = $this->request->data('tasks');
$data['result'] = $this->SseTask->deleteQueuedTask($tasks);
} else {
$tasks = $this->SseTask->getListQueuedTask();
$data['tasks'] = $tasks;
$data['result'] = !empty($tasks);
}
$this->set(compact('data'));
$this->set('_serialize', 'data');
} | php | {
"resource": ""
} |
q10671 | EventsController.queue | train | public function queue($type = null, $retry = 3000) {
$this->response->disableCache();
Configure::write('debug', 0);
if (!$this->request->is('sse')) {
throw new BadRequestException();
}
$type = (string)$type;
$result = [
'type' => '',
'progress' => 0,
'msg' => '',
'result' => null
];
$event = 'progressBar';
$retry = (int)$retry;
if (empty($type)) {
$data = json_encode($result);
$this->set(compact('retry', 'data', 'event'));
return;
}
$timestamp = null;
$workermaxruntime = (int)Configure::read('Queue.workermaxruntime');
if ($workermaxruntime > 0) {
$timestamp = time() - $workermaxruntime;
}
$jobInfo = $this->ExtendQueuedTask->getPendingJob($type, true, $timestamp);
if (empty($jobInfo)) {
$result['type'] = $type;
$result['result'] = false;
$data = json_encode($result);
$this->set(compact('retry', 'data', 'event'));
return;
}
switch ($jobInfo['ExtendQueuedTask']['status']) {
case 'COMPLETED':
$resultFlag = true;
break;
case 'NOT_READY':
case 'NOT_STARTED':
case 'FAILED':
case 'UNKNOWN':
$resultFlag = false;
break;
case 'IN_PROGRESS':
default:
$resultFlag = null;
}
$result['type'] = $type;
$result['progress'] = (float)$jobInfo['ExtendQueuedTask']['progress'];
$result['msg'] = (string)$jobInfo['ExtendQueuedTask']['failure_message'];
$result['result'] = $resultFlag;
$data = json_encode($result);
$this->set(compact('retry', 'data', 'event'));
} | php | {
"resource": ""
} |
q10672 | CheckInValidator.validate | train | public function validate($ticketCode = null)
{
if (filter_var($ticketCode, FILTER_VALIDATE_URL)) {
$asURL = explode('/', parse_url($ticketCode, PHP_URL_PATH));
$ticketCode = end($asURL);
}
// Check if a code is given to the validator
if (!isset($ticketCode)) {
return $result = array(
'Code' => self::MESSAGE_NO_CODE,
'Message' => self::message(self::MESSAGE_NO_CODE, $ticketCode),
'Type' => self::MESSAGE_TYPE_BAD,
'Ticket' => $ticketCode,
'Attendee' => null
);
}
// Check if a ticket exists with the given ticket code
if (!$this->attendee = Attendee::get()->find('TicketCode', $ticketCode)) {
return $result = array(
'Code' => self::MESSAGE_CODE_NOT_FOUND,
'Message' => self::message(self::MESSAGE_CODE_NOT_FOUND, $ticketCode),
'Type' => self::MESSAGE_TYPE_BAD,
'Ticket' => $ticketCode,
'Attendee' => null
);
} else {
$name = $this->attendee->getName();
}
// Check if the reservation is not canceled
if (!(bool)$this->attendee->Event()->getGuestList()->find('ID', $this->attendee->ID)) {
return $result = array(
'Code' => self::MESSAGE_TICKET_CANCELLED,
'Message' => self::message(self::MESSAGE_TICKET_CANCELLED, $name),
'Type' => self::MESSAGE_TYPE_BAD,
'Ticket' => $ticketCode,
'Attendee' => $this->attendee
);
}
// Check if the ticket is already checked in and not allowed to check out
elseif ((bool)$this->attendee->CheckedIn && !(bool)self::config()->get('allow_checkout')) {
return $result = array(
'Code' => self::MESSAGE_ALREADY_CHECKED_IN,
'Message' => self::message(self::MESSAGE_ALREADY_CHECKED_IN, $name),
'Type' => self::MESSAGE_TYPE_BAD,
'Ticket' => $ticketCode,
'Attendee' => $this->attendee
);
}
// Successfully checked out
elseif ((bool)$this->attendee->CheckedIn && (bool)self::config()->get('allow_checkout')) {
return $result = array(
'Code' => self::MESSAGE_CHECK_OUT_SUCCESS,
'Message' => self::message(self::MESSAGE_CHECK_OUT_SUCCESS, $name),
'Type' => self::MESSAGE_TYPE_WARNING,
'Ticket' => $ticketCode,
'Attendee' => $this->attendee
);
}
// Successfully checked in
else {
return $result = array(
'Code' => self::MESSAGE_CHECK_IN_SUCCESS,
'Message' => self::message(self::MESSAGE_CHECK_IN_SUCCESS, $name),
'Type' => self::MESSAGE_TYPE_GOOD,
'Ticket' => $ticketCode,
'Attendee' => $this->attendee
);
}
} | php | {
"resource": ""
} |
q10673 | TypedArray.offsetSet | train | public function offsetSet($index, $newval)
{
if ($newval instanceof $this->type) {
parent::offsetSet($index, $newval);
return;
}
if ($this->allowedTypes[$this->type]($newval)) {
parent::offsetSet($index, $newval);
return;
}
throw new InvalidArgumentException(__CLASS__.': Elements passed to '.__CLASS__.' must be of the type '.$this->type.'.');
} | php | {
"resource": ""
} |
q10674 | ImageListCommand.buildSearchParameter | train | protected function buildSearchParameter(array $searchFilters)
{
$search = [];
foreach ($searchFilters as $filter) {
$parts = explode(' ', trim($filter), 2);
if (empty($parts) || 2 !== \count($parts)) {
continue;
}
$search[$parts[0]] = $parts[1];
}
return $search;
} | php | {
"resource": ""
} |
q10675 | ImageListCommand.buildSortParameter | train | protected function buildSortParameter(array $sorts)
{
$sorting = [];
foreach ($sorts as $sort) {
$parts = explode(' ', trim($sort), 2);
if (empty($parts)) {
continue;
}
if (1 === \count($parts)) {
$sorting[$parts[0]] = true;
} else {
$sorting[$parts[0]] = $parts[1];
}
}
return $sorting;
} | php | {
"resource": ""
} |
q10676 | AgentCrud.getAll | train | public final function getAll(string $query, array $queryParams = null, string $fetchClass = null): array
{
return $this->query($query, $queryParams, null, $fetchClass)->getData();
} | php | {
"resource": ""
} |
q10677 | Registry.hasLogger | train | public static function hasLogger($logger)
{
if ($logger instanceof Logger) {
$index = array_search($logger, self::$loggers, true);
return false !== $index;
} else {
return isset(self::$loggers[$logger]);
}
} | php | {
"resource": ""
} |
q10678 | Registry.removeLogger | train | public static function removeLogger($logger)
{
if ($logger instanceof Logger) {
if (false !== ($idx = array_search($logger, self::$loggers, true))) {
unset(self::$loggers[$idx]);
}
} else {
unset(self::$loggers[$logger]);
}
} | php | {
"resource": ""
} |
q10679 | Registry.getInstance | train | public static function getInstance($name)
{
if (!isset(self::$loggers[$name])) {
throw new InvalidArgumentException(sprintf('Requested "%s" logger instance is not in the registry', $name));
}
return self::$loggers[$name];
} | php | {
"resource": ""
} |
q10680 | AbstractPipes.unblock | train | protected function unblock()
{
if (!$this->blocked) {
return;
}
foreach ($this->pipes as $pipe) {
stream_set_blocking($pipe, 0);
}
if (is_resource($this->input)) {
stream_set_blocking($this->input, 0);
}
$this->blocked = false;
} | php | {
"resource": ""
} |
q10681 | Discoverer.getEndpointForUrl | train | public function getEndpointForUrl($url)
{
$cacheKey = sha1($url . $this->preferredFormat . json_encode($this->supportedFormats));
if (!isset($this->cachedEndpoints[$url])) {
$this->cachedEndpoints[$url] = $this->fetchEndpointForUrl($url);
if (trim($this->cachedEndpoints[$url]) === '') {
throw new Exception('Empty url endpoints', 1360175845);
}
$this->endPointCache->set($cacheKey, $this->cachedEndpoints[$url]);
} elseif ($this->endPointCache->has($cacheKey) === true) {
$this->cachedEndpoints[$url] = $this->endPointCache->get($cacheKey);
}
return $this->cachedEndpoints[$url];
} | php | {
"resource": ""
} |
q10682 | Discoverer.fetchEndpointForUrl | train | protected function fetchEndpointForUrl($url)
{
$endPoint = null;
try {
$content = $this->browser->getContent($url);
} catch (Exception $exception) {
throw new Exception(
'Unable to fetch the page body for "' . $url . '": ' . $exception->getMessage(),
Exception::PAGE_BODY_FETCH_FAILED
);
}
preg_match_all("/<link rel=\"alternate\"[^>]+>/i",
$content,
$out);
if ($out[0]) {
foreach ($out[0] as $link) {
if (strpos($link, trim($this->preferredFormat . '+oembed')) !== false) {
$endPoint = $this->extractEndpointFromAttributes($link);
break;
}
}
} else {
throw new Exception(
'No valid oEmbed links found on the document at "' . $url . '".',
Exception::NO_OEMBED_LINKS_FOUND
);
}
return $endPoint;
} | php | {
"resource": ""
} |
q10683 | FlashHandler.all | train | public function all()
{
return array_merge($this->messages[self::DURABLE], $this->messages[self::NOW]);
} | php | {
"resource": ""
} |
q10684 | FlashHandler.load | train | protected function load()
{
$this->reset();
$messages = $this->cookie->get($this->cookieKey);
if ($messages) {
$messages = json_decode($messages, true);
if (!empty($messages[self::DURABLE])) {
$this->messages[self::DURABLE] = $messages[self::DURABLE];
}
if (!empty($messages[self::NEXT])) {
$this->messages[self::NOW] = $messages[self::NEXT];
}
$this->save();
}
return $this;
} | php | {
"resource": ""
} |
q10685 | FlashHandler.reset | train | public function reset()
{
$this->messages = [];
foreach (self::$when as $when) {
$this->messages[$when] = [];
}
return $this;
} | php | {
"resource": ""
} |
q10686 | FlashHandler.save | train | protected function save()
{
$messages = [];
foreach ([self::DURABLE, self::NEXT] as $when) {
if (!empty($this->messages[$when])) {
$messages[$when] = $this->messages[$when];
}
}
if ($messages) {
$messages = json_encode($messages);
$this->cookie->set($this->cookieKey, $messages);
} else {
$this->cookie->remove($this->cookieKey);
}
return $this;
} | php | {
"resource": ""
} |
q10687 | ProcessBuilder.setTimeout | train | public function setTimeout($timeout)
{
if (null === $timeout) {
$this->timeout = null;
return $this;
}
$timeout = (float) $timeout;
if ($timeout < 0) {
throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
}
$this->timeout = $timeout;
return $this;
} | php | {
"resource": ""
} |
q10688 | Poller.setupLogging | train | public function setupLogging(LoggerInterface $logger, array $incrementalAttributesToLog = ['dn'])
{
if (empty($incrementalAttributesToLog)) {
throw new InvalidArgumentException('List of entry attributes to be logged during incremental sync cannot be empty');
}
$this->logger = $logger;
$this->incrementalAttributesToLog = $incrementalAttributesToLog;
} | php | {
"resource": ""
} |
q10689 | Poller.poll | train | public function poll($forceFullSync = false)
{
/** @var PollTaskRepository $pollTaskRepository */
$pollTaskRepository = $this->entityManager->getRepository(PollTask::class);
$lastSuccessfulPollTask = $pollTaskRepository->findLastSuccessfulForPoller($this->getName());
$rootDseDnsHostName = $this->fetcher->getRootDseDnsHostName();
$invocationId = $this->fetcher->getInvocationId();
$isFullSyncRequired = $this->isFullSyncRequired($forceFullSync, $lastSuccessfulPollTask, $rootDseDnsHostName, $invocationId);
$highestCommitedUSN = $this->fetcher->getHighestCommittedUSN();
$currentTask = $this->createCurrentPollTask(
$invocationId,
$highestCommitedUSN,
$rootDseDnsHostName,
$lastSuccessfulPollTask,
$isFullSyncRequired
);
$this->entityManager->persist($currentTask);
$this->entityManager->flush();
try {
if ($isFullSyncRequired) {
$fetchedEntriesCount = $this->fullSync($currentTask, $highestCommitedUSN);
} else {
$usnChangedStartFrom = $lastSuccessfulPollTask->getMaxUSNChangedValue() + 1;
$fetchedEntriesCount = $this->incrementalSync($currentTask, $usnChangedStartFrom, $highestCommitedUSN);
}
$currentTask->succeed($fetchedEntriesCount);
return $fetchedEntriesCount;
} catch (Exception $e) {
$currentTask->fail($e->getMessage());
throw $e;
} finally {
$this->entityManager->flush();
}
} | php | {
"resource": ""
} |
q10690 | Poller.createCurrentPollTask | train | protected function createCurrentPollTask($invocationId, $highestCommitedUSN, $rootDseDnsHostName, $lastSuccessfulPollTask, $isFullSync)
{
$currentTask = new PollTask(
$this->name,
$invocationId,
$highestCommitedUSN,
$rootDseDnsHostName,
$lastSuccessfulPollTask,
$isFullSync
);
return $currentTask;
} | php | {
"resource": ""
} |
q10691 | Poller.isFullSyncRequired | train | private function isFullSyncRequired($forceFullSync, PollTask $lastSuccessfulSyncTask = null, $currentRootDseDnsHostName, $currentInvocationId)
{
if ($forceFullSync) {
return true;
}
if (!$lastSuccessfulSyncTask) {
return true;
}
if ($lastSuccessfulSyncTask->getRootDseDnsHostName() != $currentRootDseDnsHostName) {
return true;
}
if ($lastSuccessfulSyncTask->getInvocationId() != $currentInvocationId) {
return true;
}
return false;
} | php | {
"resource": ""
} |
q10692 | Poller.fullSync | train | private function fullSync(PollTask $currentTask, $highestCommitedUSN)
{
$entries = $this->fetcher->fullFetch($highestCommitedUSN);
$this->synchronizer->fullSync($this->name, $currentTask->getId(), $entries);
$this->logFullSync($entries);
return count($entries);
} | php | {
"resource": ""
} |
q10693 | Poller.incrementalSync | train | private function incrementalSync(PollTask $currentTask, $usnChangedStartFrom, $highestCommitedUSN)
{
list($changed, $deleted) = $this->fetcher->incrementalFetch($usnChangedStartFrom, $highestCommitedUSN, $this->detectDeleted);
$this->synchronizer->incrementalSync($this->name, $currentTask->getId(), $changed, $deleted);
$this->logIncrementalSync($changed, $deleted);
return count($changed) + count($deleted);
} | php | {
"resource": ""
} |
q10694 | Poller.logFullSync | train | private function logFullSync($entries)
{
if ($this->logger) {
$this->logger->info(sprintf("Full sync processed. Entries count: %d.", count($entries)));
}
} | php | {
"resource": ""
} |
q10695 | Poller.logIncrementalSync | train | private function logIncrementalSync($changed, $deleted)
{
if ($this->logger) {
$entriesLogReducer = function ($entry) {
return array_intersect_key($entry, array_flip($this->incrementalAttributesToLog));
};
$changedToLog = array_map($entriesLogReducer, $changed);
$deletedToLog = array_map($entriesLogReducer, $deleted);
$this->logger->info(
sprintf("Incremental changeset processed. Changed: %d, Deleted: %d.", count($changed), count($deleted)),
['changed' => $changedToLog, 'deleted' => $deletedToLog]
);
}
} | php | {
"resource": ""
} |
q10696 | ArrayListTrait.filter | train | public function filter(\Closure $closure)
{
$newInstance = new self();
$newInstance->setArray(array_filter($this->array, $closure));
return $newInstance;
} | php | {
"resource": ""
} |
q10697 | ArrayListTrait.filterByKeys | train | public function filterByKeys(array $keys)
{
/** @noinspection PhpMethodParametersCountMismatchInspection */
$newInstance = new self();
$newInstance->setArray(array_filter($this->array, function ($key) use ($keys) {
return array_search($key, $keys) !== false;
}, ARRAY_FILTER_USE_KEY));
return $newInstance;
} | php | {
"resource": ""
} |
q10698 | ArrayListTrait.map | train | public function map(\closure $mapFunction)
{
$newInstance = new self();
$newInstance->setArray(array_map($mapFunction, $this->array));
return $newInstance;
} | php | {
"resource": ""
} |
q10699 | ArrayListTrait.flatten | train | public function flatten()
{
$flattenedArray = [];
array_walk_recursive($this->array, function ($item) use (&$flattenedArray) {
$flattenedArray[] = $item;
});
$newInstance = new self();
$newInstance->setArray($flattenedArray);
return $newInstance;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.