_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q252800
LineBreaksHelper.SetWeekWords
validation
public function SetWeekWords ($weekWords, $lang = '') { if (!$lang) $lang = $this->lang; if (is_array($weekWords)) { $this->weekWords[$lang] = $weekWords; } else { $this->weekWords[$lang] = explode(',', (string) $weekWords); } return $this; }
php
{ "resource": "" }
q252801
LineBreaksHelper.SetShortcuts
validation
public function SetShortcuts (array $shortcuts, $lang = '') { if (!$lang) $lang = $this->lang; $this->shortcuts[$lang] = $shortcuts; return $this; }
php
{ "resource": "" }
q252802
LineBreaksHelper.SetUnits
validation
public function SetUnits ($units) { if (is_array($units)) { $this->units = $units; } else { $this->units = explode(',', (string) $units); } return $this; }
php
{ "resource": "" }
q252803
LineBreaksHelper.getWeekWordsUnitsAndShortcuts
validation
protected function getWeekWordsUnitsAndShortcuts ($lang) { if (!isset($this->weekWords[$lang])) { if (isset(static::$WeekWordsDefault[$lang])) { $this->weekWords[$lang] = explode(',', static::$WeekWordsDefault[$lang]); } else { $this->weekWords[$lang] = []; } } if (!$this->units) $this->units = explode(',', static::$UnitsDefault); if (!isset($this->shortcuts[$lang])) { if (isset(static::$ShortcutsDefault[$lang])) { $shortcuts = []; /** @var $shortcutsLocalized array */ foreach (static::$ShortcutsDefault[$lang] as $shortcutsLocalized) foreach ($shortcutsLocalized as $shortcut) $shortcuts[$shortcut] = str_replace(' ', ' ', $shortcut); $this->shortcuts[$lang] = & $shortcuts; } else { $this->shortcuts[$lang] = []; } } return [ $this->weekWords[$lang], $this->units, $this->shortcuts[$lang] ]; }
php
{ "resource": "" }
q252804
LineBreaksHelper.LineBreaks
validation
public function LineBreaks ($text, $lang = "") { $this->text = $text; $word = ""; $lang = $lang ? $lang : $this->lang; list($weekWords, $units, $shortcuts) = $this->getWeekWordsUnitsAndShortcuts($lang); // if there are one or more tab chars in source text, convert them into single space $this->text = preg_replace("#\t+#mu", " ", $this->text); // if there are one or more space chars in source text, convert them into single space $this->text = preg_replace("#[ ]{2,}#mu", " ", $this->text); // for each week word for ($i = 0, $l = count($weekWords); $i < $l; $i += 1) { // load current week word into $word variable $word = $weekWords[$i]; // process source text with current week word $this->processWeakWord($word); // convert first week word character into upper case (first word in sentence) $word = mb_strtoupper(mb_substr($word, 0, 1)) . mb_substr($word, 1); // process source text with current week word with first upper cased char $this->processWeakWord($word); } // for each unit(s), where is white space char before and any number before that white space char: for ($i = 0, $l = count($units); $i < $l; $i += 1) { // load current unit into $word variable $word = $units[$i]; // create regular expression pattern to search for unit(s), where is white space char before // and any number before that white space char $regExp = "#([0-9])\\s(" . $word . ")#mu"; // process replacement for all founded white spaces into fixed space html entity in source text $this->text = preg_replace( $regExp, "$1&nbsp;$2", $this->text ); } // for all special shortcuts - remove all line breaking white spaces foreach ($shortcuts as $sourceShortcut => $targetShortcut) { $this->text = str_replace($sourceShortcut, $targetShortcut, $this->text); } // for all decimals, where is space between them: // example: 9 999 999 -> 9&nbsp;999&nbsp;999 $this->text = preg_replace("#([0-9])\s([0-9])#", "$1&nbsp;$2", $this->text); return $this->text; }
php
{ "resource": "" }
q252805
LineBreaksHelper.processWeakWord
validation
protected function processWeakWord ($word) { $index = 0; $text = ' ' . $this->text . ' '; // go through infinite loop and process given week word with html fixed spaces replacement while (TRUE) { $index = mb_strpos($text, ' ' . $word . ' '); if ($index !== FALSE) { // If there is any week word and basic white space // before and after the week word in source text: // - take all source text before week word including white space before week word, // - take week word // - add fixed space html entity // - and add all rest source text after week word // and white space char after week word $text = mb_substr($text, 0, $index + 1) . $word . '&nbsp;' . mb_substr($text, $index + 1 + mb_strlen($word) + 1); // move $index variable after position, where is source text already processed $index += 1 + mb_strlen($word) + 6; // (6 - means length of space html entity: '&nbsp;' } else { // there is no other occurrence of week word in source text break; } } $this->text = mb_substr($text, 1, mb_strlen($text) - 2); }
php
{ "resource": "" }
q252806
Concrete5.getApp
validation
private function getApp() { if( is_null($this->app) ) { $this->app = \Concrete\Core\Support\Facade\Application::getFacadeApplication(); } return $this->app; }
php
{ "resource": "" }
q252807
Bootstrap.register
validation
public function register(string ...$mods) : void { $this->kms = array_unique(array_merge($this->kms, $mods)); }
php
{ "resource": "" }
q252808
Di.set
validation
public function set(string $sNameOfDi, callable $cFunction, bool $bShared = false) : Di { if ($bShared === true) { self::$_aSharedDependencyInjectorContener[md5($sNameOfDi)] = $cFunction; } else { $this->_aDependencyInjectorContener[md5($sNameOfDi)] = $cFunction; } return $this; }
php
{ "resource": "" }
q252809
Web2All_Table_ObjectIterator.count
validation
public function count() { // start the query if recordSet is not yet initialised // if the recordSet is initialised it doesn't matter if its used or not if (is_null($this->recordSet)) { $this->fetchData(); } if(is_null($this->recordcount)){ // store the number of records returned $this->recordcount = $this->recordSet->RecordCount(); } return $this->recordcount; }
php
{ "resource": "" }
q252810
Attachment.search
validation
public static function search($query, &$results = array()) { $attachments = static::getInstance(); if (!empty($query)): $words = explode(' ', $query); foreach ($words as $word) { $_results = $attachments->setListLookUpConditions("attachment_name", $word, 'OR') ->setListLookUpConditions("attachment_title", $word, 'OR') ->setListLookUpConditions("attachment_description", $word, 'OR') ->setListLookUpConditions("attachment_tags", $word, 'OR'); } $_results = $attachments ->setListLookUpConditions("attachment_owner", array($attachments->user->get("user_name_id")),"AND",true) ->setListOrderBy("o.object_created_on", "DESC") ->getObjectsList("attachment"); $rows = $_results->fetchAll(); $browsable = array("image/jpg", "image/jpeg", "image/png", "image/gif"); //Include the members section $documents = array( "filterid" => "attachments", "title" => "Documents", "results" => array() ); //Loop through fetched attachments; //@TODO might be a better way of doing this, but just trying foreach ($rows as $attachment) { $document = array( "title" => $attachment['attachment_title'], //required "description" => "", //required "type" => $attachment['object_type'], "object_uri" => $attachment['object_uri'] ); if (in_array($attachment['attachment_type'], $browsable)): $document['icon'] = "/system/object/{$attachment['object_uri']}/resize/170/170"; $document['link'] = "/system/media/photo/view/{$attachment['object_uri']}"; else: $document['media_uri'] = $attachment['object_uri']; $document['link'] = "/system/object/{$attachment['object_uri']}"; endif; $documents["results"][] = $document; } //Add the members section to the result array, only if they have items; if (!empty($documents["results"])) $results[] = $documents; endif; return true; }
php
{ "resource": "" }
q252811
Attachment.load
validation
final public static function load(&$object, &$params) { //Relaod the object $attachments = static::getInstance(); $attachment = & $object; //if is object $object if (!is_a($attachment, Entity::class)) { //Attempt to determine what type of object this is or throw an error $attachment = $attachments->loadObjectByURI($attachment); //Make sure its an object; } if ($attachment->getObjectType() !== "attachment") return false; //we only deal with attachments, let others deal withit $fileId = $attachment->getObjectType(); $filePath = FSPATH . DS . $attachment->getPropertyValue("attachment_src"); $contentType = $attachment->getPropertyValue("attachment_type"); static::place($fileId, $filePath, $contentType, $params); }
php
{ "resource": "" }
q252812
BlockEditingListener.onBlockEditing
validation
public function onBlockEditing(BlockEditingEvent $event) { $encodedBlock = $event->getFileContent(); $htmlBlock = $this->pageProductionRenderer->renderBlock($encodedBlock); $this->permalinkManager ->add($event->getFilePath(), $htmlBlock) ->save(); }
php
{ "resource": "" }
q252813
StructureProcessor.process
validation
public function process($structureName, $origin) { $def = $this->structures[$structureName]; $data = array_merge( $def->getEmptyValues(), $this->source->fetchData($structureName, $origin) ); $accessor = new PropertyAccess(); foreach ($def->getChildren() as $childDef) { $data = array_merge( $data, $this->modifyPlaceholders( $this->process($childDef['name'], $accessor->get($data, $childDef['name'])), $childDef['prefix'], $childDef['suffix'] ) ); unset($data[$childDef['name']]); } return $data; }
php
{ "resource": "" }
q252814
Response.SendHeaders
validation
public function SendHeaders() { // headers have already been sent if (headers_sent()) { return $this; } header('HTTP/'.$this->Version.' '.$this->StatusCode.' '.$this->StatusText, true, $this->StatusCode); foreach ($this->Headers->GetCookies() as $cookie) { } return $this; }
php
{ "resource": "" }
q252815
FormButtonIcon.openTag
validation
public function openTag($attributesOrElement = null) { if (null === $attributesOrElement) { return '<button>'; } if (is_array($attributesOrElement)) { $attributes = $this->createAttributesString($attributesOrElement); return sprintf('<button %s>', $attributes); } if (!$attributesOrElement instanceof ElementInterface) { throw new Exception\InvalidArgumentException( sprintf( '%s expects an array or Zend\Form\ElementInterface instance; received "%s"', __METHOD__, (is_object($attributesOrElement) ? get_class($attributesOrElement) : gettype($attributesOrElement)) ) ); } $element = $attributesOrElement; $attributes = $element->getAttributes(); $name = $element->getName(); if ($name) { $attributes['name'] = $name; } $attributes['type'] = $this->getType($element); $classList = [ 'btn', 'btn-white' ]; /** @noinspection UnSafeIsSetOverArrayInspection */ if (isset($attributes['class'])) { $attributes['class'] = implode( ' ', array_unique(array_merge(explode(' ', $attributes['class']), $classList)) ); } else { $attributes['class'] = implode(' ', $classList); } return sprintf( '<button %s>', $this->createAttributesString($attributes) ); }
php
{ "resource": "" }
q252816
RegistrationController.actionRegister
validation
public function actionRegister() { if (!$this->module->enableRegistration) { throw new NotFoundHttpException; } $model = \Yii::createObject(RegistrationForm::className()); $this->performAjaxValidation($model); if ($model->load(\Yii::$app->request->post()) && $model->register()) { return $this->render('/message', [ 'title' => \Yii::t('user', 'Your account has been created'), 'module' => $this->module, ]); } return $this->render('register', [ 'model' => $model, 'module' => $this->module, ]); }
php
{ "resource": "" }
q252817
RegistrationController.actionConnect
validation
public function actionConnect($account_id) { $account = $this->finder->findAccountById($account_id); if ($account === null || $account->getIsConnected()) { throw new NotFoundHttpException; } /** @var User $user */ $user = \Yii::createObject([ 'class' => User::className(), 'scenario' => 'connect' ]); if ($user->load(\Yii::$app->request->post()) && $user->create()) { $account->user_id = $user->id; $account->save(false); \Yii::$app->user->login($user, $this->module->rememberFor); return $this->goBack(); } return $this->render('connect', [ 'model' => $user, 'account' => $account ]); }
php
{ "resource": "" }
q252818
RegistrationController.actionConfirm
validation
public function actionConfirm($id, $code) { $user = $this->finder->findUserById($id); if ($user === null || $this->module->enableConfirmation == false) { throw new NotFoundHttpException; } $user->attemptConfirmation($code); return $this->render('/message', [ 'title' => \Yii::t('user', 'Account confirmation'), 'module' => $this->module, ]); }
php
{ "resource": "" }
q252819
RegistrationController.actionResend
validation
public function actionResend() { if ($this->module->enableConfirmation == false) { throw new NotFoundHttpException; } $model = \Yii::createObject(ResendForm::className()); $this->performAjaxValidation($model); if ($model->load(\Yii::$app->request->post()) && $model->resend()) { return $this->render('/message', [ 'title' => \Yii::t('user', 'A new confirmation link has been sent'), 'module' => $this->module, ]); } return $this->render('resend', [ 'model' => $model ]); }
php
{ "resource": "" }
q252820
Logger.config
validation
private function config() { $handler = new RotatingFileHandler($this->getFullPath(), 0, MonoLogger::INFO); $handler->setFormatter($this->getLineFormater()); $this->logger->pushHandler($handler); $this->logger->pushProcessor(new WebProcessor()); $this->logger->pushProcessor(new MemoryUsageProcessor()); }
php
{ "resource": "" }
q252821
GitSynchronizer.getStatus
validation
public function getStatus() { $message = 'Tracking '; $numRepos = 0; if (isset($this['repositories']) && (1 === ($numRepos = count($this['repositories'])))) { $message .= '1 repository.'; } else { $message .= $numRepos . ' repositories.'; } return $message; }
php
{ "resource": "" }
q252822
RedKiteCms.bootstrap
validation
public function bootstrap($rootDir, $siteName) { $this->app["red_kite_cms.root_dir"] = $rootDir; $this->siteName = $siteName; $this->checkPermissions($rootDir); $this->initCmsRequiredServices(); $this->registerProviders(); $this->registerServices(); $this->registerListeners(); $this->register($this->app); $this->boot(); $this->addWebsiteRoutes(); $this->app["dispatcher"]->dispatch( CmsEvents::CMS_BOOTED, new CmsBootedEvent($this->app["red_kite_cms.configuration_handler"]) ); }
php
{ "resource": "" }
q252823
BlockPass.getPublicRequireDefinition
validation
private function getPublicRequireDefinition(ContainerBuilder $container, $id, $type) { $serviceDefinition = $container->getDefinition($id); if (!$serviceDefinition->isPublic()) { throw new InvalidArgumentException(sprintf('The service "%s" must be public as block %s are lazy-loaded.', $id, $type)); } return $serviceDefinition; }
php
{ "resource": "" }
q252824
Pagamento.exchangeArray
validation
public function exchangeArray($array) { return $this->setId(isset($array['id'])?$array['id']:null) ->setAutenticacaoId($array['autenticacao_id']) ->setValor($array['valor']) ->setData(isset($array['data'])?$array['data']:null); }
php
{ "resource": "" }
q252825
CalcEu.exec
validation
public function exec($calcId) { $result = []; /* collect additional data */ $bonusPercent = Cfg::TEAM_BONUS_EU_PERCENT; $dwnlCompress = $this->daoBonDwnl->getByCalcId($calcId); $dwnlCurrent = $this->daoDwnl->get(); /* create maps to access data */ $mapDwnlById = $this->hlpDwnlTree->mapById($dwnlCompress, EBonDwnl::A_CUST_REF); $mapCustById = $this->hlpDwnlTree->mapById($dwnlCurrent, ECustomer::A_CUSTOMER_REF); /** * Go through all customers from compressed tree and calculate bonus. * * @var int $custId * @var EBonDwnl $custDwnl */ foreach ($mapDwnlById as $custId => $custDwnl) { /** @var ECustomer $custData */ $custData = $mapCustById[$custId]; $custMlmId = $custData->getMlmId(); $pv = $custDwnl->getPv(); $parentId = $custDwnl->getParentRef(); /** @var EBonDwnl $parentDwnl */ $parentDwnl = $mapDwnlById[$parentId]; /** @var ECustomer $parentData */ $parentData = $mapCustById[$parentId]; $parentMlmId = $parentData->getMlmId(); $scheme = $this->hlpScheme->getSchemeByCustomer($parentData); if ($scheme == Cfg::SCHEMA_EU) { $pvParent = $parentDwnl->getPv(); if ($pvParent > (Cfg::PV_QUALIFICATION_LEVEL_EU - Cfg::DEF_ZERO)) { $bonus = $this->hlpFormat->roundBonus($pv * $bonusPercent); if ($bonus > Cfg::DEF_ZERO) { $entry = new DBonus(); $entry->setCustomerRef($parentId); $entry->setDonatorRef($custId); $entry->setValue($bonus); $result[] = $entry; } $this->logger->debug("parent #$parentId (ref. #$parentMlmId) has '$bonus' as EU Team Bonus from downline customer #$custId (ref. #$custMlmId )."); } else { $this->logger->debug("parent #$parentId (ref. #$parentMlmId) does not qualified t oget EU Team Bonus from downline customer #$custId (ref. #$custMlmId )."); } } else { $this->logger->debug("Parent #$parentId (ref. #$parentMlmId) has incompatible scheme '$scheme' for EU Team Bonus."); } } unset($mapCustById); unset($mapDwnlById); return $result; }
php
{ "resource": "" }
q252826
SpoolManager.setSpoolDirectory
validation
public function setSpoolDirectory($dir) { if (!DirectoryHelper::ensureExists($dir)) { throw new \Exception( sprintf('Can not create emails spooling directory "%s"!', $dir) ); } $this->spool_dir = $dir; return $this; }
php
{ "resource": "" }
q252827
Benchmark.start
validation
public function start($taskName, $repeat = null) { $task = new Task(); $task->name($taskName); if ($repeat) { $task->repeat($repeat); } if (isset($this->_tasks[$taskName])) { throw new Exception("Task {$taskName} is already defined."); } $this->_tasks[$taskName] = $task; $task->start(); return $task; }
php
{ "resource": "" }
q252828
Benchmark.end
validation
public function end($taskName) { if (!isset($this->_tasks[$taskName])) { throw new Exception("Undefined task name: `'{$taskName}`."); } $task = $this->_tasks[$taskName]; $task->end(); return $task; }
php
{ "resource": "" }
q252829
Benchmark.duration
validation
public function duration() { $duration = 0; foreach ($this->_tasks as $task) { $duration += $task->duration(); } return $duration; }
php
{ "resource": "" }
q252830
Benchmark.matrix
validation
public function matrix() { if ($this->_matrix) { return $this->_matrix; } $this->_matrix = new Matrix($this->tasks()); $this->_matrix->process(); return $this->_matrix; }
php
{ "resource": "" }
q252831
Benchmark.title
validation
public static function title($title, $pad = '=') { $rest = (int) (78 - mb_strlen($title)) / 2; $result = "\n\n"; $result .= str_repeat($pad, $rest); $result .= ' ' . $title . ' '; $result .= str_repeat($pad, $rest); $result .= "\n\n"; return $result; }
php
{ "resource": "" }
q252832
Image.upload
validation
private function upload($path, $payload) { return Storage::disk('s3')->put($path, $payload, $this->visibility); }
php
{ "resource": "" }
q252833
Image.getFullPath
validation
public function getFullPath($file = '') { $this->name = ($file) ? $file : $this->name; return config('odin.assetsUrl') . $this->getPath() . $this->name; }
php
{ "resource": "" }
q252834
PageService.getAction
validation
public function getAction() { $id = $this->getPageId(); if ($id !== null) { $result = $this->pageList->getPage($id)->getJSON(); } else { $result = array(); foreach ($this->pageList->getPages() as $pageName) { $result[] = $this->pageList->getPage($pageName)->getJSON(); } } $this->environment->sendJSONResult($result); }
php
{ "resource": "" }
q252835
PageService.postAction
validation
public function postAction() { $request = $this->environment->getRequestHelper(); $id = $request->getIdentifierParam('name'); try { $this->pageList->getPage($id); } catch (InvalidParameterException $e) { $page = $this->pageList->addPageFromRequest($id, $request); $this->environment->sendJSONResult($page->getJSON()); return; } throw new InvalidParameterException("Page already exists"); }
php
{ "resource": "" }
q252836
PageService.getPageId
validation
private function getPageId() { if (preg_match('/\/page\/(\w+)$/', $this->name, $matches)) { $id = $matches[1]; } else { $id = $this->environment->getRequestHelper()->getIdentifierParam('id', null, true); } return $id; }
php
{ "resource": "" }
q252837
Calc.exec
validation
public function exec($dwnlBonus) { $result = []; $mapById = $this->hlpDwnlTree->mapById($dwnlBonus, EBonDwnl::A_CUST_REF); $mapTeams = $this->hlpDwnlTree->mapByTeams($dwnlBonus, EBonDwnl::A_CUST_REF, EBonDwnl::A_PARENT_REF); /** @var \Praxigento\BonusHybrid\Repo\Data\Downline $one */ foreach ($dwnlBonus as $one) { $custId = $one->getCustomerRef(); /** @var \Praxigento\BonusHybrid\Repo\Data\Downline $cust */ $cust = $mapById[$custId]; /* initial TV equal to own PV */ $tv = $cust->getPv(); if (isset($mapTeams[$custId])) { /* add PV of the front line team (first generation) */ $frontTeam = $mapTeams[$custId]; foreach ($frontTeam as $teamMemberId) { /** @var \Praxigento\BonusHybrid\Repo\Data\Downline $member */ $member = $mapById[$teamMemberId]; $memberPv = $member->getPv(); $tv += $memberPv; } } $cust->setTv($tv); $result[$custId] = $cust; } return $result; }
php
{ "resource": "" }
q252838
Cache.setCacheType
validation
public static function setCacheType(string $sCacheName) { if ($sCacheName === 'file') { self::$_sTypeOfCache = 'file'; } else if ($sCacheName === 'memcache') { self::$_sTypeOfCache = 'memcache'; } else if ($sCacheName === 'apc') { self::$_sTypeOfCache = 'apc'; } else if ($sCacheName === 'redis') { self::$_sTypeOfCache = 'redis'; } else { self::$_sTypeOfCache = 'mock'; } }
php
{ "resource": "" }
q252839
Cache._getCacheObject
validation
private static function _getCacheObject() { if (self::$_sTypeOfCache === 'file') { if (!isset(self::$_aCache['file'])) { self::$_aCache['file'] = new CacheFile; } return self::$_aCache['file']; } else if (self::$_sTypeOfCache === 'memcache') { if (!isset(self::$_aCache['memcache'])) { $oDbConf = Config::get('Memcache')->configuration; if (isset($oDbConf->port)) { $sPort = $oDbConf->port; } else { $sPort = null; } if (isset($oDbConf->timeout)) { $iTimeout = $oDbConf->timeout; } else { $iTimeout = null; } self::$_aCache['memcache'] = new CacheMemcache($oDbConf->host, $sPort, $iTimeout); } return self::$_aCache['memcache']; } else if (self::$_sTypeOfCache === 'apc') { if (!isset(self::$_aCache['apc'])) { self::$_aCache['apc'] = new Apc; } return self::$_aCache['apc']; } else if (self::$_sTypeOfCache === 'redis') { if (!isset(self::$_aCache['redis'])) { $oDbConf = Config::get('Redis')->configuration; self::$_aCache['memcache'] = new Redis($oDbConf); } return self::$_aCache['redis']; } else if (self::$_sTypeOfCache === 'mock') { if (!isset(self::$_aCache['mock'])) { self::$_aCache['mock'] = new Mock; } return self::$_aCache['mock']; } }
php
{ "resource": "" }
q252840
AppHelper.run
validation
public function run(): void { if (!$this->isAppRootSet()) { throw new Exception("The application root wasn't defined."); } if (!$this->isConfigFileSet()) { throw new Exception("The main config file wasn't defined."); } $configPath = $this->getAppRoot().$this->getConfigFile(); if (!is_readable($configPath)) { throw new Exception("It's unable to load ".$configPath .'as main config file.'); } $config = require_once $configPath; if (!is_array($config)) { throw new Exception('The main config must be an array.'); } $this->configSet = $config; }
php
{ "resource": "" }
q252841
AppHelper.getConfig
validation
public function getConfig(string $sName = '') { if (empty($sName)) { return $this->configSet; } elseif (isset($this->configSet[$sName])) { return $this->configSet[$sName]; } else { return null; } }
php
{ "resource": "" }
q252842
AppHelper.getBaseUrl
validation
private static function getBaseUrl(): ?string { $serverName = filter_input( \INPUT_SERVER, 'SERVER_NAME', \FILTER_SANITIZE_STRING ); if (!empty($serverName)) { $https = filter_input(\INPUT_SERVER, 'HTTPS', \FILTER_SANITIZE_STRING); $protocol = !empty($https) && strtolower($https) === 'on' ? 'https' : 'http'; return $protocol.'://'.$serverName; } return null; }
php
{ "resource": "" }
q252843
AppHelper.getComponentRoot
validation
public function getComponentRoot(string $name): ?string { $rootMap = $this->getConfig('componentsRootMap'); return isset($rootMap[$name]) ? $this->getAppRoot().$rootMap[$name] : null; }
php
{ "resource": "" }
q252844
ThemeAligner.align
validation
public function align(PagesCollectionParser $pagesCollectionParser) { $themeSlots = $this->findSlotsInTemplates(); $slots = $this->mergeSlotsByStatus($themeSlots); if (!array_key_exists("page", $slots)) { return; } $pageSlots = $slots["page"]; unset($slots["page"]); $files = $this->removeCommonSlots($slots); $files = array_merge($files, $this->removePageSlots($pagesCollectionParser, $pageSlots)); if (!empty($files)) { $fs = new Filesystem(); $fs->remove($files); } }
php
{ "resource": "" }
q252845
Listener.notify
validation
public function notify() { declare(ticks=1); if (is_array($this->_caller) && !empty($this->_caller)) { // array return call_user_func_array($this->_caller, [$this->_interrupt]); } else if ($this->_caller instanceof Closure) { // closure return $this->_caller->call($this, $this->_interrupt); } else if (is_callable($this->_caller)) { // callable $cl = Closure::fromCallable($this->_caller); return $cl->call($this,$this->_interrupt); } return null; }
php
{ "resource": "" }
q252846
CRC16.getHashGeneratorByDescription
validation
protected function getHashGeneratorByDescription(OptionsInterface $options, $description) { if ($description === 'predis') { return new Hash\CRC16(); } elseif ($description === 'phpiredis') { return new Hash\PhpiredisCRC16(); } else { throw new \InvalidArgumentException( 'String value for the crc16 option must be either `predis` or `phpiredis`' ); } }
php
{ "resource": "" }
q252847
ObjectType.getPHPHint
validation
public function getPHPHint($namespaceContext = NULL) { if (!isset($this->class)) { return '\stdClass'; } if (isset($namespaceContext) && trim($this->class->getNamespace(),'\\') === trim($namespaceContext,'\\')) { return $this->class->getName(); } return '\\'.$this->class->getFQN(); }
php
{ "resource": "" }
q252848
SettingsController.actionProfile
validation
public function actionProfile() { $model = $this->finder->findProfileById(\Yii::$app->user->identity->getId()); $this->performAjaxValidation($model); if ($model->load(\Yii::$app->request->post()) && $model->save()) { \Yii::$app->getSession()->setFlash('success', \Yii::t('user', 'Your profile has been updated')); return $this->refresh(); } return $this->render('profile', [ 'model' => $model, ]); }
php
{ "resource": "" }
q252849
SettingsController.actionConfirm
validation
public function actionConfirm($id, $code) { $user = $this->finder->findUserById($id); if ($user === null || $this->module->emailChangeStrategy == Module::STRATEGY_INSECURE) { throw new NotFoundHttpException; } $user->attemptEmailChange($code); return $this->redirect(['account']); }
php
{ "resource": "" }
q252850
SettingsController.actionDisconnect
validation
public function actionDisconnect($id) { $account = $this->finder->findAccountById($id); if ($account === null) { throw new NotFoundHttpException; } if ($account->user_id != \Yii::$app->user->id) { throw new ForbiddenHttpException; } $account->delete(); return $this->redirect(['networks']); }
php
{ "resource": "" }
q252851
SettingsController.connect
validation
public function connect(ClientInterface $client) { $attributes = $client->getUserAttributes(); $provider = $client->getId(); $clientId = $attributes['id']; $account = $this->finder->findAccountByProviderAndClientId($provider, $clientId); if ($account === null) { $account = \Yii::createObject([ 'class' => Account::className(), 'provider' => $provider, 'client_id' => $clientId, 'data' => json_encode($attributes), 'user_id' => \Yii::$app->user->id, ]); $account->save(false); \Yii::$app->session->setFlash('success', \Yii::t('user', 'Your account has been connected')); } else if (null == $account->user) { $account->user_id = \Yii::$app->user->id; $account->save(false); } else { \Yii::$app->session->setFlash('error', \Yii::t('user', 'This account has already been connected to another user')); } $this->action->successUrl = Url::to(['/user/settings/networks']); }
php
{ "resource": "" }
q252852
RequestFile.move
validation
public function move($path, $filename = null) { $newFilename = ($filename != null) ? $filename : $this->filename; // Valida si la ruta termina con slash $lastSlash = substr($path, strlen($path), 1); if ($lastSlash !== '/') { $path .= '/'; } // Retorno TRUE si se movio el archivo, de lo contrario FALSE $result = move_uploaded_file($this->realPath, $path . $newFilename); return $result; }
php
{ "resource": "" }
q252853
ResolveContainerCapableTrait._resolveContainer
validation
protected function _resolveContainer(BaseContainerInterface $container) { $parent = null; while ($container instanceof ContainerAwareInterface) { $parent = $container->getContainer(); if (!($parent instanceof BaseContainerInterface)) { break; } $container = $parent; } return $container; }
php
{ "resource": "" }
q252854
Staff.create
validation
public function create($account, $nickname) { $params = [ 'kf_account' => $account, 'nickname' => $nickname, ]; return $this->parseJSON('json', [self::API_CREATE, $params]); }
php
{ "resource": "" }
q252855
Staff.update
validation
public function update($account, $nickname) { $params = [ 'kf_account' => $account, 'nickname' => $nickname, ]; return $this->parseJSON('json', [self::API_UPDATE, $params]); }
php
{ "resource": "" }
q252856
Staff.delete
validation
public function delete($account) { // XXX: 微信那帮搞技术的都 TM 是 SB,url上的文本居然不 TM urlencode, // 这里客服账号因为有 @ 符,而微信不接收urlencode的账号。。 // 简直是日了... // #222 // PS: 如果你是微信做接口的,奉劝你们,尊重技术,不会别乱搞,笨不是你们的错,你们出来坑人就是大错特错。 $accessTokenField = sprintf('%s=%s', $this->accessToken->getQueryName(), $this->accessToken->getToken()); $url = sprintf(self::API_DELETE.'?%s&kf_account=%s', $accessTokenField, $account); $contents = $this->getHttp()->parseJSON(file_get_contents($url)); $this->checkAndThrow($contents); return new Collection($contents); }
php
{ "resource": "" }
q252857
Staff.invite
validation
public function invite($account, $wechatId) { $params = [ 'kf_account' => $account, 'invite_wx' => $wechatId, ]; return $this->parseJSON('json', [self::API_INVITE_BIND, $params]); }
php
{ "resource": "" }
q252858
Staff.records
validation
public function records($startTime, $endTime, $page = 1, $pageSize = 10) { $params = [ 'starttime' => is_numeric($startTime) ? $startTime : strtotime($startTime), 'endtime' => is_numeric($endTime) ? $endTime : strtotime($endTime), 'pageindex' => $page, 'pagesize' => $pageSize, ]; return $this->parseJSON('json', [self::API_RECORDS, $params]); }
php
{ "resource": "" }
q252859
Phase2.compressPhase2
validation
private function compressPhase2($calcIdWriteOff, $calcIdPhase1, $calcIdPhase2, $scheme) { $pv = $this->rouGetPv->exec($calcIdWriteOff); $dwnlPlain = $this->daoBonDwnl->getByCalcId($calcIdWriteOff); $dwnlPhase1 = $this->daoBonDwnl->getByCalcId($calcIdPhase1); $ctx = new \Praxigento\Core\Data(); $ctx->set(PCpmrsPhase2::IN_CALC_ID_PHASE2, $calcIdPhase2); $ctx->set(PCpmrsPhase2::IN_SCHEME, $scheme); $ctx->set(PCpmrsPhase2::IN_DWNL_PLAIN, $dwnlPlain); $ctx->set(PCpmrsPhase2::IN_DWNL_PHASE1, $dwnlPhase1); $ctx->set(PCpmrsPhase2::IN_MAP_PV, $pv); $out = $this->procCmprsPhase2->exec($ctx); $dwnlPhase2 = $out->get(PCpmrsPhase2::OUT_DWNL_PHASE2); $legs = $out->get(PCpmrsPhase2::OUT_LEGS); $result = [$dwnlPhase2, $legs]; return $result; }
php
{ "resource": "" }
q252860
Core.site
validation
public function site(): \TheCMSThread\Core\Main\Site { static $site; if ($site === null) { $site = $this->container->get("TheCMSThread\\Core\\Main\\Site"); } return $site; }
php
{ "resource": "" }
q252861
Core.auth
validation
public function auth(): \TheCMSThread\Core\Main\Auth { static $auth; if ($auth === null) { $auth = $this->container->get("TheCMSThread\\Core\\Main\\Auth"); } $auth->__construct(); return $auth; }
php
{ "resource": "" }
q252862
Core.view
validation
public function view(): \TheCMSThread\Core\Main\View { static $view; if ($view === null) { $view = $this->container->get("TheCMSThread\\Core\\Main\\View"); } $view->__construct($this->auth()); return $view; }
php
{ "resource": "" }
q252863
Core.api
validation
public function api(string $link = null, string $method = null): \TheCMSThread\Classes\API { static $api; if ($api === null) { $api = $this->container->get("TheCMSThread\\Core\\API"); } return $api->set($link, $method); }
php
{ "resource": "" }
q252864
Session.close
validation
public function close() { if($this->id == null) { throw new InternalException('Session not loaded'); } if(!$this->cli) { session_write_close(); } $this->id = null; }
php
{ "resource": "" }
q252865
SocialMediaScheduleHandler.getContent
validation
public function getContent(Location $location = null, Operation $operation) { if($operation) { $status = $this->contentService->getSocialMediaScheduleByOperation($operation); return $status; } return null; }
php
{ "resource": "" }
q252866
SocialMediaScheduleHandler.processContent
validation
public function processContent(Operation $operation, $data) { if(is_array($data)) { // If the status has already been created, we modify its data. $status = $this->contentService->getSocialMediaScheduleByOperation($operation); // If data comes from API call, then Locations will not be // entities, but their IDs in an array. if(!$data['locations'] instanceof ArrayCollection){ $locations = $this->em ->getRepository('CampaignChainCoreBundle:Location') ->findById(array_values($data['locations'])); $locations = new ArrayCollection($locations); } else { $locations = $data['locations']; } $status->setLocations($locations); $status->setMessage($data['message']); } else { $status = $data; } return $status; }
php
{ "resource": "" }
q252867
AbstractCliController.isrunning
validation
private function isrunning() { $pids = explode(PHP_EOL, `ps -e | awk '{print $1}'`); if (in_array($this->pid, $pids)) return true; return false; }
php
{ "resource": "" }
q252868
AbstractCliController.lock
validation
public function lock() { $lock_file = $this->getLockFile(); if (file_exists($lock_file)) { // Is running? $this->pid = file_get_contents($lock_file); if ($this->isrunning()) { error_log("==".$this->pid."== Already in progress..."); return false; } else error_log("==".$this->pid."== Previous job died abruptly..."); } $this->pid = getmypid(); $s = file_put_contents($lock_file, $this->pid); error_log("==".$this->pid."== Lock acquired, processing the job..."); return $this->pid; }
php
{ "resource": "" }
q252869
AbstractCliController.getLockFile
validation
protected function getLockFile() { $request = $this->getRequest(); $params = $request->getParams(); $controller = $params->controller; $action = $params->action; $normalizedController = strtolower(stripslashes(str_replace(__NAMESPACE__, '', $controller))); $fileBaseName = implode('_', array( basename($request->getScriptName()), $normalizedController, $action )); return $this->lockdir . DIRECTORY_SEPARATOR . $fileBaseName . self::FILE_SUFFIX; }
php
{ "resource": "" }
q252870
PvWriteOff.createOperation
validation
private function createOperation($trans, $dsBegin) { $datePerformed = $this->hlpDate->getUtcNowForDb(); $req = new \Praxigento\Accounting\Api\Service\Operation\Create\Request(); $req->setOperationTypeCode(Cfg::CODE_TYPE_OPER_PV_WRITE_OFF); $req->setDatePerformed($datePerformed); $req->setTransactions($trans); $period = substr($dsBegin, 0, 6); $note = "PV Write Off ($period)"; $req->setOperationNote($note); $resp = $this->servOperation->exec($req); $result = $resp->getOperationId(); return $result; }
php
{ "resource": "" }
q252871
PvWriteOff.getTransactions
validation
private function getTransactions($turnover, $dsEnd) { $dateApplied = $this->hlpPeriod->getTimestampUpTo($dsEnd); $result = $this->aPrepareTrans->exec($turnover, $dateApplied); return $result; }
php
{ "resource": "" }
q252872
PvWriteOff.getTransitions
validation
private function getTransitions($dsBegin, $dsEnd) { $assetTypeId = $this->daoTypeAsset->getIdByCode(Cfg::CODE_TYPE_ASSET_PV); $dateFrom = $this->hlpPeriod->getTimestampFrom($dsBegin); $dateTo = $this->hlpPeriod->getTimestampNextFrom($dsEnd); $query = $this->aQGetData->build(); $bind = [ $this->aQGetData::BND_ASSET_TYPE_ID => $assetTypeId, $this->aQGetData::BND_DATE_FROM => $dateFrom, $this->aQGetData::BND_DATE_TO => $dateTo ]; $conn = $query->getConnection(); $rs = $conn->fetchAll($query, $bind); $result = []; foreach ($rs as $one) { $item = new \Praxigento\BonusHybrid\Service\Calc\PvWriteOff\A\Data\Trans($one); $result[] = $item; } return $result; }
php
{ "resource": "" }
q252873
PvWriteOff.groupPvTrans
validation
private function groupPvTrans($transData) { $result = []; foreach ($transData as $one) { $debitAccId = $one->get(DTrans::A_ACC_ID_DEBIT); $creditAccId = $one->get(DTrans::A_ACC_ID_CREDIT); $value = $one->get(DTrans::A_AMOUNT); if (isset($result[$debitAccId])) { $result[$debitAccId] -= $value; } else { $result[$debitAccId] = -$value; } if (isset($result[$creditAccId])) { $result[$creditAccId] += $value; } else { $result[$creditAccId] = $value; } } return $result; }
php
{ "resource": "" }
q252874
PvWriteOff.saveLog
validation
private function saveLog($operIdWriteOff, $calcId) { /* log PvWriteOff operation itself */ $log = new ELogOper(); $log->setCalcId($calcId); $log->setOperId($operIdWriteOff); $this->daoLogOper->create($log); }
php
{ "resource": "" }
q252875
Relation.bindPage
validation
public function bindPage(array $deviceIdentifier, array $pageIds) { $params = [ 'device_identifier' => $deviceIdentifier, 'page_ids' => $pageIds, ]; return $this->parseJSON('json', [self::API_DEVICE_BINDPAGE, $params]); }
php
{ "resource": "" }
q252876
Relation.getPageByDeviceId
validation
public function getPageByDeviceId(array $deviceIdentifier, $raw = false) { $params = [ 'type' => 1, 'device_identifier' => $deviceIdentifier, ]; $result = $this->parseJSON('json', [self::API_RELATION_SEARCH, $params]); if ($raw === true) { return $result; } $page_ids = []; if (!empty($result->data['relations'])) { foreach ($result->data['relations'] as $item) { $page_ids[] = $item['page_id']; } } return $page_ids; }
php
{ "resource": "" }
q252877
Relation.getDeviceByPageId
validation
public function getDeviceByPageId($pageId, $begin, $count) { $params = [ 'type' => 2, 'page_id' => intval($pageId), 'begin' => intval($begin), 'count' => intval($count), ]; return $this->parseJSON('json', [self::API_RELATION_SEARCH, $params]); }
php
{ "resource": "" }
q252878
Collector.getTableRegistry
validation
public function getTableRegistry() { if (is_null($this->_tableRegistry)) { $objectTypeClass = Yii::$app->classes['ObjectTypeRegistry']; $this->_tableRegistry = []; if ($objectTypeClass::tableExists()) { $om = $objectTypeClass::find()->all(); $this->_tableRegistry = ArrayHelper::index($om, 'name'); } } return $this->_tableRegistry; }
php
{ "resource": "" }
q252879
Collector.getAuthorities
validation
public function getAuthorities() { $authorities = []; foreach ($this->getAll() as $typeItem) { if (isset($typeItem->object) && $typeItem->object->getBehavior('Authority') !== null) { $authorities[$typeItem->object->systemId] = $typeItem->object; } } return $authorities; }
php
{ "resource": "" }
q252880
View.getColumnSettings
validation
public function getColumnSettings() { if (is_null($this->_columnSettings)) { $this->_columnSettings = []; foreach ($this->columns as $key => $c) { if (!$c->visible) { continue; } $this->_columnSettings[$key] = ['label' => $c->getDataLabel()]; if (!isset($c->htmlOptions)) { $c->htmlOptions = []; } $this->_columnSettings[$key]['htmlOptions'] = $c->htmlOptions; $sortableResolve = $this->dataProvider->sort->resolveAttribute($c->name); $this->_columnSettings[$key]['sortable'] = !empty($sortableResolve); } } return $this->_columnSettings; }
php
{ "resource": "" }
q252881
View.getData
validation
public function getData() { if (is_null($this->_currentData)) { $this->_currentDataRaw = $this->dataProvider->getData(); $this->_currentData = []; $itemNumber = $this->dataProvider->pagination->offset; $row = 0; foreach ($this->_currentDataRaw as $r) { $p = ['itemNumber' => $itemNumber, 'id' => $r->primaryKey, 'values' => []]; foreach ($this->columns as $key => $c) { $p['values'][$key] = $c->getDataValue($row, $r, false); } $p['acl'] = []; if ($this->owner->instanceSettings['whoAmI'] === 'parent' and isset($r->childObject) and $r->childObject->hasBehavior('Access')) { $p['acl'] = $r->childObject->aclSummary(); } elseif ($this->owner->instanceSettings['whoAmI'] === 'child' and isset($r->parentObject) and $r->parentObject->hasBehavior('Access')) { $p['acl'] = $r->parentObject->aclSummary(); } elseif ($r->hasBehavior('Access')) { $p['acl'] = $r->aclSummary(); } $this->_currentData['item-' . $itemNumber] = $p; $row++; $itemNumber++; } } return $this->_currentData; }
php
{ "resource": "" }
q252882
View.getColumns
validation
public function getColumns() { if (is_null($this->_columns)) { $this->columns = $this->dataProvider->model->attributeNames(); } return $this->_columns; }
php
{ "resource": "" }
q252883
View.getTotalItems
validation
public function getTotalItems() { if (is_null($this->_totalItems)) { $this->_totalItems = $this->dataProvider->totalItemCount; } return $this->_totalItems; }
php
{ "resource": "" }
q252884
View.getFormatter
validation
public function getFormatter() { if ($this->_formatter === null) { $this->_formatter = Yii::$app->format; } return $this->_formatter; }
php
{ "resource": "" }
q252885
Pipeline.getConnection
validation
protected function getConnection() { $connection = $this->getClient()->getConnection(); if ($connection instanceof ReplicationInterface) { $connection->switchToMaster(); } return $connection; }
php
{ "resource": "" }
q252886
APIGenerator.addOperationGetter
validation
function addOperationGetter( $methodName, OperationDefinition $operation, OperationGenerator $operationGenerator ) { $operationName = $this->normalizeMethodName($methodName); $operationClassName = $this->normalizeClassName($methodName); $methodGenerator = new MethodGenerator($operationName); $apiParameters = $this->getAPIParameters(); $body = ''; //All required parameters must be passed in when the operation is created. $requiredParameters = $operation->getRequiredParams(); $paramsStrings = []; $requiredParamsStringsWithDollar = []; $tags = []; $requiredParamsStringsWithDollar[] = '$this'; foreach($requiredParameters as $requiredParam) { $translatedParam = ucfirst($this->translateParameter($requiredParam->getName())); $normalizedParamName = normalizeParamName($requiredParam->getName()); if (array_key_exists($requiredParam->getName(), $apiParameters) == true) { $requiredParamsStringsWithDollar[] = sprintf( '$this->get%s()', $translatedParam ); } else { $paramsStrings[] = $normalizedParamName; $tags[] = new GenericTag( 'param', $requiredParam->getType().' $'.$requiredParam->getName().' '.$requiredParam->getDescription() ); //TODO - replace with array_map on $paramsStrings $requiredParamsStringsWithDollar[] = '$'.$normalizedParamName; } } $paramString = implode(', ', $requiredParamsStringsWithDollar); $methodGenerator->setParameters($paramsStrings); $tags[] = new GenericTag( 'return', '\\'.$operationGenerator->getFQCN().' The new operation ' ); $body .= "\$instance = new $operationClassName($paramString);".PHP_EOL; $body .= "return \$instance;".PHP_EOL; $docBlockGenerator = new DocBlockGenerator($methodName); $docBlockGenerator->setLongDescription($operation->getSummary()); $docBlockGenerator->setTags($tags); $methodGenerator->setDocBlock($docBlockGenerator); $methodGenerator->setBody($body); $this->classGenerator->addMethodFromGenerator($methodGenerator); $this->interfaceGenerator->addMethodFromGenerator($methodGenerator); }
php
{ "resource": "" }
q252887
APIGenerator.generateExecuteDocBlock
validation
private function generateExecuteDocBlock($methodDescription, $returnType) { $docBlock = new DocBlockGenerator($methodDescription, null); $tags[] = new GenericTag('return', $returnType); $docBlock->setTags($tags); return $docBlock; }
php
{ "resource": "" }
q252888
APIGenerator.parseAndAddServiceFromFile
validation
function parseAndAddServiceFromFile($serviceFilename) { $service = require $serviceFilename; if ($service == false) { throw new APIBuilderException("Failed to open service file `$serviceFilename`."); } if (is_array($service) == false) { throw new APIBuilderException("File `$serviceFilename` did not return a service array. Cannot build API from it."); } $this->parseAndAddService($service); }
php
{ "resource": "" }
q252889
Benri_Auth_Adapter_DbTable.authenticate
validation
public function authenticate() { $this->_authenticateSetup(); $dbSelect = $this->_authenticateCreateSelect(); $identity = $this->_authenticateQuerySelect($dbSelect); $authResult = $this->_authenticateValidateResultSet($identity); if ($authResult instanceof Zend_Auth_Result) { return $authResult; } /// _authenticateValidateResult() attempts to make certain that only /// one record was returned in the resultset. return $this->_authenticateValidateResult(array_shift($identity)); }
php
{ "resource": "" }
q252890
Benri_Auth_Adapter_DbTable._authenticateCreateSelect
validation
protected function _authenticateCreateSelect() { $dbSelect = clone $this->getDbSelect(); $dbSelect->from($this->_tableName) ->where("{$this->_identityColumn} = ?", $this->_identity) ->limit(1); return $dbSelect; }
php
{ "resource": "" }
q252891
Benri_Auth_Adapter_DbTable._authenticateValidateResult
validation
protected function _authenticateValidateResult($resultIdentity) { $code = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID; $message = 'Supplied credential is invalid.'; if (Benri_Util_String::verifyPassword($this->_credential, $resultIdentity[$this->_credentialColumn])) { $code = Zend_Auth_Result::SUCCESS; $message = 'Authentication successful.'; $this->_resultRow = $resultIdentity; } $this->_authenticateResultInfo['code'] = $code; $this->_authenticateResultInfo['messages'][] = $message; /// _authenticateCreateAuthResult creates a Zend_Auth_Result object /// from the information that has been collected during the /// Benri_Auth_Adapter_DbTable::authenticate() attempt. return $this->_authenticateCreateAuthResult(); }
php
{ "resource": "" }
q252892
ProductMapper.getProduct
validation
public function getProduct(array $productData) { // check if all mandatory fields are present foreach ($this->mandatoryFields as $mandatoryField) { if (!array_key_exists($mandatoryField, $productData)) { throw new ProductException("The field '$mandatoryField' is missing in the given product data"); } } // try to create a product from the available data try { // sku $sku = new SKU($productData[self::FIELD_SKU]); // slug $slug = new Slug($productData[self::FIELD_SLUG]); // product content $content = $this->contentMapper->getContent($productData); $product = new Product($sku, $slug, $content); return $product; } catch (\Exception $productException) { throw new ProductException(sprintf("Failed to create a product from the given data: %s", $productException->getMessage()), $productException); } }
php
{ "resource": "" }
q252893
Benri_Bootstrap._initRestRoute
validation
protected function _initRestRoute() { $front = Zend_Controller_Front::getInstance(); $front->setResponse(new Benri_Controller_Response_Http()); $front->setRequest(new Benri_Controller_Request_Http()); $front->getRouter()->addRoute('benri-app', new Zend_Rest_Route($front)); }
php
{ "resource": "" }
q252894
Benri_Bootstrap._initDbResource
validation
protected function _initDbResource() { $registry = $this->getPluginResource('db'); if (!$registry) { return; } // // options in configs/application $options = $registry->getOptions(); if (array_key_exists('dsn', $options) && '' !== $options['dsn']) { $options['params'] = array_replace( $options['params'], $this->_parseDsn($options['dsn']) ); } $registry->setOptions($options); }
php
{ "resource": "" }
q252895
Benri_Bootstrap._initMultiDbResources
validation
protected function _initMultiDbResources() { $registry = $this->getPluginResource('multidb'); if (!$registry) { return; } // // options in configs/application $options = $registry->getOptions(); foreach ($options as &$connection) { if ('db://' === substr($connection['dbname'], 0, 5)) { $connection = array_replace( $connection, $this->_parseDsn($connection['dbname']) ); } } Zend_Registry::set('multidb', $registry->setOptions($options)); }
php
{ "resource": "" }
q252896
Benri_Bootstrap._parseDsn
validation
private function _parseDsn($dsn) { $dsn = parse_url($dsn); $cfg = []; // // Some drivers (a.k.a. PDO_PGSQL) complains if the port is set // without a value, even NULL if (isset($dsn['port'])) { $cfg['port'] = $dsn['port']; } return $cfg + [ 'dbname' => isset($dsn['path']) ? trim($dsn['path'], '/') : null, 'host' => isset($dsn['host']) ? $dsn['host'] : null, 'password' => isset($dsn['pass']) ? $dsn['pass'] : null, 'username' => isset($dsn['user']) ? $dsn['user'] : null, ]; }
php
{ "resource": "" }
q252897
Module.getShortName
validation
public function getShortName() { preg_match('/Widget([A-Za-z]+)\\\Module/', get_class($this), $matches); if (!isset($matches[1])) { throw new Exception(get_class($this) . " is not set up correctly!"); } return $matches[1]; }
php
{ "resource": "" }
q252898
RedirectResponse.make
validation
public function make() { /* * Se guardan los headers si es que hay en la configuracion * para luego utilizarlos al construir la redireccion */ if (count($this->headers) > 0) { if (!$this->session->exists('headersInRedirect', 'redirect') || !$this->session->get('headersInRedirect', 'redirect')) { $this->session->set('redirectPath', $this->path, 'redirect'); $this->session->set('headersInRedirect', $this->headers, 'redirect'); } } header("Location: $this->path"); exit(); }
php
{ "resource": "" }
q252899
JavaXmlPropertiesUtils.addEntriesToFile
validation
public static function addEntriesToFile($file, $entries) { $properties = self::readFromFile($file); foreach ($entries as $key => $value) { $properties[$key] = $value; } self::saveToFile($file, $properties); }
php
{ "resource": "" }