repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
makinacorpus/drupal-ucms
ucms_seo/src/Path/AliasManager.php
AliasManager.isPathAliasProtected
public function isPathAliasProtected($nodeId, $siteId) { return (bool)$this ->database ->query( "SELECT is_protected FROM {ucms_seo_route} WHERE node_id = :node AND site_id = :site", [':node' => $nodeId, ':site' => $siteId] ) ->fetchField() ; }
php
public function isPathAliasProtected($nodeId, $siteId) { return (bool)$this ->database ->query( "SELECT is_protected FROM {ucms_seo_route} WHERE node_id = :node AND site_id = :site", [':node' => $nodeId, ':site' => $siteId] ) ->fetchField() ; }
[ "public", "function", "isPathAliasProtected", "(", "$", "nodeId", ",", "$", "siteId", ")", "{", "return", "(", "bool", ")", "$", "this", "->", "database", "->", "query", "(", "\"SELECT is_protected FROM {ucms_seo_route} WHERE node_id = :node AND site_id = :site\"", ",",...
Is the current path alias protected (i.e. manually set by user) @param int $nodeId @param int $siteId @return bool
[ "Is", "the", "current", "path", "alias", "protected", "(", "i", ".", "e", ".", "manually", "set", "by", "user", ")" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Path/AliasManager.php#L379-L389
makinacorpus/drupal-ucms
ucms_seo/src/Path/AliasManager.php
AliasManager.getPathAlias
public function getPathAlias($nodeId, $siteId) { $route = $this ->database ->query( "SELECT route, is_outdated FROM {ucms_seo_route} WHERE node_id = :node AND site_id = :site", [':node' => $nodeId, ':site' => $siteId] ) ->fetch() ; if (!$route || $route->is_outdated) { return $this->computeAndStorePathAlias($nodeId, $siteId, ($route ? $route->route : null)); } else { return $route->route; } }
php
public function getPathAlias($nodeId, $siteId) { $route = $this ->database ->query( "SELECT route, is_outdated FROM {ucms_seo_route} WHERE node_id = :node AND site_id = :site", [':node' => $nodeId, ':site' => $siteId] ) ->fetch() ; if (!$route || $route->is_outdated) { return $this->computeAndStorePathAlias($nodeId, $siteId, ($route ? $route->route : null)); } else { return $route->route; } }
[ "public", "function", "getPathAlias", "(", "$", "nodeId", ",", "$", "siteId", ")", "{", "$", "route", "=", "$", "this", "->", "database", "->", "query", "(", "\"SELECT route, is_outdated FROM {ucms_seo_route} WHERE node_id = :node AND site_id = :site\"", ",", "[", "':...
Get alias for node on site Internally, if no alias was already computed, this will recompute and store it into a custom route match table. @param int $nodeId @param int $siteId @return string
[ "Get", "alias", "for", "node", "on", "site" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Path/AliasManager.php#L402-L418
makinacorpus/drupal-ucms
ucms_seo/src/Path/AliasManager.php
AliasManager.matchPath
public function matchPath($alias, $siteId) { $nodeId = $this ->database ->query( "SELECT node_id FROM {ucms_seo_route} WHERE route = :route AND site_id = :site", [':route' => $alias, ':site' => $siteId] ) ->fetchField() ; return $nodeId ? ((int)$nodeId) : null; }
php
public function matchPath($alias, $siteId) { $nodeId = $this ->database ->query( "SELECT node_id FROM {ucms_seo_route} WHERE route = :route AND site_id = :site", [':route' => $alias, ':site' => $siteId] ) ->fetchField() ; return $nodeId ? ((int)$nodeId) : null; }
[ "public", "function", "matchPath", "(", "$", "alias", ",", "$", "siteId", ")", "{", "$", "nodeId", "=", "$", "this", "->", "database", "->", "query", "(", "\"SELECT node_id FROM {ucms_seo_route} WHERE route = :route AND site_id = :site\"", ",", "[", "':route'", "=>"...
Match path on given site @todo this one will be *very* hard to compute without umenu taking care of it for us; @param string $alias @param int $siteId @return null|int The node identifier if found
[ "Match", "path", "on", "given", "site" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Path/AliasManager.php#L432-L444
makinacorpus/drupal-ucms
ucms_seo/src/Action/SiteActionProvider.php
SiteActionProvider.getActions
public function getActions($item, $primaryOnly = false, array $groups = []) { $ret = []; if ($this->service->userCanEditSiteSeo($this->currentUser, $item)) { $ret[] = new Action($this->t("SEO parameters"), 'admin/dashboard/site/' . $item->id . '/seo-edit', null, 'globe', 1, false, false, false, 'seo'); $ret[] = new Action($this->t("SEO aliases"), 'admin/dashboard/site/' . $item->id . '/seo-aliases', null, 'link', 2, false, false, false, 'seo'); $ret[] = new Action($this->t("SEO redirects"), 'admin/dashboard/site/' . $item->id . '/seo-redirects', null, 'random', 3, false, false, false, 'seo'); } return $ret; }
php
public function getActions($item, $primaryOnly = false, array $groups = []) { $ret = []; if ($this->service->userCanEditSiteSeo($this->currentUser, $item)) { $ret[] = new Action($this->t("SEO parameters"), 'admin/dashboard/site/' . $item->id . '/seo-edit', null, 'globe', 1, false, false, false, 'seo'); $ret[] = new Action($this->t("SEO aliases"), 'admin/dashboard/site/' . $item->id . '/seo-aliases', null, 'link', 2, false, false, false, 'seo'); $ret[] = new Action($this->t("SEO redirects"), 'admin/dashboard/site/' . $item->id . '/seo-redirects', null, 'random', 3, false, false, false, 'seo'); } return $ret; }
[ "public", "function", "getActions", "(", "$", "item", ",", "$", "primaryOnly", "=", "false", ",", "array", "$", "groups", "=", "[", "]", ")", "{", "$", "ret", "=", "[", "]", ";", "if", "(", "$", "this", "->", "service", "->", "userCanEditSiteSeo", ...
{inheritdoc}
[ "{", "inheritdoc", "}" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Action/SiteActionProvider.php#L41-L52
saxulum/saxulum-elasticsearch-querybuilder
src/Converter/ScalarToNodeConverter.php
ScalarToNodeConverter.convert
public function convert($value, string $path = '', bool $allowSerializeEmpty = false): AbstractNode { if (null === $value) { return NullNode::create(); } $type = gettype($value); if (!isset($this->typeMapping[$type])) { throw new \InvalidArgumentException( sprintf('Type %s is not supported, at path %s', is_object($value) ? get_class($value) : $type, $path) ); } $node = $this->typeMapping[$type]; return $node::create($value, $allowSerializeEmpty); }
php
public function convert($value, string $path = '', bool $allowSerializeEmpty = false): AbstractNode { if (null === $value) { return NullNode::create(); } $type = gettype($value); if (!isset($this->typeMapping[$type])) { throw new \InvalidArgumentException( sprintf('Type %s is not supported, at path %s', is_object($value) ? get_class($value) : $type, $path) ); } $node = $this->typeMapping[$type]; return $node::create($value, $allowSerializeEmpty); }
[ "public", "function", "convert", "(", "$", "value", ",", "string", "$", "path", "=", "''", ",", "bool", "$", "allowSerializeEmpty", "=", "false", ")", ":", "AbstractNode", "{", "if", "(", "null", "===", "$", "value", ")", "{", "return", "NullNode", "::...
@param bool|float|int|null|string $value @param string $path @param bool $allowSerializeEmpty @return AbstractNode @throws \InvalidArgumentException
[ "@param", "bool|float|int|null|string", "$value", "@param", "string", "$path", "@param", "bool", "$allowSerializeEmpty" ]
train
https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/Converter/ScalarToNodeConverter.php#L35-L52
makinacorpus/drupal-ucms
ucms_site/src/Controller/AutocompleteController.php
AutocompleteController.userAutocompleteAction
public function userAutocompleteAction($string) { $manager = $this->getSiteManager(); $account = $this->getCurrentUser(); if (!$manager->getAccess()->userIsWebmaster($account) && !$this->isGranted(Access::PERM_USER_MANAGE_ALL)) { throw $this->createAccessDeniedException(); } $database = $this->getDatabaseConnection(); $q = $database ->select('users', 'u') ->fields('u', ['uid', 'name']) ->condition('u.name', '%' . $database->escapeLike($string) . '%', 'LIKE') ->condition('u.uid', [0, 1], 'NOT IN') ->orderBy('u.name', 'asc') ->range(0, 16) ->addTag('ucms_user_access') ; $suggest = []; foreach ($q->execute()->fetchAll() as $record) { $key = $record->name . ' [' . $record->uid . ']'; $suggest[$key] = check_plain($record->name); } return new JsonResponse($suggest); }
php
public function userAutocompleteAction($string) { $manager = $this->getSiteManager(); $account = $this->getCurrentUser(); if (!$manager->getAccess()->userIsWebmaster($account) && !$this->isGranted(Access::PERM_USER_MANAGE_ALL)) { throw $this->createAccessDeniedException(); } $database = $this->getDatabaseConnection(); $q = $database ->select('users', 'u') ->fields('u', ['uid', 'name']) ->condition('u.name', '%' . $database->escapeLike($string) . '%', 'LIKE') ->condition('u.uid', [0, 1], 'NOT IN') ->orderBy('u.name', 'asc') ->range(0, 16) ->addTag('ucms_user_access') ; $suggest = []; foreach ($q->execute()->fetchAll() as $record) { $key = $record->name . ' [' . $record->uid . ']'; $suggest[$key] = check_plain($record->name); } return new JsonResponse($suggest); }
[ "public", "function", "userAutocompleteAction", "(", "$", "string", ")", "{", "$", "manager", "=", "$", "this", "->", "getSiteManager", "(", ")", ";", "$", "account", "=", "$", "this", "->", "getCurrentUser", "(", ")", ";", "if", "(", "!", "$", "manage...
User autocomplete callback
[ "User", "autocomplete", "callback" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Controller/AutocompleteController.php#L45-L73
someline/starter-framework
src/Someline/Repository/Generators/Commands/RepositoryCommand.php
RepositoryCommand.fire
public function fire() { $this->generators = new Collection(); $this->generators->push(new MigrationGenerator([ 'name' => 'create_' . snake_case(str_plural($this->argument('name'))) . '_table', 'fields' => $this->option('fillable'), 'force' => $this->option('force'), ])); $modelGenerator = new ModelGenerator([ 'name' => $this->argument('name'), 'fillable' => $this->option('fillable'), 'force' => $this->option('force') ]); $this->generators->push($modelGenerator); $this->generators->push(new RepositoryInterfaceGenerator([ 'name' => $this->argument('name'), 'force' => $this->option('force'), ])); foreach ($this->generators as $generator) { $generator->run(); } $model = $modelGenerator->getRootNamespace() . '\\' . $modelGenerator->getName(); $model = str_replace([ "\\", '/' ], '\\', $model); try { (new RepositoryEloquentGenerator([ 'name' => $this->argument('name'), 'rules' => $this->option('rules'), 'validator' => $this->option('validator'), 'presenter' => $this->option('presenter'), 'force' => $this->option('force'), 'model' => $model ]))->run(); $this->info("Repository created successfully."); } catch (FileAlreadyExistsException $e) { $this->error($this->type . ' already exists!'); return false; } }
php
public function fire() { $this->generators = new Collection(); $this->generators->push(new MigrationGenerator([ 'name' => 'create_' . snake_case(str_plural($this->argument('name'))) . '_table', 'fields' => $this->option('fillable'), 'force' => $this->option('force'), ])); $modelGenerator = new ModelGenerator([ 'name' => $this->argument('name'), 'fillable' => $this->option('fillable'), 'force' => $this->option('force') ]); $this->generators->push($modelGenerator); $this->generators->push(new RepositoryInterfaceGenerator([ 'name' => $this->argument('name'), 'force' => $this->option('force'), ])); foreach ($this->generators as $generator) { $generator->run(); } $model = $modelGenerator->getRootNamespace() . '\\' . $modelGenerator->getName(); $model = str_replace([ "\\", '/' ], '\\', $model); try { (new RepositoryEloquentGenerator([ 'name' => $this->argument('name'), 'rules' => $this->option('rules'), 'validator' => $this->option('validator'), 'presenter' => $this->option('presenter'), 'force' => $this->option('force'), 'model' => $model ]))->run(); $this->info("Repository created successfully."); } catch (FileAlreadyExistsException $e) { $this->error($this->type . ' already exists!'); return false; } }
[ "public", "function", "fire", "(", ")", "{", "$", "this", "->", "generators", "=", "new", "Collection", "(", ")", ";", "$", "this", "->", "generators", "->", "push", "(", "new", "MigrationGenerator", "(", "[", "'name'", "=>", "'create_'", ".", "snake_cas...
Execute the command. @return void
[ "Execute", "the", "command", "." ]
train
https://github.com/someline/starter-framework/blob/38d3e97ca75dadb05bdc9020f73c78653dbecf15/src/Someline/Repository/Generators/Commands/RepositoryCommand.php#L49-L97
makinacorpus/drupal-ucms
ucms_contrib/src/Admin/NodeTabsForm.php
NodeTabsForm.buildForm
public function buildForm(array $form, FormStateInterface $form_state) { $form['media'] = [ '#title' => $this->t("Media tab"), '#type' => 'fieldset', ]; $form['media']['media_types'] = [ '#type' => 'checkboxes', '#options' => node_type_get_names(), '#default_value' => $this->typeHandler->getMediaTypes(), ]; $form['content'] = [ '#title' => $this->t("Content tab"), '#type' => 'fieldset', ]; $form['content']['editorial'] = [ '#title' => $this->t("Editorial content types"), '#type' => 'checkboxes', '#options' => node_type_get_names(), '#default_value' => $this->typeHandler->getEditorialContentTypes(), ]; $form['content']['component'] = [ '#title' => $this->t("Component content types"), '#type' => 'checkboxes', '#options' => node_type_get_names(), '#default_value' => $this->typeHandler->getComponentTypes(), ]; $form['content']['locked'] = [ '#title' => $this->t("Locked components"), '#type' => 'checkboxes', '#options' => node_type_get_names(), '#default_value' => $this->typeHandler->getLockedTypes(), ]; $form['actions']['#type'] = 'actions'; $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Save configuration'), ]; return $form; }
php
public function buildForm(array $form, FormStateInterface $form_state) { $form['media'] = [ '#title' => $this->t("Media tab"), '#type' => 'fieldset', ]; $form['media']['media_types'] = [ '#type' => 'checkboxes', '#options' => node_type_get_names(), '#default_value' => $this->typeHandler->getMediaTypes(), ]; $form['content'] = [ '#title' => $this->t("Content tab"), '#type' => 'fieldset', ]; $form['content']['editorial'] = [ '#title' => $this->t("Editorial content types"), '#type' => 'checkboxes', '#options' => node_type_get_names(), '#default_value' => $this->typeHandler->getEditorialContentTypes(), ]; $form['content']['component'] = [ '#title' => $this->t("Component content types"), '#type' => 'checkboxes', '#options' => node_type_get_names(), '#default_value' => $this->typeHandler->getComponentTypes(), ]; $form['content']['locked'] = [ '#title' => $this->t("Locked components"), '#type' => 'checkboxes', '#options' => node_type_get_names(), '#default_value' => $this->typeHandler->getLockedTypes(), ]; $form['actions']['#type'] = 'actions'; $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Save configuration'), ]; return $form; }
[ "public", "function", "buildForm", "(", "array", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "$", "form", "[", "'media'", "]", "=", "[", "'#title'", "=>", "$", "this", "->", "t", "(", "\"Media tab\"", ")", ",", "'#type'", "=>", ...
{@inheritDoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_contrib/src/Admin/NodeTabsForm.php#L46-L90
makinacorpus/drupal-ucms
ucms_contrib/src/Admin/NodeTabsForm.php
NodeTabsForm.validateForm
public function validateForm(array &$form, FormStateInterface $form_state) { $components = array_filter($form_state->getValue('component')); $editorial = array_filter($form_state->getValue('editorial')); $media = array_filter($form_state->getValue('media_types')); // Media and content can't be both if (count(array_diff($media, $components, $editorial)) != count($media)) { $form_state->setErrorByName('component_types', $this->t("Media can't be content as well.")); } // Editorial and components can't be both if (count(array_diff($components, $editorial)) != count($components)) { $form_state->setErrorByName('component_types', $this->t("Editorial content can't be components as well.")); } }
php
public function validateForm(array &$form, FormStateInterface $form_state) { $components = array_filter($form_state->getValue('component')); $editorial = array_filter($form_state->getValue('editorial')); $media = array_filter($form_state->getValue('media_types')); // Media and content can't be both if (count(array_diff($media, $components, $editorial)) != count($media)) { $form_state->setErrorByName('component_types', $this->t("Media can't be content as well.")); } // Editorial and components can't be both if (count(array_diff($components, $editorial)) != count($components)) { $form_state->setErrorByName('component_types', $this->t("Editorial content can't be components as well.")); } }
[ "public", "function", "validateForm", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "$", "components", "=", "array_filter", "(", "$", "form_state", "->", "getValue", "(", "'component'", ")", ")", ";", "$", "editorial...
{@inheritDoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_contrib/src/Admin/NodeTabsForm.php#L95-L110
makinacorpus/drupal-ucms
ucms_contrib/src/Admin/NodeTabsForm.php
NodeTabsForm.submitForm
public function submitForm(array &$form, FormStateInterface $form_state) { $this->typeHandler->setMediaTypes($form_state->getValue('media_types')); $this->typeHandler->setEditorialContentTypes($form_state->getValue('editorial')); $this->typeHandler->setComponentTypes($form_state->getValue('component')); $this->typeHandler->setLockedTypes($form_state->getValue('locked')); drupal_set_message($this->t('The configuration options have been saved.')); }
php
public function submitForm(array &$form, FormStateInterface $form_state) { $this->typeHandler->setMediaTypes($form_state->getValue('media_types')); $this->typeHandler->setEditorialContentTypes($form_state->getValue('editorial')); $this->typeHandler->setComponentTypes($form_state->getValue('component')); $this->typeHandler->setLockedTypes($form_state->getValue('locked')); drupal_set_message($this->t('The configuration options have been saved.')); }
[ "public", "function", "submitForm", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "$", "this", "->", "typeHandler", "->", "setMediaTypes", "(", "$", "form_state", "->", "getValue", "(", "'media_types'", ")", ")", ";"...
{@inheritDoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_contrib/src/Admin/NodeTabsForm.php#L115-L123
skeeks-cms/cms-marketplace
src/models/PackageModel.php
PackageModel.fetchInstalls
static public function fetchInstalls() { //Коды установленных пакетов $extensionCodes = ArrayHelper::map(\Yii::$app->extensions, 'name', 'name'); $result = \Yii::$app->cmsMarketplace->fetch([ 'packages', [ //'codes' => $extensionCodes, 'per-page' => 200 ] ]); $items = ArrayHelper::getValue($result, 'items'); $resultModels = []; if ($items) { foreach ($items as $data) { $model = new static([ 'apiData' => $data ]); $resultModels[$model->getPackagistCode()] = $model; } } return $resultModels; }
php
static public function fetchInstalls() { //Коды установленных пакетов $extensionCodes = ArrayHelper::map(\Yii::$app->extensions, 'name', 'name'); $result = \Yii::$app->cmsMarketplace->fetch([ 'packages', [ //'codes' => $extensionCodes, 'per-page' => 200 ] ]); $items = ArrayHelper::getValue($result, 'items'); $resultModels = []; if ($items) { foreach ($items as $data) { $model = new static([ 'apiData' => $data ]); $resultModels[$model->getPackagistCode()] = $model; } } return $resultModels; }
[ "static", "public", "function", "fetchInstalls", "(", ")", "{", "//Коды установленных пакетов", "$", "extensionCodes", "=", "ArrayHelper", "::", "map", "(", "\\", "Yii", "::", "$", "app", "->", "extensions", ",", "'name'", ",", "'name'", ")", ";", "$", "resu...
Установленные пакеты @return static[]
[ "Установленные", "пакеты" ]
train
https://github.com/skeeks-cms/cms-marketplace/blob/e6ae203adaeacc39c7eac8b38a8b8b4d20975cad/src/models/PackageModel.php#L64-L92
mosbth/Anax-MVC
src/ThemeEngine/CThemeBasic.php
CThemeBasic.render
public function render() { // Prepare details $path = $this->config['settings']['path']; $name = $this->config['settings']['name'] . '/'; $template = 'index.tpl.php'; $functions = 'functions.php'; // Include theme specific functions file $file = $path . $name . $functions; if (is_readable($file)) { include $file; } // Create views for regions, from config-file if (isset($this->config['views'])) { foreach ($this->config['views'] as $view) { $this->di->views->add($view['template'], $view['data'], $view['region'], $view['sort']); } } // Sen response headers, if any. $this->di->response->sendHeaders(); // Create a view to execute the default template file $tpl = $path . $name . $template; $data = array_merge($this->config['data'], $this->data); $view = $this->di->get('view'); $view->set($tpl, $data); $view->setDI($this->di); $view->render(); }
php
public function render() { // Prepare details $path = $this->config['settings']['path']; $name = $this->config['settings']['name'] . '/'; $template = 'index.tpl.php'; $functions = 'functions.php'; // Include theme specific functions file $file = $path . $name . $functions; if (is_readable($file)) { include $file; } // Create views for regions, from config-file if (isset($this->config['views'])) { foreach ($this->config['views'] as $view) { $this->di->views->add($view['template'], $view['data'], $view['region'], $view['sort']); } } // Sen response headers, if any. $this->di->response->sendHeaders(); // Create a view to execute the default template file $tpl = $path . $name . $template; $data = array_merge($this->config['data'], $this->data); $view = $this->di->get('view'); $view->set($tpl, $data); $view->setDI($this->di); $view->render(); }
[ "public", "function", "render", "(", ")", "{", "// Prepare details", "$", "path", "=", "$", "this", "->", "config", "[", "'settings'", "]", "[", "'path'", "]", ";", "$", "name", "=", "$", "this", "->", "config", "[", "'settings'", "]", "[", "'name'", ...
Render the theme by applying the variables onto the template files. @return void
[ "Render", "the", "theme", "by", "applying", "the", "variables", "onto", "the", "template", "files", "." ]
train
https://github.com/mosbth/Anax-MVC/blob/5574d105bcec9df8e57532a321585f6521b4581c/src/ThemeEngine/CThemeBasic.php#L124-L155
makinacorpus/drupal-ucms
ucms_composition/src/Command/MigrateFromLayoutCommand.php
MigrateFromLayoutCommand.parseSquash
private function parseSquash(string $string) : array { // As always, regexes to the rescue $matches = []; // @todo find out why using /^...$/ does not work capturing all groups if (!preg_match_all('/((\(\w+(?:\s+\w+)+\)\s*)+?)/ui', trim($string), $matches)) { throw new \InvalidArgumentException(); } $ret = []; foreach ($matches[1] as $group) { $ret[] = array_filter(preg_split('/[\(\)\s]+/', $group)); } return $ret; }
php
private function parseSquash(string $string) : array { // As always, regexes to the rescue $matches = []; // @todo find out why using /^...$/ does not work capturing all groups if (!preg_match_all('/((\(\w+(?:\s+\w+)+\)\s*)+?)/ui', trim($string), $matches)) { throw new \InvalidArgumentException(); } $ret = []; foreach ($matches[1] as $group) { $ret[] = array_filter(preg_split('/[\(\)\s]+/', $group)); } return $ret; }
[ "private", "function", "parseSquash", "(", "string", "$", "string", ")", ":", "array", "{", "// As always, regexes to the rescue", "$", "matches", "=", "[", "]", ";", "// @todo find out why using /^...$/ does not work capturing all groups", "if", "(", "!", "preg_match_all...
Parse the squash option @param string $string @return null|string[][]
[ "Parse", "the", "squash", "option" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_composition/src/Command/MigrateFromLayoutCommand.php#L62-L78
makinacorpus/drupal-ucms
ucms_composition/src/Command/MigrateFromLayoutCommand.php
MigrateFromLayoutCommand.migrateWithSquash
private function migrateWithSquash(array $groups, bool $useRegionAsStyle = false) { /** @var \DatabaseConnection $database */ $database = $this->getContainer()->get('database'); $database->query(" delete from {layout} "); // Build the when case for the query $cases = []; $params = []; foreach ($groups as $index => $group) { $first = reset($group); foreach ($group as $pos => $region) { $argFirst = ':group_' . $index . '_first_' . $pos; $argCurrent = ':group_' . $index . '_current_' . $pos; $params[$argFirst] = $first; $params[$argCurrent] = $region; $cases[] = "when " . $argCurrent . " then " . $argFirst; } } // Example working command: // bin/console -vvv ucms:composition:migate --region-as-style --squash="(content front1 front2 front3 front4) (footer1 footer2 footer3 footer4)" // This will happily fetch and merge all layout we want to migrate at once $database->query(" create temporary table {temp_layout_migrate} as select l.id as layout_id, l.nid, l.site_id, case d.region " . implode("\n ", $cases) . " else d.region end as new_region, region, 0 as new_id from {ucms_layout} l join {ucms_layout_data} d on d.layout_id = l.id group by l.id, d.region, l.site_id, l.nid ", $params); // Because some regions we priorize on squashing might not contain // content, they will be inexistant in the temporary table, we need // to recreate them by looking up for missing layouts // DISTINCT here is important, it avoids duplicates $database->query(" insert into {temp_layout_migrate} ( layout_id, nid, site_id, region, new_region ) select distinct ext.layout_id, ext.nid, ext.site_id, ext.new_region, ext.new_region from {temp_layout_migrate} ext where not exists ( select 1 from {temp_layout_migrate} int where int.region = ext.new_region and int.layout_id = ext.layout_id ) "); // In opposition to programmatic simple merge algorithm that keeps all // regions, we must not create all layouts but only those whose are // tied to non-squashed regions, then the WHERE $database->query(" insert into {layout} (site_id, node_id, region) select site_id, nid, region from {temp_layout_migrate} where region = new_region ", $params); // Fetch newly created layout identifiers for the very last request // to run $database->query(" update temp_layout_migrate set new_id = ( select id from layout l where l.region = temp_layout_migrate.new_region and l.site_id = temp_layout_migrate.site_id and l.node_id = temp_layout_migrate.nid limit 1 ) "); // And here we go for the final data migration, layout items! if ($useRegionAsStyle) { $database->query(" insert into {layout_data} (layout_id, item_type, item_id, style, position) select t.new_id, 'node', d.nid, d.region, d.weight from {ucms_layout_data} d join {temp_layout_migrate} t on t.layout_id = d.layout_id and t.region = d.region "); } else { $database->query(" insert into {layout_data} (layout_id, item_type, item_id, style, position) select t.new_id, 'node', d.nid, d.view_mode, d.weight from {ucms_layout_data} d join {temp_layout_migrate} t on t.layout_id = d.layout_id and t.region = d.region "); } }
php
private function migrateWithSquash(array $groups, bool $useRegionAsStyle = false) { /** @var \DatabaseConnection $database */ $database = $this->getContainer()->get('database'); $database->query(" delete from {layout} "); // Build the when case for the query $cases = []; $params = []; foreach ($groups as $index => $group) { $first = reset($group); foreach ($group as $pos => $region) { $argFirst = ':group_' . $index . '_first_' . $pos; $argCurrent = ':group_' . $index . '_current_' . $pos; $params[$argFirst] = $first; $params[$argCurrent] = $region; $cases[] = "when " . $argCurrent . " then " . $argFirst; } } // Example working command: // bin/console -vvv ucms:composition:migate --region-as-style --squash="(content front1 front2 front3 front4) (footer1 footer2 footer3 footer4)" // This will happily fetch and merge all layout we want to migrate at once $database->query(" create temporary table {temp_layout_migrate} as select l.id as layout_id, l.nid, l.site_id, case d.region " . implode("\n ", $cases) . " else d.region end as new_region, region, 0 as new_id from {ucms_layout} l join {ucms_layout_data} d on d.layout_id = l.id group by l.id, d.region, l.site_id, l.nid ", $params); // Because some regions we priorize on squashing might not contain // content, they will be inexistant in the temporary table, we need // to recreate them by looking up for missing layouts // DISTINCT here is important, it avoids duplicates $database->query(" insert into {temp_layout_migrate} ( layout_id, nid, site_id, region, new_region ) select distinct ext.layout_id, ext.nid, ext.site_id, ext.new_region, ext.new_region from {temp_layout_migrate} ext where not exists ( select 1 from {temp_layout_migrate} int where int.region = ext.new_region and int.layout_id = ext.layout_id ) "); // In opposition to programmatic simple merge algorithm that keeps all // regions, we must not create all layouts but only those whose are // tied to non-squashed regions, then the WHERE $database->query(" insert into {layout} (site_id, node_id, region) select site_id, nid, region from {temp_layout_migrate} where region = new_region ", $params); // Fetch newly created layout identifiers for the very last request // to run $database->query(" update temp_layout_migrate set new_id = ( select id from layout l where l.region = temp_layout_migrate.new_region and l.site_id = temp_layout_migrate.site_id and l.node_id = temp_layout_migrate.nid limit 1 ) "); // And here we go for the final data migration, layout items! if ($useRegionAsStyle) { $database->query(" insert into {layout_data} (layout_id, item_type, item_id, style, position) select t.new_id, 'node', d.nid, d.region, d.weight from {ucms_layout_data} d join {temp_layout_migrate} t on t.layout_id = d.layout_id and t.region = d.region "); } else { $database->query(" insert into {layout_data} (layout_id, item_type, item_id, style, position) select t.new_id, 'node', d.nid, d.view_mode, d.weight from {ucms_layout_data} d join {temp_layout_migrate} t on t.layout_id = d.layout_id and t.region = d.region "); } }
[ "private", "function", "migrateWithSquash", "(", "array", "$", "groups", ",", "bool", "$", "useRegionAsStyle", "=", "false", ")", "{", "/** @var \\DatabaseConnection $database */", "$", "database", "=", "$", "this", "->", "getContainer", "(", ")", "->", "get", "...
It's the easiest procedure: it just merge the old schema into the new one by doing a few temporary steps: very fast, very easy.
[ "It", "s", "the", "easiest", "procedure", ":", "it", "just", "merge", "the", "old", "schema", "into", "the", "new", "one", "by", "doing", "a", "few", "temporary", "steps", ":", "very", "fast", "very", "easy", "." ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_composition/src/Command/MigrateFromLayoutCommand.php#L84-L198
makinacorpus/drupal-ucms
ucms_composition/src/Command/MigrateFromLayoutCommand.php
MigrateFromLayoutCommand.migrateKeepingRegions
private function migrateKeepingRegions(bool $useRegionAsStyle = false) { /** @var \DatabaseConnection $database */ $database = $this->getContainer()->get('database'); $database->query(" delete from {layout} "); $database->query(" create temporary table {temp_layout_migrate} as select l.id as layout_id, l.nid, l.site_id, region, 0 as new_id from {ucms_layout} l join {ucms_layout_data} d on d.layout_id = l.id group by l.id, d.region, l.site_id, l.nid "); $database->query(" insert into {layout} (site_id, node_id, region) select site_id, nid, region from {temp_layout_migrate} "); $database->query(" update {temp_layout_migrate} set new_id = ( select id from {layout} l where l.region = {temp_layout_migrate}.region and l.site_id = {temp_layout_migrate}.site_id and l.node_id = {temp_layout_migrate}.nid ) "); if ($useRegionAsStyle) { $database->query(" insert into {layout_data} (layout_id, item_type, item_id, style, position) select t.new_id, 'node', d.nid, d.region, d.weight from {ucms_layout_data} d join {temp_layout_migrate} t on t.layout_id = d.layout_id and t.region = d.region "); } else { $database->query(" insert into {layout_data} (layout_id, item_type, item_id, style, position) select t.new_id, 'node', d.nid, d.view_mode, d.weight from {ucms_layout_data} d join {temp_layout_migrate} t on t.layout_id = d.layout_id and t.region = d.region "); } }
php
private function migrateKeepingRegions(bool $useRegionAsStyle = false) { /** @var \DatabaseConnection $database */ $database = $this->getContainer()->get('database'); $database->query(" delete from {layout} "); $database->query(" create temporary table {temp_layout_migrate} as select l.id as layout_id, l.nid, l.site_id, region, 0 as new_id from {ucms_layout} l join {ucms_layout_data} d on d.layout_id = l.id group by l.id, d.region, l.site_id, l.nid "); $database->query(" insert into {layout} (site_id, node_id, region) select site_id, nid, region from {temp_layout_migrate} "); $database->query(" update {temp_layout_migrate} set new_id = ( select id from {layout} l where l.region = {temp_layout_migrate}.region and l.site_id = {temp_layout_migrate}.site_id and l.node_id = {temp_layout_migrate}.nid ) "); if ($useRegionAsStyle) { $database->query(" insert into {layout_data} (layout_id, item_type, item_id, style, position) select t.new_id, 'node', d.nid, d.region, d.weight from {ucms_layout_data} d join {temp_layout_migrate} t on t.layout_id = d.layout_id and t.region = d.region "); } else { $database->query(" insert into {layout_data} (layout_id, item_type, item_id, style, position) select t.new_id, 'node', d.nid, d.view_mode, d.weight from {ucms_layout_data} d join {temp_layout_migrate} t on t.layout_id = d.layout_id and t.region = d.region "); } }
[ "private", "function", "migrateKeepingRegions", "(", "bool", "$", "useRegionAsStyle", "=", "false", ")", "{", "/** @var \\DatabaseConnection $database */", "$", "database", "=", "$", "this", "->", "getContainer", "(", ")", "->", "get", "(", "'database'", ")", ";",...
It's the easiest procedure: it just merge the old schema into the new one by doing a few temporary steps: very fast, very easy.
[ "It", "s", "the", "easiest", "procedure", ":", "it", "just", "merge", "the", "old", "schema", "into", "the", "new", "one", "by", "doing", "a", "few", "temporary", "steps", ":", "very", "fast", "very", "easy", "." ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_composition/src/Command/MigrateFromLayoutCommand.php#L204-L265
makinacorpus/drupal-ucms
ucms_composition/src/Command/MigrateFromLayoutCommand.php
MigrateFromLayoutCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { if (!db_table_exists('ucms_layout')) { $output->writeln("<error>Table 'ucms_layout' is not found, there is no data to migrate</error>"); return -1; } if (!module_exists('phplayout') || !module_exists('ucms_composition')) { $output->writeln("one of the 'ucms_composition' or 'phplayout' module is disabled, enabling it"); module_enable(['phplayout', 'ucms_composition']); } /** @var \DatabaseConnection $database */ $database = $this->getContainer()->get('database'); $exists = (bool)$database->query("select 1 from {layout}")->fetchField(); if ($exists) { if (!$input->getOption('force-recreate')) { $output->writeln("<error>'layout' table contains data, use --force-recreate switch to drop all existing data before migrating</error>"); return -1; } $output->writeln("<comment>'layout' table contains data and will be dropped</comment>"); } $squash = null; $useRegionAsStyle = (bool)$input->getOption('region-as-style'); if ($string = $input->getOption("squash")) { try { $squash = $this->parseSquash($string); } catch (\InvalidArgumentException $e) { $output->writeln('<error>given --squash parameter is invalid</error>'); return -1; } } if ($squash) { $this->migrateWithSquash($squash, $useRegionAsStyle); } else if (!$input->getOption('merge-regions')) { $this->migrateKeepingRegions($useRegionAsStyle); } // Print a small synthesis $ucmsEmptyLayoutCount = $database->query("select count(*) from {ucms_layout} l where not exists (select 1 from {ucms_layout_data} where layout_id = l.id)")->fetchField(); $ucmsLayoutCount = $database->query("select count(*) from {ucms_layout}")->fetchField(); $ucmsLayoutDataCount = $database->query("select count(*) from {ucms_layout_data}")->fetchField(); $layoutCount = $database->query("select count(*) from {layout}")->fetchField(); $layoutDataCount = $database->query("select count(*) from {layout_data}")->fetchField(); $output->writeln('<info>' . sprintf('%d layouts migrated into %d new ones', $ucmsLayoutCount, $layoutCount) . '</info>'); $output->writeln('<info>' . sprintf('%d layouts were empty', $ucmsEmptyLayoutCount) . '</info>'); $output->writeln('<info>' . sprintf('%d layouts items migrated into %d new ones', $ucmsLayoutDataCount, $layoutDataCount) . '</info>'); }
php
protected function execute(InputInterface $input, OutputInterface $output) { if (!db_table_exists('ucms_layout')) { $output->writeln("<error>Table 'ucms_layout' is not found, there is no data to migrate</error>"); return -1; } if (!module_exists('phplayout') || !module_exists('ucms_composition')) { $output->writeln("one of the 'ucms_composition' or 'phplayout' module is disabled, enabling it"); module_enable(['phplayout', 'ucms_composition']); } /** @var \DatabaseConnection $database */ $database = $this->getContainer()->get('database'); $exists = (bool)$database->query("select 1 from {layout}")->fetchField(); if ($exists) { if (!$input->getOption('force-recreate')) { $output->writeln("<error>'layout' table contains data, use --force-recreate switch to drop all existing data before migrating</error>"); return -1; } $output->writeln("<comment>'layout' table contains data and will be dropped</comment>"); } $squash = null; $useRegionAsStyle = (bool)$input->getOption('region-as-style'); if ($string = $input->getOption("squash")) { try { $squash = $this->parseSquash($string); } catch (\InvalidArgumentException $e) { $output->writeln('<error>given --squash parameter is invalid</error>'); return -1; } } if ($squash) { $this->migrateWithSquash($squash, $useRegionAsStyle); } else if (!$input->getOption('merge-regions')) { $this->migrateKeepingRegions($useRegionAsStyle); } // Print a small synthesis $ucmsEmptyLayoutCount = $database->query("select count(*) from {ucms_layout} l where not exists (select 1 from {ucms_layout_data} where layout_id = l.id)")->fetchField(); $ucmsLayoutCount = $database->query("select count(*) from {ucms_layout}")->fetchField(); $ucmsLayoutDataCount = $database->query("select count(*) from {ucms_layout_data}")->fetchField(); $layoutCount = $database->query("select count(*) from {layout}")->fetchField(); $layoutDataCount = $database->query("select count(*) from {layout_data}")->fetchField(); $output->writeln('<info>' . sprintf('%d layouts migrated into %d new ones', $ucmsLayoutCount, $layoutCount) . '</info>'); $output->writeln('<info>' . sprintf('%d layouts were empty', $ucmsEmptyLayoutCount) . '</info>'); $output->writeln('<info>' . sprintf('%d layouts items migrated into %d new ones', $ucmsLayoutDataCount, $layoutDataCount) . '</info>'); }
[ "protected", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", "{", "if", "(", "!", "db_table_exists", "(", "'ucms_layout'", ")", ")", "{", "$", "output", "->", "writeln", "(", "\"<error>Table 'ucms_layout' i...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_composition/src/Command/MigrateFromLayoutCommand.php#L270-L323
makinacorpus/drupal-ucms
ucms_site/src/Form/SiteSwitch.php
SiteSwitch.buildForm
public function buildForm(array $form, FormStateInterface $form_state, Site $site = null, $state = null) { $form_state->setTemporaryValue('site', $site); $form_state->setTemporaryValue('state', $state); $question = $this->t( "Switch site @site to state @state ?", [ '@site' => $site->title, '@state' => $this->t(SiteState::getList()[$state]), ] ); $form = confirm_form($form, $question, 'admin/dashboard/site/' . $site->id); $form['message'] = [ '#type' => 'textarea', '#title' => $this->t("Reason"), '#attributes' => ['placeholder' => $this->t("Describe here why you're switching this site's state")], ]; return $form; }
php
public function buildForm(array $form, FormStateInterface $form_state, Site $site = null, $state = null) { $form_state->setTemporaryValue('site', $site); $form_state->setTemporaryValue('state', $state); $question = $this->t( "Switch site @site to state @state ?", [ '@site' => $site->title, '@state' => $this->t(SiteState::getList()[$state]), ] ); $form = confirm_form($form, $question, 'admin/dashboard/site/' . $site->id); $form['message'] = [ '#type' => 'textarea', '#title' => $this->t("Reason"), '#attributes' => ['placeholder' => $this->t("Describe here why you're switching this site's state")], ]; return $form; }
[ "public", "function", "buildForm", "(", "array", "$", "form", ",", "FormStateInterface", "$", "form_state", ",", "Site", "$", "site", "=", "null", ",", "$", "state", "=", "null", ")", "{", "$", "form_state", "->", "setTemporaryValue", "(", "'site'", ",", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Form/SiteSwitch.php#L74-L94
makinacorpus/drupal-ucms
ucms_site/src/Form/SiteSwitch.php
SiteSwitch.submitForm
public function submitForm(array &$form, FormStateInterface $form_state) { $site = $form_state->getTemporaryValue('site'); $state = (int)$form_state->getTemporaryValue('state'); $data = ['from' => $site->state, 'to' => $state, 'message' => $form_state->getValue('message')]; $list = SiteState::getList(); $tx = null; try { $tx = $this->db->startTransaction(); $site->state = $state; $this->manager->getStorage()->save($site, ['state']); $this->dispatcher->dispatch(SiteEvents::EVENT_SWITCH, new SiteEvent($site, $this->currentUser()->uid, $data)); unset($tx); drupal_set_message( $this->t( "Site @site has been switched from @from to @to", [ '@site' => $site->title, '@from' => $this->t($list[$data['from']]), '@to' => $this->t($list[$data['to']]), ] ) ); } catch (\Exception $e) { if ($tx) { try { $tx->rollback(); } catch (\Exception $e2) { watchdog_exception('ucms_site', $e2); } watchdog_exception('ucms_site', $e); drupal_set_message( $this->t( "There was an error switching site @site from @from to @to", [ '@site' => $site->title, '@from' => $this->t($list[$data['from']]), '@to' => $this->t($list[$data['to']]), ] ), 'error' ); } } $form_state->setRedirect('admin/dashboard/site'); }
php
public function submitForm(array &$form, FormStateInterface $form_state) { $site = $form_state->getTemporaryValue('site'); $state = (int)$form_state->getTemporaryValue('state'); $data = ['from' => $site->state, 'to' => $state, 'message' => $form_state->getValue('message')]; $list = SiteState::getList(); $tx = null; try { $tx = $this->db->startTransaction(); $site->state = $state; $this->manager->getStorage()->save($site, ['state']); $this->dispatcher->dispatch(SiteEvents::EVENT_SWITCH, new SiteEvent($site, $this->currentUser()->uid, $data)); unset($tx); drupal_set_message( $this->t( "Site @site has been switched from @from to @to", [ '@site' => $site->title, '@from' => $this->t($list[$data['from']]), '@to' => $this->t($list[$data['to']]), ] ) ); } catch (\Exception $e) { if ($tx) { try { $tx->rollback(); } catch (\Exception $e2) { watchdog_exception('ucms_site', $e2); } watchdog_exception('ucms_site', $e); drupal_set_message( $this->t( "There was an error switching site @site from @from to @to", [ '@site' => $site->title, '@from' => $this->t($list[$data['from']]), '@to' => $this->t($list[$data['to']]), ] ), 'error' ); } } $form_state->setRedirect('admin/dashboard/site'); }
[ "public", "function", "submitForm", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "$", "site", "=", "$", "form_state", "->", "getTemporaryValue", "(", "'site'", ")", ";", "$", "state", "=", "(", "int", ")", "$", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Form/SiteSwitch.php#L99-L153
makinacorpus/drupal-ucms
ucms_user/src/Form/UserEdit.php
UserEdit.buildForm
public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = null) { $form['#form_horizontal'] = true; if ($user === null) { $user = $this->entityManager->getStorage('user')->create(); } $form_state->setTemporaryValue('user', $user); $form['name'] = array( '#type' => 'textfield', '#title' => $this->t('Lastname / Firstname'), '#default_value' => !$user->isNew() ? $user->getAccountName() : '', '#maxlength' => 60, '#required' => true, '#weight' => -10, ); $form['mail'] = array( '#type' => 'textfield', '#title' => $this->t('Email'), '#default_value' => $user->getEmail(), '#maxlength' => EMAIL_MAX_LENGTH, '#required' => true, '#weight' => -5, ); if ($user->id() === $this->currentUser()->id()) { $form['mail']['#disabled'] = true; $form['mail']['#description'] = $this->t("Please use this form to edit your e-mail: !link", [ '!link' => l($this->t("change my e-mail"), 'admin/dashboard/user/my-account'), ]); } $allRoles = $this->siteManager->getAccess()->getDrupalRoleList(); unset($allRoles[DRUPAL_ANONYMOUS_RID]); unset($allRoles[DRUPAL_AUTHENTICATED_RID]); $form['roles'] = [ '#type' => 'checkboxes', '#title' => $this->t('Roles'), '#options' => $allRoles, '#default_value' => $user->getRoles(), ]; if ($user->isNew()) { $form['enable'] = array( '#type' => 'checkbox', '#title' => $this->t('Enable the user'), '#default_value' => 0, '#description' => $this->t("You will have to define a password and pass it on to the user by yourself."), ); $form['password_container'] = [ // Yes, a container... because password_confirm elements seem to not support #states property. '#type' => 'container', '#states' => [ 'visible' => [':input[name="enable"]' => ['checked' => true]], 'enabled' => [':input[name="enable"]' => ['checked' => true]], // This one to avoid non matching values at submit... ], 'password' => [ '#type' => 'password_confirm', '#size' => 20, '#description' => $this->t("!count characters at least. Mix letters, digits and special characters for a better password.", ['!count' => UCMS_USER_PWD_MIN_LENGTH]), ], ]; } $form['actions'] = ['#type' => 'actions']; $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $user->isNew() ? $this->t('Create') : $this->t('Save'), ]; return $form; }
php
public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = null) { $form['#form_horizontal'] = true; if ($user === null) { $user = $this->entityManager->getStorage('user')->create(); } $form_state->setTemporaryValue('user', $user); $form['name'] = array( '#type' => 'textfield', '#title' => $this->t('Lastname / Firstname'), '#default_value' => !$user->isNew() ? $user->getAccountName() : '', '#maxlength' => 60, '#required' => true, '#weight' => -10, ); $form['mail'] = array( '#type' => 'textfield', '#title' => $this->t('Email'), '#default_value' => $user->getEmail(), '#maxlength' => EMAIL_MAX_LENGTH, '#required' => true, '#weight' => -5, ); if ($user->id() === $this->currentUser()->id()) { $form['mail']['#disabled'] = true; $form['mail']['#description'] = $this->t("Please use this form to edit your e-mail: !link", [ '!link' => l($this->t("change my e-mail"), 'admin/dashboard/user/my-account'), ]); } $allRoles = $this->siteManager->getAccess()->getDrupalRoleList(); unset($allRoles[DRUPAL_ANONYMOUS_RID]); unset($allRoles[DRUPAL_AUTHENTICATED_RID]); $form['roles'] = [ '#type' => 'checkboxes', '#title' => $this->t('Roles'), '#options' => $allRoles, '#default_value' => $user->getRoles(), ]; if ($user->isNew()) { $form['enable'] = array( '#type' => 'checkbox', '#title' => $this->t('Enable the user'), '#default_value' => 0, '#description' => $this->t("You will have to define a password and pass it on to the user by yourself."), ); $form['password_container'] = [ // Yes, a container... because password_confirm elements seem to not support #states property. '#type' => 'container', '#states' => [ 'visible' => [':input[name="enable"]' => ['checked' => true]], 'enabled' => [':input[name="enable"]' => ['checked' => true]], // This one to avoid non matching values at submit... ], 'password' => [ '#type' => 'password_confirm', '#size' => 20, '#description' => $this->t("!count characters at least. Mix letters, digits and special characters for a better password.", ['!count' => UCMS_USER_PWD_MIN_LENGTH]), ], ]; } $form['actions'] = ['#type' => 'actions']; $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $user->isNew() ? $this->t('Create') : $this->t('Save'), ]; return $form; }
[ "public", "function", "buildForm", "(", "array", "$", "form", ",", "FormStateInterface", "$", "form_state", ",", "UserInterface", "$", "user", "=", "null", ")", "{", "$", "form", "[", "'#form_horizontal'", "]", "=", "true", ";", "if", "(", "$", "user", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_user/src/Form/UserEdit.php#L85-L161
makinacorpus/drupal-ucms
ucms_user/src/Form/UserEdit.php
UserEdit.validateForm
public function validateForm(array &$form, FormStateInterface $form_state) { // Trim whitespace from mail, to prevent confusing 'e-mail not valid' // warnings often caused by cutting and pasting. $mail = $form_state->getValue('mail'); $mail = trim($mail); $form_state->setValue('mail', $mail); // Validate the e-mail address, and check if it is taken by an existing user. if ($error = user_validate_mail($mail)) { $form_state->setErrorByName('mail', $error); } else { /* @var UserInterface $user */ $user = $form_state->getTemporaryValue('user'); $q = db_select('users') ->fields('users', array('uid')) ->condition('mail', db_like($mail), 'LIKE') ->range(0, 1); if (!$user->isNew()) { $q->condition('uid', $user->id(), '<>'); } if ((bool) $q->execute()->fetchField()) { form_set_error('mail', $this->t('The e-mail address %email is already taken.', array('%email' => $mail))); } // Validate username must be unique $userName = $form_state->getValue('name'); $q = db_select('users')->fields('users', ['uid'])->condition('name', db_like($userName), 'LIKE'); if (!$user->isNew()) { $q->condition('uid', $user->id(), '<>'); } $exists = $q->range(0, 1)->execute()->fetchField(); if ($exists) { $form_state->setErrorByName('name', $this->t("A user with the same user name already exists.")); } } if ((int) $form_state->getValue('enable') === 1) { if (strlen($form_state->getValue('password')) === 0) { $form_state->setErrorByName('password', $this->t("You must define a password to enable the user.")); } elseif (strlen($form_state->getValue('password')) < UCMS_USER_PWD_MIN_LENGTH) { $form_state->setErrorByName('password', $this->t("The password must contain !count characters at least.", ['!count' => UCMS_USER_PWD_MIN_LENGTH])); } } }
php
public function validateForm(array &$form, FormStateInterface $form_state) { // Trim whitespace from mail, to prevent confusing 'e-mail not valid' // warnings often caused by cutting and pasting. $mail = $form_state->getValue('mail'); $mail = trim($mail); $form_state->setValue('mail', $mail); // Validate the e-mail address, and check if it is taken by an existing user. if ($error = user_validate_mail($mail)) { $form_state->setErrorByName('mail', $error); } else { /* @var UserInterface $user */ $user = $form_state->getTemporaryValue('user'); $q = db_select('users') ->fields('users', array('uid')) ->condition('mail', db_like($mail), 'LIKE') ->range(0, 1); if (!$user->isNew()) { $q->condition('uid', $user->id(), '<>'); } if ((bool) $q->execute()->fetchField()) { form_set_error('mail', $this->t('The e-mail address %email is already taken.', array('%email' => $mail))); } // Validate username must be unique $userName = $form_state->getValue('name'); $q = db_select('users')->fields('users', ['uid'])->condition('name', db_like($userName), 'LIKE'); if (!$user->isNew()) { $q->condition('uid', $user->id(), '<>'); } $exists = $q->range(0, 1)->execute()->fetchField(); if ($exists) { $form_state->setErrorByName('name', $this->t("A user with the same user name already exists.")); } } if ((int) $form_state->getValue('enable') === 1) { if (strlen($form_state->getValue('password')) === 0) { $form_state->setErrorByName('password', $this->t("You must define a password to enable the user.")); } elseif (strlen($form_state->getValue('password')) < UCMS_USER_PWD_MIN_LENGTH) { $form_state->setErrorByName('password', $this->t("The password must contain !count characters at least.", ['!count' => UCMS_USER_PWD_MIN_LENGTH])); } } }
[ "public", "function", "validateForm", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "// Trim whitespace from mail, to prevent confusing 'e-mail not valid'", "// warnings often caused by cutting and pasting.", "$", "mail", "=", "$", "f...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_user/src/Form/UserEdit.php#L167-L216
makinacorpus/drupal-ucms
ucms_user/src/Form/UserEdit.php
UserEdit.submitForm
public function submitForm(array &$form, FormStateInterface $form_state) { $user = $form_state->getTemporaryValue('user'); $is_new = $user->isNew(); // Stores this information to use it after save. $user->setUsername($form_state->getValue('name')); $user->setEmail($form_state->getValue('mail')); // New user if ($is_new) { require_once DRUPAL_ROOT . '/includes/password.inc'; if ((int) $form_state->getValue('enable') === 1) { $user->pass = user_hash_password($form_state->getValue('password')); $user->status = 1; } else { $user->pass = user_hash_password(user_password(20)); $user->status = 0; } } // Prepares user roles $userRoles = array_filter($form_state->getValue('roles', [])); $siteRoles = $this->siteManager->getAccess()->getRolesAssociations(); foreach (array_keys($siteRoles) as $rid) { if (isset($user->roles[$rid])) { $userRoles[$rid] = true; } } $user->roles = $userRoles; // Saves the user if ($this->entityManager->getStorage('user')->save($user)) { if ($is_new) { drupal_set_message($this->t("The new user @name has been created.", array('@name' => $user->name))); if ($user->isActive()) { $this->tokenManager->sendTokenMail($user, 'ucms_user', 'new-account-enabled'); } else { $this->tokenManager->sendTokenMail($user, 'ucms_user', 'new-account-disabled'); } $this->dispatcher->dispatch('user:add', new UserEvent($user->uid, $this->currentUser()->uid)); } else { drupal_set_message($this->t("The user @name has been updated.", array('@name' => $user->name))); $this->dispatcher->dispatch('user:edit', new UserEvent($user->uid, $this->currentUser()->uid)); } } else { drupal_set_message($this->t("An error occured. Please try again."), 'error'); } $form_state->setRedirect('admin/dashboard/user'); }
php
public function submitForm(array &$form, FormStateInterface $form_state) { $user = $form_state->getTemporaryValue('user'); $is_new = $user->isNew(); // Stores this information to use it after save. $user->setUsername($form_state->getValue('name')); $user->setEmail($form_state->getValue('mail')); // New user if ($is_new) { require_once DRUPAL_ROOT . '/includes/password.inc'; if ((int) $form_state->getValue('enable') === 1) { $user->pass = user_hash_password($form_state->getValue('password')); $user->status = 1; } else { $user->pass = user_hash_password(user_password(20)); $user->status = 0; } } // Prepares user roles $userRoles = array_filter($form_state->getValue('roles', [])); $siteRoles = $this->siteManager->getAccess()->getRolesAssociations(); foreach (array_keys($siteRoles) as $rid) { if (isset($user->roles[$rid])) { $userRoles[$rid] = true; } } $user->roles = $userRoles; // Saves the user if ($this->entityManager->getStorage('user')->save($user)) { if ($is_new) { drupal_set_message($this->t("The new user @name has been created.", array('@name' => $user->name))); if ($user->isActive()) { $this->tokenManager->sendTokenMail($user, 'ucms_user', 'new-account-enabled'); } else { $this->tokenManager->sendTokenMail($user, 'ucms_user', 'new-account-disabled'); } $this->dispatcher->dispatch('user:add', new UserEvent($user->uid, $this->currentUser()->uid)); } else { drupal_set_message($this->t("The user @name has been updated.", array('@name' => $user->name))); $this->dispatcher->dispatch('user:edit', new UserEvent($user->uid, $this->currentUser()->uid)); } } else { drupal_set_message($this->t("An error occured. Please try again."), 'error'); } $form_state->setRedirect('admin/dashboard/user'); }
[ "public", "function", "submitForm", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "$", "user", "=", "$", "form_state", "->", "getTemporaryValue", "(", "'user'", ")", ";", "$", "is_new", "=", "$", "user", "->", "i...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_user/src/Form/UserEdit.php#L222-L276
someline/starter-framework
src/Someline/Api/Middleware/ApiAccessMiddleware.php
ApiAccessMiddleware.handle
public function handle($request, Closure $next) { try { $response = $next($request); // Was an exception thrown? If so and available catch in our middleware if (isset($response->exception) && $response->exception) { throw $response->exception; } return $response; } catch (OAuthException $e) { $message = env('API_DEBUG') ? $e->getMessage() : null; throw new HttpException($e->httpStatusCode, $message, $e, $e->getHttpHeaders()); } catch (HttpResponseException $e) { $message = env('API_DEBUG') ? $e->getMessage() : null; throw new HttpException($e->getResponse()->getStatusCode(), $message, $e); } catch (AuthenticationException $e) { throw new UnauthorizedHttpException(null, $e->getMessage(), $e); } catch (ValidatorException $e) { $messageBag = $e->getMessageBag(); throw new ResourceException($messageBag->first(), $messageBag->all()); } catch (ModelNotFoundException $e) { throw new NotFoundHttpException('No results found.'); } }
php
public function handle($request, Closure $next) { try { $response = $next($request); // Was an exception thrown? If so and available catch in our middleware if (isset($response->exception) && $response->exception) { throw $response->exception; } return $response; } catch (OAuthException $e) { $message = env('API_DEBUG') ? $e->getMessage() : null; throw new HttpException($e->httpStatusCode, $message, $e, $e->getHttpHeaders()); } catch (HttpResponseException $e) { $message = env('API_DEBUG') ? $e->getMessage() : null; throw new HttpException($e->getResponse()->getStatusCode(), $message, $e); } catch (AuthenticationException $e) { throw new UnauthorizedHttpException(null, $e->getMessage(), $e); } catch (ValidatorException $e) { $messageBag = $e->getMessageBag(); throw new ResourceException($messageBag->first(), $messageBag->all()); } catch (ModelNotFoundException $e) { throw new NotFoundHttpException('No results found.'); } }
[ "public", "function", "handle", "(", "$", "request", ",", "Closure", "$", "next", ")", "{", "try", "{", "$", "response", "=", "$", "next", "(", "$", "request", ")", ";", "// Was an exception thrown? If so and available catch in our middleware", "if", "(", "isset...
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed @throws HttpException
[ "Handle", "an", "incoming", "request", "." ]
train
https://github.com/someline/starter-framework/blob/38d3e97ca75dadb05bdc9020f73c78653dbecf15/src/Someline/Api/Middleware/ApiAccessMiddleware.php#L30-L55
makinacorpus/drupal-ucms
ucms_search/src/Form/SearchForm.php
SearchForm.buildForm
public function buildForm(array $form, FormStateInterface $form_state, $node = null) { $request = $this->requestStack->getCurrentRequest(); $form['#method'] = 'get'; $form['#action'] = url('node/'.$node->nid); $form['#after_build'][] = '::formAfterBuild'; $form['#token'] = false; $form['#attributes'] = ['class' => [drupal_html_class($this->getFormId())]]; $form[Search::PARAM_FULLTEXT_QUERY] = [ '#type' => 'textfield', '#default_value' => $request->query->get(Search::PARAM_FULLTEXT_QUERY), '#prefix' => '<div class="input-group">', '#attributes' => [ 'class' => [], 'placeholder' => $this->t("Specify your keywords"), ], ]; // No need to use an input submit with GET method. Furthermore, it won't be // exposed as GET parameter with an input button. $form['submit'] = [ '#type' => 'button', '#content' => '<span class="fa fa-search"></span>', '#prefix' => '<span class="input-group-btn">', '#suffix' => '</span></div>', ]; return $form; }
php
public function buildForm(array $form, FormStateInterface $form_state, $node = null) { $request = $this->requestStack->getCurrentRequest(); $form['#method'] = 'get'; $form['#action'] = url('node/'.$node->nid); $form['#after_build'][] = '::formAfterBuild'; $form['#token'] = false; $form['#attributes'] = ['class' => [drupal_html_class($this->getFormId())]]; $form[Search::PARAM_FULLTEXT_QUERY] = [ '#type' => 'textfield', '#default_value' => $request->query->get(Search::PARAM_FULLTEXT_QUERY), '#prefix' => '<div class="input-group">', '#attributes' => [ 'class' => [], 'placeholder' => $this->t("Specify your keywords"), ], ]; // No need to use an input submit with GET method. Furthermore, it won't be // exposed as GET parameter with an input button. $form['submit'] = [ '#type' => 'button', '#content' => '<span class="fa fa-search"></span>', '#prefix' => '<span class="input-group-btn">', '#suffix' => '</span></div>', ]; return $form; }
[ "public", "function", "buildForm", "(", "array", "$", "form", ",", "FormStateInterface", "$", "form_state", ",", "$", "node", "=", "null", ")", "{", "$", "request", "=", "$", "this", "->", "requestStack", "->", "getCurrentRequest", "(", ")", ";", "$", "f...
{inheritdoc} @param array $form @param \Drupal\Core\Form\FormStateInterface $form_state @param null|NodeInterface $node @return array
[ "{", "inheritdoc", "}" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/Form/SearchForm.php#L52-L82
despark/ignicms
src/Console/Commands/File/ClearTemp.php
ClearTemp.handle
public function handle() { $deleteBefore = Carbon::now()->subWeek(); $filesToDelete = $this->tempModel->where('created_at', '<=', $deleteBefore)->get(); $failed = []; foreach ($filesToDelete as $file) { // delete the file if (! \File::delete($file->getTempPath())) { $this->output->warning(sprintf('%s file not found. Skipping...', $file->getTempPath())); } } $deletedRecords = DB::table($this->tempModel->getTable()) ->where('created_at', '<=', $deleteBefore) ->delete(); $this->output->success(sprintf('%d temp file cleaned', $deletedRecords)); }
php
public function handle() { $deleteBefore = Carbon::now()->subWeek(); $filesToDelete = $this->tempModel->where('created_at', '<=', $deleteBefore)->get(); $failed = []; foreach ($filesToDelete as $file) { // delete the file if (! \File::delete($file->getTempPath())) { $this->output->warning(sprintf('%s file not found. Skipping...', $file->getTempPath())); } } $deletedRecords = DB::table($this->tempModel->getTable()) ->where('created_at', '<=', $deleteBefore) ->delete(); $this->output->success(sprintf('%d temp file cleaned', $deletedRecords)); }
[ "public", "function", "handle", "(", ")", "{", "$", "deleteBefore", "=", "Carbon", "::", "now", "(", ")", "->", "subWeek", "(", ")", ";", "$", "filesToDelete", "=", "$", "this", "->", "tempModel", "->", "where", "(", "'created_at'", ",", "'<='", ",", ...
Run command.
[ "Run", "command", "." ]
train
https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/src/Console/Commands/File/ClearTemp.php#L47-L65
despark/ignicms
public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Config.php
CI_Config.load
function load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) { $file = ($file == '') ? 'config' : str_replace('.php', '', $file); $found = FALSE; $loaded = FALSE; $check_locations = defined('ENVIRONMENT') ? array(ENVIRONMENT.'/'.$file, $file) : array($file); foreach ($this->_config_paths as $path) { foreach ($check_locations as $location) { $file_path = $path.'config/'.$location.'.php'; if (in_array($file_path, $this->is_loaded, TRUE)) { $loaded = TRUE; continue 2; } if (file_exists($file_path)) { $found = TRUE; break; } } if ($found === FALSE) { continue; } include($file_path); if ( ! isset($config) OR ! is_array($config)) { if ($fail_gracefully === TRUE) { return FALSE; } show_error('Your '.$file_path.' file does not appear to contain a valid configuration array.'); } if ($use_sections === TRUE) { if (isset($this->config[$file])) { $this->config[$file] = array_merge($this->config[$file], $config); } else { $this->config[$file] = $config; } } else { $this->config = array_merge($this->config, $config); } $this->is_loaded[] = $file_path; unset($config); $loaded = TRUE; log_message('debug', 'Config file loaded: '.$file_path); break; } if ($loaded === FALSE) { if ($fail_gracefully === TRUE) { return FALSE; } show_error('The configuration file '.$file.'.php does not exist.'); } return TRUE; }
php
function load($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) { $file = ($file == '') ? 'config' : str_replace('.php', '', $file); $found = FALSE; $loaded = FALSE; $check_locations = defined('ENVIRONMENT') ? array(ENVIRONMENT.'/'.$file, $file) : array($file); foreach ($this->_config_paths as $path) { foreach ($check_locations as $location) { $file_path = $path.'config/'.$location.'.php'; if (in_array($file_path, $this->is_loaded, TRUE)) { $loaded = TRUE; continue 2; } if (file_exists($file_path)) { $found = TRUE; break; } } if ($found === FALSE) { continue; } include($file_path); if ( ! isset($config) OR ! is_array($config)) { if ($fail_gracefully === TRUE) { return FALSE; } show_error('Your '.$file_path.' file does not appear to contain a valid configuration array.'); } if ($use_sections === TRUE) { if (isset($this->config[$file])) { $this->config[$file] = array_merge($this->config[$file], $config); } else { $this->config[$file] = $config; } } else { $this->config = array_merge($this->config, $config); } $this->is_loaded[] = $file_path; unset($config); $loaded = TRUE; log_message('debug', 'Config file loaded: '.$file_path); break; } if ($loaded === FALSE) { if ($fail_gracefully === TRUE) { return FALSE; } show_error('The configuration file '.$file.'.php does not exist.'); } return TRUE; }
[ "function", "load", "(", "$", "file", "=", "''", ",", "$", "use_sections", "=", "FALSE", ",", "$", "fail_gracefully", "=", "FALSE", ")", "{", "$", "file", "=", "(", "$", "file", "==", "''", ")", "?", "'config'", ":", "str_replace", "(", "'.php'", "...
Load Config File @access public @param string the config file name @param boolean if configuration values should be loaded into their own section @param boolean true if errors should just return false, false if an error message should be displayed @return boolean if the file was loaded correctly
[ "Load", "Config", "File" ]
train
https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Config.php#L96-L175
despark/ignicms
public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Config.php
CI_Config.item
function item($item, $index = '') { if ($index == '') { if ( ! isset($this->config[$item])) { return FALSE; } $pref = $this->config[$item]; } else { if ( ! isset($this->config[$index])) { return FALSE; } if ( ! isset($this->config[$index][$item])) { return FALSE; } $pref = $this->config[$index][$item]; } return $pref; }
php
function item($item, $index = '') { if ($index == '') { if ( ! isset($this->config[$item])) { return FALSE; } $pref = $this->config[$item]; } else { if ( ! isset($this->config[$index])) { return FALSE; } if ( ! isset($this->config[$index][$item])) { return FALSE; } $pref = $this->config[$index][$item]; } return $pref; }
[ "function", "item", "(", "$", "item", ",", "$", "index", "=", "''", ")", "{", "if", "(", "$", "index", "==", "''", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "config", "[", "$", "item", "]", ")", ")", "{", "return", "FALSE", ...
Fetch a config file item @access public @param string the config item name @param string the index name @param bool @return string
[ "Fetch", "a", "config", "file", "item" ]
train
https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Config.php#L189-L216
despark/ignicms
public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Config.php
CI_Config.slash_item
function slash_item($item) { if ( ! isset($this->config[$item])) { return FALSE; } if( trim($this->config[$item]) == '') { return ''; } return rtrim($this->config[$item], '/').'/'; }
php
function slash_item($item) { if ( ! isset($this->config[$item])) { return FALSE; } if( trim($this->config[$item]) == '') { return ''; } return rtrim($this->config[$item], '/').'/'; }
[ "function", "slash_item", "(", "$", "item", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "config", "[", "$", "item", "]", ")", ")", "{", "return", "FALSE", ";", "}", "if", "(", "trim", "(", "$", "this", "->", "config", "[", "$", ...
Fetch a config file item - adds slash after item (if item is not empty) @access public @param string the config item name @param bool @return string
[ "Fetch", "a", "config", "file", "item", "-", "adds", "slash", "after", "item", "(", "if", "item", "is", "not", "empty", ")" ]
train
https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Config.php#L228-L240
despark/ignicms
public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Config.php
CI_Config.site_url
function site_url($uri = '') { if ($uri == '') { return $this->slash_item('base_url').$this->item('index_page'); } if ($this->item('enable_query_strings') == FALSE) { $suffix = ($this->item('url_suffix') == FALSE) ? '' : $this->item('url_suffix'); return $this->slash_item('base_url').$this->slash_item('index_page').$this->_uri_string($uri).$suffix; } else { return $this->slash_item('base_url').$this->item('index_page').'?'.$this->_uri_string($uri); } }
php
function site_url($uri = '') { if ($uri == '') { return $this->slash_item('base_url').$this->item('index_page'); } if ($this->item('enable_query_strings') == FALSE) { $suffix = ($this->item('url_suffix') == FALSE) ? '' : $this->item('url_suffix'); return $this->slash_item('base_url').$this->slash_item('index_page').$this->_uri_string($uri).$suffix; } else { return $this->slash_item('base_url').$this->item('index_page').'?'.$this->_uri_string($uri); } }
[ "function", "site_url", "(", "$", "uri", "=", "''", ")", "{", "if", "(", "$", "uri", "==", "''", ")", "{", "return", "$", "this", "->", "slash_item", "(", "'base_url'", ")", ".", "$", "this", "->", "item", "(", "'index_page'", ")", ";", "}", "if"...
Site URL Returns base_url . index_page [. uri_string] @access public @param string the URI string @return string
[ "Site", "URL", "Returns", "base_url", ".", "index_page", "[", ".", "uri_string", "]" ]
train
https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Config.php#L252-L268
despark/ignicms
public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Config.php
CI_Config._uri_string
protected function _uri_string($uri) { if ($this->item('enable_query_strings') == FALSE) { if (is_array($uri)) { $uri = implode('/', $uri); } $uri = trim($uri, '/'); } else { if (is_array($uri)) { $i = 0; $str = ''; foreach ($uri as $key => $val) { $prefix = ($i == 0) ? '' : '&'; $str .= $prefix.$key.'='.$val; $i++; } $uri = $str; } } return $uri; }
php
protected function _uri_string($uri) { if ($this->item('enable_query_strings') == FALSE) { if (is_array($uri)) { $uri = implode('/', $uri); } $uri = trim($uri, '/'); } else { if (is_array($uri)) { $i = 0; $str = ''; foreach ($uri as $key => $val) { $prefix = ($i == 0) ? '' : '&'; $str .= $prefix.$key.'='.$val; $i++; } $uri = $str; } } return $uri; }
[ "protected", "function", "_uri_string", "(", "$", "uri", ")", "{", "if", "(", "$", "this", "->", "item", "(", "'enable_query_strings'", ")", "==", "FALSE", ")", "{", "if", "(", "is_array", "(", "$", "uri", ")", ")", "{", "$", "uri", "=", "implode", ...
Build URI string for use in Config::site_url() and Config::base_url() @access protected @param $uri @return string
[ "Build", "URI", "string", "for", "use", "in", "Config", "::", "site_url", "()", "and", "Config", "::", "base_url", "()" ]
train
https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Config.php#L294-L320
despark/ignicms
public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Config.php
CI_Config._assign_to_config
function _assign_to_config($items = array()) { if (is_array($items)) { foreach ($items as $key => $val) { $this->set_item($key, $val); } } }
php
function _assign_to_config($items = array()) { if (is_array($items)) { foreach ($items as $key => $val) { $this->set_item($key, $val); } } }
[ "function", "_assign_to_config", "(", "$", "items", "=", "array", "(", ")", ")", "{", "if", "(", "is_array", "(", "$", "items", ")", ")", "{", "foreach", "(", "$", "items", "as", "$", "key", "=>", "$", "val", ")", "{", "$", "this", "->", "set_ite...
Assign to Config This function is called by the front controller (CodeIgniter.php) after the Config class is instantiated. It permits config items to be assigned or overriden by variables contained in the index.php file @access private @param array @return void
[ "Assign", "to", "Config" ]
train
https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/public/admin_assets/plugins/tinymce/plugins/jbimages/ci/system/core/Config.php#L364-L373
makinacorpus/drupal-ucms
ucms_tree/src/Action/TreeDeleteProcessor.php
TreeDeleteProcessor.processAll
public function processAll($items) { /** @var \MakinaCorpus\Umenu\Menu $item */ foreach ($items as $item) { $this->menuStorage->delete($item->getId()); } return $this->formatPlural( count($item), "Menu tree has been deleted", "@count menu trees have been deleted" ); }
php
public function processAll($items) { /** @var \MakinaCorpus\Umenu\Menu $item */ foreach ($items as $item) { $this->menuStorage->delete($item->getId()); } return $this->formatPlural( count($item), "Menu tree has been deleted", "@count menu trees have been deleted" ); }
[ "public", "function", "processAll", "(", "$", "items", ")", "{", "/** @var \\MakinaCorpus\\Umenu\\Menu $item */", "foreach", "(", "$", "items", "as", "$", "item", ")", "{", "$", "this", "->", "menuStorage", "->", "delete", "(", "$", "item", "->", "getId", "(...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_tree/src/Action/TreeDeleteProcessor.php#L71-L83
makinacorpus/drupal-ucms
ucms_site/src/EventDispatcher/NodeEventSubscriber.php
NodeEventSubscriber.getSubscribedEvents
static public function getSubscribedEvents() { return [ NodeCollectionEvent::EVENT_LOAD => [ ['onLoad', 0] ], NodeEvent::EVENT_PREPARE => [ ['onPrepare', 128] ], NodeEvent::EVENT_PREINSERT => [ ['onPreInsert', 0] ], NodeEvent::EVENT_INSERT => [ ['onInsert', 0], ['onPostInsert', -32], ], NodeEvent::EVENT_SAVE => [ ['onSave', 0] ], NodeEvents::ACCESS_CHANGE => [ ['onNodeAccessChange', 0], ], ]; }
php
static public function getSubscribedEvents() { return [ NodeCollectionEvent::EVENT_LOAD => [ ['onLoad', 0] ], NodeEvent::EVENT_PREPARE => [ ['onPrepare', 128] ], NodeEvent::EVENT_PREINSERT => [ ['onPreInsert', 0] ], NodeEvent::EVENT_INSERT => [ ['onInsert', 0], ['onPostInsert', -32], ], NodeEvent::EVENT_SAVE => [ ['onSave', 0] ], NodeEvents::ACCESS_CHANGE => [ ['onNodeAccessChange', 0], ], ]; }
[ "static", "public", "function", "getSubscribedEvents", "(", ")", "{", "return", "[", "NodeCollectionEvent", "::", "EVENT_LOAD", "=>", "[", "[", "'onLoad'", ",", "0", "]", "]", ",", "NodeEvent", "::", "EVENT_PREPARE", "=>", "[", "[", "'onPrepare'", ",", "128"...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/EventDispatcher/NodeEventSubscriber.php#L50-L73
accompli/accompli
src/AccompliEvents.php
AccompliEvents.getEventNames
public static function getEventNames() { return array( self::CREATE_CONNECTION, self::DEPLOY_COMMAND_COMPLETE, self::DEPLOY_RELEASE, self::DEPLOY_RELEASE_COMPLETE, self::DEPLOY_RELEASE_FAILED, self::GATHER_FACTS, self::GET_WORKSPACE, self::INITIALIZE, self::INSTALL_COMMAND_COMPLETE, self::INSTALL_RELEASE, self::INSTALL_RELEASE_COMPLETE, self::INSTALL_RELEASE_FAILED, self::LOG, self::PREPARE_DEPLOY_RELEASE, self::PREPARE_RELEASE, self::PREPARE_WORKSPACE, self::ROLLBACK_RELEASE, self::ROLLBACK_RELEASE_COMPLETE, self::ROLLBACK_RELEASE_FAILED, ); }
php
public static function getEventNames() { return array( self::CREATE_CONNECTION, self::DEPLOY_COMMAND_COMPLETE, self::DEPLOY_RELEASE, self::DEPLOY_RELEASE_COMPLETE, self::DEPLOY_RELEASE_FAILED, self::GATHER_FACTS, self::GET_WORKSPACE, self::INITIALIZE, self::INSTALL_COMMAND_COMPLETE, self::INSTALL_RELEASE, self::INSTALL_RELEASE_COMPLETE, self::INSTALL_RELEASE_FAILED, self::LOG, self::PREPARE_DEPLOY_RELEASE, self::PREPARE_RELEASE, self::PREPARE_WORKSPACE, self::ROLLBACK_RELEASE, self::ROLLBACK_RELEASE_COMPLETE, self::ROLLBACK_RELEASE_FAILED, ); }
[ "public", "static", "function", "getEventNames", "(", ")", "{", "return", "array", "(", "self", "::", "CREATE_CONNECTION", ",", "self", "::", "DEPLOY_COMMAND_COMPLETE", ",", "self", "::", "DEPLOY_RELEASE", ",", "self", "::", "DEPLOY_RELEASE_COMPLETE", ",", "self",...
Returns an array with all the event names (constants). @return array
[ "Returns", "an", "array", "with", "all", "the", "event", "names", "(", "constants", ")", "." ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/AccompliEvents.php#L207-L230
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Locale/Language/Standard.php
Standard.searchItems
public function searchItems( \stdClass $params ) { $manager = $this->getManager(); $total = 0; $search = $manager->createSearch(); if( isset( $params->options->showall ) && $params->options->showall == false ) { $localeManager = \Aimeos\MShop\Locale\Manager\Factory::createManager( $this->getContext() ); $langids = []; foreach( $localeManager->searchItems( $localeManager->createSearch() ) as $item ) { $langids[] = $item->getLanguageId(); } if( !empty( $langids ) ) { $search->setConditions( $search->compare( '==', 'locale.language.id', $langids ) ); } } $search = $this->initCriteria( $search, $params ); $sort = $search->getSortations(); $sort[] = $search->sort( '+', 'locale.language.label' ); $search->setSortations( $sort ); $items = $this->getManager()->searchItems( $search, [], $total ); return array( 'items' => $this->toArray( $items ), 'total' => $total, 'success' => true, ); }
php
public function searchItems( \stdClass $params ) { $manager = $this->getManager(); $total = 0; $search = $manager->createSearch(); if( isset( $params->options->showall ) && $params->options->showall == false ) { $localeManager = \Aimeos\MShop\Locale\Manager\Factory::createManager( $this->getContext() ); $langids = []; foreach( $localeManager->searchItems( $localeManager->createSearch() ) as $item ) { $langids[] = $item->getLanguageId(); } if( !empty( $langids ) ) { $search->setConditions( $search->compare( '==', 'locale.language.id', $langids ) ); } } $search = $this->initCriteria( $search, $params ); $sort = $search->getSortations(); $sort[] = $search->sort( '+', 'locale.language.label' ); $search->setSortations( $sort ); $items = $this->getManager()->searchItems( $search, [], $total ); return array( 'items' => $this->toArray( $items ), 'total' => $total, 'success' => true, ); }
[ "public", "function", "searchItems", "(", "\\", "stdClass", "$", "params", ")", "{", "$", "manager", "=", "$", "this", "->", "getManager", "(", ")", ";", "$", "total", "=", "0", ";", "$", "search", "=", "$", "manager", "->", "createSearch", "(", ")",...
Retrieves all items matching the given criteria. @param \stdClass $params Associative array containing the parameters @return array List of associative arrays with item properties, total number of items and success property
[ "Retrieves", "all", "items", "matching", "the", "given", "criteria", "." ]
train
https://github.com/aimeos/ai-admin-extadm/blob/594ee7cec90fd63a4773c05c93f353e66d9b3408/controller/extjs/src/Controller/ExtJS/Locale/Language/Standard.php#L89-L123
someline/starter-framework
src/Someline/Api/Middleware/ApiAuthMiddleware.php
ApiAuthMiddleware.handle
public function handle($request, Closure $next, $grant = null) { $route = $this->router->getCurrentRoute(); /** * FOR (Internal API requests) * @note GRANT(user) will always be able to access routes that are protected by: GRANT(client) * * For OAuth grants from password (i.e. Resource Owner: user) * @Auth will only check once, because user exists in auth afterwards * * For OAuth grants from client_credentials (i.e. Resource Owner: client) * @Auth will always check, because user is never exists in auth */ if (!$this->auth->check(false)) { $this->auth->authenticate($route->getAuthenticationProviders()); $provider = $this->auth->getProviderUsed(); /** @var OAuth2 $provider */ if ($provider instanceof OAuth2) { // check oauth grant type if (!is_null($grant) && $provider->getResourceOwnerType() !== $grant) { throw new AccessDeniedException(); } } // login user through Auth $user = $this->auth->getUser(); if ($user instanceof User) { \Auth::login($user); event(new UserLoggedInEvent($user)); } } return $next($request); }
php
public function handle($request, Closure $next, $grant = null) { $route = $this->router->getCurrentRoute(); /** * FOR (Internal API requests) * @note GRANT(user) will always be able to access routes that are protected by: GRANT(client) * * For OAuth grants from password (i.e. Resource Owner: user) * @Auth will only check once, because user exists in auth afterwards * * For OAuth grants from client_credentials (i.e. Resource Owner: client) * @Auth will always check, because user is never exists in auth */ if (!$this->auth->check(false)) { $this->auth->authenticate($route->getAuthenticationProviders()); $provider = $this->auth->getProviderUsed(); /** @var OAuth2 $provider */ if ($provider instanceof OAuth2) { // check oauth grant type if (!is_null($grant) && $provider->getResourceOwnerType() !== $grant) { throw new AccessDeniedException(); } } // login user through Auth $user = $this->auth->getUser(); if ($user instanceof User) { \Auth::login($user); event(new UserLoggedInEvent($user)); } } return $next($request); }
[ "public", "function", "handle", "(", "$", "request", ",", "Closure", "$", "next", ",", "$", "grant", "=", "null", ")", "{", "$", "route", "=", "$", "this", "->", "router", "->", "getCurrentRoute", "(", ")", ";", "/**\n * FOR (Internal API requests)\n...
Perform authentication before a request is executed. @param \Illuminate\Http\Request $request @param \Closure $next @param $grant @return mixed @throws AccessDeniedException
[ "Perform", "authentication", "before", "a", "request", "is", "executed", "." ]
train
https://github.com/someline/starter-framework/blob/38d3e97ca75dadb05bdc9020f73c78653dbecf15/src/Someline/Api/Middleware/ApiAuthMiddleware.php#L56-L93
loyals-online/silverstripe-tinymce4
code/forms/CustomHtmlEditorConfig.php
CustomHtmlEditorConfig.get
public static function get($identifier = 'default') { if (!array_key_exists($identifier, self::$configs)) self::$configs[$identifier] = new CustomHtmlEditorConfig(); return self::$configs[$identifier]; }
php
public static function get($identifier = 'default') { if (!array_key_exists($identifier, self::$configs)) self::$configs[$identifier] = new CustomHtmlEditorConfig(); return self::$configs[$identifier]; }
[ "public", "static", "function", "get", "(", "$", "identifier", "=", "'default'", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "identifier", ",", "self", "::", "$", "configs", ")", ")", "self", "::", "$", "configs", "[", "$", "identifier", "]...
Get the HtmlEditorConfig object for the given identifier. This is a correct way to get an HtmlEditorConfig instance - do not call 'new' @param $identifier string - the identifier for the config set @return HtmlEditorConfig - the configuration object. This will be created if it does not yet exist for that identifier
[ "Get", "the", "HtmlEditorConfig", "object", "for", "the", "given", "identifier", ".", "This", "is", "a", "correct", "way", "to", "get", "an", "HtmlEditorConfig", "instance", "-", "do", "not", "call", "new" ]
train
https://github.com/loyals-online/silverstripe-tinymce4/blob/c0603d074ebbb6b8a429f2d2856778e3643bba34/code/forms/CustomHtmlEditorConfig.php#L28-L31
loyals-online/silverstripe-tinymce4
code/forms/CustomHtmlEditorConfig.php
CustomHtmlEditorConfig.setOptions
public function setOptions($a) { foreach ($a as $k=>$v) { $this->settings[$k] = $v; } return $this; }
php
public function setOptions($a) { foreach ($a as $k=>$v) { $this->settings[$k] = $v; } return $this; }
[ "public", "function", "setOptions", "(", "$", "a", ")", "{", "foreach", "(", "$", "a", "as", "$", "k", "=>", "$", "v", ")", "{", "$", "this", "->", "settings", "[", "$", "k", "]", "=", "$", "v", ";", "}", "return", "$", "this", ";", "}" ]
Set multiple options @param $a array - The options to set, as keys and values of the array @return null
[ "Set", "multiple", "options" ]
train
https://github.com/loyals-online/silverstripe-tinymce4/blob/c0603d074ebbb6b8a429f2d2856778e3643bba34/code/forms/CustomHtmlEditorConfig.php#L182-L187
loyals-online/silverstripe-tinymce4
code/forms/CustomHtmlEditorConfig.php
CustomHtmlEditorConfig.enablePlugins
public function enablePlugins() { $plugins = func_get_args(); if (is_array(current($plugins))) $plugins = current($plugins); foreach ($plugins as $plugin => $path) { // if plugins are passed without a path if(is_numeric($plugin)) { $plugin = $path; $path = null; } if (!array_key_exists($plugin, $this->plugins)) $this->plugins[$plugin] = $path; } }
php
public function enablePlugins() { $plugins = func_get_args(); if (is_array(current($plugins))) $plugins = current($plugins); foreach ($plugins as $plugin => $path) { // if plugins are passed without a path if(is_numeric($plugin)) { $plugin = $path; $path = null; } if (!array_key_exists($plugin, $this->plugins)) $this->plugins[$plugin] = $path; } }
[ "public", "function", "enablePlugins", "(", ")", "{", "$", "plugins", "=", "func_get_args", "(", ")", ";", "if", "(", "is_array", "(", "current", "(", "$", "plugins", ")", ")", ")", "$", "plugins", "=", "current", "(", "$", "plugins", ")", ";", "fore...
Enable one or several plugins. Will maintain unique list if already enabled plugin is re-passed. If passed in as a map of plugin-name to path, the plugin will be loaded by tinymce.PluginManager.load() instead of through tinyMCE.init(). Keep in mind that these externals plugins require a dash-prefix in their name. @see http://wiki.moxiecode.com/index.php/TinyMCE:API/tinymce.PluginManager/load @param String [0..] a string, or several strings, or a single array of strings - The plugins to enable @return null
[ "Enable", "one", "or", "several", "plugins", ".", "Will", "maintain", "unique", "list", "if", "already", "enabled", "plugin", "is", "re", "-", "passed", ".", "If", "passed", "in", "as", "a", "map", "of", "plugin", "-", "name", "to", "path", "the", "plu...
train
https://github.com/loyals-online/silverstripe-tinymce4/blob/c0603d074ebbb6b8a429f2d2856778e3643bba34/code/forms/CustomHtmlEditorConfig.php#L200-L211
loyals-online/silverstripe-tinymce4
code/forms/CustomHtmlEditorConfig.php
CustomHtmlEditorConfig.disablePlugins
public function disablePlugins() { $plugins = func_get_args(); if (is_array(current($plugins))) $plugins = current($plugins); foreach ($plugins as $plugin) { if(array_key_exists($plugin, $this->plugins)) { unset($this->plugins[$plugin]); } } return $this; }
php
public function disablePlugins() { $plugins = func_get_args(); if (is_array(current($plugins))) $plugins = current($plugins); foreach ($plugins as $plugin) { if(array_key_exists($plugin, $this->plugins)) { unset($this->plugins[$plugin]); } } return $this; }
[ "public", "function", "disablePlugins", "(", ")", "{", "$", "plugins", "=", "func_get_args", "(", ")", ";", "if", "(", "is_array", "(", "current", "(", "$", "plugins", ")", ")", ")", "$", "plugins", "=", "current", "(", "$", "plugins", ")", ";", "for...
Enable one or several plugins. Will properly handle being passed a plugin that is already disabled @param String [0..] a string, or several strings, or a single array of strings - The plugins to disable @return null
[ "Enable", "one", "or", "several", "plugins", ".", "Will", "properly", "handle", "being", "passed", "a", "plugin", "that", "is", "already", "disabled" ]
train
https://github.com/loyals-online/silverstripe-tinymce4/blob/c0603d074ebbb6b8a429f2d2856778e3643bba34/code/forms/CustomHtmlEditorConfig.php#L218-L228
loyals-online/silverstripe-tinymce4
code/forms/CustomHtmlEditorConfig.php
CustomHtmlEditorConfig.addButtonsToLine
public function addButtonsToLine() { $inserts = func_get_args(); $line = array_shift($inserts); if (is_array($inserts[0])) $inserts = $inserts[0]; foreach ($inserts as $button) { $this->buttons[$line][] = $button; } return $this; }
php
public function addButtonsToLine() { $inserts = func_get_args(); $line = array_shift($inserts); if (is_array($inserts[0])) $inserts = $inserts[0]; foreach ($inserts as $button) { $this->buttons[$line][] = $button; } return $this; }
[ "public", "function", "addButtonsToLine", "(", ")", "{", "$", "inserts", "=", "func_get_args", "(", ")", ";", "$", "line", "=", "array_shift", "(", "$", "inserts", ")", ";", "if", "(", "is_array", "(", "$", "inserts", "[", "0", "]", ")", ")", "$", ...
Add buttons to the end of a line @param integer from 1..3 @param string a string, or several strings, or a single array of strings - The button names to add to the end of this line @return null
[ "Add", "buttons", "to", "the", "end", "of", "a", "line" ]
train
https://github.com/loyals-online/silverstripe-tinymce4/blob/c0603d074ebbb6b8a429f2d2856778e3643bba34/code/forms/CustomHtmlEditorConfig.php#L264-L273
loyals-online/silverstripe-tinymce4
code/forms/CustomHtmlEditorConfig.php
CustomHtmlEditorConfig.insertButtonsBefore
public function insertButtonsBefore() { $inserts = func_get_args(); $before = array_shift($inserts); return $this->modifyButtons($before, 0, 0, $inserts); }
php
public function insertButtonsBefore() { $inserts = func_get_args(); $before = array_shift($inserts); return $this->modifyButtons($before, 0, 0, $inserts); }
[ "public", "function", "insertButtonsBefore", "(", ")", "{", "$", "inserts", "=", "func_get_args", "(", ")", ";", "$", "before", "=", "array_shift", "(", "$", "inserts", ")", ";", "return", "$", "this", "->", "modifyButtons", "(", "$", "before", ",", "0",...
Insert buttons before the first occurance of another button @param string - the name of the button to insert other buttons before @param string a string, or several strings, or a single array of strings - the button names to insert before that button @return boolean - true if insertion occured, false if it did not (because the given button name was not found)
[ "Insert", "buttons", "before", "the", "first", "occurance", "of", "another", "button" ]
train
https://github.com/loyals-online/silverstripe-tinymce4/blob/c0603d074ebbb6b8a429f2d2856778e3643bba34/code/forms/CustomHtmlEditorConfig.php#L303-L307
loyals-online/silverstripe-tinymce4
code/forms/CustomHtmlEditorConfig.php
CustomHtmlEditorConfig.insertButtonsAfter
public function insertButtonsAfter() { $inserts = func_get_args(); $after = array_shift($inserts); return $this->modifyButtons($after, 1, 0, $inserts); }
php
public function insertButtonsAfter() { $inserts = func_get_args(); $after = array_shift($inserts); return $this->modifyButtons($after, 1, 0, $inserts); }
[ "public", "function", "insertButtonsAfter", "(", ")", "{", "$", "inserts", "=", "func_get_args", "(", ")", ";", "$", "after", "=", "array_shift", "(", "$", "inserts", ")", ";", "return", "$", "this", "->", "modifyButtons", "(", "$", "after", ",", "1", ...
Insert buttons after the first occurance of another button @param string - the name of the button to insert other buttons after @param string a string, or several strings, or a single array of strings - the button names to insert after that button @return boolean - true if insertion occured, false if it did not (because the given button name was not found)
[ "Insert", "buttons", "after", "the", "first", "occurance", "of", "another", "button" ]
train
https://github.com/loyals-online/silverstripe-tinymce4/blob/c0603d074ebbb6b8a429f2d2856778e3643bba34/code/forms/CustomHtmlEditorConfig.php#L316-L320
loyals-online/silverstripe-tinymce4
code/forms/CustomHtmlEditorConfig.php
CustomHtmlEditorConfig.require_js
public static function require_js() { require_once TINYMCE4_PATH . '/thirdparty/tinymce/tiny_mce_gzip.php'; $useGzip = Config::inst()->get('CustomHtmlEditorField', 'use_gzip'); $configs = array(); $externalPlugins = array(); $internalPlugins = array(); $languages = array(); foreach (self::$configs as $configID => $config) { $settings = $config->settings; // parse plugins $configPlugins = array(); foreach($config->plugins as $plugin => $path) { if(!$path) { $configPlugins[] = $plugin; $internalPlugins[] = $plugin; } else { $configPlugins[] = '-' . $plugin; if ( !array_key_exists($plugin, $externalPlugins) ) { $externalPlugins[$plugin] = sprintf( 'tinymce.PluginManager.load("%s", "%s");', $plugin, $path ); } } } // save config plugins settings $settings['plugins'] = implode(',', $configPlugins); // buttons foreach ($config->buttons as $i=>$buttons) { // $settings['theme_advanced_buttons'.$i] = implode(',', $buttons); // tinymce3 $settings['toolbar'.$i] = implode(',', $buttons); // tinymce4 } // languages $languages[] = $config->getOption('language'); // save this config settings $configs[$configID] = $settings; } // tinyMCE JS requirement if ( $useGzip ) { $tag = TinyMCE4_Compressor::renderTag(array( 'url' => TINYMCE4_DIR . '/thirdparty/tinymce/tiny_mce_gzip.php', 'plugins' => implode(',', $internalPlugins), 'themes' => 'advanced', 'languages' => implode(",", array_filter($languages)) ), true); preg_match('/src="([^"]*)"/', $tag, $matches); Requirements::javascript(html_entity_decode($matches[1])); } else{ Requirements::javascript(TINYMCE4_DIR . '/thirdparty/tinymce/jquery.tinymce.min.js'); } // block old scripts Requirements::block(MCE_ROOT . 'tiny_mce_src.js'); Requirements::block(FRAMEWORK_DIR ."/javascript/HtmlEditorField.js"); Requirements::block('htmlEditorConfig'); // load replacements Requirements::javascript(TINYMCE4_DIR ."/javascript/HtmlEditorField.js"); if(Member::currentUser()) { CustomHtmlEditorConfig::set_active(Member::currentUser()->getHtmlEditorConfigForCMS()); } // prepare external plugins js string $externalPlugins = array_values($externalPlugins); $externalPlugins = implode("\n ", $externalPlugins); // tinyMCE config object and external plugings $configsJS = " if((typeof tinyMCE != 'undefined')) { $externalPlugins var ssTinyMceConfig = " . Convert::raw2json($configs) . "; }"; Requirements::customScript($configsJS, 'customHtmlEditorConfig'); }
php
public static function require_js() { require_once TINYMCE4_PATH . '/thirdparty/tinymce/tiny_mce_gzip.php'; $useGzip = Config::inst()->get('CustomHtmlEditorField', 'use_gzip'); $configs = array(); $externalPlugins = array(); $internalPlugins = array(); $languages = array(); foreach (self::$configs as $configID => $config) { $settings = $config->settings; // parse plugins $configPlugins = array(); foreach($config->plugins as $plugin => $path) { if(!$path) { $configPlugins[] = $plugin; $internalPlugins[] = $plugin; } else { $configPlugins[] = '-' . $plugin; if ( !array_key_exists($plugin, $externalPlugins) ) { $externalPlugins[$plugin] = sprintf( 'tinymce.PluginManager.load("%s", "%s");', $plugin, $path ); } } } // save config plugins settings $settings['plugins'] = implode(',', $configPlugins); // buttons foreach ($config->buttons as $i=>$buttons) { // $settings['theme_advanced_buttons'.$i] = implode(',', $buttons); // tinymce3 $settings['toolbar'.$i] = implode(',', $buttons); // tinymce4 } // languages $languages[] = $config->getOption('language'); // save this config settings $configs[$configID] = $settings; } // tinyMCE JS requirement if ( $useGzip ) { $tag = TinyMCE4_Compressor::renderTag(array( 'url' => TINYMCE4_DIR . '/thirdparty/tinymce/tiny_mce_gzip.php', 'plugins' => implode(',', $internalPlugins), 'themes' => 'advanced', 'languages' => implode(",", array_filter($languages)) ), true); preg_match('/src="([^"]*)"/', $tag, $matches); Requirements::javascript(html_entity_decode($matches[1])); } else{ Requirements::javascript(TINYMCE4_DIR . '/thirdparty/tinymce/jquery.tinymce.min.js'); } // block old scripts Requirements::block(MCE_ROOT . 'tiny_mce_src.js'); Requirements::block(FRAMEWORK_DIR ."/javascript/HtmlEditorField.js"); Requirements::block('htmlEditorConfig'); // load replacements Requirements::javascript(TINYMCE4_DIR ."/javascript/HtmlEditorField.js"); if(Member::currentUser()) { CustomHtmlEditorConfig::set_active(Member::currentUser()->getHtmlEditorConfigForCMS()); } // prepare external plugins js string $externalPlugins = array_values($externalPlugins); $externalPlugins = implode("\n ", $externalPlugins); // tinyMCE config object and external plugings $configsJS = " if((typeof tinyMCE != 'undefined')) { $externalPlugins var ssTinyMceConfig = " . Convert::raw2json($configs) . "; }"; Requirements::customScript($configsJS, 'customHtmlEditorConfig'); }
[ "public", "static", "function", "require_js", "(", ")", "{", "require_once", "TINYMCE4_PATH", ".", "'/thirdparty/tinymce/tiny_mce_gzip.php'", ";", "$", "useGzip", "=", "Config", "::", "inst", "(", ")", "->", "get", "(", "'CustomHtmlEditorField'", ",", "'use_gzip'", ...
Generate the JavaScript that will set TinyMCE's configuration: - Parse all configurations into JSON objects to be used in JavaScript - Includes TinyMCE and configurations using the {@link Requirements} system
[ "Generate", "the", "JavaScript", "that", "will", "set", "TinyMCE", "s", "configuration", ":", "-", "Parse", "all", "configurations", "into", "JSON", "objects", "to", "be", "used", "in", "JavaScript", "-", "Includes", "TinyMCE", "and", "configurations", "using", ...
train
https://github.com/loyals-online/silverstripe-tinymce4/blob/c0603d074ebbb6b8a429f2d2856778e3643bba34/code/forms/CustomHtmlEditorConfig.php#L340-L425
makinacorpus/drupal-ucms
ucms_group/src/Form/GroupEdit.php
GroupEdit.buildForm
public function buildForm(array $form, FormStateInterface $form_state, Group $group = null) { $form['#form_horizontal'] = true; if (!$group) { $group = new Group(); } $form_state->setTemporaryValue('group', $group); $form['title'] = [ '#title' => $this->t("Name"), '#type' => 'textfield', '#default_value' => $group->getTitle(), '#attributes' => ['placeholder' => $this->t("Ouest union")], '#maxlength' => 255, '#required' => true, ]; $form['is_ghost'] = [ '#title' => $this->t("Content is invisible in global content"), '#type' => 'checkbox', '#default_value' => $group->isGhost(), '#description' => $this->t("This is only the default value for content, it may be changed on a per-content basis."), ]; $allThemeList = $this->siteManager->getDefaultAllowedThemesOptionList(); $form['allowed_themes'] = [ '#title' => $this->t("Allowed themes for group"), '#type' => 'checkboxes', '#options' => $allThemeList, '#default_value' => $group->getAttribute('allowed_themes', []), '#description' => $this->t("Check at least one theme here to restrict allowed themes for this group."), ]; $form['actions']['#type'] = 'actions'; $form['actions']['continue'] = [ '#type' => 'submit', '#value' => $this->t("Save"), ]; $form['actions']['cancel'] = [ '#markup' => l( $this->t("Cancel"), isset($_GET['destination']) ? $_GET['destination'] : 'admin/dashboard/group', ['attributes' => ['class' => ['btn', 'btn-danger']]] ), ]; return $form; }
php
public function buildForm(array $form, FormStateInterface $form_state, Group $group = null) { $form['#form_horizontal'] = true; if (!$group) { $group = new Group(); } $form_state->setTemporaryValue('group', $group); $form['title'] = [ '#title' => $this->t("Name"), '#type' => 'textfield', '#default_value' => $group->getTitle(), '#attributes' => ['placeholder' => $this->t("Ouest union")], '#maxlength' => 255, '#required' => true, ]; $form['is_ghost'] = [ '#title' => $this->t("Content is invisible in global content"), '#type' => 'checkbox', '#default_value' => $group->isGhost(), '#description' => $this->t("This is only the default value for content, it may be changed on a per-content basis."), ]; $allThemeList = $this->siteManager->getDefaultAllowedThemesOptionList(); $form['allowed_themes'] = [ '#title' => $this->t("Allowed themes for group"), '#type' => 'checkboxes', '#options' => $allThemeList, '#default_value' => $group->getAttribute('allowed_themes', []), '#description' => $this->t("Check at least one theme here to restrict allowed themes for this group."), ]; $form['actions']['#type'] = 'actions'; $form['actions']['continue'] = [ '#type' => 'submit', '#value' => $this->t("Save"), ]; $form['actions']['cancel'] = [ '#markup' => l( $this->t("Cancel"), isset($_GET['destination']) ? $_GET['destination'] : 'admin/dashboard/group', ['attributes' => ['class' => ['btn', 'btn-danger']]] ), ]; return $form; }
[ "public", "function", "buildForm", "(", "array", "$", "form", ",", "FormStateInterface", "$", "form_state", ",", "Group", "$", "group", "=", "null", ")", "{", "$", "form", "[", "'#form_horizontal'", "]", "=", "true", ";", "if", "(", "!", "$", "group", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_group/src/Form/GroupEdit.php#L48-L97
makinacorpus/drupal-ucms
ucms_group/src/Form/GroupEdit.php
GroupEdit.submitForm
public function submitForm(array &$form, FormStateInterface $form_state) { $group = &$form_state->getTemporaryValue('group'); $values = &$form_state->getValues(); /** @var $group Group */ $group->setTitle($values['title']); $group->setIsGhost($values['is_ghost']); foreach (['allowed_themes'] as $name) { $list = $form_state->getValue($name, []); $list = array_values(array_filter($list)); if ($list) { $group->setAttribute($name, $list); } else { $group->deleteAttribute($name); } } $isNew = !$group->getId(); $this->groupManager->save($group, ['title', 'is_ghost', 'attributes']); if ($isNew) { drupal_set_message($this->t("Group %title has been created", ['%title' => $group->getTitle()])); } else { drupal_set_message($this->t("Group %title has been updated", ['%title' => $group->getTitle()])); } $form_state->setRedirect('admin/dashboard/group/' . $group->getId()); }
php
public function submitForm(array &$form, FormStateInterface $form_state) { $group = &$form_state->getTemporaryValue('group'); $values = &$form_state->getValues(); /** @var $group Group */ $group->setTitle($values['title']); $group->setIsGhost($values['is_ghost']); foreach (['allowed_themes'] as $name) { $list = $form_state->getValue($name, []); $list = array_values(array_filter($list)); if ($list) { $group->setAttribute($name, $list); } else { $group->deleteAttribute($name); } } $isNew = !$group->getId(); $this->groupManager->save($group, ['title', 'is_ghost', 'attributes']); if ($isNew) { drupal_set_message($this->t("Group %title has been created", ['%title' => $group->getTitle()])); } else { drupal_set_message($this->t("Group %title has been updated", ['%title' => $group->getTitle()])); } $form_state->setRedirect('admin/dashboard/group/' . $group->getId()); }
[ "public", "function", "submitForm", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "$", "group", "=", "&", "$", "form_state", "->", "getTemporaryValue", "(", "'group'", ")", ";", "$", "values", "=", "&", "$", "for...
Step B form submit
[ "Step", "B", "form", "submit" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_group/src/Form/GroupEdit.php#L102-L131
artkonekt/gears
src/Backend/BackendFactory.php
BackendFactory.create
public static function create(string $driver) : Backend { if (strpos($driver, '\\') === false) { $class = __NAMESPACE__ . '\\Drivers\\' . studly_case($driver); } else { $class = $driver; } if (!class_exists($class)) { throw new \InvalidArgumentException( sprintf( 'Class `%s` does not exist, so it\'s far from being a good settings backend candidate', $class ) ); } return app()->make($class); }
php
public static function create(string $driver) : Backend { if (strpos($driver, '\\') === false) { $class = __NAMESPACE__ . '\\Drivers\\' . studly_case($driver); } else { $class = $driver; } if (!class_exists($class)) { throw new \InvalidArgumentException( sprintf( 'Class `%s` does not exist, so it\'s far from being a good settings backend candidate', $class ) ); } return app()->make($class); }
[ "public", "static", "function", "create", "(", "string", "$", "driver", ")", ":", "Backend", "{", "if", "(", "strpos", "(", "$", "driver", ",", "'\\\\'", ")", "===", "false", ")", "{", "$", "class", "=", "__NAMESPACE__", ".", "'\\\\Drivers\\\\'", ".", ...
Creates a new backend instance based on the passed driver @param string $driver Can be a short name for built in drivers eg. 'database' or a FQCN @return Backend
[ "Creates", "a", "new", "backend", "instance", "based", "on", "the", "passed", "driver" ]
train
https://github.com/artkonekt/gears/blob/6c006a3e8e334d8100aab768a2a5e807bcac5695/src/Backend/BackendFactory.php#L25-L43
makinacorpus/drupal-ucms
ucms_site/src/NodeManager.php
NodeManager.createReference
public function createReference(Site $site, NodeInterface $node) { $nodeId = $node->id(); $siteId = $site->getId(); $this ->db ->merge('ucms_site_node') ->key(['nid' => $nodeId, 'site_id' => $siteId]) ->execute() ; if (!in_array($siteId, $node->ucms_sites)) { $node->ucms_sites[] = $siteId; } $this->eventDispatcher->dispatch(NodeEvents::ACCESS_CHANGE, new ResourceEvent('node', [$nodeId])); $this->eventDispatcher->dispatch(SiteEvents::EVENT_ATTACH, new SiteAttachEvent($siteId, $nodeId)); }
php
public function createReference(Site $site, NodeInterface $node) { $nodeId = $node->id(); $siteId = $site->getId(); $this ->db ->merge('ucms_site_node') ->key(['nid' => $nodeId, 'site_id' => $siteId]) ->execute() ; if (!in_array($siteId, $node->ucms_sites)) { $node->ucms_sites[] = $siteId; } $this->eventDispatcher->dispatch(NodeEvents::ACCESS_CHANGE, new ResourceEvent('node', [$nodeId])); $this->eventDispatcher->dispatch(SiteEvents::EVENT_ATTACH, new SiteAttachEvent($siteId, $nodeId)); }
[ "public", "function", "createReference", "(", "Site", "$", "site", ",", "NodeInterface", "$", "node", ")", "{", "$", "nodeId", "=", "$", "node", "->", "id", "(", ")", ";", "$", "siteId", "=", "$", "site", "->", "getId", "(", ")", ";", "$", "this", ...
Reference node into a site @param Site $site @param NodeInterface $node
[ "Reference", "node", "into", "a", "site" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/NodeManager.php#L91-L109
makinacorpus/drupal-ucms
ucms_site/src/NodeManager.php
NodeManager.createReferenceBulkForNode
public function createReferenceBulkForNode($nodeId, $siteIdList) { // @todo Optimize me foreach ($siteIdList as $siteId) { $this ->db ->merge('ucms_site_node') ->key(['nid' => $nodeId, 'site_id' => $siteId]) ->execute() ; } $this ->entityManager ->getStorage('node') ->resetCache([$nodeId]) ; $this->eventDispatcher->dispatch(NodeEvents::ACCESS_CHANGE, new ResourceEvent('node', [$nodeId])); $this->eventDispatcher->dispatch(SiteEvents::EVENT_ATTACH, new SiteAttachEvent($siteIdList, $nodeId)); }
php
public function createReferenceBulkForNode($nodeId, $siteIdList) { // @todo Optimize me foreach ($siteIdList as $siteId) { $this ->db ->merge('ucms_site_node') ->key(['nid' => $nodeId, 'site_id' => $siteId]) ->execute() ; } $this ->entityManager ->getStorage('node') ->resetCache([$nodeId]) ; $this->eventDispatcher->dispatch(NodeEvents::ACCESS_CHANGE, new ResourceEvent('node', [$nodeId])); $this->eventDispatcher->dispatch(SiteEvents::EVENT_ATTACH, new SiteAttachEvent($siteIdList, $nodeId)); }
[ "public", "function", "createReferenceBulkForNode", "(", "$", "nodeId", ",", "$", "siteIdList", ")", "{", "// @todo Optimize me", "foreach", "(", "$", "siteIdList", "as", "$", "siteId", ")", "{", "$", "this", "->", "db", "->", "merge", "(", "'ucms_site_node'",...
Reference a single within multiple sites @param int $nodeId @param int[] $siteIdList
[ "Reference", "a", "single", "within", "multiple", "sites" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/NodeManager.php#L117-L137
makinacorpus/drupal-ucms
ucms_site/src/NodeManager.php
NodeManager.createReferenceBulkInSite
public function createReferenceBulkInSite($siteId, $nodeIdList) { // @todo Optimize me foreach ($nodeIdList as $nodeId) { $this ->db ->merge('ucms_site_node') ->key(['nid' => $nodeId, 'site_id' => $siteId]) ->execute() ; } $this ->entityManager ->getStorage('node') ->resetCache($nodeIdList) ; $this->eventDispatcher->dispatch(NodeEvents::ACCESS_CHANGE, new ResourceEvent('node', $nodeIdList)); $this->eventDispatcher->dispatch(SiteEvents::EVENT_ATTACH, new SiteAttachEvent($siteId, $nodeIdList)); }
php
public function createReferenceBulkInSite($siteId, $nodeIdList) { // @todo Optimize me foreach ($nodeIdList as $nodeId) { $this ->db ->merge('ucms_site_node') ->key(['nid' => $nodeId, 'site_id' => $siteId]) ->execute() ; } $this ->entityManager ->getStorage('node') ->resetCache($nodeIdList) ; $this->eventDispatcher->dispatch(NodeEvents::ACCESS_CHANGE, new ResourceEvent('node', $nodeIdList)); $this->eventDispatcher->dispatch(SiteEvents::EVENT_ATTACH, new SiteAttachEvent($siteId, $nodeIdList)); }
[ "public", "function", "createReferenceBulkInSite", "(", "$", "siteId", ",", "$", "nodeIdList", ")", "{", "// @todo Optimize me", "foreach", "(", "$", "nodeIdList", "as", "$", "nodeId", ")", "{", "$", "this", "->", "db", "->", "merge", "(", "'ucms_site_node'", ...
Reference multiple nodes within a single site @param int $siteId @param int[] $nodeIdList
[ "Reference", "multiple", "nodes", "within", "a", "single", "site" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/NodeManager.php#L145-L165
makinacorpus/drupal-ucms
ucms_site/src/NodeManager.php
NodeManager.createUnsavedClone
public function createUnsavedClone(NodeInterface $original, array $updates = []) { // This method, instead of the clone operator, will actually drop all // existing references and pointers and give you raw values. // All credits to https://stackoverflow.com/a/10831885/5826569 $node = unserialize(serialize($original)); $node->nid = null; $node->vid = null; $node->tnid = null; $node->log = null; $node->created = null; $node->changed = null; $node->path = null; $node->files = []; // Fills in the some default values. $node->status = 0; $node->promote = 0; $node->sticky = 0; $node->revision = 1; // Resets sites information. $node->site_id = null; $node->ucms_sites = []; // Sets the origin_id and parent_id. $node->parent_nid = $original->id(); $node->origin_nid = empty($original->origin_nid) ? $original->id() : $original->origin_nid; // Forces node indexing. $node->ucms_index_now = 1; // @todo find a better way // Sets the node's owner. if (isset($updates['uid'])) { $account = $this->entityManager->getStorage('user')->load($updates['uid']); $node->uid = $account->id(); $node->name = $account->getAccountName(); $node->revision_uid = $account->id(); unset($updates['uid']); } foreach ($updates as $key => $value) { $node->{$key} = $value; } return $node; }
php
public function createUnsavedClone(NodeInterface $original, array $updates = []) { // This method, instead of the clone operator, will actually drop all // existing references and pointers and give you raw values. // All credits to https://stackoverflow.com/a/10831885/5826569 $node = unserialize(serialize($original)); $node->nid = null; $node->vid = null; $node->tnid = null; $node->log = null; $node->created = null; $node->changed = null; $node->path = null; $node->files = []; // Fills in the some default values. $node->status = 0; $node->promote = 0; $node->sticky = 0; $node->revision = 1; // Resets sites information. $node->site_id = null; $node->ucms_sites = []; // Sets the origin_id and parent_id. $node->parent_nid = $original->id(); $node->origin_nid = empty($original->origin_nid) ? $original->id() : $original->origin_nid; // Forces node indexing. $node->ucms_index_now = 1; // @todo find a better way // Sets the node's owner. if (isset($updates['uid'])) { $account = $this->entityManager->getStorage('user')->load($updates['uid']); $node->uid = $account->id(); $node->name = $account->getAccountName(); $node->revision_uid = $account->id(); unset($updates['uid']); } foreach ($updates as $key => $value) { $node->{$key} = $value; } return $node; }
[ "public", "function", "createUnsavedClone", "(", "NodeInterface", "$", "original", ",", "array", "$", "updates", "=", "[", "]", ")", "{", "// This method, instead of the clone operator, will actually drop all", "// existing references and pointers and give you raw values.", "// A...
Create unsaved node clone @param NodeInterface $original Original node to clone @param array $updates Any fields that will replace properties on the new node object, set the 'uid' property as user identifier @return NodeInterface Unsaved clone
[ "Create", "unsaved", "node", "clone" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/NodeManager.php#L179-L222
makinacorpus/drupal-ucms
ucms_site/src/NodeManager.php
NodeManager.createAndSaveClone
public function createAndSaveClone(NodeInterface $original, array $updates = []) { $clone = $this->createUnsavedClone($original, $updates); $this->entityManager->getStorage('node')->save($clone); return $clone; }
php
public function createAndSaveClone(NodeInterface $original, array $updates = []) { $clone = $this->createUnsavedClone($original, $updates); $this->entityManager->getStorage('node')->save($clone); return $clone; }
[ "public", "function", "createAndSaveClone", "(", "NodeInterface", "$", "original", ",", "array", "$", "updates", "=", "[", "]", ")", "{", "$", "clone", "=", "$", "this", "->", "createUnsavedClone", "(", "$", "original", ",", "$", "updates", ")", ";", "$"...
Clone the given node @param NodeInterface $original Original node to clone @param array $updates Any fields that will replace properties on the new node object, set the 'uid' property as user identifier @return NodeInterface New duplicated node, it has already been saved, to update values use the $updates parameter
[ "Clone", "the", "given", "node" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/NodeManager.php#L237-L243
makinacorpus/drupal-ucms
ucms_site/src/NodeManager.php
NodeManager.deleteReferenceBulkFromSite
public function deleteReferenceBulkFromSite($siteId, $nodeIdList) { if (!$nodeIdList) { return; } $this ->db ->delete('ucms_site_node') ->condition('nid', $nodeIdList) ->condition('site_id', $siteId) ->execute() ; $this ->entityManager ->getStorage('node') ->resetCache($nodeIdList) ; $this->eventDispatcher->dispatch(NodeEvents::ACCESS_CHANGE, new ResourceEvent('node', $nodeIdList)); $this->eventDispatcher->dispatch(SiteEvents::EVENT_DETACH, new SiteAttachEvent($siteId, $nodeIdList)); }
php
public function deleteReferenceBulkFromSite($siteId, $nodeIdList) { if (!$nodeIdList) { return; } $this ->db ->delete('ucms_site_node') ->condition('nid', $nodeIdList) ->condition('site_id', $siteId) ->execute() ; $this ->entityManager ->getStorage('node') ->resetCache($nodeIdList) ; $this->eventDispatcher->dispatch(NodeEvents::ACCESS_CHANGE, new ResourceEvent('node', $nodeIdList)); $this->eventDispatcher->dispatch(SiteEvents::EVENT_DETACH, new SiteAttachEvent($siteId, $nodeIdList)); }
[ "public", "function", "deleteReferenceBulkFromSite", "(", "$", "siteId", ",", "$", "nodeIdList", ")", "{", "if", "(", "!", "$", "nodeIdList", ")", "{", "return", ";", "}", "$", "this", "->", "db", "->", "delete", "(", "'ucms_site_node'", ")", "->", "cond...
Unreference node for a site @param int $siteId @param int[] $nodeIdList
[ "Unreference", "node", "for", "a", "site" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/NodeManager.php#L251-L273
makinacorpus/drupal-ucms
ucms_site/src/NodeManager.php
NodeManager.findSiteCandidatesForReference
public function findSiteCandidatesForReference(NodeInterface $node, $userId) { $ne = $this ->db ->select('ucms_site_node', 'sn') ->where("sn.site_id = sa.site_id") ->condition('sn.nid', $node->id()) ; $ne->addExpression('1'); $idList = $this ->db ->select('ucms_site_access', 'sa') ->fields('sa', ['site_id']) ->condition('sa.uid', $userId) ->notExists($ne) ->groupBy('sa.site_id') ->execute() ->fetchCol() ; return $this->manager->getStorage()->loadAll($idList); }
php
public function findSiteCandidatesForReference(NodeInterface $node, $userId) { $ne = $this ->db ->select('ucms_site_node', 'sn') ->where("sn.site_id = sa.site_id") ->condition('sn.nid', $node->id()) ; $ne->addExpression('1'); $idList = $this ->db ->select('ucms_site_access', 'sa') ->fields('sa', ['site_id']) ->condition('sa.uid', $userId) ->notExists($ne) ->groupBy('sa.site_id') ->execute() ->fetchCol() ; return $this->manager->getStorage()->loadAll($idList); }
[ "public", "function", "findSiteCandidatesForReference", "(", "NodeInterface", "$", "node", ",", "$", "userId", ")", "{", "$", "ne", "=", "$", "this", "->", "db", "->", "select", "(", "'ucms_site_node'", ",", "'sn'", ")", "->", "where", "(", "\"sn.site_id = s...
Find candidate sites for referencing this node @param NodeInterface $node @param int $userId @return Site[]
[ "Find", "candidate", "sites", "for", "referencing", "this", "node" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/NodeManager.php#L283-L305
makinacorpus/drupal-ucms
ucms_site/src/NodeManager.php
NodeManager.findSiteCandidatesForCloning
public function findSiteCandidatesForCloning(NodeInterface $node, $userId) { /* * The right and only working query for this. * SELECT DISTINCT(sa.site_id) FROM ucms_site_access sa JOIN ucms_site_node sn ON sn.site_id = sa.site_id WHERE sa.uid = 13 -- current user AND sn. AND sa.role = 1 -- webmaster AND sa.site_id <> 2 -- node current site AND NOT EXISTS ( SELECT 1 FROM node en WHERE en.site_id = sa.site_id AND ( en.parent_nid = 6 -- node we are looking for OR nid = 6 ) ) ; */ $sq = $this ->db ->select('node', 'en') ->where('en.site_id = sa.site_id') ->where('en.parent_nid = :nid1 OR nid = :nid2', [':nid1' => $node->id(), ':nid2' => $node->id()]) ; $sq->addExpression('1'); $q = $this ->db ->select('ucms_site_access', 'sa') ->fields('sa', ['site_id']) ->condition('sa.uid', $userId) ->condition('sa.role', Access::ROLE_WEBMASTER) ; $q->join('ucms_site_node', 'sn', 'sn.site_id = sa.site_id'); $q->condition('sn.nid', $node->id()); // The node might not be attached to any site if it is a global content if ($node->site_id) { $q->condition('sa.site_id', $node->site_id, '<>'); } $idList = $q ->notExists($sq) ->addTag('ucms_site_access') ->execute() ->fetchCol() ; return $this->manager->getStorage()->loadAll($idList); }
php
public function findSiteCandidatesForCloning(NodeInterface $node, $userId) { /* * The right and only working query for this. * SELECT DISTINCT(sa.site_id) FROM ucms_site_access sa JOIN ucms_site_node sn ON sn.site_id = sa.site_id WHERE sa.uid = 13 -- current user AND sn. AND sa.role = 1 -- webmaster AND sa.site_id <> 2 -- node current site AND NOT EXISTS ( SELECT 1 FROM node en WHERE en.site_id = sa.site_id AND ( en.parent_nid = 6 -- node we are looking for OR nid = 6 ) ) ; */ $sq = $this ->db ->select('node', 'en') ->where('en.site_id = sa.site_id') ->where('en.parent_nid = :nid1 OR nid = :nid2', [':nid1' => $node->id(), ':nid2' => $node->id()]) ; $sq->addExpression('1'); $q = $this ->db ->select('ucms_site_access', 'sa') ->fields('sa', ['site_id']) ->condition('sa.uid', $userId) ->condition('sa.role', Access::ROLE_WEBMASTER) ; $q->join('ucms_site_node', 'sn', 'sn.site_id = sa.site_id'); $q->condition('sn.nid', $node->id()); // The node might not be attached to any site if it is a global content if ($node->site_id) { $q->condition('sa.site_id', $node->site_id, '<>'); } $idList = $q ->notExists($sq) ->addTag('ucms_site_access') ->execute() ->fetchCol() ; return $this->manager->getStorage()->loadAll($idList); }
[ "public", "function", "findSiteCandidatesForCloning", "(", "NodeInterface", "$", "node", ",", "$", "userId", ")", "{", "/*\n * The right and only working query for this.\n *\n SELECT DISTINCT(sa.site_id)\n FROM ucms_site_access sa\n JOIN ucms_...
Find candidate sites for cloning this node @param NodeInterface $node @param int $userId @return Site[]
[ "Find", "candidate", "sites", "for", "cloning", "this", "node" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/NodeManager.php#L315-L374
makinacorpus/drupal-ucms
ucms_site/src/NodeManager.php
NodeManager.getCloningMapping
public function getCloningMapping(Site $site) { if (isset($this->cloningMapping[$site->getId()])) { return $this->cloningMapping[$site->getId()]; } $q = $this->db ->select('node', 'n') ->fields('n', ['parent_nid', 'nid']) ->isNotNull('parent_nid') ->condition('site_id', $site->id) ->condition('status', NODE_PUBLISHED) ->orderBy('created', 'ASC') ; $mapping = []; foreach ($q->execute()->fetchAll() as $row) { if (isset($mapping[(int) $row->parent_nid])) { continue; } $mapping[(int) $row->parent_nid] = (int) $row->nid; } $this->cloningMapping[$site->getId()] = $mapping; return $mapping; }
php
public function getCloningMapping(Site $site) { if (isset($this->cloningMapping[$site->getId()])) { return $this->cloningMapping[$site->getId()]; } $q = $this->db ->select('node', 'n') ->fields('n', ['parent_nid', 'nid']) ->isNotNull('parent_nid') ->condition('site_id', $site->id) ->condition('status', NODE_PUBLISHED) ->orderBy('created', 'ASC') ; $mapping = []; foreach ($q->execute()->fetchAll() as $row) { if (isset($mapping[(int) $row->parent_nid])) { continue; } $mapping[(int) $row->parent_nid] = (int) $row->nid; } $this->cloningMapping[$site->getId()] = $mapping; return $mapping; }
[ "public", "function", "getCloningMapping", "(", "Site", "$", "site", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "cloningMapping", "[", "$", "site", "->", "getId", "(", ")", "]", ")", ")", "{", "return", "$", "this", "->", "cloningMapping", ...
Provides a mapping array of parent identifiers to clone identifiers. If there is several clones for a same parent, the first created will be passed. @param Site $site @return integer[]
[ "Provides", "a", "mapping", "array", "of", "parent", "identifiers", "to", "clone", "identifiers", "." ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/NodeManager.php#L386-L413
platformsh/console-form
src/Field/BooleanField.php
BooleanField.normalize
protected function normalize($value) { if (is_bool($value)) { return $value; } elseif (preg_match('/^(0|false|no|n)$/i', $value)) { return false; } elseif (preg_match('/^(1|true|yes|y)$/i', $value)) { return true; } else { throw new InvalidValueException(sprintf( "Invalid value for '%s': %s (expected 1, 0, true, or false)", $this->name, $value )); } }
php
protected function normalize($value) { if (is_bool($value)) { return $value; } elseif (preg_match('/^(0|false|no|n)$/i', $value)) { return false; } elseif (preg_match('/^(1|true|yes|y)$/i', $value)) { return true; } else { throw new InvalidValueException(sprintf( "Invalid value for '%s': %s (expected 1, 0, true, or false)", $this->name, $value )); } }
[ "protected", "function", "normalize", "(", "$", "value", ")", "{", "if", "(", "is_bool", "(", "$", "value", ")", ")", "{", "return", "$", "value", ";", "}", "elseif", "(", "preg_match", "(", "'/^(0|false|no|n)$/i'", ",", "$", "value", ")", ")", "{", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/platformsh/console-form/blob/5263fe8c6c976e10f4495c9e00c92cc2d410a673/src/Field/BooleanField.php#L38-L56
tck/zf-imageresizer
src/TckImageResizer/Service/ImageProcessing.php
ImageProcessing.process
public function process($source, $target, $commands) { $targetFolder = pathinfo($target, PATHINFO_DIRNAME); if (!file_exists($targetFolder)) { mkdir($targetFolder, 0777, true); } $this->image = $this->getImagineService()->open($source); foreach ($this->analyseCommands($commands) as $command) { if ($this->runCommand($command)) { continue; } $this->runCustomCommand($command); } $this->image->save($target); }
php
public function process($source, $target, $commands) { $targetFolder = pathinfo($target, PATHINFO_DIRNAME); if (!file_exists($targetFolder)) { mkdir($targetFolder, 0777, true); } $this->image = $this->getImagineService()->open($source); foreach ($this->analyseCommands($commands) as $command) { if ($this->runCommand($command)) { continue; } $this->runCustomCommand($command); } $this->image->save($target); }
[ "public", "function", "process", "(", "$", "source", ",", "$", "target", ",", "$", "commands", ")", "{", "$", "targetFolder", "=", "pathinfo", "(", "$", "target", ",", "PATHINFO_DIRNAME", ")", ";", "if", "(", "!", "file_exists", "(", "$", "targetFolder",...
Process command to image source and save to target @param string $source @param string $target @param string $commands @return void
[ "Process", "command", "to", "image", "source", "and", "save", "to", "target" ]
train
https://github.com/tck/zf-imageresizer/blob/7461f588bbf12cbf9544a68778541d052b68fd07/src/TckImageResizer/Service/ImageProcessing.php#L82-L97
tck/zf-imageresizer
src/TckImageResizer/Service/ImageProcessing.php
ImageProcessing.process404
public function process404($target, $commands) { if (file_exists($target)) { return; } $targetFolder = pathinfo($target, PATHINFO_DIRNAME); if (!file_exists($targetFolder)) { mkdir($targetFolder, 0777, true); } $text = 'Not found'; $backgroundColor = null; $color = null; $width = null; $height = null; foreach ($this->analyseCommands($commands) as $command) { if ('thumb' === $command['command'] || 'resize' === $command['command']) { $width = $command['params'][0]; $height = $command['params'][1]; } elseif ('404' === $command['command']) { if (isset($command['params'][0]) && UrlSafeBase64::valid($command['params'][0])) { $text = UrlSafeBase64::decode($command['params'][0]); } if (isset($command['params'][1])) { $backgroundColor = $command['params'][1]; } if (isset($command['params'][2])) { $color = $command['params'][2]; } if (isset($command['params'][3])) { $width = $command['params'][3]; } if (isset($command['params'][4])) { $height = $command['params'][4]; } } } $this->image404($text, $backgroundColor, $color, $width, $height); $this->image->save($target); }
php
public function process404($target, $commands) { if (file_exists($target)) { return; } $targetFolder = pathinfo($target, PATHINFO_DIRNAME); if (!file_exists($targetFolder)) { mkdir($targetFolder, 0777, true); } $text = 'Not found'; $backgroundColor = null; $color = null; $width = null; $height = null; foreach ($this->analyseCommands($commands) as $command) { if ('thumb' === $command['command'] || 'resize' === $command['command']) { $width = $command['params'][0]; $height = $command['params'][1]; } elseif ('404' === $command['command']) { if (isset($command['params'][0]) && UrlSafeBase64::valid($command['params'][0])) { $text = UrlSafeBase64::decode($command['params'][0]); } if (isset($command['params'][1])) { $backgroundColor = $command['params'][1]; } if (isset($command['params'][2])) { $color = $command['params'][2]; } if (isset($command['params'][3])) { $width = $command['params'][3]; } if (isset($command['params'][4])) { $height = $command['params'][4]; } } } $this->image404($text, $backgroundColor, $color, $width, $height); $this->image->save($target); }
[ "public", "function", "process404", "(", "$", "target", ",", "$", "commands", ")", "{", "if", "(", "file_exists", "(", "$", "target", ")", ")", "{", "return", ";", "}", "$", "targetFolder", "=", "pathinfo", "(", "$", "target", ",", "PATHINFO_DIRNAME", ...
Process command to create 404 image and save to target @param string $target @param string $commands @return void
[ "Process", "command", "to", "create", "404", "image", "and", "save", "to", "target" ]
train
https://github.com/tck/zf-imageresizer/blob/7461f588bbf12cbf9544a68778541d052b68fd07/src/TckImageResizer/Service/ImageProcessing.php#L107-L149
tck/zf-imageresizer
src/TckImageResizer/Service/ImageProcessing.php
ImageProcessing.analyseCommands
protected function analyseCommands($commands) { $commandList = []; foreach (explode('$', $commands) as $commandLine) { $params = explode(',', $commandLine); $command = array_shift($params); $commandList[] = [ 'command' => $command, 'params' => $params, ]; } return $commandList; }
php
protected function analyseCommands($commands) { $commandList = []; foreach (explode('$', $commands) as $commandLine) { $params = explode(',', $commandLine); $command = array_shift($params); $commandList[] = [ 'command' => $command, 'params' => $params, ]; } return $commandList; }
[ "protected", "function", "analyseCommands", "(", "$", "commands", ")", "{", "$", "commandList", "=", "[", "]", ";", "foreach", "(", "explode", "(", "'$'", ",", "$", "commands", ")", "as", "$", "commandLine", ")", "{", "$", "params", "=", "explode", "("...
Analyse commands string and returns array with command/params keys @param string $commands @return array
[ "Analyse", "commands", "string", "and", "returns", "array", "with", "command", "/", "params", "keys" ]
train
https://github.com/tck/zf-imageresizer/blob/7461f588bbf12cbf9544a68778541d052b68fd07/src/TckImageResizer/Service/ImageProcessing.php#L158-L170
tck/zf-imageresizer
src/TckImageResizer/Service/ImageProcessing.php
ImageProcessing.runCommand
protected function runCommand($command) { $method = 'image' . ucfirst(strtolower($command['command'])); if (!method_exists($this, $method)) { return false; } call_user_func_array([$this, $method], $command['params']); return true; }
php
protected function runCommand($command) { $method = 'image' . ucfirst(strtolower($command['command'])); if (!method_exists($this, $method)) { return false; } call_user_func_array([$this, $method], $command['params']); return true; }
[ "protected", "function", "runCommand", "(", "$", "command", ")", "{", "$", "method", "=", "'image'", ".", "ucfirst", "(", "strtolower", "(", "$", "command", "[", "'command'", "]", ")", ")", ";", "if", "(", "!", "method_exists", "(", "$", "this", ",", ...
Run command if exists @param array $command @return boolean
[ "Run", "command", "if", "exists" ]
train
https://github.com/tck/zf-imageresizer/blob/7461f588bbf12cbf9544a68778541d052b68fd07/src/TckImageResizer/Service/ImageProcessing.php#L179-L188
tck/zf-imageresizer
src/TckImageResizer/Service/ImageProcessing.php
ImageProcessing.runCustomCommand
protected function runCustomCommand($command) { if (!CommandRegistry::hasCommand($command['command'])) { throw new BadMethodCallException('Command "' . $command['command'] . '" not found'); } $customCommand = CommandRegistry::getCommand($command['command']); array_unshift($command['params'], $this->image); call_user_func_array($customCommand, $command['params']); return true; }
php
protected function runCustomCommand($command) { if (!CommandRegistry::hasCommand($command['command'])) { throw new BadMethodCallException('Command "' . $command['command'] . '" not found'); } $customCommand = CommandRegistry::getCommand($command['command']); array_unshift($command['params'], $this->image); call_user_func_array($customCommand, $command['params']); return true; }
[ "protected", "function", "runCustomCommand", "(", "$", "command", ")", "{", "if", "(", "!", "CommandRegistry", "::", "hasCommand", "(", "$", "command", "[", "'command'", "]", ")", ")", "{", "throw", "new", "BadMethodCallException", "(", "'Command \"'", ".", ...
Run custom command if exists @param array $command @return boolean
[ "Run", "custom", "command", "if", "exists" ]
train
https://github.com/tck/zf-imageresizer/blob/7461f588bbf12cbf9544a68778541d052b68fd07/src/TckImageResizer/Service/ImageProcessing.php#L197-L208
tck/zf-imageresizer
src/TckImageResizer/Service/ImageProcessing.php
ImageProcessing.imageThumb
protected function imageThumb($width, $height) { $width = (int) $width; $height = (int) $height; if ($width <= 0) { throw new BadMethodCallException('Invalid parameter width for command "thumb"'); } if ($height <= 0) { throw new BadMethodCallException('Invalid parameter height for command "thumb"'); } $this->image = $this->image->thumbnail(new Box($width, $height)); }
php
protected function imageThumb($width, $height) { $width = (int) $width; $height = (int) $height; if ($width <= 0) { throw new BadMethodCallException('Invalid parameter width for command "thumb"'); } if ($height <= 0) { throw new BadMethodCallException('Invalid parameter height for command "thumb"'); } $this->image = $this->image->thumbnail(new Box($width, $height)); }
[ "protected", "function", "imageThumb", "(", "$", "width", ",", "$", "height", ")", "{", "$", "width", "=", "(", "int", ")", "$", "width", ";", "$", "height", "=", "(", "int", ")", "$", "height", ";", "if", "(", "$", "width", "<=", "0", ")", "{"...
Command image thumb @param int $width @param int $height @return void
[ "Command", "image", "thumb" ]
train
https://github.com/tck/zf-imageresizer/blob/7461f588bbf12cbf9544a68778541d052b68fd07/src/TckImageResizer/Service/ImageProcessing.php#L218-L229
tck/zf-imageresizer
src/TckImageResizer/Service/ImageProcessing.php
ImageProcessing.imageResize
protected function imageResize($width, $height) { $width = (int) $width; $height = (int) $height; if ($width <= 0) { throw new BadMethodCallException('Invalid parameter width for command "resize"'); } if ($height <= 0) { throw new BadMethodCallException('Invalid parameter height for command "resize"'); } $this->image->resize(new Box($width, $height)); }
php
protected function imageResize($width, $height) { $width = (int) $width; $height = (int) $height; if ($width <= 0) { throw new BadMethodCallException('Invalid parameter width for command "resize"'); } if ($height <= 0) { throw new BadMethodCallException('Invalid parameter height for command "resize"'); } $this->image->resize(new Box($width, $height)); }
[ "protected", "function", "imageResize", "(", "$", "width", ",", "$", "height", ")", "{", "$", "width", "=", "(", "int", ")", "$", "width", ";", "$", "height", "=", "(", "int", ")", "$", "height", ";", "if", "(", "$", "width", "<=", "0", ")", "{...
Command image resize @param int $width @param int $height @return void
[ "Command", "image", "resize" ]
train
https://github.com/tck/zf-imageresizer/blob/7461f588bbf12cbf9544a68778541d052b68fd07/src/TckImageResizer/Service/ImageProcessing.php#L239-L250
tck/zf-imageresizer
src/TckImageResizer/Service/ImageProcessing.php
ImageProcessing.imageGamma
protected function imageGamma($correction) { $correction = (float) $correction; $this->image->effects()->gamma($correction); }
php
protected function imageGamma($correction) { $correction = (float) $correction; $this->image->effects()->gamma($correction); }
[ "protected", "function", "imageGamma", "(", "$", "correction", ")", "{", "$", "correction", "=", "(", "float", ")", "$", "correction", ";", "$", "this", "->", "image", "->", "effects", "(", ")", "->", "gamma", "(", "$", "correction", ")", ";", "}" ]
Command image gamma @param float $correction @return void
[ "Command", "image", "gamma" ]
train
https://github.com/tck/zf-imageresizer/blob/7461f588bbf12cbf9544a68778541d052b68fd07/src/TckImageResizer/Service/ImageProcessing.php#L279-L284
tck/zf-imageresizer
src/TckImageResizer/Service/ImageProcessing.php
ImageProcessing.imageColorize
protected function imageColorize($hexColor) { if (strlen($hexColor) != 6 || !preg_match('![0-9abcdef]!i', $hexColor)) { throw new BadMethodCallException('Invalid parameter color for command "colorize"'); } $color = $this->image->palette()->color('#' . $hexColor); $this->image->effects()->colorize($color); }
php
protected function imageColorize($hexColor) { if (strlen($hexColor) != 6 || !preg_match('![0-9abcdef]!i', $hexColor)) { throw new BadMethodCallException('Invalid parameter color for command "colorize"'); } $color = $this->image->palette()->color('#' . $hexColor); $this->image->effects()->colorize($color); }
[ "protected", "function", "imageColorize", "(", "$", "hexColor", ")", "{", "if", "(", "strlen", "(", "$", "hexColor", ")", "!=", "6", "||", "!", "preg_match", "(", "'![0-9abcdef]!i'", ",", "$", "hexColor", ")", ")", "{", "throw", "new", "BadMethodCallExcept...
Command image colorize @param string $hexColor @return void
[ "Command", "image", "colorize" ]
train
https://github.com/tck/zf-imageresizer/blob/7461f588bbf12cbf9544a68778541d052b68fd07/src/TckImageResizer/Service/ImageProcessing.php#L293-L301
tck/zf-imageresizer
src/TckImageResizer/Service/ImageProcessing.php
ImageProcessing.imageBlur
protected function imageBlur($sigma = 1) { $sigma = (float) $sigma; $this->image->effects()->blur($sigma); }
php
protected function imageBlur($sigma = 1) { $sigma = (float) $sigma; $this->image->effects()->blur($sigma); }
[ "protected", "function", "imageBlur", "(", "$", "sigma", "=", "1", ")", "{", "$", "sigma", "=", "(", "float", ")", "$", "sigma", ";", "$", "this", "->", "image", "->", "effects", "(", ")", "->", "blur", "(", "$", "sigma", ")", ";", "}" ]
Command image blur @param float $sigma @return void
[ "Command", "image", "blur" ]
train
https://github.com/tck/zf-imageresizer/blob/7461f588bbf12cbf9544a68778541d052b68fd07/src/TckImageResizer/Service/ImageProcessing.php#L320-L325
tck/zf-imageresizer
src/TckImageResizer/Service/ImageProcessing.php
ImageProcessing.image404
protected function image404($text, $backgroundColor, $color, $width, $height) { $text = (string) $text; $backgroundColor = (string) $backgroundColor; $color = (string) $color; $width = (int) $width; $height = (int) $height; if (strlen($backgroundColor) != 6 || !preg_match('![0-9abcdef]!i', $backgroundColor)) { $backgroundColor = 'F8F8F8'; } if (strlen($color) != 6 || !preg_match('![0-9abcdef]!i', $color)) { $color = '777777'; } if ($width <= 0) { $width = 100; } if ($height <= 0) { $height = 100; } $palette = new RGB(); $size = new Box($width, $height); $this->image = $this->getImagineService()->create($size, $palette->color('#' . $backgroundColor, 0)); if ($text) { $this->drawCenteredText($text, $color); } }
php
protected function image404($text, $backgroundColor, $color, $width, $height) { $text = (string) $text; $backgroundColor = (string) $backgroundColor; $color = (string) $color; $width = (int) $width; $height = (int) $height; if (strlen($backgroundColor) != 6 || !preg_match('![0-9abcdef]!i', $backgroundColor)) { $backgroundColor = 'F8F8F8'; } if (strlen($color) != 6 || !preg_match('![0-9abcdef]!i', $color)) { $color = '777777'; } if ($width <= 0) { $width = 100; } if ($height <= 0) { $height = 100; } $palette = new RGB(); $size = new Box($width, $height); $this->image = $this->getImagineService()->create($size, $palette->color('#' . $backgroundColor, 0)); if ($text) { $this->drawCenteredText($text, $color); } }
[ "protected", "function", "image404", "(", "$", "text", ",", "$", "backgroundColor", ",", "$", "color", ",", "$", "width", ",", "$", "height", ")", "{", "$", "text", "=", "(", "string", ")", "$", "text", ";", "$", "backgroundColor", "=", "(", "string"...
Command image resize @param string $text @param string $backgroundColor @param string $color @param int $width @param int $height @return void
[ "Command", "image", "resize" ]
train
https://github.com/tck/zf-imageresizer/blob/7461f588bbf12cbf9544a68778541d052b68fd07/src/TckImageResizer/Service/ImageProcessing.php#L347-L375
tck/zf-imageresizer
src/TckImageResizer/Service/ImageProcessing.php
ImageProcessing.drawCenteredText
protected function drawCenteredText($text, $color) { $width = $this->image->getSize()->getWidth(); $height = $this->image->getSize()->getHeight(); $fontColor = $this->image->palette()->color('#' . $color); $fontSize = 48; $widthFactor = $width > 160 ? 0.8 : 0.9; $heightFactor = $height > 160 ? 0.8 : 0.9; do { $font = $this->getImagineService() ->font(__DIR__ . '/../../../data/font/Roboto-Regular.ttf', $fontSize, $fontColor); $fontBox = $font->box($text); $fontSize = round($fontSize * 0.8); } while ($fontSize > 5 && ($width * $widthFactor < $fontBox->getWidth() || $height * $heightFactor < $fontBox->getHeight())); $pointX = max(0, floor(($width - $fontBox->getWidth()) / 2)); $pointY = max(0, floor(($height - $fontBox->getHeight()) / 2)); $this->image->draw()->text($text, $font, new Point($pointX, $pointY)); }
php
protected function drawCenteredText($text, $color) { $width = $this->image->getSize()->getWidth(); $height = $this->image->getSize()->getHeight(); $fontColor = $this->image->palette()->color('#' . $color); $fontSize = 48; $widthFactor = $width > 160 ? 0.8 : 0.9; $heightFactor = $height > 160 ? 0.8 : 0.9; do { $font = $this->getImagineService() ->font(__DIR__ . '/../../../data/font/Roboto-Regular.ttf', $fontSize, $fontColor); $fontBox = $font->box($text); $fontSize = round($fontSize * 0.8); } while ($fontSize > 5 && ($width * $widthFactor < $fontBox->getWidth() || $height * $heightFactor < $fontBox->getHeight())); $pointX = max(0, floor(($width - $fontBox->getWidth()) / 2)); $pointY = max(0, floor(($height - $fontBox->getHeight()) / 2)); $this->image->draw()->text($text, $font, new Point($pointX, $pointY)); }
[ "protected", "function", "drawCenteredText", "(", "$", "text", ",", "$", "color", ")", "{", "$", "width", "=", "$", "this", "->", "image", "->", "getSize", "(", ")", "->", "getWidth", "(", ")", ";", "$", "height", "=", "$", "this", "->", "image", "...
Draw centered text in current image @param string $text @param string $color @return void
[ "Draw", "centered", "text", "in", "current", "image" ]
train
https://github.com/tck/zf-imageresizer/blob/7461f588bbf12cbf9544a68778541d052b68fd07/src/TckImageResizer/Service/ImageProcessing.php#L385-L406
runcmf/runbb
src/RunBB/Model/Admin/Plugins.php
Plugins.deactivate
public function deactivate($name) { $name = Container::get('hooks')->fire('model.plugin.deactivate.name', $name); $activePlugins = $this->manager->getActivePlugins(); // Check if plugin is actually activated if (($k = array_search($name, $activePlugins)) !== false) { $plugin = DB::forTable('plugins')->where('name', $name)->find_one(); if (!$plugin) { $plugin = DB::forTable('plugins')->create()->set('name', $name); } $plugin->set('active', 0); // Allow additionnal deactivate functions $this->manager->deactivate($name); $plugin = Container::get('hooks')->fireDB('model.plugin.deactivate', $plugin); $plugin->save(); $this->manager->setActivePlugins(); return $plugin; } return true; }
php
public function deactivate($name) { $name = Container::get('hooks')->fire('model.plugin.deactivate.name', $name); $activePlugins = $this->manager->getActivePlugins(); // Check if plugin is actually activated if (($k = array_search($name, $activePlugins)) !== false) { $plugin = DB::forTable('plugins')->where('name', $name)->find_one(); if (!$plugin) { $plugin = DB::forTable('plugins')->create()->set('name', $name); } $plugin->set('active', 0); // Allow additionnal deactivate functions $this->manager->deactivate($name); $plugin = Container::get('hooks')->fireDB('model.plugin.deactivate', $plugin); $plugin->save(); $this->manager->setActivePlugins(); return $plugin; } return true; }
[ "public", "function", "deactivate", "(", "$", "name", ")", "{", "$", "name", "=", "Container", "::", "get", "(", "'hooks'", ")", "->", "fire", "(", "'model.plugin.deactivate.name'", ",", "$", "name", ")", ";", "$", "activePlugins", "=", "$", "this", "->"...
Deactivate a plugin
[ "Deactivate", "a", "plugin" ]
train
https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Model/Admin/Plugins.php#L99-L123
runcmf/runbb
src/RunBB/Model/Admin/Plugins.php
Plugins.uninstall
public function uninstall($name) { $name = Container::get('hooks')->fire('model.plugin.uninstall.name', $name); $activePlugins = $this->manager->getActivePlugins(); // Check if plugin is disabled, for security if (!in_array($name, $activePlugins)) { $plugin = DB::forTable('plugins')->where('name', $name)->find_one(); if ($plugin) { $plugin->delete(); } // Allow additional uninstalling functions $this->manager->uninstall($name); if (file_exists(ForumEnv::get('FORUM_ROOT').'plugins'.DIRECTORY_SEPARATOR.$name)) { AdminUtils::deleteFolder(ForumEnv::get('FORUM_ROOT').'plugins'.DIRECTORY_SEPARATOR.$name); } $this->manager->setActivePlugins(); } return true; }
php
public function uninstall($name) { $name = Container::get('hooks')->fire('model.plugin.uninstall.name', $name); $activePlugins = $this->manager->getActivePlugins(); // Check if plugin is disabled, for security if (!in_array($name, $activePlugins)) { $plugin = DB::forTable('plugins')->where('name', $name)->find_one(); if ($plugin) { $plugin->delete(); } // Allow additional uninstalling functions $this->manager->uninstall($name); if (file_exists(ForumEnv::get('FORUM_ROOT').'plugins'.DIRECTORY_SEPARATOR.$name)) { AdminUtils::deleteFolder(ForumEnv::get('FORUM_ROOT').'plugins'.DIRECTORY_SEPARATOR.$name); } $this->manager->setActivePlugins(); } return true; }
[ "public", "function", "uninstall", "(", "$", "name", ")", "{", "$", "name", "=", "Container", "::", "get", "(", "'hooks'", ")", "->", "fire", "(", "'model.plugin.uninstall.name'", ",", "$", "name", ")", ";", "$", "activePlugins", "=", "$", "this", "->", ...
Uninstall a plugin after deactivated
[ "Uninstall", "a", "plugin", "after", "deactivated" ]
train
https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Model/Admin/Plugins.php#L128-L151
bitExpert/adroit
src/bitExpert/Adroit/Resolver/AbstractResolverMiddleware.php
AbstractResolverMiddleware.validateResolvers
private function validateResolvers(array $resolvers) { foreach ($resolvers as $index => $resolver) { if (!$this->isValidResolver($resolver)) { throw new \InvalidArgumentException(sprintf( 'Resolver at index %s of type "%s" is not valid resolver type', $index, get_class($resolver) )); } } }
php
private function validateResolvers(array $resolvers) { foreach ($resolvers as $index => $resolver) { if (!$this->isValidResolver($resolver)) { throw new \InvalidArgumentException(sprintf( 'Resolver at index %s of type "%s" is not valid resolver type', $index, get_class($resolver) )); } } }
[ "private", "function", "validateResolvers", "(", "array", "$", "resolvers", ")", "{", "foreach", "(", "$", "resolvers", "as", "$", "index", "=>", "$", "resolver", ")", "{", "if", "(", "!", "$", "this", "->", "isValidResolver", "(", "$", "resolver", ")", ...
Internal resolver setter which validates the resolvers @param \bitExpert\Adroit\Resolver\Resolver[] $resolvers @throws \InvalidArgumentException
[ "Internal", "resolver", "setter", "which", "validates", "the", "resolvers" ]
train
https://github.com/bitExpert/adroit/blob/ecba7e59b864c88bd4639c87194ad842320e5f76/src/bitExpert/Adroit/Resolver/AbstractResolverMiddleware.php#L47-L58
despark/ignicms
src/Models/Image.php
Image.__isset
public function __isset($key) { $result = parent::__isset($key); if ($result) { return $result; } // if (! $result && $key == 'identifier') { // $resourceModel = $this->getResourceModel(); // if ($resourceModel && $resourceModel instanceof AdminModel) { // return ! is_null($resourceModel->getIdentifier()); // } // } // If we don't have a value try to find it in metadata if (! $result && $key != 'meta') { return isset($this->meta[$key]); } }
php
public function __isset($key) { $result = parent::__isset($key); if ($result) { return $result; } // if (! $result && $key == 'identifier') { // $resourceModel = $this->getResourceModel(); // if ($resourceModel && $resourceModel instanceof AdminModel) { // return ! is_null($resourceModel->getIdentifier()); // } // } // If we don't have a value try to find it in metadata if (! $result && $key != 'meta') { return isset($this->meta[$key]); } }
[ "public", "function", "__isset", "(", "$", "key", ")", "{", "$", "result", "=", "parent", "::", "__isset", "(", "$", "key", ")", ";", "if", "(", "$", "result", ")", "{", "return", "$", "result", ";", "}", "// if (! $result && $key == 'identifier') {...
Override magic isset so we can check for identifier metadata and properties. @param string $key @return bool
[ "Override", "magic", "isset", "so", "we", "can", "check", "for", "identifier", "metadata", "and", "properties", "." ]
train
https://github.com/despark/ignicms/blob/d55775a4656a7e99017d2ef3f8160599d600d2a7/src/Models/Image.php#L423-L440
accompli/accompli
src/Configuration/Configuration.php
Configuration.load
public function load($configurationFile = null) { $this->hosts = array(); $this->configuration = array(); if (isset($configurationFile)) { $this->configurationFile = $configurationFile; } if (file_exists($this->configurationFile) === false) { throw new InvalidArgumentException(sprintf('The configuration file "%s" is not valid.', $this->configurationFile)); } $json = file_get_contents($this->configurationFile); $this->validateSyntax($json); $json = $this->importExtendedConfiguration($json); if ($this->validateSchema($json)) { $this->configuration = json_decode($json, true); } $this->processEventSubscribers(); }
php
public function load($configurationFile = null) { $this->hosts = array(); $this->configuration = array(); if (isset($configurationFile)) { $this->configurationFile = $configurationFile; } if (file_exists($this->configurationFile) === false) { throw new InvalidArgumentException(sprintf('The configuration file "%s" is not valid.', $this->configurationFile)); } $json = file_get_contents($this->configurationFile); $this->validateSyntax($json); $json = $this->importExtendedConfiguration($json); if ($this->validateSchema($json)) { $this->configuration = json_decode($json, true); } $this->processEventSubscribers(); }
[ "public", "function", "load", "(", "$", "configurationFile", "=", "null", ")", "{", "$", "this", "->", "hosts", "=", "array", "(", ")", ";", "$", "this", "->", "configuration", "=", "array", "(", ")", ";", "if", "(", "isset", "(", "$", "configuration...
Loads and validates the JSON configuration. @param string|null $configurationFile @throws InvalidArgumentException
[ "Loads", "and", "validates", "the", "JSON", "configuration", "." ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Configuration/Configuration.php#L73-L96
accompli/accompli
src/Configuration/Configuration.php
Configuration.validateSyntax
private function validateSyntax($json) { $parser = new JsonParser(); $result = $parser->lint($json); if ($result === null) { return; } throw new ParsingException(sprintf("The configuration file \"%s\" does not contain valid JSON.\n%s", $this->configurationFile, $result->getMessage()), $result->getDetails()); }
php
private function validateSyntax($json) { $parser = new JsonParser(); $result = $parser->lint($json); if ($result === null) { return; } throw new ParsingException(sprintf("The configuration file \"%s\" does not contain valid JSON.\n%s", $this->configurationFile, $result->getMessage()), $result->getDetails()); }
[ "private", "function", "validateSyntax", "(", "$", "json", ")", "{", "$", "parser", "=", "new", "JsonParser", "(", ")", ";", "$", "result", "=", "$", "parser", "->", "lint", "(", "$", "json", ")", ";", "if", "(", "$", "result", "===", "null", ")", ...
Validates the syntax of $json. @param string $json @throws ParsingException
[ "Validates", "the", "syntax", "of", "$json", "." ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Configuration/Configuration.php#L105-L114
accompli/accompli
src/Configuration/Configuration.php
Configuration.validateSchema
private function validateSchema($json) { $jsonData = json_decode($json); $schemaData = json_decode(file_get_contents($this->configurationSchema)); $validator = new Validator(); $validator->check($jsonData, $schemaData); if ($validator->isValid() === false) { $errors = array(); foreach ($validator->getErrors() as $error) { $errorMessage = $error['message']; if (isset($error['property'])) { $errorMessage = $error['property'].' : '.$errorMessage; } $errors[] = $errorMessage; } throw new JSONValidationException(sprintf('The configuration file "%s" does not match the expected JSON schema.', $this->configurationFile), $errors); } return true; }
php
private function validateSchema($json) { $jsonData = json_decode($json); $schemaData = json_decode(file_get_contents($this->configurationSchema)); $validator = new Validator(); $validator->check($jsonData, $schemaData); if ($validator->isValid() === false) { $errors = array(); foreach ($validator->getErrors() as $error) { $errorMessage = $error['message']; if (isset($error['property'])) { $errorMessage = $error['property'].' : '.$errorMessage; } $errors[] = $errorMessage; } throw new JSONValidationException(sprintf('The configuration file "%s" does not match the expected JSON schema.', $this->configurationFile), $errors); } return true; }
[ "private", "function", "validateSchema", "(", "$", "json", ")", "{", "$", "jsonData", "=", "json_decode", "(", "$", "json", ")", ";", "$", "schemaData", "=", "json_decode", "(", "file_get_contents", "(", "$", "this", "->", "configurationSchema", ")", ")", ...
Validates the $json content with the JSON schema. @param string $json @return bool @throws JSONValidationException
[ "Validates", "the", "$json", "content", "with", "the", "JSON", "schema", "." ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Configuration/Configuration.php#L125-L146
accompli/accompli
src/Configuration/Configuration.php
Configuration.importExtendedConfiguration
private function importExtendedConfiguration($json) { $configuration = json_decode($json, true); if (isset($configuration['$extend'])) { $extendConfigurationFile = $configuration['$extend']; $extendConfigurationFileScheme = parse_url($extendConfigurationFile, PHP_URL_SCHEME); if (substr($extendConfigurationFile, 0, 1) === '/' || isset($extendConfigurationFileScheme) === false) { $extendConfigurationFile = sprintf('%s/%s', dirname($this->configurationFile), $configuration['$extend']); } unset($configuration['$extend']); $parentConfiguration = new static($extendConfigurationFile, $this->configurationSchema); $parentConfiguration->load(); $configuration = array_merge_recursive($parentConfiguration->configuration, $configuration); $json = json_encode($configuration); } return $json; }
php
private function importExtendedConfiguration($json) { $configuration = json_decode($json, true); if (isset($configuration['$extend'])) { $extendConfigurationFile = $configuration['$extend']; $extendConfigurationFileScheme = parse_url($extendConfigurationFile, PHP_URL_SCHEME); if (substr($extendConfigurationFile, 0, 1) === '/' || isset($extendConfigurationFileScheme) === false) { $extendConfigurationFile = sprintf('%s/%s', dirname($this->configurationFile), $configuration['$extend']); } unset($configuration['$extend']); $parentConfiguration = new static($extendConfigurationFile, $this->configurationSchema); $parentConfiguration->load(); $configuration = array_merge_recursive($parentConfiguration->configuration, $configuration); $json = json_encode($configuration); } return $json; }
[ "private", "function", "importExtendedConfiguration", "(", "$", "json", ")", "{", "$", "configuration", "=", "json_decode", "(", "$", "json", ",", "true", ")", ";", "if", "(", "isset", "(", "$", "configuration", "[", "'$extend'", "]", ")", ")", "{", "$",...
Imports the configuration file defined in the $extend key. @param string $json @return string
[ "Imports", "the", "configuration", "file", "defined", "in", "the", "$extend", "key", "." ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Configuration/Configuration.php#L155-L175
accompli/accompli
src/Configuration/Configuration.php
Configuration.processEventSubscribers
private function processEventSubscribers() { if (isset($this->configuration['events']['subscribers'])) { foreach ($this->configuration['events']['subscribers'] as $i => $subscriber) { if (is_string($subscriber)) { $this->configuration['events']['subscribers'][$i] = array('class' => $subscriber); } } } }
php
private function processEventSubscribers() { if (isset($this->configuration['events']['subscribers'])) { foreach ($this->configuration['events']['subscribers'] as $i => $subscriber) { if (is_string($subscriber)) { $this->configuration['events']['subscribers'][$i] = array('class' => $subscriber); } } } }
[ "private", "function", "processEventSubscribers", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "configuration", "[", "'events'", "]", "[", "'subscribers'", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "configuration", "[", "'events'...
Processes event subscriber configurations to match the same format.
[ "Processes", "event", "subscriber", "configurations", "to", "match", "the", "same", "format", "." ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Configuration/Configuration.php#L180-L189
accompli/accompli
src/Configuration/Configuration.php
Configuration.getHosts
public function getHosts() { if (empty($this->hosts) && isset($this->configuration['hosts'])) { foreach ($this->configuration['hosts'] as $host) { $this->hosts[] = ObjectFactory::getInstance()->newInstance(Host::class, $host); } } return $this->hosts; }
php
public function getHosts() { if (empty($this->hosts) && isset($this->configuration['hosts'])) { foreach ($this->configuration['hosts'] as $host) { $this->hosts[] = ObjectFactory::getInstance()->newInstance(Host::class, $host); } } return $this->hosts; }
[ "public", "function", "getHosts", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "hosts", ")", "&&", "isset", "(", "$", "this", "->", "configuration", "[", "'hosts'", "]", ")", ")", "{", "foreach", "(", "$", "this", "->", "configuration",...
Returns the configured hosts. @return Host[]
[ "Returns", "the", "configured", "hosts", "." ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Configuration/Configuration.php#L196-L205
accompli/accompli
src/Configuration/Configuration.php
Configuration.getHostsByStage
public function getHostsByStage($stage) { if (Host::isValidStage($stage) === false) { throw new UnexpectedValueException(sprintf("'%s' is not a valid stage.", $stage)); } $hosts = array(); foreach ($this->getHosts() as $host) { if ($host->getStage() === $stage) { $hosts[] = $host; } } return $hosts; }
php
public function getHostsByStage($stage) { if (Host::isValidStage($stage) === false) { throw new UnexpectedValueException(sprintf("'%s' is not a valid stage.", $stage)); } $hosts = array(); foreach ($this->getHosts() as $host) { if ($host->getStage() === $stage) { $hosts[] = $host; } } return $hosts; }
[ "public", "function", "getHostsByStage", "(", "$", "stage", ")", "{", "if", "(", "Host", "::", "isValidStage", "(", "$", "stage", ")", "===", "false", ")", "{", "throw", "new", "UnexpectedValueException", "(", "sprintf", "(", "\"'%s' is not a valid stage.\"", ...
Returns the configured hosts for $stage. @param string $stage @return Host[] @throws UnexpectedValueException when $stage is not a valid type
[ "Returns", "the", "configured", "hosts", "for", "$stage", "." ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Configuration/Configuration.php#L216-L230
aginev/acl
src/Http/Controllers/PermissionController.php
PermissionController.store
public function store(Request $request) { $data = $request->all(); $data['resource'] = $data['controller'] . '@' . $data['method']; $validator = Validator::make( $data, $this->getValidationRules() ); if ($validator->fails()) { return back()->withInput()->withErrors($validator); } Permission::create($data); return redirect()->action('\Aginev\Acl\Http\Controllers\PermissionController@index') ->with('success', trans('acl::permission.create.created')); }
php
public function store(Request $request) { $data = $request->all(); $data['resource'] = $data['controller'] . '@' . $data['method']; $validator = Validator::make( $data, $this->getValidationRules() ); if ($validator->fails()) { return back()->withInput()->withErrors($validator); } Permission::create($data); return redirect()->action('\Aginev\Acl\Http\Controllers\PermissionController@index') ->with('success', trans('acl::permission.create.created')); }
[ "public", "function", "store", "(", "Request", "$", "request", ")", "{", "$", "data", "=", "$", "request", "->", "all", "(", ")", ";", "$", "data", "[", "'resource'", "]", "=", "$", "data", "[", "'controller'", "]", ".", "'@'", ".", "$", "data", ...
Store a newly created resource in storage. @param Request $request @return Response
[ "Store", "a", "newly", "created", "resource", "in", "storage", "." ]
train
https://github.com/aginev/acl/blob/7dcbe39c0955c3da7487f5d528423dd6e7ac7fd1/src/Http/Controllers/PermissionController.php#L41-L59
aginev/acl
src/Http/Controllers/PermissionController.php
PermissionController.update
public function update($id, Request $request) { $permission = Permission::findOrFail($id); $data = $request->all(); $data['resource'] = $data['controller'] . '@' . $data['method']; $validator = Validator::make( $data, $this->getValidationRules() ); if ($validator->fails()) { return back()->withErrors($validator->messages()); } $permission->update($data); return redirect()->action('\Aginev\Acl\Http\Controllers\PermissionController@index') ->with('success', trans('acl::permission.edit.updated')); }
php
public function update($id, Request $request) { $permission = Permission::findOrFail($id); $data = $request->all(); $data['resource'] = $data['controller'] . '@' . $data['method']; $validator = Validator::make( $data, $this->getValidationRules() ); if ($validator->fails()) { return back()->withErrors($validator->messages()); } $permission->update($data); return redirect()->action('\Aginev\Acl\Http\Controllers\PermissionController@index') ->with('success', trans('acl::permission.edit.updated')); }
[ "public", "function", "update", "(", "$", "id", ",", "Request", "$", "request", ")", "{", "$", "permission", "=", "Permission", "::", "findOrFail", "(", "$", "id", ")", ";", "$", "data", "=", "$", "request", "->", "all", "(", ")", ";", "$", "data",...
Update the specified resource in storage. @param int $id @param Request $request @return Response
[ "Update", "the", "specified", "resource", "in", "storage", "." ]
train
https://github.com/aginev/acl/blob/7dcbe39c0955c3da7487f5d528423dd6e7ac7fd1/src/Http/Controllers/PermissionController.php#L97-L117
shpasser/GaeSupport
src/Shpasser/GaeSupport/GaeSupportServiceProvider.php
GaeSupportServiceProvider.register
public function register() { $this->app['gae.setup'] = $this->app->share(function($app) { return new SetupCommand; }); $this->commands('gae.setup'); }
php
public function register() { $this->app['gae.setup'] = $this->app->share(function($app) { return new SetupCommand; }); $this->commands('gae.setup'); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "app", "[", "'gae.setup'", "]", "=", "$", "this", "->", "app", "->", "share", "(", "function", "(", "$", "app", ")", "{", "return", "new", "SetupCommand", ";", "}", ")", ";", "$", ...
Register the service provider. @return void
[ "Register", "the", "service", "provider", "." ]
train
https://github.com/shpasser/GaeSupport/blob/7f37f2bf177a4e8f1cbefdf04f49b51016e85ae3/src/Shpasser/GaeSupport/GaeSupportServiceProvider.php#L20-L28
oasmobile/php-aws-wrappers
src/AwsWrappers/DynamoDbItem.php
DynamoDbItem.offsetGet
public function offsetGet($offset) { if (!array_key_exists($offset, $this->data)) { throw new \OutOfBoundsException("Attribute $offset does not exist in DynamoDbItem!"); } return static::toUntypedValue($this->data[$offset]); }
php
public function offsetGet($offset) { if (!array_key_exists($offset, $this->data)) { throw new \OutOfBoundsException("Attribute $offset does not exist in DynamoDbItem!"); } return static::toUntypedValue($this->data[$offset]); }
[ "public", "function", "offsetGet", "(", "$", "offset", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "offset", ",", "$", "this", "->", "data", ")", ")", "{", "throw", "new", "\\", "OutOfBoundsException", "(", "\"Attribute $offset does not exist in Dy...
Offset to retrieve @link http://php.net/manual/en/arrayaccess.offsetget.php @param mixed $offset <p> The offset to retrieve. </p> @return mixed Can return all value types. @since 5.0.0
[ "Offset", "to", "retrieve" ]
train
https://github.com/oasmobile/php-aws-wrappers/blob/0f756dc60ef6f51e9a99f67c9125289e40f19e3f/src/AwsWrappers/DynamoDbItem.php#L241-L248
oasmobile/php-aws-wrappers
src/AwsWrappers/DynamoDbItem.php
DynamoDbItem.offsetUnset
public function offsetUnset($offset) { if (!array_key_exists($offset, $this->data)) { throw new \OutOfBoundsException("Attribute $offset does not exist in DynamoDbItem!"); } unset($this->data[$offset]); }
php
public function offsetUnset($offset) { if (!array_key_exists($offset, $this->data)) { throw new \OutOfBoundsException("Attribute $offset does not exist in DynamoDbItem!"); } unset($this->data[$offset]); }
[ "public", "function", "offsetUnset", "(", "$", "offset", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "offset", ",", "$", "this", "->", "data", ")", ")", "{", "throw", "new", "\\", "OutOfBoundsException", "(", "\"Attribute $offset does not exist in ...
Offset to unset @link http://php.net/manual/en/arrayaccess.offsetunset.php @param mixed $offset <p> The offset to unset. </p> @return void @since 5.0.0
[ "Offset", "to", "unset" ]
train
https://github.com/oasmobile/php-aws-wrappers/blob/0f756dc60ef6f51e9a99f67c9125289e40f19e3f/src/AwsWrappers/DynamoDbItem.php#L282-L289
makinacorpus/drupal-ucms
ucms_group/src/Form/GroupMemberAddExisting.php
GroupMemberAddExisting.validateForm
public function validateForm(array &$form, FormStateInterface $form_state) { $user = $form_state->getValue('name'); $matches = []; if (preg_match('/\[(\d+)\]$/', $user, $matches) !== 1 || $matches[1] < 2) { $form_state->setErrorByName('name', $this->t("The user can't be identified.")); } else { $user = $this->entityManager->getStorage('user')->load($matches[1]); if (null === $user) { $form_state->setErrorByName('name', $this->t("The user doesn't exist.")); } else { $form_state->setTemporaryValue('user', $user); } } }
php
public function validateForm(array &$form, FormStateInterface $form_state) { $user = $form_state->getValue('name'); $matches = []; if (preg_match('/\[(\d+)\]$/', $user, $matches) !== 1 || $matches[1] < 2) { $form_state->setErrorByName('name', $this->t("The user can't be identified.")); } else { $user = $this->entityManager->getStorage('user')->load($matches[1]); if (null === $user) { $form_state->setErrorByName('name', $this->t("The user doesn't exist.")); } else { $form_state->setTemporaryValue('user', $user); } } }
[ "public", "function", "validateForm", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "$", "user", "=", "$", "form_state", "->", "getValue", "(", "'name'", ")", ";", "$", "matches", "=", "[", "]", ";", "if", "(",...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_group/src/Form/GroupMemberAddExisting.php#L84-L99
makinacorpus/drupal-ucms
ucms_group/src/Form/GroupMemberAddExisting.php
GroupMemberAddExisting.submitForm
public function submitForm(array &$form, FormStateInterface $form_state) { /** @var \Drupal\user\UserInterface $user */ $user = $form_state->getTemporaryValue('user'); if ($this->groupManager->addMember($form_state->getValue('group'), $user->id())) { drupal_set_message($this->t("!name has been added to group.", [ '!name' => $user->getDisplayName(), ])); } else { drupal_set_message($this->t("!name is already a member of this group.", [ '!name' => $user->getDisplayName(), ])); } }
php
public function submitForm(array &$form, FormStateInterface $form_state) { /** @var \Drupal\user\UserInterface $user */ $user = $form_state->getTemporaryValue('user'); if ($this->groupManager->addMember($form_state->getValue('group'), $user->id())) { drupal_set_message($this->t("!name has been added to group.", [ '!name' => $user->getDisplayName(), ])); } else { drupal_set_message($this->t("!name is already a member of this group.", [ '!name' => $user->getDisplayName(), ])); } }
[ "public", "function", "submitForm", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "/** @var \\Drupal\\user\\UserInterface $user */", "$", "user", "=", "$", "form_state", "->", "getTemporaryValue", "(", "'user'", ")", ";", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_group/src/Form/GroupMemberAddExisting.php#L104-L118
shopgate/cart-integration-sdk
src/configuration.php
ShopgateConfig.loadArray
public function loadArray(array $data = array()) { // if no $data was passed try loading the default configuration file if (empty($data)) { $this->loadFile(); return; } // if data was passed, map via setters $unmappedData = parent::loadArray($data); // put the rest into $this->additionalSettings $this->mapAdditionalSettings($unmappedData); }
php
public function loadArray(array $data = array()) { // if no $data was passed try loading the default configuration file if (empty($data)) { $this->loadFile(); return; } // if data was passed, map via setters $unmappedData = parent::loadArray($data); // put the rest into $this->additionalSettings $this->mapAdditionalSettings($unmappedData); }
[ "public", "function", "loadArray", "(", "array", "$", "data", "=", "array", "(", ")", ")", "{", "// if no $data was passed try loading the default configuration file", "if", "(", "empty", "(", "$", "data", ")", ")", "{", "$", "this", "->", "loadFile", "(", ")"...
Tries to assign the values of an array to the configuration fields or load it from a file. This overrides ShopgateContainer::loadArray() which is called on object instantiation. It tries to assign the values of $data to the class attributes by $data's keys. If a key is not the name of a class attribute it's appended to $this->additionalSettings.<br /> <br /> If $data is empty or not an array, the method calls $this->loadFile(). @param $data array<string, mixed> The data to be assigned to the configuration. @return void
[ "Tries", "to", "assign", "the", "values", "of", "an", "array", "to", "the", "configuration", "fields", "or", "load", "it", "from", "a", "file", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/configuration.php#L705-L719
shopgate/cart-integration-sdk
src/configuration.php
ShopgateConfig.loadFile
public function loadFile($path = null) { $config = null; // try loading files if (!empty($path) && file_exists($path)) { // try $path $config = $this->includeFile($path); if (!$config) { throw new ShopgateLibraryException( ShopgateLibraryException::CONFIG_READ_WRITE_ERROR, 'The passed configuration file "' . $path . '" does not exist or does not define the $shopgate_config variable.' ); } } else { // try myconfig.php $config = $this->includeFile($this->buildConfigFilePath()); // if unsuccessful, use default configuration values if (!$config) { return; } } // if we got here, we have a $shopgate_config to load $unmappedData = parent::loadArray($config); $this->mapAdditionalSettings($unmappedData); }
php
public function loadFile($path = null) { $config = null; // try loading files if (!empty($path) && file_exists($path)) { // try $path $config = $this->includeFile($path); if (!$config) { throw new ShopgateLibraryException( ShopgateLibraryException::CONFIG_READ_WRITE_ERROR, 'The passed configuration file "' . $path . '" does not exist or does not define the $shopgate_config variable.' ); } } else { // try myconfig.php $config = $this->includeFile($this->buildConfigFilePath()); // if unsuccessful, use default configuration values if (!$config) { return; } } // if we got here, we have a $shopgate_config to load $unmappedData = parent::loadArray($config); $this->mapAdditionalSettings($unmappedData); }
[ "public", "function", "loadFile", "(", "$", "path", "=", "null", ")", "{", "$", "config", "=", "null", ";", "// try loading files", "if", "(", "!", "empty", "(", "$", "path", ")", "&&", "file_exists", "(", "$", "path", ")", ")", "{", "// try $path", ...
Tries to load the configuration from a file. If a $path is passed, this method tries to include the file. If that fails an exception is thrown.<br /> <br /> If $path is empty it tries to load .../shopgate_library/config/myconfig.php or if that fails, .../shopgate_library/config/config.php is tried to be loaded. If that fails too, an exception is thrown.<br /> <br /> The configuration file must be a PHP script defining an indexed array called $shopgate_config containing the desired configuration values to set. If that is not the case, an exception is thrown @param string $path The path to the configuration file or nothing to load the default Shopgate Cart Integration SDK configuration files. @throws ShopgateLibraryException in case a configuration file could not be loaded or the $shopgate_config is not set.
[ "Tries", "to", "load", "the", "configuration", "from", "a", "file", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/configuration.php#L739-L767
shopgate/cart-integration-sdk
src/configuration.php
ShopgateConfig.loadByShopNumber
public function loadByShopNumber($shopNumber) { if (empty($shopNumber) || !preg_match($this->coreValidations['shop_number'], $shopNumber)) { throw new ShopgateLibraryException( ShopgateLibraryException::CONFIG_READ_WRITE_ERROR, 'configuration file cannot be found without shop number' ); } // find all config files $configFile = null; $files = scandir(dirname($this->buildConfigFilePath())); ob_start(); foreach ($files as $file) { if (!is_file($this->buildConfigFilePath($file))) { continue; } $shopgate_config = null; /** @noinspection PhpIncludeInspection */ include($this->buildConfigFilePath($file)); if (isset($shopgate_config) && isset($shopgate_config['shop_number']) && ($shopgate_config['shop_number'] == $shopNumber)) { $configFile = $this->buildConfigFilePath($file); break; } } ob_end_clean(); if (empty($configFile)) { throw new ShopgateLibraryException( ShopgateLibraryException::CONFIG_READ_WRITE_ERROR, 'no configuration file found for shop number "' . $shopNumber . '"', true, false ); } $this->loadFile($configFile); $this->initFileNames(); }
php
public function loadByShopNumber($shopNumber) { if (empty($shopNumber) || !preg_match($this->coreValidations['shop_number'], $shopNumber)) { throw new ShopgateLibraryException( ShopgateLibraryException::CONFIG_READ_WRITE_ERROR, 'configuration file cannot be found without shop number' ); } // find all config files $configFile = null; $files = scandir(dirname($this->buildConfigFilePath())); ob_start(); foreach ($files as $file) { if (!is_file($this->buildConfigFilePath($file))) { continue; } $shopgate_config = null; /** @noinspection PhpIncludeInspection */ include($this->buildConfigFilePath($file)); if (isset($shopgate_config) && isset($shopgate_config['shop_number']) && ($shopgate_config['shop_number'] == $shopNumber)) { $configFile = $this->buildConfigFilePath($file); break; } } ob_end_clean(); if (empty($configFile)) { throw new ShopgateLibraryException( ShopgateLibraryException::CONFIG_READ_WRITE_ERROR, 'no configuration file found for shop number "' . $shopNumber . '"', true, false ); } $this->loadFile($configFile); $this->initFileNames(); }
[ "public", "function", "loadByShopNumber", "(", "$", "shopNumber", ")", "{", "if", "(", "empty", "(", "$", "shopNumber", ")", "||", "!", "preg_match", "(", "$", "this", "->", "coreValidations", "[", "'shop_number'", "]", ",", "$", "shopNumber", ")", ")", ...
Loads the configuration file for a given Shopgate shop number. @param string $shopNumber The shop number. @throws ShopgateLibraryException in case the $shopNumber is empty or no configuration file can be found.
[ "Loads", "the", "configuration", "file", "for", "a", "given", "Shopgate", "shop", "number", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/configuration.php#L776-L815
shopgate/cart-integration-sdk
src/configuration.php
ShopgateConfig.loadByLanguage
public function loadByLanguage($language) { if (!is_null($language) && !preg_match('/[a-z]{2}/', $language)) { throw new ShopgateLibraryException( ShopgateLibraryException::CONFIG_READ_WRITE_ERROR, 'invalid language code "' . $language . '"', true, false ); } $this->loadFile($this->buildConfigFilePath('myconfig-' . $language . '.php')); $this->initFileNames(); }
php
public function loadByLanguage($language) { if (!is_null($language) && !preg_match('/[a-z]{2}/', $language)) { throw new ShopgateLibraryException( ShopgateLibraryException::CONFIG_READ_WRITE_ERROR, 'invalid language code "' . $language . '"', true, false ); } $this->loadFile($this->buildConfigFilePath('myconfig-' . $language . '.php')); $this->initFileNames(); }
[ "public", "function", "loadByLanguage", "(", "$", "language", ")", "{", "if", "(", "!", "is_null", "(", "$", "language", ")", "&&", "!", "preg_match", "(", "'/[a-z]{2}/'", ",", "$", "language", ")", ")", "{", "throw", "new", "ShopgateLibraryException", "("...
Loads the configuration file by a given language or the global configuration file. @param string|null $language the ISO-639 code of the language or null to load global configuration @throws ShopgateLibraryException
[ "Loads", "the", "configuration", "file", "by", "a", "given", "language", "or", "the", "global", "configuration", "file", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/configuration.php#L824-L837
shopgate/cart-integration-sdk
src/configuration.php
ShopgateConfig.initFileNames
protected function initFileNames() { $this->items_csv_filename = 'items-' . $this->language . '.csv'; $this->items_xml_filename = 'items-' . $this->language . '.xml'; $this->items_json_filename = 'items-' . $this->language . '.json'; $this->media_csv_filename = 'media-' . $this->language . '.csv'; $this->categories_csv_filename = 'categories-' . $this->language . '.csv'; $this->categories_xml_filename = 'categories-' . $this->language . '.xml'; $this->categories_json_filename = 'categories-' . $this->language . '.json'; $this->reviews_csv_filename = 'reviews-' . $this->language . '.csv'; $this->access_log_filename = 'access-' . $this->language . '.log'; $this->request_log_filename = 'request-' . $this->language . '.log'; $this->error_log_filename = 'error-' . $this->language . '.log'; $this->debug_log_filename = 'debug-' . $this->language . '.log'; $this->redirect_keyword_cache_filename = 'redirect_keywords-' . $this->language . '.txt'; $this->redirect_skip_keyword_cache_filename = 'skip_redirect_keywords-' . $this->language . '.txt'; }
php
protected function initFileNames() { $this->items_csv_filename = 'items-' . $this->language . '.csv'; $this->items_xml_filename = 'items-' . $this->language . '.xml'; $this->items_json_filename = 'items-' . $this->language . '.json'; $this->media_csv_filename = 'media-' . $this->language . '.csv'; $this->categories_csv_filename = 'categories-' . $this->language . '.csv'; $this->categories_xml_filename = 'categories-' . $this->language . '.xml'; $this->categories_json_filename = 'categories-' . $this->language . '.json'; $this->reviews_csv_filename = 'reviews-' . $this->language . '.csv'; $this->access_log_filename = 'access-' . $this->language . '.log'; $this->request_log_filename = 'request-' . $this->language . '.log'; $this->error_log_filename = 'error-' . $this->language . '.log'; $this->debug_log_filename = 'debug-' . $this->language . '.log'; $this->redirect_keyword_cache_filename = 'redirect_keywords-' . $this->language . '.txt'; $this->redirect_skip_keyword_cache_filename = 'skip_redirect_keywords-' . $this->language . '.txt'; }
[ "protected", "function", "initFileNames", "(", ")", "{", "$", "this", "->", "items_csv_filename", "=", "'items-'", ".", "$", "this", "->", "language", ".", "'.csv'", ";", "$", "this", "->", "items_xml_filename", "=", "'items-'", ".", "$", "this", "->", "la...
Sets the file names according to the language of the configuration.
[ "Sets", "the", "file", "names", "according", "to", "the", "language", "of", "the", "configuration", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/configuration.php#L842-L863
shopgate/cart-integration-sdk
src/configuration.php
ShopgateConfig.saveFile
public function saveFile(array $fieldList, $path = null, $validate = true) { // if desired, validate before doing anything else if ($validate) { $this->validate($fieldList); } // preserve values of the fields to save $saveFields = array(); $currentConfig = $this->toArray(); foreach ($fieldList as $field) { $saveFields[$field] = (isset($currentConfig[$field])) ? $currentConfig[$field] : null; } // load the current configuration file try { $this->loadFile($path); } catch (ShopgateLibraryException $e) { ShopgateLogger::getInstance()->log( '-- Don\'t worry about the "error reading or writing configuration", that was just a routine check during saving.' ); } // merge old config with new values $newConfig = array_merge($this->toArray(), $saveFields); // default if no path to the configuration file is set if (empty($path)) { $path = $this->buildConfigFilePath(); } // create the array definition string and save it to the file $shopgateConfigFile = "<?php\n\$shopgate_config = " . var_export($newConfig, true) . ';'; if (!@file_put_contents($path, $shopgateConfigFile)) { throw new ShopgateLibraryException( ShopgateLibraryException::CONFIG_READ_WRITE_ERROR, 'The configuration file "' . $path . '" could not be saved.' ); } }
php
public function saveFile(array $fieldList, $path = null, $validate = true) { // if desired, validate before doing anything else if ($validate) { $this->validate($fieldList); } // preserve values of the fields to save $saveFields = array(); $currentConfig = $this->toArray(); foreach ($fieldList as $field) { $saveFields[$field] = (isset($currentConfig[$field])) ? $currentConfig[$field] : null; } // load the current configuration file try { $this->loadFile($path); } catch (ShopgateLibraryException $e) { ShopgateLogger::getInstance()->log( '-- Don\'t worry about the "error reading or writing configuration", that was just a routine check during saving.' ); } // merge old config with new values $newConfig = array_merge($this->toArray(), $saveFields); // default if no path to the configuration file is set if (empty($path)) { $path = $this->buildConfigFilePath(); } // create the array definition string and save it to the file $shopgateConfigFile = "<?php\n\$shopgate_config = " . var_export($newConfig, true) . ';'; if (!@file_put_contents($path, $shopgateConfigFile)) { throw new ShopgateLibraryException( ShopgateLibraryException::CONFIG_READ_WRITE_ERROR, 'The configuration file "' . $path . '" could not be saved.' ); } }
[ "public", "function", "saveFile", "(", "array", "$", "fieldList", ",", "$", "path", "=", "null", ",", "$", "validate", "=", "true", ")", "{", "// if desired, validate before doing anything else", "if", "(", "$", "validate", ")", "{", "$", "this", "->", "vali...
Saves the desired configuration fields to the specified file or myconfig.php. This calls $this->loadFile() with the given $path to load the current configuration. In case that fails, the $shopgate_config array is initialized empty. The values defined in $fieldList are then validated (if desired), assigned to $shopgate_config and saved to the specified file or myconfig.php. In case the file cannot be (over)written or created, an exception with code ShopgateLibrary::CONFIG_READ_WRITE_ERROR is thrown. In case the validation fails for one or more fields, an exception with code ShopgateLibrary::CONFIG_INVALID_VALUE is thrown. The failed fields are appended as additional information in form of a comma-separated list. @param string[] $fieldList The list of fieldnames that should be saved to the configuration file. @param string $path The path to the configuration file or empty to use .../shopgate_library/config/myconfig.php. @param bool $validate True to validate the fields that should be set. @throws ShopgateLibraryException in case the configuration can't be loaded or saved.
[ "Saves", "the", "desired", "configuration", "fields", "to", "the", "specified", "file", "or", "myconfig", ".", "php", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/configuration.php#L895-L936
shopgate/cart-integration-sdk
src/configuration.php
ShopgateConfig.saveFileForLanguage
public function saveFileForLanguage(array $fieldList, $language = null, $validate = true) { $fileName = null; if (!is_null($language)) { $this->setLanguage($language); $fieldList[] = 'language'; $fileName = $this->buildConfigFilePath('myconfig-' . $language . '.php'); } $this->saveFile($fieldList, $fileName, $validate); }
php
public function saveFileForLanguage(array $fieldList, $language = null, $validate = true) { $fileName = null; if (!is_null($language)) { $this->setLanguage($language); $fieldList[] = 'language'; $fileName = $this->buildConfigFilePath('myconfig-' . $language . '.php'); } $this->saveFile($fieldList, $fileName, $validate); }
[ "public", "function", "saveFileForLanguage", "(", "array", "$", "fieldList", ",", "$", "language", "=", "null", ",", "$", "validate", "=", "true", ")", "{", "$", "fileName", "=", "null", ";", "if", "(", "!", "is_null", "(", "$", "language", ")", ")", ...
Saves the desired fields to the configuration file for a given language or global configuration @param string[] $fieldList the list of fieldnames that should be saved to the configuration file. @param string $language the ISO-639 code of the language or null to save to global configuration @param bool $validate true to validate the fields that should be set. @throws ShopgateLibraryException in case the configuration can't be loaded or saved.
[ "Saves", "the", "desired", "fields", "to", "the", "configuration", "file", "for", "a", "given", "language", "or", "global", "configuration" ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/configuration.php#L947-L957
shopgate/cart-integration-sdk
src/configuration.php
ShopgateConfig.checkDuplicates
public function checkDuplicates() { $shopNumbers = array(); $files = scandir(dirname($this->buildConfigFilePath())); foreach ($files as $file) { if (!is_file($this->buildConfigFilePath($file))) { continue; } $shopgate_config = null; /** @noinspection PhpIncludeInspection */ include($this->buildConfigFilePath($file)); if (isset($shopgate_config) && isset($shopgate_config['shop_number'])) { if (in_array($shopgate_config['shop_number'], $shopNumbers)) { return true; } else { $shopNumbers[] = $shopgate_config['shop_number']; } } } return false; }
php
public function checkDuplicates() { $shopNumbers = array(); $files = scandir(dirname($this->buildConfigFilePath())); foreach ($files as $file) { if (!is_file($this->buildConfigFilePath($file))) { continue; } $shopgate_config = null; /** @noinspection PhpIncludeInspection */ include($this->buildConfigFilePath($file)); if (isset($shopgate_config) && isset($shopgate_config['shop_number'])) { if (in_array($shopgate_config['shop_number'], $shopNumbers)) { return true; } else { $shopNumbers[] = $shopgate_config['shop_number']; } } } return false; }
[ "public", "function", "checkDuplicates", "(", ")", "{", "$", "shopNumbers", "=", "array", "(", ")", ";", "$", "files", "=", "scandir", "(", "dirname", "(", "$", "this", "->", "buildConfigFilePath", "(", ")", ")", ")", ";", "foreach", "(", "$", "files",...
Checks for duplicate shop numbers in multiple configurations. This checks all files in the configuration folder and shop numbers in all configuration files. @return bool true if there are duplicates, false otherwise.
[ "Checks", "for", "duplicate", "shop", "numbers", "in", "multiple", "configurations", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/configuration.php#L967-L990
shopgate/cart-integration-sdk
src/configuration.php
ShopgateConfig.checkMultipleConfigs
public function checkMultipleConfigs() { $files = scandir(dirname($this->buildConfigFilePath())); $counter = 0; foreach ($files as $file) { if (!is_file($this->buildConfigFilePath($file))) { continue; } if (substr($file, -4) !== '.php') { continue; } ob_start(); /** @noinspection PhpIncludeInspection */ include($this->buildConfigFilePath($file)); ob_end_clean(); if (!isset($shopgate_config)) { continue; } $counter++; unset($shopgate_config); } return ($counter > 1); }
php
public function checkMultipleConfigs() { $files = scandir(dirname($this->buildConfigFilePath())); $counter = 0; foreach ($files as $file) { if (!is_file($this->buildConfigFilePath($file))) { continue; } if (substr($file, -4) !== '.php') { continue; } ob_start(); /** @noinspection PhpIncludeInspection */ include($this->buildConfigFilePath($file)); ob_end_clean(); if (!isset($shopgate_config)) { continue; } $counter++; unset($shopgate_config); } return ($counter > 1); }
[ "public", "function", "checkMultipleConfigs", "(", ")", "{", "$", "files", "=", "scandir", "(", "dirname", "(", "$", "this", "->", "buildConfigFilePath", "(", ")", ")", ")", ";", "$", "counter", "=", "0", ";", "foreach", "(", "$", "files", "as", "$", ...
Checks if there is more than one configuration file available. @return bool true if multiple configuration files are available, false otherwise.
[ "Checks", "if", "there", "is", "more", "than", "one", "configuration", "file", "available", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/configuration.php#L997-L1024
shopgate/cart-integration-sdk
src/configuration.php
ShopgateConfig.useGlobalFor
public function useGlobalFor($language) { $fileName = $this->buildConfigFilePath('myconfig-' . $language . '.php'); if (file_exists($fileName)) { if (!@unlink($fileName)) { throw new ShopgateLibraryException( ShopgateLibraryException::CONFIG_READ_WRITE_ERROR, 'Error deleting configuration file "' . $fileName . "'." ); } } }
php
public function useGlobalFor($language) { $fileName = $this->buildConfigFilePath('myconfig-' . $language . '.php'); if (file_exists($fileName)) { if (!@unlink($fileName)) { throw new ShopgateLibraryException( ShopgateLibraryException::CONFIG_READ_WRITE_ERROR, 'Error deleting configuration file "' . $fileName . "'." ); } } }
[ "public", "function", "useGlobalFor", "(", "$", "language", ")", "{", "$", "fileName", "=", "$", "this", "->", "buildConfigFilePath", "(", "'myconfig-'", ".", "$", "language", ".", "'.php'", ")", ";", "if", "(", "file_exists", "(", "$", "fileName", ")", ...
Removes the configuration file for the language requested. @param string $language the ISO-639 code of the language or null to load global configuration @throws ShopgateLibraryException in case the file exists but cannot be deleted.
[ "Removes", "the", "configuration", "file", "for", "the", "language", "requested", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/configuration.php#L1045-L1056
shopgate/cart-integration-sdk
src/configuration.php
ShopgateConfig.includeFile
private function includeFile($path) { $shopgate_config = null; // try including the file if (file_exists($path)) { ob_start(); /** @noinspection PhpIncludeInspection */ include($path); ob_end_clean(); } else { return false; } // check $shopgate_config if (!isset($shopgate_config) || !is_array($shopgate_config)) { return false; } else { return $shopgate_config; } }
php
private function includeFile($path) { $shopgate_config = null; // try including the file if (file_exists($path)) { ob_start(); /** @noinspection PhpIncludeInspection */ include($path); ob_end_clean(); } else { return false; } // check $shopgate_config if (!isset($shopgate_config) || !is_array($shopgate_config)) { return false; } else { return $shopgate_config; } }
[ "private", "function", "includeFile", "(", "$", "path", ")", "{", "$", "shopgate_config", "=", "null", ";", "// try including the file", "if", "(", "file_exists", "(", "$", "path", ")", ")", "{", "ob_start", "(", ")", ";", "/** @noinspection PhpIncludeInspection...
Tries to include the specified file and check for $shopgate_config. @param string $path The path to the configuration file. @return mixed[]|bool The $shopgate_config array if the file was included and defined $shopgate_config, false otherwise.
[ "Tries", "to", "include", "the", "specified", "file", "and", "check", "for", "$shopgate_config", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/configuration.php#L2278-L2298
shopgate/cart-integration-sdk
src/configuration.php
ShopgateConfig.mapAdditionalSettings
private function mapAdditionalSettings($data = array()) { foreach ($data as $key => $value) { $this->additionalSettings[$key] = $value; } }
php
private function mapAdditionalSettings($data = array()) { foreach ($data as $key => $value) { $this->additionalSettings[$key] = $value; } }
[ "private", "function", "mapAdditionalSettings", "(", "$", "data", "=", "array", "(", ")", ")", "{", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "additionalSettings", "[", "$", "key", "]", "=", "$", ...
Maps the passed data to the additional settings array. @param array <string, mixed> $data The data to map.
[ "Maps", "the", "passed", "data", "to", "the", "additional", "settings", "array", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/configuration.php#L2305-L2310
shopgate/cart-integration-sdk
src/configuration.php
ShopgateConfigOld.setConfig
final public static function setConfig(array $newConfig, $validate = true) { self::deprecated(__METHOD__); if ($validate) { self::validateConfig($newConfig); } self::$config = array_merge(self::$config, $newConfig); }
php
final public static function setConfig(array $newConfig, $validate = true) { self::deprecated(__METHOD__); if ($validate) { self::validateConfig($newConfig); } self::$config = array_merge(self::$config, $newConfig); }
[ "final", "public", "static", "function", "setConfig", "(", "array", "$", "newConfig", ",", "$", "validate", "=", "true", ")", "{", "self", "::", "deprecated", "(", "__METHOD__", ")", ";", "if", "(", "$", "validate", ")", "{", "self", "::", "validateConfi...
Übergeben und überprüfen der Einstellungen. @deprecated @param array $newConfig @param bool $validate @throws ShopgateLibraryException
[ "Übergeben", "und", "überprüfen", "der", "Einstellungen", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/configuration.php#L2552-L2560
shopgate/cart-integration-sdk
src/configuration.php
ShopgateConfigOld.validateAndReturnConfig
final public static function validateAndReturnConfig() { self::deprecated(__METHOD__); try { self::validateConfig(self::$config); } catch (ShopgateLibraryException $e) { throw $e; } return self::getConfig(); }
php
final public static function validateAndReturnConfig() { self::deprecated(__METHOD__); try { self::validateConfig(self::$config); } catch (ShopgateLibraryException $e) { throw $e; } return self::getConfig(); }
[ "final", "public", "static", "function", "validateAndReturnConfig", "(", ")", "{", "self", "::", "deprecated", "(", "__METHOD__", ")", ";", "try", "{", "self", "::", "validateConfig", "(", "self", "::", "$", "config", ")", ";", "}", "catch", "(", "Shopgate...
Gibt das Konfigurations-Array zurück. @deprecated
[ "Gibt", "das", "Konfigurations", "-", "Array", "zurück", "." ]
train
https://github.com/shopgate/cart-integration-sdk/blob/cf12ecf8bdb8f4c407209000002fd00261e53b06/src/configuration.php#L2567-L2578