_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q254100 | Router.addRoute | validation | public function addRoute(string $verb, string $path, array $callback): Router
{
$this->routeCollector->addRoute($verb, $path, $callback);
return $this;
} | php | {
"resource": ""
} |
q254101 | Router.getDispatcher | validation | public function getDispatcher(): Dispatcher
{
if ($this->forceReload || !file_exists($this->cacheFile)) {
$dispatchData = $this->buildCache();
} else {
/** @noinspection PhpIncludeInspection */
$dispatchData = require $this->cacheFile;
}
return call_user_func($this->dispatcherFactory, $dispatchData);
} | php | {
"resource": ""
} |
q254102 | Router.buildCache | validation | private function buildCache(): array
{
$dispatchData = $this->routeCollector->getData();
file_put_contents($this->cacheFile, '<?php return ' . var_export($dispatchData, true) . ';');
return $dispatchData;
} | php | {
"resource": ""
} |
q254103 | ContentfulTwigExtension.parseBehaviour | validation | public function parseBehaviour(\stdClass $block, $search)
{
if (!isset($block->behaviour)) {
return false;
}
$behaviours = array();
foreach (explode(' ', trim($block->behaviour)) as $b) {
if (strstr($b, ':')) {
list($name, $prop) = explode(':', $b, 2);
$behaviours[$name] = $prop;
} else {
$behaviours[$b] = true;
}
}
return isset($behaviours[$search]) ? $behaviours[$search] : false;
} | php | {
"resource": ""
} |
q254104 | OpenStack.getCachedIdentityService | validation | protected function getCachedIdentityService(Cache $cache, array $options): CachedIdentityService
{
if (!isset($options['authUrl'])) {
throw new \InvalidArgumentException("'authUrl' is a required option");
}
$stack = HandlerStack::create();
if (!empty($options['debugLog'])
&& !empty($options['logger'])
&& !empty($options['messageFormatter'])
) {
$stack->push(GuzzleMiddleware::log($options['logger'], $options['messageFormatter']));
}
$clientOptions = [
'base_uri' => Utils::normalizeUrl($options['authUrl']),
'handler' => $stack,
];
if (isset($options['requestOptions'])) {
$clientOptions = array_merge($options['requestOptions'], $clientOptions);
}
$service = CachedIdentityService::factory(new Client($clientOptions));
$service->setCache($cache);
return $service;
} | php | {
"resource": ""
} |
q254105 | Benri_Controller_Plugin_CORS.postDispatch | validation | public function postDispatch(Zend_Controller_Request_Abstract $request)
{
$methods = implode(', ', array_unique($this->_methods));
$headers = implode(', ', array_unique($this->_headers));
if ($this->_credentials) {
header('Access-Control-Allow-Credentials: true', true);
}
header("Access-Control-Allow-Origin: {$this->_origin}", true);
header("Access-Control-Allow-Methods: {$methods}", true);
header("Access-Control-Allow-Headers: {$headers}", true);
header("Access-Control-Max-Age: {$this->_maxAge}", true);
header('X-XSS-Protection: 1; mode=block', true);
header('X-Frame-Options: SAMEORIGIN', true);
} | php | {
"resource": ""
} |
q254106 | API.clearQuota | validation | public function clearQuota()
{
$appid = $this->getAccessToken()->getAppId();
return $this->parseJSON('json', [self::API_CLEAR_QUOTA, compact('appid')]);
} | php | {
"resource": ""
} |
q254107 | SimplePlugin.init_locales | validation | public function init_locales() {
if (!empty($this->textdomain) && $this->locales_initialized !== true) {
load_plugin_textdomain($this->textdomain, true, $this->get_id());
$this->locales_initialized = true;
}
} | php | {
"resource": ""
} |
q254108 | SimplePlugin.init_options | validation | public function init_options() {
if (!is_array($this->options)) {
$this->options = array();
}
$options_id = $this->get_id('-options');
$options = get_option($options_id);
$need_update = false;
if($options === false) {
$need_update = true;
$options = array();
}
foreach($this->options as $key => $value) {
if(!array_key_exists($key, $options)) {
$options[$key] = $value;
}
}
if(!array_key_exists('latest_used_version', $options)) {
$options['latest_used_version'] = $this->version;
$need_update = true;
}
if($need_update === true) {
update_option($options_id, $options);
}
return $options;
} | php | {
"resource": ""
} |
q254109 | RecoveryForm.resetPassword | validation | public function resetPassword(Token $token)
{
if (!$this->validate() || $token->user === null) {
return false;
}
if ($token->user->resetPassword($this->password)) {
\Yii::$app->session->setFlash('success', \Yii::t('user', 'Your password has been changed successfully.'));
$token->delete();
} else {
\Yii::$app->session->setFlash('danger', \Yii::t('user', 'An error occurred and your password has not been changed. Please try again later.'));
}
return true;
} | php | {
"resource": ""
} |
q254110 | Ldap.bind | validation | public function bind($sUser, $sPassword) : Ldap
{
return $this->_bConnected = ldap_bind($this->_rConnect, $sUser, $sPassword);
return $this;
} | php | {
"resource": ""
} |
q254111 | Ldap.unbind | validation | public function unbind() : bool
{
if ($this->_bConnected) { return $this->_bConnected = ldap_unbind($this->_rConnect); }
else { return true; }
} | php | {
"resource": ""
} |
q254112 | Ldap.search | validation | public function search(string $sFilter, array $aAttributes)
{
return ldap_search($this->_rConnect, $this->_sBase, $sFilter, $aAttributes);
} | php | {
"resource": ""
} |
q254113 | ValidatorBuilder.setElementRequired | validation | public function setElementRequired(\Zend\Form\Element $element) {
$element->setAttribute('required', 'true'); //set browser validation
$this->form->getInputFilter()->get($element->getAttribute('name'))->setAllowEmpty(false); //set backend requirement
} | php | {
"resource": ""
} |
q254114 | ValidatorBuilder.getElementValidatorChain | validation | protected function getElementValidatorChain(\Zend\Form\Element $element) {
$elementName = $element->getAttribute('name');
return $this->form->getInputFilter()->get($elementName)->getValidatorChain();
} | php | {
"resource": ""
} |
q254115 | SaveThemeController.saveAction | validation | public function saveAction(Request $request, Application $app)
{
$options = array(
"configuration_handler" => $app["red_kite_cms.configuration_handler"],
"plugin_manager" => $app["red_kite_cms.plugin_manager"],
"theme_deployer" => $app["red_kite_cms.theme_deployer"],
"page" => clone($app["red_kite_cms.page"]),
);
return parent::save($options);
} | php | {
"resource": ""
} |
q254116 | MW_EXT_Kernel.getJSON | validation | public static function getJSON( $src ) {
$src = file_get_contents( $src );
$out = json_decode( $src, true );
return $out;
} | php | {
"resource": ""
} |
q254117 | Cerberus.setNamespace | validation | private function setNamespace($serviceName = null)
{
if ($serviceName === null) {
$this->storage->getOptions()->setNamespace($this->defaultNamespace);
} else {
$this->storage->getOptions()->setNamespace($serviceName);
}
} | php | {
"resource": ""
} |
q254118 | SEO_Icons_SiteConfig_DataExtension.generateAndroidManifest | validation | public function generateAndroidManifest()
{
//// Android Pinicon Manifest
$pinicon = $this->owner->AndroidPinicon();
if ($pinicon->exists()) {
//
$manifest = new stdClass();
//
$manifest->name = $this->owner->PiniconTitle;
// $manifest->start_url = null; @todo Maybe implement
// $manifest->display = null; @todo Maybe implement
// $manifest->orientation = null; @todo Maybe implement
$manifest->icons = array();
// 0.75x density icon
array_push($manifest->icons, array(
'src' => $pinicon->Fill(36, 36)->getAbsoluteURL(),
'sizes' => '36x36',
'type' => 'image/png',
'density' => 0.75
));
// 1x density icon
array_push($manifest->icons, array(
'src' => $pinicon->Fill(48, 48)->getAbsoluteURL(),
'sizes' => '48x48',
'type' => 'image/png',
'density' => 1
));
// 1.5x density icon
array_push($manifest->icons, array(
'src' => $pinicon->Fill(72, 72)->getAbsoluteURL(),
'sizes' => '72x72',
'type' => 'image/png',
'density' => 1.5
));
// 2x density icon
array_push($manifest->icons, array(
'src' => $pinicon->Fill(96, 96)->getAbsoluteURL(),
'sizes' => '96x96',
'type' => 'image/png',
'density' => 2
));
// 3x density icon
array_push($manifest->icons, array(
'src' => $pinicon->Fill(144, 144)->getAbsoluteURL(),
'sizes' => '144x144',
'type' => 'image/png',
'density' => 3
));
// 4x density icon
array_push($manifest->icons, array(
'src' => $pinicon->Fill(192, 192)->getAbsoluteURL(),
'sizes' => '192x192',
'type' => 'image/png',
'density' => 4
));
// create file
$bytes = file_put_contents(Director::baseFolder() . '/manifest.json', json_encode($manifest));
//
if ($bytes !== false) {
// success
return true;
}
}
// default return
return false;
} | php | {
"resource": ""
} |
q254119 | RangeFilter.setValue | validation | public function setValue($value)
{
$this->value = $value;
/** @noinspection NotOptimalIfConditionsInspection */
if (is_array($value) && array_key_exists('start', $value) && array_key_exists('end', $value)) {
$start = (float) $value['start'];
$end = (float) $value['end'];
if ($start <= $end) {
$this->startElement->setValue($start);
$this->endElement->setValue($end);
}
}
return $this;
} | php | {
"resource": ""
} |
q254120 | ToolbarManager.render | validation | public function render()
{
$plugins = $this->pluginManager->getBlockPlugins();
$toolbar = array();
$left[] = $this->twig->render("RedKiteCms/Resources/views/Editor/Toolbar/_toolbar_left_buttons.html.twig");
$right[] = $this->twig->render("RedKiteCms/Resources/views/Editor/Toolbar/_toolbar_right_buttons.html.twig");
foreach ($plugins as $plugin) {
if (!$plugin->hasToolbar()) {
continue;
}
$left[] = $this->addButtons($plugin, 'left');
$right[] = $this->addButtons($plugin, 'right');
}
$toolbar["left"] = implode("\n", $left);
$toolbar["right"] = implode("\n", $right);
return $toolbar;
} | php | {
"resource": ""
} |
q254121 | RegistrationForm.register | validation | public function register()
{
if (!$this->validate()) {
return false;
}
$this->user->setAttributes([
'email' => $this->email,
'username' => $this->username,
'password' => $this->password
]);
return $this->user->register();
} | php | {
"resource": ""
} |
q254122 | DataSource.getForeignDataItem | validation | public function getForeignDataItem($key)
{
if (!isset($this->_foreignDataItems[$key])) {
$this->createForeignDataItem(null, ['foreignPrimaryKey' => $key]);
}
if (isset($this->_foreignDataItems[$key])) {
return $this->_foreignDataItems[$key];
}
return false;
} | php | {
"resource": ""
} |
q254123 | DataSource.getUnmappedKeys | validation | public function getUnmappedKeys()
{
$u = [];
$f = $this->unmappedForeignKeys;
$l = $this->unmappedLocalKeys;
if (!empty($f)) {
$u['foreign'] = $f;
}
if (!empty($l)) {
$u['local'] = $l;
}
return $u;
} | php | {
"resource": ""
} |
q254124 | DataSource.getUnmappedLocalKeys | validation | public function getUnmappedLocalKeys()
{
$u = array_diff(array_keys($this->localModel->getMetaData()->columns), array_keys($this->_map));
unset($u[$this->localPrimaryKeyName]);
return $u;
} | php | {
"resource": ""
} |
q254125 | DataSource.getKeyTranslation | validation | public function getKeyTranslation(Model $foreignObject, $key = null)
{
if (isset($key)) {
return $this->internalGetKeyTranslation($foreignObject, $key);
}
foreach ($this->keys as $keyName => $keyField) {
if (!empty($foreignObject->{$keyField})) {
$key = $this->generateKey($foreignObject, $keyName, $foreignObject->{$keyField});
$result = $this->internalGetKeyTranslation($foreignObject, $key);
if (!empty($result)) {
return $result;
}
}
}
return false;
} | php | {
"resource": ""
} |
q254126 | DataSource.getReverseKeyTranslation | validation | public function getReverseKeyTranslation($localObject)
{
$key = is_object($localObject) ? $localObject->primaryKey : $localObject;
if ($this->settings['universalKey']) {
//return KeyTranslation::findOne(['registry_id' => $key]);
return KeyTranslation::find()->where(['registry_id' => $key])->one();
} else {
//return KeyTranslation::findOne(['registry_id' => $key, 'data_interface_id' => $this->module->collectorItem->interfaceObject->primaryKey]);
return KeyTranslation::find()->where(['registry_id' => $key, 'data_interface_id' => $this->module->collectorItem->interfaceObject->primaryKey])->one();
}
} | php | {
"resource": ""
} |
q254127 | Photo.setRawPhoto | validation | public function setRawPhoto($photo)
{
if (empty($photo)) {
return true;
}
if (!($photo instanceof FileInterface)) {
$photo = RawFile::createRawInstance($photo);
}
return $this->setStorage($photo);
} | php | {
"resource": ""
} |
q254128 | ComposerPackagesOrderCompiler.getComposer | validation | private function getComposer($fileOrPackage) {
if(isset($this->jsonCache[$fileOrPackage]))
return $this->jsonCache[$fileOrPackage];
if($file = $this->files[$fileOrPackage] ?? NULL) {
return $this->getComposer($file);
}
if(is_dir($fileOrPackage))
$fileOrPackage .= "/composer.json";
if(is_file($fileOrPackage)) {
$json = json_decode( file_get_contents($fileOrPackage), true );
$name = $json["name"];
$this->jsonCache[$name] = $json;
$this->files[$name] = $fileOrPackage;
return $json;
}
return NULL;
} | php | {
"resource": ""
} |
q254129 | Collector.getTheme | validation | public function getTheme()
{
if (!isset($this->_theme)) {
return $this->_lastLoadedTheme->object;
}
if (!isset($this->_theme)) {
throw new Exception("No theme has been loaded!");
}
return $this->_theme;
} | php | {
"resource": ""
} |
q254130 | Collector.getIdentity | validation | public function getIdentity($view)
{
if (!isset($view->assetBundles[$this->identityAssetBundle])) {
return false;
}
return Yii::$app->assetManager->getBundle($this->identityAssetBundle);
} | php | {
"resource": ""
} |
q254131 | Container.createView | validation | public function createView() : \stdClass
{
$oView = new \stdClass;
$oView->form = $this->_sView;
$oView->form_start = $this->_oForm->getFormInObject()->start;
$oView->form_end = $this->_oForm->getFormInObject()->end;
$oView->form_row = array();
foreach ($this->_oForm->getFormInObject()->form as $sKey => $mValue) {
if ($mValue instanceof Container) {
$oNewForm = $mValue->createView();
$oView->form_row[$sKey] = $oNewForm->form_row;
} else {
$oView->form_row[$sKey] = $mValue;
}
}
return $oView;
} | php | {
"resource": ""
} |
q254132 | Redirect.redirectCorrectDomainSystemParams | validation | protected function redirectCorrectDomainSystemParams (& $domainParams) {
$localizationParamName = static::URL_PARAM_LOCALIZATION;
if (isset($domainParams[$localizationParamName])) {
$domainParams[$localizationParamName] = $this->redirectLocalizationGetUrlValueAndUnsetGet(
$domainParams[$localizationParamName]
);
}
} | php | {
"resource": ""
} |
q254133 | FormCollection.render | validation | public function render(ElementInterface $element)
{
$renderer = $this->getView();
if (!method_exists($renderer, 'plugin')) {
return '';
}
$wrapperClass = '';
$elementMarkup = '';
$templateMarkup = '';
$attributesString = '';
$label = '';
if ($element instanceof CollectionElement && $element->shouldCreateTemplate()) {
$templateMarkup = $this->renderTemplate($element);
}
foreach ($element->getIterator() as $elementOrFieldset) {
/** @var ElementInterface $elementOrFieldset */
$elementMarkup .= $this->renderElement($elementOrFieldset);
}
$helperFormButtonIcon = $this->getFormButtonIconHelper();
$helperLabel = $this->getLabelHelper();
$elementMarkup .= sprintf(
$this->elementWrap,
'',
$helperFormButtonIcon(
new Button(
null,
[
'label' => 'Add New',
'icon' => 'fa fa-plus-circle'
]
)
),
''
);
if ($this->shouldWrap) {
$attributes = $element->getAttributes();
/** @noinspection UnSafeIsSetOverArrayInspection */
if (isset($attributes['class'])) {
$wrapperClass = $attributes['class'];
unset($attributes['class']);
}
unset($attributes['name']);
$attributesString = count($attributes) ? ' ' . $this->createAttributesString($attributes) : '';
/** @noinspection IsEmptyFunctionUsageInspection */
if (!empty($element->getLabel())) {
$label = $helperLabel($element);
}
}
return sprintf(
$this->wrapper,
$wrapperClass,
$attributesString,
$label,
$this->horizontalWrapClass,
$elementMarkup,
$templateMarkup
);
} | php | {
"resource": ""
} |
q254134 | Session.create | validation | public function create($account, $openId)
{
$params = [
'kf_account' => $account,
'openid' => $openId,
];
return $this->parseJSON('json', [self::API_CREATE, $params]);
} | php | {
"resource": ""
} |
q254135 | Session.close | validation | public function close($account, $openId)
{
$params = [
'kf_account' => $account,
'openid' => $openId,
];
return $this->parseJSON('json', [self::API_CLOSE, $params]);
} | php | {
"resource": ""
} |
q254136 | AccompanyingPeriod.setPerson | validation | public function setPerson(\Chill\PersonBundle\Entity\Person $person = null)
{
$this->person = $person;
return $this;
} | php | {
"resource": ""
} |
q254137 | AccompanyingPeriod.isClosingAfterOpening | validation | public function isClosingAfterOpening() {
$diff = $this->getOpeningDate()->diff($this->getClosingDate());
if ($diff->invert === 0) {
return true;
} else {
return false;
}
} | php | {
"resource": ""
} |
q254138 | Redirect.to | validation | public function to(string $path, int $status = 301, array $headers = array()) {
return $this->makeRedirect($path, $status, $headers);
} | php | {
"resource": ""
} |
q254139 | Translator.translate | validation | public static function translate($message, $parameters = array(), $domain = "RedKiteCms", $locale = null)
{
if (null === self::$translator) {
return $message;
}
return self::$translator->trans($message, $parameters, $domain, $locale);
} | php | {
"resource": ""
} |
q254140 | HttpEmulator.getResponse | validation | public function getResponse()
{
if ($this->response) {
return $this->response;
}
return $this->response = \GuzzleHttp\Psr7\parse_response($this->getResponseStream());
} | php | {
"resource": ""
} |
q254141 | HttpEmulator.offsetGet | validation | public function offsetGet($offset)
{
if ($offset === 'headers') {
$headers = [
'HTTP/' . $this->getResponse()->getProtocolVersion() . ' ' . $this->getResponse()->getStatusCode() . ' ' . $this->getResponse()->getReasonPhrase()
];
foreach ($this->getResponse()->getHeaders() as $header => $values) {
foreach ($values as $value) {
$headers[] = $header . ': ' . $value;
}
}
return $headers;
}
} | php | {
"resource": ""
} |
q254142 | HttpApiAction.addSource | validation | private function addSource(array $arguments = array())
{
$this->builder->addSource(
array_key_exists('cache', $this->source) ? $this->createCacheAdapter() : new HttpApiAdapter(),
new Request(array(
'source' => $this->source,
'arguments' => $arguments,
'service' => $this->getGroup()->getService()->getName(),
'group' => $this->getGroup()->getName(),
'action' => $this->getName(),
)));
} | php | {
"resource": ""
} |
q254143 | HttpApiAction.addVirtualizationWorker | validation | private function addVirtualizationWorker($arguments = array())
{
$this->builder->addWorker(new VirtualizationWorker(
$this->registry,
$this->virtualProperties,
$this->deserialization,
$arguments
));
} | php | {
"resource": ""
} |
q254144 | HttpApiAction.createCacheAdapter | validation | private function createCacheAdapter()
{
$extraData = &$this->extraData;
return new CallbackAdapter(function (Request $request) use (&$extraData) {
$poolName = 'default';
if (isset($this->source['cache']['pool'])) {
$poolName = $this->source['cache']['pool'];
}
$adapter = new CacheAdapter(
$this->registry->getCachePool($poolName),
new HttpApiAdapter(),
function (Request $request) {
$data = $request->getData();
return $this->registry->generateCacheItemKey(
sprintf('%s.%s.%s', $data['service'], $data['group'], $data['action']),
$data['arguments']
);
}
);
$response = $adapter->receive($request);
$extraData = $response->getHeaders();
return $response;
});
} | php | {
"resource": ""
} |
q254145 | Authorizer.setAccessToken | validation | public function setAccessToken($token, $expires = 7200)
{
$this->cache->save($this->getAccessTokenCacheKey(), $token, $expires);
return $this;
} | php | {
"resource": ""
} |
q254146 | ApiActions.index | validation | public function index(FilterRequest $request)
{
$limit = $request->request->get('limit', 15);
$limit = ($limit > 49) ? 50 : $limit;
$filter = $this->repository->filter($request);
if ($this->list || $request->request->get('search_type') == 'list') {
$resources = $filter->get(1000);
} else {
$resources = $filter->paginate($limit);
}
if ($resources->count() < 1) {
// return $this->notFound();
}
return $this->success($resources);
} | php | {
"resource": ""
} |
q254147 | ApiActions.show | validation | public function show($id, FilterRequest $request)
{
$id = $this->getRealId($id);
$request->criteria[] = 'id,=,' . $id;
$resource = $this->repository->filter($request)->first();
//$resource = $this->repository->find($id);
if (! $resource) {
// return $this->notFound();
}
return $this->success($resource);
} | php | {
"resource": ""
} |
q254148 | ApiActions.store | validation | public function store(FilterRequest $request)
{
$this->fieldManager = $this->getFieldManager();
$this->validate($request->request, $this->fieldManager->store());
$input = $request->all();
$resource = $this->repository->create($input);
if (! $resource) {
// return $this->notFound();
}
return $this->created($resource);
} | php | {
"resource": ""
} |
q254149 | ApiActions.update | validation | public function update(FilterRequest $request, $id)
{
$this->fieldManager = $this->getFieldManager();
$this->validate($request->request, $this->fieldManager->update());
$id = $this->getRealId($id);
$resource = $this->repository->update($request->all(), $id);
if (! $resource) {
// return $this->notFound();
}
return $this->success($resource);
} | php | {
"resource": ""
} |
q254150 | BaseManager.all | validation | public function all()
{
$_filters = $this->filters; // store filters
if (!$this->allowDeleted) {
$this->filters = array("`" . $this->table . "`.deleted = 0"); // reset them
} else {
$this->filters = array();
}
$values = $this->values();
$this->filters = $_filters; // restore filters
return $values;
} | php | {
"resource": ""
} |
q254151 | BaseManager.group | validation | public function group($group)
{
if (!is_array($group)) {
$this->group = array($group);
} else {
$this->group = $group;
}
return $this;
} | php | {
"resource": ""
} |
q254152 | BaseManager.getCountSQL | validation | public function getCountSQL()
{
$statement = [];
if ($this->distinct) {
$distinct = 'DISTINCT ';
} else {
$distinct = '';
}
$statement[] = "(SELECT $distinct`" . $this->table . "`.*";
$statement[] = $this->getFrom();
$statement[] = $this->getJoin();
$statement[] = $this->getWhere();
$statement[] = $this->getOrder();
$statement[] = ")";
foreach ($this->unions as $union) {
$statement[] = "UNION ".$distinct;
$statement[] = $union->getCountSQL();
}
// Remove null values
$statement = array_filter($statement);
$sql = implode("\n", $statement);
return $sql;
} | php | {
"resource": ""
} |
q254153 | BaseManager.join | validation | public function join(
BaseManager $manager,
$type = null,
$column = null,
$column_right = null
) {
$this->joins[$manager->table] = array(
'manager' => $manager,
'type' => $type,
'column' => $column,
'column_right' => $column_right
);
return $this;
} | php | {
"resource": ""
} |
q254154 | BaseManager.cache | validation | public function cache($flag, $expiry = null)
{
$this->cache = (boolean) $flag;
if (!is_null($expiry)) {
$this->cacheExpiry = $expiry;
}
return $this;
} | php | {
"resource": ""
} |
q254155 | BaseManager.getWhereAsArray | validation | protected function getWhereAsArray()
{
$filters = [];
if (!empty($this->filters)) {
$filters = $this->filters;
}
if (!$this->allowDeleted) {
$filters[] = "(`" . $this->table . "`.deleted = 0 OR `" . $this->table . "`.deleted IS NULL)";
}
if (!empty($this->joins)) {
foreach ($this->joins as $join) {
$manager = $join['manager'];
$filters = array_merge($filters, $manager->getWhereAsArray());
}
}
return $filters;
} | php | {
"resource": ""
} |
q254156 | BaseManager.getColumnReference | validation | protected function getColumnReference($column, $tableless)
{
if ($tableless) {
return $column;
}
// check if table is already defined
if (count(explode(".", $column)) > 1) {
return $column;
}
return "`" . $this->table . "`.`" . $column . "`";
} | php | {
"resource": ""
} |
q254157 | BaseManager.resultToModels | validation | protected function resultToModels($result)
{
$models = array();
foreach ($result as $r) {
$pk = $r->{$this->pk};
try {
// It is inefficient to fetch every record from the DB here
// Instead, pass in the result data
$models[] = new $this->class($pk, $r);
} catch (\Exception $e) {
}
}
return $models;
} | php | {
"resource": ""
} |
q254158 | Repository.sumValor | validation | public function sumValor()
{
$tableGateway = new TableGateway($this->tableName, $this->dbAdapter);
$sql = $tableGateway->getSql();
$select = $sql->select()->columns(array('sum' => new Expression('SUM(valor)')));
return $tableGateway->selectWith($select)->current();
} | php | {
"resource": ""
} |
q254159 | RepositoryContentAdapter.findContentType | validation | protected function findContentType($spaceId, $contentTypeName)
{
$contentTypes = $this->contentTypeRepo->findNewestByName($spaceId, $contentTypeName);
if ($contentTypes->isEmpty()) {
throw new InvalidArgumentException(
sprintf(
'Content type "%s" in space "%s" not found!',
$contentTypeName,
$spaceId
)
);
}
if ($contentTypes->count() > 1) {
throw new InvalidArgumentException(
sprintf(
'Multiple content types with name "%s" found in space "%s"!',
$contentTypeName,
$spaceId
)
);
}
$contentType = $contentTypes->first();
return $contentType;
} | php | {
"resource": ""
} |
q254160 | FilterRequest.setFilters | validation | public function setFilters()
{
$this->activeQueryLog()
->setFields()
->setCriteriaByQueryString()
->setCriteria()
->setIncludes()
->setLimit()
->setOrder()
->setGroup();
} | php | {
"resource": ""
} |
q254161 | DataSource.getTotal | validation | public function getTotal()
{
if (!$this->isReady()) {
return 0;
}
if (is_null($this->_countTotal)) {
$this->_countTotal = 0;
if (in_array($this->settings['direction'], ['to_local', 'both'])) {
$this->_countTotal += count($this->foreignDataItems);
}
if (in_array($this->settings['direction'], ['to_foreign', 'both'])) {
$this->_countTotal += count($this->localDataItems);
}
}
return $this->_countTotal;
} | php | {
"resource": ""
} |
q254162 | DataSource.getRemaining | validation | public function getRemaining()
{
if (is_null($this->_countRemaining)) {
$this->_countRemaining = $this->total;
}
return $this->_countRemaining;
} | php | {
"resource": ""
} |
q254163 | DataSource.getForeignDataItems | validation | public function getForeignDataItems()
{
if (!isset($this->_foreignDataItems)) {
$this->_foreignDataItems = [];
$this->trigger(self::EVENT_LOAD_FOREIGN_DATA_ITEMS);
}
return $this->_foreignDataItems;
} | php | {
"resource": ""
} |
q254164 | DataSource.getLocalDataItems | validation | public function getLocalDataItems()
{
if (!isset($this->_localDataItems)) {
$this->trigger(self::EVENT_LOAD_LOCAL_DATA_ITEMS);
}
return $this->_localDataItems;
} | php | {
"resource": ""
} |
q254165 | DataSource.getHandledLocalDataItems | validation | public function getHandledLocalDataItems()
{
$handled = [];
foreach ($this->localDataItems as $local) {
if ($local->handled) {
$handled[] = $local;
}
}
return $handled;
} | php | {
"resource": ""
} |
q254166 | DataSource.setSearch | validation | public function setSearch($value)
{
if (!is_object($value)) {
if (!isset($value['class'])) {
$value['class'] = $this->searchClass;
}
$value = Yii::createObject($value);
}
$value->dataSource = $this;
$this->_search = $value;
} | php | {
"resource": ""
} |
q254167 | ConfirmController.actionIndex | validation | public function actionIndex($search)
{
$user = $this->finder->findUserByUsernameOrEmail($search);
if ($user === null) {
$this->stdout(\Yii::t('user', 'User is not found') . "\n", Console::FG_RED);
} else {
if ($user->confirm()) {
$this->stdout(\Yii::t('user', 'User has been confirmed') . "\n", Console::FG_GREEN);
} else {
$this->stdout(\Yii::t('user', 'Error occurred while confirming user') . "\n", Console::FG_RED);
}
}
} | php | {
"resource": ""
} |
q254168 | POI.lists | validation | public function lists($offset = 0, $limit = 10)
{
$params = [
'begin' => $offset,
'limit' => $limit,
];
return $this->parseJSON('json', [self::API_LIST, $params]);
} | php | {
"resource": ""
} |
q254169 | POI.update | validation | public function update($poiId, array $data)
{
$data = array_merge($data, ['poi_id' => $poiId]);
$params = [
'business' => ['base_info' => $data],
];
return $this->parseJSON('json', [self::API_UPDATE, $params]);
} | php | {
"resource": ""
} |
q254170 | JsonList.get | validation | public function get()
{
$totalEntities = $this->repository->countTotal();
if(!is_null($this->category)){
$entities = $this->repository->findAllForDataTablesByCategory($this->search, $this->sortColumn, $this->sortDirection, $this->category);
}elseif(!is_null($this->entityId)){
$entities = $this->repository->findAllForDataTables($this->search, $this->sortColumn, $this->sortDirection, $this->entityId, $this->locale);
}elseif(!is_null($this->agreementId)){
$entities = $this->repository->findByAgreementForDataTables($this->search, $this->sortColumn, $this->sortDirection, $this->agreementId);
}elseif(!is_null($this->advertId)){
$entities = $this->repository->findByAdvertForDataTables($this->search, $this->sortColumn, $this->sortDirection, $this->advertId);
}else{
$entities = $this->repository->findAllForDataTables($this->search, $this->sortColumn, $this->sortDirection, null, $this->locale);
}
$totalFilteredEntities = count($entities->getScalarResult());
// paginate
$entities->setFirstResult($this->offset)
->setMaxResults($this->limit);
$data = $entities->getResult();
return array(
'iTotalRecords' => $totalEntities,
'iTotalDisplayRecords' => $totalFilteredEntities,
'sEcho' => $this->echo,
'aaData' => $data
);
} | php | {
"resource": ""
} |
q254171 | User.attemptConfirmation | validation | public function attemptConfirmation($code)
{
/** @var Token $token */
$token = $this->finder->findToken([
'user_id' => $this->id,
'code' => $code,
'type' => Token::TYPE_CONFIRMATION,
])->one();
if ($token === null || $token->isExpired) {
\Yii::$app->session->setFlash('danger', \Yii::t('user', 'The confirmation link is invalid or expired. Please try requesting a new one.'));
} else {
$token->delete();
$this->confirmed_at = time();
\Yii::$app->user->login($this);
\Yii::getLogger()->log('User has been confirmed', Logger::LEVEL_INFO);
if ($this->save(false)) {
\Yii::$app->session->setFlash('success', \Yii::t('user', 'Thank you, registration is now complete.'));
} else {
\Yii::$app->session->setFlash('danger', \Yii::t('user', 'Something went wrong and your account has not been confirmed.'));
}
}
} | php | {
"resource": ""
} |
q254172 | RoutingBase.createRouter | validation | public function createRouter($debug = false)
{
if (null === $this->routesFile) {
throw new LogicException('The derived class must define the string variable "routesFile"');
}
if (!is_string($this->routesFile)) {
throw new LogicException('"routesFile" variable must be a string value');
}
$isProduction = $this->configurationHandler->isProduction();
$cacheDir = null;
if (!$debug && $isProduction) {
$cacheDir = $this->configurationHandler->siteCacheDir() . '/routes';
}
$this->router = new Router(
new YamlFileLoader($this->fileLocator),
$this->routesFile,
array('cache_dir' => $cacheDir)
);
return $this->router;
} | php | {
"resource": ""
} |
q254173 | LoadContentNewsData.generateContentAttribute | validation | protected function generateContentAttribute($name, $value, $type = 'text')
{
$attribute = new ContentAttribute();
$attribute->setName($name);
$attribute->setValue($value);
if (is_array($value)) {
$value = '';
}
$attribute->setStringValue($value);
$attribute->setType($type);
return $attribute;
} | php | {
"resource": ""
} |
q254174 | LoadContentNewsData.generateContent | validation | protected function generateContent($type, $id, $name, $language)
{
$content = new Content();
$content->setContentId($id);
$content->setContentType($type);
$content->setDeleted(false);
$content->setName($name);
$content->setLanguage($language);
$content->setStatus($this->getReference('status-published'));
$content->setVersion('1');
$content->setSiteId('2');
$date = new \DateTime("now");
$content->setVersionName($content->getName().'_'. $date->format("Y-m-d_H:i:s"));
return $content;
} | php | {
"resource": ""
} |
q254175 | BlockManagerMove.move | validation | public function move($baseDir, array $options, $username)
{
$this->resolveMoveOptions($options);
if (array_key_exists("targetSlot", $options)) {
$options["slot"] = $options["targetSlot"];
$block = $this->moveBlockToAnotherSlot($baseDir, $options, $username);
return $block;
}
$options["slot"] = $options["sourceSlot"];
$block = $this->moveBlockToSameSlot($baseDir, $options, $username);
return $block;
} | php | {
"resource": ""
} |
q254176 | BlockManagerMove.resolveMoveOptions | validation | protected function resolveMoveOptions(array $options)
{
if ($this->optionsResolved) {
// @codeCoverageIgnoreStart
return;
// @codeCoverageIgnoreEnd
}
$this->optionsResolver->clear();
$this->optionsResolver->setRequired(
array(
'page',
'language',
'country',
'sourceSlot',
'position',
)
);
$this->optionsResolver->setDefined(
array(
'targetSlot',
'blockname',
'oldName',
'newName',
'slot',
)
);
$this->optionsResolver->resolve($options);
$this->optionsResolved = true;
} | php | {
"resource": ""
} |
q254177 | BlockManagerMove.moveArchiveDir | validation | private function moveArchiveDir($archiveSourceFile, $archiveTargetFile, $blockName, $slotName)
{
if (!is_dir($archiveSourceFile)) {
return;
}
$this->filesystem->mirror($archiveSourceFile, $archiveTargetFile);
$this->filesystem->remove($archiveSourceFile);
$historyChanged = array();
$historyFile = $archiveTargetFile . '/history.json';
$history = json_decode(file_get_contents($historyFile), true);
foreach($history as $key => $values) {
$values["name"] = $blockName;
$values["slot_name"] = $slotName;
$historyChanged[$key] = $values;
}
file_put_contents($historyFile, json_encode($historyChanged));
} | php | {
"resource": ""
} |
q254178 | BlockManagerMove.changeBlockSlotAndName | validation | private function changeBlockSlotAndName($targetFile, $blockName, $slotName)
{
$block = json_decode(FilesystemTools::readFile($targetFile), true);
$block["name"] = $blockName;
$block["slot_name"] = $slotName;
$json = json_encode($block);
FilesystemTools::writeFile($targetFile, $json);
return $block;
} | php | {
"resource": ""
} |
q254179 | NumberField.setMin | validation | public function setMin($value){
$this->setTag('min',$value);
if($this->getValidator()){
$this->getValidator()->setOption('min',$value);
}
} | php | {
"resource": ""
} |
q254180 | NumberField.setMax | validation | public function setMax($value){
$this->setTag('max',$value);
if($this->getValidator()){
$this->getValidator()->setOption('max',$value);
}
} | php | {
"resource": ""
} |
q254181 | Consumer.assertClient | validation | private function assertClient(ClientInterface $client)
{
if ($client->getConnection() instanceof AggregateConnectionInterface) {
throw new NotSupportedException(
'Cannot initialize a monitor consumer over aggregate connections.'
);
}
if ($client->getCommandFactory()->supportsCommand('MONITOR') === false) {
throw new NotSupportedException("'MONITOR' is not supported by the current command factory.");
}
} | php | {
"resource": ""
} |
q254182 | Authority.storePermissions | validation | public function storePermissions($params = array()) {
//2. Saniitize the data
$authorityAreaTitle = $this->input->getString("area-title");
$authorityAreaURI = $this->input->getString("area-uri");
$authorityAreaAction = $this->input->getString("area-action");
$authorityAreaPermission = $this->input->getString("area-permission");
$authorityId = $this->input->getInt("area-authority");
//3. Synchronize and bind to table object
$table = $this->load->table("?authority_permissions");
$aData = array(
"authority_id" => $authorityId,
"permission_area_uri" => strtolower($authorityAreaURI),
"permission" => strtolower($authorityAreaPermission),
"permission_type" => strtolower($authorityAreaAction),
"permission_title" => $authorityAreaTitle
);
//All fields required;
foreach ($aData as $k => $item) {
if (empty($item)) {
$this->setError(_t("Please complete all permission fields; Provide a title and uri defining the area, a permission type and value"));
return false;
}
}
if (!$table->bindData($aData)) {
throw new \Platform\Exception($table->getError());
return false;
}
//@TODO: Check that we are not denying permission to an authority whose parent is granted the permission!!!
//Check the Permission Area URI, make sure its not a route id,
//We need exact URI paths, Throw an error if it does not make sense
if ($table->isNewRow()) {
}
//5. Save the table modifications
if (!$table->save()) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q254183 | FormFactory.create | validation | public function create($className, $username)
{
$reflectionClass = new \ReflectionClass($className);
$permalinks = $this->pagesParser
->contributor($username)
->parse()
->permalinksByLanguage(
$this->configurationHandler->language() . '_' . $this->configurationHandler->country()
);
$permalinksForSelect = (!empty($permalinks)) ? array_combine($permalinks, $permalinks) : array();
$params = array($permalinksForSelect);
$form = $this->formFactory->create($reflectionClass->newInstanceArgs($params));
return $form->createView();
} | php | {
"resource": ""
} |
q254184 | AuthenticationService.authenticate | validation | public function authenticate(AdapterInterface $adapter = null)
{
$event = clone $this->getEvent();
$event->setName(AuthenticationEvent::EVENT_AUTH);
if (!$adapter) {
$adapter = $this->getAdapter();
}
if ($adapter) {
$event->setAdapter($adapter);
}
$this->getEventManager()->trigger($event);
return $event->getResult();
} | php | {
"resource": ""
} |
q254185 | SteadyQueue.setDefaultQueues | validation | function setDefaultQueues(array $defaultQueues)
{
$this->_defaults = $defaultQueues;
$queues = StdArray::of($this->queues)->withMergeRecursive($defaultQueues, true);
$this->queues = $queues->value;
return $this;
} | php | {
"resource": ""
} |
q254186 | TaggableBehavior.getTagValues | validation | public function getTagValues($asString = false)
{
if ($this->_tagsList === null && !$this->owner->getIsNewRecord()) {
// the list of tags is not initialized
$this->_tagsList = [];
// trying to obtain related models
$relation = $this->owner->getRelation('tagsList', false);
if ($relation instanceof ActiveQuery) {
$this->_tagsList = array_unique($relation->select('text')->column());
}
}
return $asString === true ? implode(',', $this->_tagsList) : $this->_tagsList;
} | php | {
"resource": ""
} |
q254187 | TaggableBehavior.parseTags | validation | protected function parseTags($tags)
{
return array_unique(is_array($tags) ? array_filter($tags) : preg_split('/\s*,\s*/', $tags, -1, PREG_SPLIT_NO_EMPTY));
} | php | {
"resource": ""
} |
q254188 | TaggableBehavior.ownerHasTagAttribute | validation | protected function ownerHasTagAttribute()
{
if ($this->_hasTagAttribute === null) {
$this->_hasTagAttribute = $this->owner->hasAttribute('tags');
}
return $this->_hasTagAttribute;
} | php | {
"resource": ""
} |
q254189 | TaggableBehavior.removeTagValues | validation | public function removeTagValues($tags)
{
$this->_tagsList = array_diff($this->getTagValues(), $this->parseTags($tags));
$this->updateOwnerTags();
} | php | {
"resource": ""
} |
q254190 | TaggableBehavior.afterSave | validation | public function afterSave()
{
if ($this->_tagsList === null) {
return;
}
$relation = $this->owner->getRelation('tagsList', false);
if (!($relation instanceof ActiveQuery)) {
return;
}
if (!$this->owner->getIsNewRecord()) {
// clear old tags
$this->beforeDelete();
$this->afterDelete();
}
/** @var ActiveRecord $relationClass */
$relationClass = $relation->modelClass;
$ownerTagsList = [];
foreach ($this->_tagsList as $tagText) {
/* @var ActiveRecord $tag */
$tag = $relationClass::findOne(['text' => $tagText]);
if ($tag === null) {
$tag = new $relationClass();
$tag->setAttribute('text', $tagText);
}
$tag->setAttribute('count', $tag->getAttribute('count') + 1);
if ($tag->save()) {
$ownerTagsList[] = [$this->owner->getPrimaryKey(), $tag->getPrimaryKey()];
}
}
if (!empty($ownerTagsList)) {
$this->owner->getDb()
->createCommand()
->batchInsert($relation->via->from[0], [key($relation->via->link), current($relation->link)], $ownerTagsList)
->execute();
}
} | php | {
"resource": ""
} |
q254191 | TaggableBehavior.beforeDelete | validation | public function beforeDelete()
{
// store tag ids list
$this->_tagsForDelete = [];
$relation = $this->owner->getRelation('tagsList', false);
if ($relation instanceof ActiveQuery) {
$this->_tagsForDelete = (new Query())
->select(current($relation->link))
->from($relation->via->from[0])
->where([key($relation->via->link) => $this->owner->getPrimaryKey()])
->column($this->owner->getDb());
}
} | php | {
"resource": ""
} |
q254192 | TaggableBehavior.afterDelete | validation | public function afterDelete()
{
// after complete owner delete delete tags links
if (!empty($this->_tagsForDelete)) {
$relation = $this->owner->getRelation('tagsList', false);
if ($relation instanceof ActiveQuery) {
/** @var ActiveRecord $class */
$class = $relation->modelClass;
// decrease counters
$class::updateAllCounters(['count' => -1], ['in', $class::primaryKey(), $this->_tagsForDelete]);
// delete links
$this->owner->getDb()
->createCommand()
->delete($relation->via->from[0], [key($relation->via->link) => $this->owner->getPrimaryKey()])
->execute();
}
$this->_tagsForDelete = [];
}
} | php | {
"resource": ""
} |
q254193 | DataItem.getForeignParents | validation | public function getForeignParents()
{
$parents = [];
foreach ($this->dataSource->foreignParentKeys as $keySet) {
$model = $keySet['foreignModel'];
unset($keySet['foreignModel']);
if (!empty($this->foreignObject->{$keySet['foreignId']})) {
$keySet['foreignId'] = $this->foreignObject->{$keySet['foreignId']};
if (!isset($parents[$model])) {
$parents[$model] = [];
}
$parents[$model][] = $keySet;
}
}
return $parents;
} | php | {
"resource": ""
} |
q254194 | DataItem.getForeignChildren | validation | public function getForeignChildren()
{
$children = [];
foreach ($this->dataSource->foreignChildKeys as $keySet) {
$model = $keySet['foreignModel'];
unset($keySet['foreignModel']);
if (!empty($this->foreignObject->{$keySet['foreignId']})) {
$keySet['foreignId'] = $this->foreignObject->{$keySet['foreignId']};
if (!isset($children[$model])) {
$children[$model] = [];
}
$children[$model][] = $keySet;
}
}
return $children;
} | php | {
"resource": ""
} |
q254195 | Payment.priceStringToInt | validation | public static function priceStringToInt(string $str, string $propertyPath = '') : int
{
$str = trim($str);
// verify format of string
if (!preg_match('/(\.|,)[0-9]{2}$/', $str)) {
throw new \InvalidArgumentException(($propertyPath ? $propertyPath.' (value: "'.$str.'")' : $str).
' does not match the currency string format');
}
$str = preg_replace('/[^0-9]+/', '', $str);
return intval($str);
} | php | {
"resource": ""
} |
q254196 | KeyTranslation.getObject | validation | public function getObject($checkAccess = true)
{
$registryClass = Yii::$app->classes['Registry'];
$return = $registryClass::getObject($this->registry_id, $checkAccess);
if (get_class($return) === 'cascade\models\Registry') {
\d($this->registry_id);
//throw new \Exception("TRANSLATION WHATTTT AGAIN?!");
exit;
}
return $return;
} | php | {
"resource": ""
} |
q254197 | ArrayStore.remove | validation | public function remove($id)
{
if (!$this->has($id)) {
throw new NotFoundException(sprintf('%s not found in %s', $id, __CLASS__));
}
unset($this->objects[$id]);
} | php | {
"resource": ""
} |
q254198 | ModelAdapter.authenticate | validation | public function authenticate()
{
$identity = $this->getIdentity();
$results = $this->model->findByIdentity($identity);
$identityObject = null;
$count = 0;
foreach ($results as $identityObject) {
if ($count > 1) {
return new Result(
Result::FAILURE_IDENTITY_AMBIGUOUS,
$identity,
['More than one record matches the supplied identity.']
);
}
$count++;
}
if ($count == 0) {
return new Result(
Result::FAILURE_IDENTITY_NOT_FOUND,
$identity,
['A record with the supplied identity could not be found.']
);
}
if ($identityObject instanceof ObjectInterface) {
if ($identityObject->validateCredential($this->getCredential())) {
return new Result(Result::SUCCESS, $identity);
} // else
return new Result(
Result::FAILURE_CREDENTIAL_INVALID,
$identity,
['wrong password']
);
}
return new Result(
Result::FAILURE_UNCATEGORIZED,
$identity,
['generic error']
);
} | php | {
"resource": ""
} |
q254199 | Injector.inject | validation | public function inject(...$injects) : void
{
$container = new Container;
$requested = [];
foreach ($injects as $inject) {
if (is_string($inject)) {
$requested[] = $inject;
} elseif (is_callable($inject)) {
$reflection = new ReflectionFunction($inject);
foreach ($reflection->getParameters() as $param) {
$requested[] = $param->name;
}
}
}
foreach ($requested as $dependency) {
$this->$dependency = $container->get($dependency);
}
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.