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_user/src/Datasource/UserAdminDatasource.php
UserAdminDatasource.getFilters
public function getFilters() { $roles = $this->access->getDrupalRoleList(); foreach ($roles as $rid => $role) { if (in_array($rid, [DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID])) { unset($roles[$rid]); } } $statuses = [ 1 => $this->t("Enabled"), 0 => $this->t("Disabled"), ]; return [ (new Filter('role', $this->t("Role")))->setChoicesMap($roles), (new Filter('status', $this->t("Status")))->setChoicesMap($statuses), ]; }
php
public function getFilters() { $roles = $this->access->getDrupalRoleList(); foreach ($roles as $rid => $role) { if (in_array($rid, [DRUPAL_ANONYMOUS_RID, DRUPAL_AUTHENTICATED_RID])) { unset($roles[$rid]); } } $statuses = [ 1 => $this->t("Enabled"), 0 => $this->t("Disabled"), ]; return [ (new Filter('role', $this->t("Role")))->setChoicesMap($roles), (new Filter('status', $this->t("Status")))->setChoicesMap($statuses), ]; }
[ "public", "function", "getFilters", "(", ")", "{", "$", "roles", "=", "$", "this", "->", "access", "->", "getDrupalRoleList", "(", ")", ";", "foreach", "(", "$", "roles", "as", "$", "rid", "=>", "$", "role", ")", "{", "if", "(", "in_array", "(", "$...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_user/src/Datasource/UserAdminDatasource.php#L50-L68
makinacorpus/drupal-ucms
ucms_user/src/Datasource/UserAdminDatasource.php
UserAdminDatasource.getItems
public function getItems(Query $query) { $q = $this ->db ->select('users', 'u') ->fields('u', ['uid']) ; $q->addTag('ucms_user_access'); if ($query->has('status')) { $q->condition('u.status', $query->get('status')); } if ($query->has('role')) { $q->join('users_roles', 'ur', "u.uid = ur.uid"); $q->condition('ur.rid', $query->get('role')); } if ($query->hasSortField()) { $q->orderBy($query->getSortField(), $query->getSortOrder()); } $search = $query->getSearchString(); if ($search) { $q->condition('u.name', '%' . db_like($search) . '%', 'LIKE'); } // Exclude admin and anonymous users $q->condition('u.uid', 0, '!=')->condition('u.uid', 1, '!='); /** @var \MakinaCorpus\Drupal\Calista\Datasource\QueryExtender\DrupalPager $pager */ $pager = $q->extend(DrupalPager::class)->setDatasourceQuery($query); $idList = $pager->execute()->fetchCol(); $items = $this->entityManager->getStorage('user')->loadMultiple($idList); return $this->createResult($items, $pager->getTotalCount()); }
php
public function getItems(Query $query) { $q = $this ->db ->select('users', 'u') ->fields('u', ['uid']) ; $q->addTag('ucms_user_access'); if ($query->has('status')) { $q->condition('u.status', $query->get('status')); } if ($query->has('role')) { $q->join('users_roles', 'ur', "u.uid = ur.uid"); $q->condition('ur.rid', $query->get('role')); } if ($query->hasSortField()) { $q->orderBy($query->getSortField(), $query->getSortOrder()); } $search = $query->getSearchString(); if ($search) { $q->condition('u.name', '%' . db_like($search) . '%', 'LIKE'); } // Exclude admin and anonymous users $q->condition('u.uid', 0, '!=')->condition('u.uid', 1, '!='); /** @var \MakinaCorpus\Drupal\Calista\Datasource\QueryExtender\DrupalPager $pager */ $pager = $q->extend(DrupalPager::class)->setDatasourceQuery($query); $idList = $pager->execute()->fetchCol(); $items = $this->entityManager->getStorage('user')->loadMultiple($idList); return $this->createResult($items, $pager->getTotalCount()); }
[ "public", "function", "getItems", "(", "Query", "$", "query", ")", "{", "$", "q", "=", "$", "this", "->", "db", "->", "select", "(", "'users'", ",", "'u'", ")", "->", "fields", "(", "'u'", ",", "[", "'uid'", "]", ")", ";", "$", "q", "->", "addT...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_user/src/Datasource/UserAdminDatasource.php#L87-L124
index0h/yii2-phar
src/iterators/Iterator.php
Iterator.createFile
protected function createFile() { $event = new FileEvent([ 'realPath' => $this->iterator->current(), 'relativePath' => $this->iterator->getRelativePath() ]); $this->module->trigger(Module::EVENT_PROCESS_FILE, $event); $this->file = $event; }
php
protected function createFile() { $event = new FileEvent([ 'realPath' => $this->iterator->current(), 'relativePath' => $this->iterator->getRelativePath() ]); $this->module->trigger(Module::EVENT_PROCESS_FILE, $event); $this->file = $event; }
[ "protected", "function", "createFile", "(", ")", "{", "$", "event", "=", "new", "FileEvent", "(", "[", "'realPath'", "=>", "$", "this", "->", "iterator", "->", "current", "(", ")", ",", "'relativePath'", "=>", "$", "this", "->", "iterator", "->", "getRel...
Create file event and trigger in from module.
[ "Create", "file", "event", "and", "trigger", "in", "from", "module", "." ]
train
https://github.com/index0h/yii2-phar/blob/dc347242cca028affec78718b35fd22a34e2d3b8/src/iterators/Iterator.php#L134-L144
index0h/yii2-phar
src/iterators/Iterator.php
Iterator.dropFile
protected function dropFile() { if (($this->file !== null) && ($this->file->isTemporary === true)) { @unlink($this->file->realPath); } $this->file = null; }
php
protected function dropFile() { if (($this->file !== null) && ($this->file->isTemporary === true)) { @unlink($this->file->realPath); } $this->file = null; }
[ "protected", "function", "dropFile", "(", ")", "{", "if", "(", "(", "$", "this", "->", "file", "!==", "null", ")", "&&", "(", "$", "this", "->", "file", "->", "isTemporary", "===", "true", ")", ")", "{", "@", "unlink", "(", "$", "this", "->", "fi...
Remove file after next/rewind call.
[ "Remove", "file", "after", "next", "/", "rewind", "call", "." ]
train
https://github.com/index0h/yii2-phar/blob/dc347242cca028affec78718b35fd22a34e2d3b8/src/iterators/Iterator.php#L149-L156
index0h/yii2-phar
src/iterators/Iterator.php
Iterator.isIgnored
protected function isIgnored($current) { if (is_dir($current) === true) { return false; } foreach ($this->ignore as $pattern) { if (preg_match($pattern, $current) > 0) { return false; } } return true; }
php
protected function isIgnored($current) { if (is_dir($current) === true) { return false; } foreach ($this->ignore as $pattern) { if (preg_match($pattern, $current) > 0) { return false; } } return true; }
[ "protected", "function", "isIgnored", "(", "$", "current", ")", "{", "if", "(", "is_dir", "(", "$", "current", ")", "===", "true", ")", "{", "return", "false", ";", "}", "foreach", "(", "$", "this", "->", "ignore", "as", "$", "pattern", ")", "{", "...
@param string $current Path to file/folder. @return bool
[ "@param", "string", "$current", "Path", "to", "file", "/", "folder", "." ]
train
https://github.com/index0h/yii2-phar/blob/dc347242cca028affec78718b35fd22a34e2d3b8/src/iterators/Iterator.php#L163-L175
amphp/loop
lib/EvLoop.php
EvLoop.dispatch
protected function dispatch($blocking) { $this->handle->run($blocking ? \Ev::RUN_ONCE : \Ev::RUN_ONCE | \Ev::RUN_NOWAIT); }
php
protected function dispatch($blocking) { $this->handle->run($blocking ? \Ev::RUN_ONCE : \Ev::RUN_ONCE | \Ev::RUN_NOWAIT); }
[ "protected", "function", "dispatch", "(", "$", "blocking", ")", "{", "$", "this", "->", "handle", "->", "run", "(", "$", "blocking", "?", "\\", "Ev", "::", "RUN_ONCE", ":", "\\", "Ev", "::", "RUN_ONCE", "|", "\\", "Ev", "::", "RUN_NOWAIT", ")", ";", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/amphp/loop/blob/c7fbdfb7125e03b5653b13db1950fb45344e8e1b/lib/EvLoop.php#L117-L119
amphp/loop
lib/EvLoop.php
EvLoop.activate
protected function activate(array $watchers) { foreach ($watchers as $watcher) { if (!isset($this->events[$id = $watcher->id])) { switch ($watcher->type) { case Watcher::READABLE: $this->events[$id] = $this->handle->io($watcher->value, \Ev::READ, $this->ioCallback, $watcher); break; case Watcher::WRITABLE: $this->events[$id] = $this->handle->io($watcher->value, \Ev::WRITE, $this->ioCallback, $watcher); break; case Watcher::DELAY: case Watcher::REPEAT: $interval = $watcher->value / self::MILLISEC_PER_SEC; $this->events[$id] = $this->handle->timer( $interval, $watcher->type & Watcher::REPEAT ? $interval : 0, $this->timerCallback, $watcher ); break; case Watcher::SIGNAL: $this->events[$id] = $this->handle->signal($watcher->value, $this->signalCallback, $watcher); break; default: throw new \DomainException("Unknown watcher type"); } } else { $this->events[$id]->start(); } if ($watcher->type === Watcher::SIGNAL) { $this->signals[$id] = $this->events[$id]; } } }
php
protected function activate(array $watchers) { foreach ($watchers as $watcher) { if (!isset($this->events[$id = $watcher->id])) { switch ($watcher->type) { case Watcher::READABLE: $this->events[$id] = $this->handle->io($watcher->value, \Ev::READ, $this->ioCallback, $watcher); break; case Watcher::WRITABLE: $this->events[$id] = $this->handle->io($watcher->value, \Ev::WRITE, $this->ioCallback, $watcher); break; case Watcher::DELAY: case Watcher::REPEAT: $interval = $watcher->value / self::MILLISEC_PER_SEC; $this->events[$id] = $this->handle->timer( $interval, $watcher->type & Watcher::REPEAT ? $interval : 0, $this->timerCallback, $watcher ); break; case Watcher::SIGNAL: $this->events[$id] = $this->handle->signal($watcher->value, $this->signalCallback, $watcher); break; default: throw new \DomainException("Unknown watcher type"); } } else { $this->events[$id]->start(); } if ($watcher->type === Watcher::SIGNAL) { $this->signals[$id] = $this->events[$id]; } } }
[ "protected", "function", "activate", "(", "array", "$", "watchers", ")", "{", "foreach", "(", "$", "watchers", "as", "$", "watcher", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "events", "[", "$", "id", "=", "$", "watcher", "->", "id...
{@inheritdoc}
[ "{" ]
train
https://github.com/amphp/loop/blob/c7fbdfb7125e03b5653b13db1950fb45344e8e1b/lib/EvLoop.php#L124-L162
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.verifyConfig
private function verifyConfig() { foreach (Config::KEYS as $key) { if (!isset(Config::get()[$key])) { throw new OrmException('Key "'.$key.'" is not given.'); } } }
php
private function verifyConfig() { foreach (Config::KEYS as $key) { if (!isset(Config::get()[$key])) { throw new OrmException('Key "'.$key.'" is not given.'); } } }
[ "private", "function", "verifyConfig", "(", ")", "{", "foreach", "(", "Config", "::", "KEYS", "as", "$", "key", ")", "{", "if", "(", "!", "isset", "(", "Config", "::", "get", "(", ")", "[", "$", "key", "]", ")", ")", "{", "throw", "new", "OrmExce...
Vérifier que tout est bien renseigné dans la config @throws OrmException
[ "Vérifier", "que", "tout", "est", "bien", "renseigné", "dans", "la", "config" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L119-L126
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.setDbTable
private function setDbTable() { if (isset($this->table) && $this->table != null) { $this->dbTable = $this->table; } else { $classModel = get_called_class(); $classModelExplode = explode('\\', $classModel); $tableSnakePlural = Str::snakePlural(end($classModelExplode)); $this->dbTable = Config::get()['prefix'].$tableSnakePlural; } }
php
private function setDbTable() { if (isset($this->table) && $this->table != null) { $this->dbTable = $this->table; } else { $classModel = get_called_class(); $classModelExplode = explode('\\', $classModel); $tableSnakePlural = Str::snakePlural(end($classModelExplode)); $this->dbTable = Config::get()['prefix'].$tableSnakePlural; } }
[ "private", "function", "setDbTable", "(", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "table", ")", "&&", "$", "this", "->", "table", "!=", "null", ")", "{", "$", "this", "->", "dbTable", "=", "$", "this", "->", "table", ";", "}", "else...
Modifier table avec prefix _Si le nom de la table est précisée dans Model enfant : Récupérer manuellement nom de la table avec propriétée "table" dans Model enfant _Si non : Récupérer dynamiquement nom de la table selon nom du Model enfant (nom de la table doit être nom de la classe au pluriel)
[ "Modifier", "table", "avec", "prefix" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L136-L146
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.callGetterOrSetter
private function callGetterOrSetter(string $method, array $arguments) { $propertyWithUpper = lcfirst(substr($method, 3, mb_strlen($method))); $property = Str::convertCamelCaseToSnakeCase($propertyWithUpper); if (!property_exists(get_called_class(), $property)) { throw new OrmException('Property "'.$property.'" no exist.'); return false; } if (substr($method, 0, 3) === 'get') { // getter return $this->$property; } if (substr($method, 0, 3) === 'set') { // setter $this->assignProperty($method, $property, $arguments[0]); } return; }
php
private function callGetterOrSetter(string $method, array $arguments) { $propertyWithUpper = lcfirst(substr($method, 3, mb_strlen($method))); $property = Str::convertCamelCaseToSnakeCase($propertyWithUpper); if (!property_exists(get_called_class(), $property)) { throw new OrmException('Property "'.$property.'" no exist.'); return false; } if (substr($method, 0, 3) === 'get') { // getter return $this->$property; } if (substr($method, 0, 3) === 'set') { // setter $this->assignProperty($method, $property, $arguments[0]); } return; }
[ "private", "function", "callGetterOrSetter", "(", "string", "$", "method", ",", "array", "$", "arguments", ")", "{", "$", "propertyWithUpper", "=", "lcfirst", "(", "substr", "(", "$", "method", ",", "3", ",", "mb_strlen", "(", "$", "method", ")", ")", ")...
Si getter, retourner propriété. si setter, assigner valeur à une propriété @param string $method @param array $arguments @return bool|void @throws OrmException
[ "Si", "getter", "retourner", "propriété", ".", "si", "setter", "assigner", "valeur", "à", "une", "propriété" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L156-L176
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.callFindBy
private function callFindBy(string $method, array $arguments) { $whereByWithUpper = lcfirst(substr($method, 6, mb_strlen($method))); $whereBy = Str::convertCamelCaseToSnakeCase($whereByWithUpper); return $this->where($whereBy, '=', $arguments[0])->find(); }
php
private function callFindBy(string $method, array $arguments) { $whereByWithUpper = lcfirst(substr($method, 6, mb_strlen($method))); $whereBy = Str::convertCamelCaseToSnakeCase($whereByWithUpper); return $this->where($whereBy, '=', $arguments[0])->find(); }
[ "private", "function", "callFindBy", "(", "string", "$", "method", ",", "array", "$", "arguments", ")", "{", "$", "whereByWithUpper", "=", "lcfirst", "(", "substr", "(", "$", "method", ",", "6", ",", "mb_strlen", "(", "$", "method", ")", ")", ")", ";",...
Find WHERE une condition @param string $method @param array $arguments @return $this
[ "Find", "WHERE", "une", "condition" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L185-L191
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.callFindOrFailBy
private function callFindOrFailBy(string $method, array $arguments) { $whereByWithUpper = lcfirst(substr($method, 12, mb_strlen($method))); $whereBy = Str::convertCamelCaseToSnakeCase($whereByWithUpper); return $this->where($whereBy, '=', $arguments[0])->findOrFail(); }
php
private function callFindOrFailBy(string $method, array $arguments) { $whereByWithUpper = lcfirst(substr($method, 12, mb_strlen($method))); $whereBy = Str::convertCamelCaseToSnakeCase($whereByWithUpper); return $this->where($whereBy, '=', $arguments[0])->findOrFail(); }
[ "private", "function", "callFindOrFailBy", "(", "string", "$", "method", ",", "array", "$", "arguments", ")", "{", "$", "whereByWithUpper", "=", "lcfirst", "(", "substr", "(", "$", "method", ",", "12", ",", "mb_strlen", "(", "$", "method", ")", ")", ")",...
Find ou erreur HTTP 404 WHERE une condition @param string $method @param array $arguments @return $this
[ "Find", "ou", "erreur", "HTTP", "404", "WHERE", "une", "condition" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L200-L206
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.callFindAllBy
private function callFindAllBy(string $method, array $arguments) { $whereByWithUpper = lcfirst(substr($method, 9, mb_strlen($method))); $whereBy = Str::convertCamelCaseToSnakeCase($whereByWithUpper); return $this->where($whereBy, '=', $arguments[0])->findAll(); }
php
private function callFindAllBy(string $method, array $arguments) { $whereByWithUpper = lcfirst(substr($method, 9, mb_strlen($method))); $whereBy = Str::convertCamelCaseToSnakeCase($whereByWithUpper); return $this->where($whereBy, '=', $arguments[0])->findAll(); }
[ "private", "function", "callFindAllBy", "(", "string", "$", "method", ",", "array", "$", "arguments", ")", "{", "$", "whereByWithUpper", "=", "lcfirst", "(", "substr", "(", "$", "method", ",", "9", ",", "mb_strlen", "(", "$", "method", ")", ")", ")", "...
Find all WHERE une condition @param string $method @param array $arguments @return array
[ "Find", "all", "WHERE", "une", "condition" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L215-L221
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.callCountBy
private function callCountBy(string $method, array $arguments) { $whereByWithUpper = lcfirst(substr($method, 7, mb_strlen($method))); $whereBy = Str::convertCamelCaseToSnakeCase($whereByWithUpper); $column = (isset($arguments[1])) ? $arguments[1] : '*'; return $this->where($whereBy, '=', $arguments[0])->count($column); }
php
private function callCountBy(string $method, array $arguments) { $whereByWithUpper = lcfirst(substr($method, 7, mb_strlen($method))); $whereBy = Str::convertCamelCaseToSnakeCase($whereByWithUpper); $column = (isset($arguments[1])) ? $arguments[1] : '*'; return $this->where($whereBy, '=', $arguments[0])->count($column); }
[ "private", "function", "callCountBy", "(", "string", "$", "method", ",", "array", "$", "arguments", ")", "{", "$", "whereByWithUpper", "=", "lcfirst", "(", "substr", "(", "$", "method", ",", "7", ",", "mb_strlen", "(", "$", "method", ")", ")", ")", ";"...
Count WHERE une condition @param string $method @param array $arguments @return int
[ "Count", "WHERE", "une", "condition" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L230-L238
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.whereIn
final public function whereIn(string $column, array $values) { $this->query->addWhereIn($column, $values); return $this; }
php
final public function whereIn(string $column, array $values) { $this->query->addWhereIn($column, $values); return $this; }
[ "final", "public", "function", "whereIn", "(", "string", "$", "column", ",", "array", "$", "values", ")", "{", "$", "this", "->", "query", "->", "addWhereIn", "(", "$", "column", ",", "$", "values", ")", ";", "return", "$", "this", ";", "}" ]
Pour ajouter condition(s) avec WHERE IN (et avec AND si plusieurs conditions) @param string $column @param array $values @return $this
[ "Pour", "ajouter", "condition", "(", "s", ")", "avec", "WHERE", "IN", "(", "et", "avec", "AND", "si", "plusieurs", "conditions", ")" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L432-L437
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.orWhereIn
final public function orWhereIn(string $column, array $values) { $this->query->addOrWhereIn($column, $values); return $this; }
php
final public function orWhereIn(string $column, array $values) { $this->query->addOrWhereIn($column, $values); return $this; }
[ "final", "public", "function", "orWhereIn", "(", "string", "$", "column", ",", "array", "$", "values", ")", "{", "$", "this", "->", "query", "->", "addOrWhereIn", "(", "$", "column", ",", "$", "values", ")", ";", "return", "$", "this", ";", "}" ]
Pour ajouter condition(s) avec WHERE IN (et avec OR si plusieurs conditions) @param string $column @param array $values @return $this
[ "Pour", "ajouter", "condition", "(", "s", ")", "avec", "WHERE", "IN", "(", "et", "avec", "OR", "si", "plusieurs", "conditions", ")" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L446-L451
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.orderBy
final public function orderBy(string $orderBy, string $order = 'ASC') { $this->query->addOrderBy($orderBy, $order); return $this; }
php
final public function orderBy(string $orderBy, string $order = 'ASC') { $this->query->addOrderBy($orderBy, $order); return $this; }
[ "final", "public", "function", "orderBy", "(", "string", "$", "orderBy", ",", "string", "$", "order", "=", "'ASC'", ")", "{", "$", "this", "->", "query", "->", "addOrderBy", "(", "$", "orderBy", ",", "$", "order", ")", ";", "return", "$", "this", ";"...
Pour éventuellement ajouter un orderBy avec un order @param string $orderBy - Afficher par @param string $order - Ordre d'affichage @return $this
[ "Pour", "éventuellement", "ajouter", "un", "orderBy", "avec", "un", "order" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L460-L465
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.callError404
private function callError404() { list($controller, $method) = explode('@', Config::get()['error404']); if (!class_exists($controller)) { throw new OrmException('Class "'.$controller.'" not found.'); } $controllerInstantiate = new $controller(); if (!method_exists($controllerInstantiate, $method)) { throw new OrmException('Method "'.$method.'" not found in '.$controller.'.'); } return $controllerInstantiate->$method(); }
php
private function callError404() { list($controller, $method) = explode('@', Config::get()['error404']); if (!class_exists($controller)) { throw new OrmException('Class "'.$controller.'" not found.'); } $controllerInstantiate = new $controller(); if (!method_exists($controllerInstantiate, $method)) { throw new OrmException('Method "'.$method.'" not found in '.$controller.'.'); } return $controllerInstantiate->$method(); }
[ "private", "function", "callError404", "(", ")", "{", "list", "(", "$", "controller", ",", "$", "method", ")", "=", "explode", "(", "'@'", ",", "Config", "::", "get", "(", ")", "[", "'error404'", "]", ")", ";", "if", "(", "!", "class_exists", "(", ...
Appeler l'action d'erreur HTTP 404 @throws OrmException @return mixed
[ "Appeler", "l", "action", "d", "erreur", "HTTP", "404" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L516-L531
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.find
final public function find(int $id = null) { $result = $this->first($id); if (!$result) { return null; } $this->setProperties($result); return $this; }
php
final public function find(int $id = null) { $result = $this->first($id); if (!$result) { return null; } $this->setProperties($result); return $this; }
[ "final", "public", "function", "find", "(", "int", "$", "id", "=", "null", ")", "{", "$", "result", "=", "$", "this", "->", "first", "(", "$", "id", ")", ";", "if", "(", "!", "$", "result", ")", "{", "return", "null", ";", "}", "$", "this", "...
Pour les requetes SQL qui retournent une seule ligne @param int|null $id @return $this|null - Object hydraté
[ "Pour", "les", "requetes", "SQL", "qui", "retournent", "une", "seule", "ligne" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L539-L550
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.first
private function first(int $id = null) { $this->firstIsSelected = true; // utile pour active record if ($id) { $this->where('id', '=', $id); } $this->query->setStartSelect(); $this->limit(1); $this->query->prepare()->bindWhere()->bindLimit()->execute(); return $this->query->fetch(); }
php
private function first(int $id = null) { $this->firstIsSelected = true; // utile pour active record if ($id) { $this->where('id', '=', $id); } $this->query->setStartSelect(); $this->limit(1); $this->query->prepare()->bindWhere()->bindLimit()->execute(); return $this->query->fetch(); }
[ "private", "function", "first", "(", "int", "$", "id", "=", "null", ")", "{", "$", "this", "->", "firstIsSelected", "=", "true", ";", "// utile pour active record\r", "if", "(", "$", "id", ")", "{", "$", "this", "->", "where", "(", "'id'", ",", "'='", ...
Pour retourner le résultat d'une requete SQL qui retourne une seule ligne @param int|null $id @return mixed
[ "Pour", "retourner", "le", "résultat", "d", "une", "requete", "SQL", "qui", "retourne", "une", "seule", "ligne" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L558-L573
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.findAll
final public function findAll() { $this->query->setStartSelect(); $this->query->prepare()->bindWhere()->bindLimit()->execute(); $this->setRowCount(); $collection = new Collection($this, $this->query->getSqlQuery()); $this->query->close(); return $collection(); }
php
final public function findAll() { $this->query->setStartSelect(); $this->query->prepare()->bindWhere()->bindLimit()->execute(); $this->setRowCount(); $collection = new Collection($this, $this->query->getSqlQuery()); $this->query->close(); return $collection(); }
[ "final", "public", "function", "findAll", "(", ")", "{", "$", "this", "->", "query", "->", "setStartSelect", "(", ")", ";", "$", "this", "->", "query", "->", "prepare", "(", ")", "->", "bindWhere", "(", ")", "->", "bindLimit", "(", ")", "->", "execut...
Pour les requetes SQL qui retournent plusieurs lignes @return array - Un tableaux d'objets hydratés du model
[ "Pour", "les", "requetes", "SQL", "qui", "retournent", "plusieurs", "lignes" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L580-L593
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.query
final protected function query(string $sql, array $otpions = []) { $query = new Query($this); return $query->query($sql, $otpions); }
php
final protected function query(string $sql, array $otpions = []) { $query = new Query($this); return $query->query($sql, $otpions); }
[ "final", "protected", "function", "query", "(", "string", "$", "sql", ",", "array", "$", "otpions", "=", "[", "]", ")", "{", "$", "query", "=", "new", "Query", "(", "$", "this", ")", ";", "return", "$", "query", "->", "query", "(", "$", "sql", ",...
Pour les requetes SQL "complexes" @param string $sql @param array $otpions @return mixed - Requete
[ "Pour", "les", "requetes", "SQL", "complexes" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L637-L642
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.fill
final public function fill(array $data) { // Si dans les keys de $data il les valeurs de $fillable, assigner foreach ($this->fillable as $property) { if (array_key_exists($property, $data)){ $method = 'set'.ucfirst(Str::convertSnakeCaseToCamelCase($property)); $this->assignProperty($method, $property, $data[$property]); } } }
php
final public function fill(array $data) { // Si dans les keys de $data il les valeurs de $fillable, assigner foreach ($this->fillable as $property) { if (array_key_exists($property, $data)){ $method = 'set'.ucfirst(Str::convertSnakeCaseToCamelCase($property)); $this->assignProperty($method, $property, $data[$property]); } } }
[ "final", "public", "function", "fill", "(", "array", "$", "data", ")", "{", "// Si dans les keys de $data il les valeurs de $fillable, assigner\r", "foreach", "(", "$", "this", "->", "fillable", "as", "$", "property", ")", "{", "if", "(", "array_key_exists", "(", ...
Pour assigner en masse @param array $data
[ "Pour", "assigner", "en", "masse" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L699-L709
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.assignProperty
private function assignProperty(string $method, string $property, $value) { $mutatorMethod = $method.'Attribute'; // on prépare la valeur à sauvegarder dans la BDD if (method_exists($this, $mutatorMethod)) { $this->toSave[$property] = $this->$mutatorMethod($value); } else { $this->toSave[$property] = $value; } // on assigne la valeur à la propriétée $this->$property = $this->toSave[$property]; }
php
private function assignProperty(string $method, string $property, $value) { $mutatorMethod = $method.'Attribute'; // on prépare la valeur à sauvegarder dans la BDD if (method_exists($this, $mutatorMethod)) { $this->toSave[$property] = $this->$mutatorMethod($value); } else { $this->toSave[$property] = $value; } // on assigne la valeur à la propriétée $this->$property = $this->toSave[$property]; }
[ "private", "function", "assignProperty", "(", "string", "$", "method", ",", "string", "$", "property", ",", "$", "value", ")", "{", "$", "mutatorMethod", "=", "$", "method", ".", "'Attribute'", ";", "// on prépare la valeur à sauvegarder dans la BDD\r", "if", "(",...
Assigner une propriétée @param string $method @param string $property @param $value
[ "Assigner", "une", "propriétée" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L718-L731
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.save
final public function save() { if ($this->firstIsSelected === true) { $this->update($this->toSave); } else { $this->create($this->toSave); } }
php
final public function save() { if ($this->firstIsSelected === true) { $this->update($this->toSave); } else { $this->create($this->toSave); } }
[ "final", "public", "function", "save", "(", ")", "{", "if", "(", "$", "this", "->", "firstIsSelected", "===", "true", ")", "{", "$", "this", "->", "update", "(", "$", "this", "->", "toSave", ")", ";", "}", "else", "{", "$", "this", "->", "create", ...
Insérer ou modifier un élément avec le design pattern Active Record
[ "Insérer", "ou", "modifier", "un", "élément", "avec", "le", "design", "pattern", "Active", "Record" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L736-L743
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.create
final public function create(array $data) { $this->query->setStartInsert($data); $this->query->prepare()->bindValuesForInsert($data)->execute(); $this->setRowCount(); $this->query->close(); }
php
final public function create(array $data) { $this->query->setStartInsert($data); $this->query->prepare()->bindValuesForInsert($data)->execute(); $this->setRowCount(); $this->query->close(); }
[ "final", "public", "function", "create", "(", "array", "$", "data", ")", "{", "$", "this", "->", "query", "->", "setStartInsert", "(", "$", "data", ")", ";", "$", "this", "->", "query", "->", "prepare", "(", ")", "->", "bindValuesForInsert", "(", "$", ...
Pour les requetes SQL INSERT INTO - Insertion d'une nouvelle ligne @param array $data - Colonnes où faire le INSERT, et valeurs à insérer
[ "Pour", "les", "requetes", "SQL", "INSERT", "INTO", "-", "Insertion", "d", "une", "nouvelle", "ligne" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L750-L759
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.update
final public function update(array $data) { $this->query->setStartUpdate($data); $this->query->prepare()->bindSetForUpdate($data)->bindWhere()->bindLimit()->execute(); $this->setRowCount(); $this->query->close(); }
php
final public function update(array $data) { $this->query->setStartUpdate($data); $this->query->prepare()->bindSetForUpdate($data)->bindWhere()->bindLimit()->execute(); $this->setRowCount(); $this->query->close(); }
[ "final", "public", "function", "update", "(", "array", "$", "data", ")", "{", "$", "this", "->", "query", "->", "setStartUpdate", "(", "$", "data", ")", ";", "$", "this", "->", "query", "->", "prepare", "(", ")", "->", "bindSetForUpdate", "(", "$", "...
Pour les requetes SQL UPDATE - Modifications sur des lignes existantes @param array $data - Colonnes où faire le UPDATE, et valeurs à insérer
[ "Pour", "les", "requetes", "SQL", "UPDATE", "-", "Modifications", "sur", "des", "lignes", "existantes" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L766-L775
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.delete
final public function delete() { $this->query->setStartDelete(); $this->query->prepare()->bindWhere()->bindLimit()->execute(); $this->setRowCount(); $this->query->close(); }
php
final public function delete() { $this->query->setStartDelete(); $this->query->prepare()->bindWhere()->bindLimit()->execute(); $this->setRowCount(); $this->query->close(); }
[ "final", "public", "function", "delete", "(", ")", "{", "$", "this", "->", "query", "->", "setStartDelete", "(", ")", ";", "$", "this", "->", "query", "->", "prepare", "(", ")", "->", "bindWhere", "(", ")", "->", "bindLimit", "(", ")", "->", "execute...
Pour les requetes SQL DELETE - Supprimer ligne(s) dans une table
[ "Pour", "les", "requetes", "SQL", "DELETE", "-", "Supprimer", "ligne", "(", "s", ")", "dans", "une", "table" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L788-L797
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.setProperties
private function setProperties($query) { foreach ($query as $property => $value) { if (property_exists(get_called_class(), $property)) { $this->$property = $value; } } }
php
private function setProperties($query) { foreach ($query as $property => $value) { if (property_exists(get_called_class(), $property)) { $this->$property = $value; } } }
[ "private", "function", "setProperties", "(", "$", "query", ")", "{", "foreach", "(", "$", "query", "as", "$", "property", "=>", "$", "value", ")", "{", "if", "(", "property_exists", "(", "get_called_class", "(", ")", ",", "$", "property", ")", ")", "{"...
Pour hydrater un objet à partir d'une requete SQL qui récupère une seule ligne @param mixed $query - Résultat d'une requete SQL qui récupère une seule ligne
[ "Pour", "hydrater", "un", "objet", "à", "partir", "d", "une", "requete", "SQL", "qui", "récupère", "une", "seule", "ligne" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L888-L895
stephweb/daw-php-orm
src/DawPhpOrm/Database/BaseModel.php
BaseModel.getHydratedObjects
final protected function getHydratedObjects($query): array { $collection = new Collection($this, $query); $this->query->close($query); return $collection(); }
php
final protected function getHydratedObjects($query): array { $collection = new Collection($this, $query); $this->query->close($query); return $collection(); }
[ "final", "protected", "function", "getHydratedObjects", "(", "$", "query", ")", ":", "array", "{", "$", "collection", "=", "new", "Collection", "(", "$", "this", ",", "$", "query", ")", ";", "$", "this", "->", "query", "->", "close", "(", "$", "query",...
Hydrater des objets du Model @param mixed $query - Résultat d'une requete SQL qui récupère plusieurs lignes @return array - Collection d'objets
[ "Hydrater", "des", "objets", "du", "Model" ]
train
https://github.com/stephweb/daw-php-orm/blob/0c37e3baa1420cf9e3feff122016329de3764bcc/src/DawPhpOrm/Database/BaseModel.php#L903-L910
alexandresalome/pagination
Pager.php
Pager.setPage
public function setPage($page) { $this->offset = (max(1, (int) $page) - 1) * $this->perPage; return $this; }
php
public function setPage($page) { $this->offset = (max(1, (int) $page) - 1) * $this->perPage; return $this; }
[ "public", "function", "setPage", "(", "$", "page", ")", "{", "$", "this", "->", "offset", "=", "(", "max", "(", "1", ",", "(", "int", ")", "$", "page", ")", "-", "1", ")", "*", "$", "this", "->", "perPage", ";", "return", "$", "this", ";", "}...
Changes the current page. @param int $page the page to jump to. @return Pager
[ "Changes", "the", "current", "page", "." ]
train
https://github.com/alexandresalome/pagination/blob/bef7e290a8514baf418a57f52c879528779d75d1/Pager.php#L67-L72
alexandresalome/pagination
Pager.php
Pager.getPageRange
public function getPageRange($range = 4) { $from = max(1, $this->getPage() - $range); $to = min($this->getPageCount(), $this->getPage() + $range); return range($from, $to); }
php
public function getPageRange($range = 4) { $from = max(1, $this->getPage() - $range); $to = min($this->getPageCount(), $this->getPage() + $range); return range($from, $to); }
[ "public", "function", "getPageRange", "(", "$", "range", "=", "4", ")", "{", "$", "from", "=", "max", "(", "1", ",", "$", "this", "->", "getPage", "(", ")", "-", "$", "range", ")", ";", "$", "to", "=", "min", "(", "$", "this", "->", "getPageCou...
Returns an array of page numbers for a given range. @return array
[ "Returns", "an", "array", "of", "page", "numbers", "for", "a", "given", "range", "." ]
train
https://github.com/alexandresalome/pagination/blob/bef7e290a8514baf418a57f52c879528779d75d1/Pager.php#L148-L154
aimeos/ai-admin-extadm
controller/extjs/src/Controller/ExtJS/Price/Standard.php
Standard.searchItems
public function searchItems( \stdClass $params ) { $this->checkParams( $params, array( 'site' ) ); $this->setLocale( $params->site ); $total = 0; $search = $this->initCriteria( $this->getManager()->createSearch(), $params ); if( isset( $params->domain ) && isset( $params->parentid ) && ( !isset( $params->options->showall ) || $params->options->showall == false ) ) { $listManager = \Aimeos\MShop\Factory::createManager( $this->getContext(), $params->domain . '/lists' ); $criteria = $listManager->createSearch(); $expr = []; $expr[] = $criteria->compare( '==', $params->domain . '.lists.parentid', $params->parentid ); $expr[] = $criteria->compare( '==', $params->domain . '.lists.domain', 'price' ); $criteria->setConditions( $criteria->combine( '&&', $expr ) ); $result = $listManager->searchItems( $criteria ); $ids = []; foreach( $result as $items ) { $ids[] = $items->getRefId(); } $expr = []; $expr[] = $search->compare( '==', 'price.id', $ids ); $expr[] = $search->getConditions(); $search->setConditions( $search->combine( '&&', $expr ) ); } $items = $this->getManager()->searchItems( $search, [], $total ); return array( 'items' => $this->toArray( $items ), 'total' => $total, 'success' => true, ); }
php
public function searchItems( \stdClass $params ) { $this->checkParams( $params, array( 'site' ) ); $this->setLocale( $params->site ); $total = 0; $search = $this->initCriteria( $this->getManager()->createSearch(), $params ); if( isset( $params->domain ) && isset( $params->parentid ) && ( !isset( $params->options->showall ) || $params->options->showall == false ) ) { $listManager = \Aimeos\MShop\Factory::createManager( $this->getContext(), $params->domain . '/lists' ); $criteria = $listManager->createSearch(); $expr = []; $expr[] = $criteria->compare( '==', $params->domain . '.lists.parentid', $params->parentid ); $expr[] = $criteria->compare( '==', $params->domain . '.lists.domain', 'price' ); $criteria->setConditions( $criteria->combine( '&&', $expr ) ); $result = $listManager->searchItems( $criteria ); $ids = []; foreach( $result as $items ) { $ids[] = $items->getRefId(); } $expr = []; $expr[] = $search->compare( '==', 'price.id', $ids ); $expr[] = $search->getConditions(); $search->setConditions( $search->combine( '&&', $expr ) ); } $items = $this->getManager()->searchItems( $search, [], $total ); return array( 'items' => $this->toArray( $items ), 'total' => $total, 'success' => true, ); }
[ "public", "function", "searchItems", "(", "\\", "stdClass", "$", "params", ")", "{", "$", "this", "->", "checkParams", "(", "$", "params", ",", "array", "(", "'site'", ")", ")", ";", "$", "this", "->", "setLocale", "(", "$", "params", "->", "site", "...
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/Price/Standard.php#L45-L84
makinacorpus/drupal-ucms
ucms_contrib/src/EventDispatcher/NodeReferenceCollectEvent.php
NodeReferenceCollectEvent.addReferences
public function addReferences($type, $nodeIdList, $field = null) { if (!is_array($nodeIdList)) { $nodeIdList = [$nodeIdList]; } $sourceId = $this->getNode()->id(); foreach ($nodeIdList as $nodeId) { $this->references[$type . $nodeId] = new NodeReference($sourceId, $nodeId, $type, $field); } }
php
public function addReferences($type, $nodeIdList, $field = null) { if (!is_array($nodeIdList)) { $nodeIdList = [$nodeIdList]; } $sourceId = $this->getNode()->id(); foreach ($nodeIdList as $nodeId) { $this->references[$type . $nodeId] = new NodeReference($sourceId, $nodeId, $type, $field); } }
[ "public", "function", "addReferences", "(", "$", "type", ",", "$", "nodeIdList", ",", "$", "field", "=", "null", ")", "{", "if", "(", "!", "is_array", "(", "$", "nodeIdList", ")", ")", "{", "$", "nodeIdList", "=", "[", "$", "nodeIdList", "]", ";", ...
Add one or more references @param int|int[] $nodeIdList Node identifiers list @param string $type Reference type for business purposes, 'media', 'link' or any other @param string $field Field name this reference was found into
[ "Add", "one", "or", "more", "references" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_contrib/src/EventDispatcher/NodeReferenceCollectEvent.php#L50-L61
fogs/tagging-bundle
Service/TagManager.php
TagManager.findTags
public function findTags($search) { return $this->em ->createQueryBuilder() ->select('t.name') ->from($this->tagClass, 't') ->where('t.slug LIKE :search') ->setParameter('search', strtolower('%' . $search . '%')) ->setMaxResults(5) ->orderBy('t.name') ->getQuery() ->getResult(Query::HYDRATE_SCALAR) ; }
php
public function findTags($search) { return $this->em ->createQueryBuilder() ->select('t.name') ->from($this->tagClass, 't') ->where('t.slug LIKE :search') ->setParameter('search', strtolower('%' . $search . '%')) ->setMaxResults(5) ->orderBy('t.name') ->getQuery() ->getResult(Query::HYDRATE_SCALAR) ; }
[ "public", "function", "findTags", "(", "$", "search", ")", "{", "return", "$", "this", "->", "em", "->", "createQueryBuilder", "(", ")", "->", "select", "(", "'t.name'", ")", "->", "from", "(", "$", "this", "->", "tagClass", ",", "'t'", ")", "->", "w...
Search for tags @param string $search
[ "Search", "for", "tags" ]
train
https://github.com/fogs/tagging-bundle/blob/1541b7f80462ed6fc0136f72dcbab67790ff17b6/Service/TagManager.php#L32-L45
qloog/yaf-library
src/Views/View.php
View.assign
public function assign($name, $value = null) { if (is_array($name)) { $this->data = array_merge($this->data, $name); } else { $this->data[$name] = $value; } return true; }
php
public function assign($name, $value = null) { if (is_array($name)) { $this->data = array_merge($this->data, $name); } else { $this->data[$name] = $value; } return true; }
[ "public", "function", "assign", "(", "$", "name", ",", "$", "value", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "name", ")", ")", "{", "$", "this", "->", "data", "=", "array_merge", "(", "$", "this", "->", "data", ",", "$", "name", ...
模板赋值 @param array|string $name @param null|string $value @return bool
[ "模板赋值" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Views/View.php#L125-L134
qloog/yaf-library
src/Views/View.php
View.display
public function display($tpl, $data = array()) { if ($this->isRending) { throw new RenderException('Display is called.'); } $this->assign($data); echo $this->render($tpl, $data); return true; }
php
public function display($tpl, $data = array()) { if ($this->isRending) { throw new RenderException('Display is called.'); } $this->assign($data); echo $this->render($tpl, $data); return true; }
[ "public", "function", "display", "(", "$", "tpl", ",", "$", "data", "=", "array", "(", ")", ")", "{", "if", "(", "$", "this", "->", "isRending", ")", "{", "throw", "new", "RenderException", "(", "'Display is called.'", ")", ";", "}", "$", "this", "->...
渲染并输出 @param string $tpl @param array $data @return bool @throws RenderException
[ "渲染并输出" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Views/View.php#L170-L181
qloog/yaf-library
src/Views/View.php
View.render
public function render($tpl, $data = []) { $isFirst = false; if (!$this->isRending) { $this->isRending = $isFirst = true; $this->block = new Block(); } if (substr_compare($tpl, $this->ext, -strlen($this->ext)) !== 0) { $tpl .= $this->ext; } if ($this->stacks && $tpl[0] !== '/') { $path = dirname(current($this->stacks)) . '/' . $tpl; } else { $path = $this->getScriptPath() . '/' . $tpl; } $realPath = realpath($path); if ($realPath === false) { throw new RenderException('Not found the template: ' . $path); } array_unshift($this->stacks, $realPath); $content = $this->extractRender($realPath, $data); if ($isFirst) { $content = $this->block->replace($content); } array_shift($this->stacks); return $content; }
php
public function render($tpl, $data = []) { $isFirst = false; if (!$this->isRending) { $this->isRending = $isFirst = true; $this->block = new Block(); } if (substr_compare($tpl, $this->ext, -strlen($this->ext)) !== 0) { $tpl .= $this->ext; } if ($this->stacks && $tpl[0] !== '/') { $path = dirname(current($this->stacks)) . '/' . $tpl; } else { $path = $this->getScriptPath() . '/' . $tpl; } $realPath = realpath($path); if ($realPath === false) { throw new RenderException('Not found the template: ' . $path); } array_unshift($this->stacks, $realPath); $content = $this->extractRender($realPath, $data); if ($isFirst) { $content = $this->block->replace($content); } array_shift($this->stacks); return $content; }
[ "public", "function", "render", "(", "$", "tpl", ",", "$", "data", "=", "[", "]", ")", "{", "$", "isFirst", "=", "false", ";", "if", "(", "!", "$", "this", "->", "isRending", ")", "{", "$", "this", "->", "isRending", "=", "$", "isFirst", "=", "...
渲染模板 @param string $tpl @param array $data @return String @throws RenderException
[ "渲染模板" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Views/View.php#L191-L224
qloog/yaf-library
src/Views/View.php
View.extend
public function extend($tpl, array $data = []) { echo $this->render($tpl, array_merge($this->data, $data)); }
php
public function extend($tpl, array $data = []) { echo $this->render($tpl, array_merge($this->data, $data)); }
[ "public", "function", "extend", "(", "$", "tpl", ",", "array", "$", "data", "=", "[", "]", ")", "{", "echo", "$", "this", "->", "render", "(", "$", "tpl", ",", "array_merge", "(", "$", "this", "->", "data", ",", "$", "data", ")", ")", ";", "}" ...
继承模板 @param $tpl @param $data
[ "继承模板" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Views/View.php#L249-L252
qloog/yaf-library
src/Views/View.php
View.escape
public function escape($string, $flags = 'html') { switch ($flags) { case 'url' : return urlencode($string); case 'quotes' : return addcslashes($string, '"\'\\'); case 'phone' : if (strlen($string) < 8) { return substr($string, 0, -4) . '****'; } return substr($string, 0, 3) . '****' . substr($string, -4); case 'json' : return json_encode($string); case 'html' : default : return htmlspecialchars($string, ENT_QUOTES|ENT_HTML5); } }
php
public function escape($string, $flags = 'html') { switch ($flags) { case 'url' : return urlencode($string); case 'quotes' : return addcslashes($string, '"\'\\'); case 'phone' : if (strlen($string) < 8) { return substr($string, 0, -4) . '****'; } return substr($string, 0, 3) . '****' . substr($string, -4); case 'json' : return json_encode($string); case 'html' : default : return htmlspecialchars($string, ENT_QUOTES|ENT_HTML5); } }
[ "public", "function", "escape", "(", "$", "string", ",", "$", "flags", "=", "'html'", ")", "{", "switch", "(", "$", "flags", ")", "{", "case", "'url'", ":", "return", "urlencode", "(", "$", "string", ")", ";", "case", "'quotes'", ":", "return", "addc...
转义HTML @param string $string @param string $flags html|url|json @return mixed
[ "转义HTML" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Views/View.php#L261-L279
makinacorpus/drupal-ucms
ucms_contrib/src/DependencyInjection/ContribExtension.php
ContribExtension.load
public function load(array $configs, ContainerBuilder $container) { $configuration = $this->getConfiguration($configs, $container); // From the configured pages, build services foreach ($configs as $config) { // Do not process everything at once, it will erase array keys // of all pages definitions except those from the very first config // file, and break all our services identifiers $config = $this->processConfiguration($configuration, [$config]); if (empty($config['admin_pages'])) { // If any (one or more) module, extension or app config itself // provided pages, we drop defaults, but in case none did, we // must provide something to the user. // All strings will be translated automatically at runtime. $config['admin_pages'] = [ 'mine' => [ 'title' => "My content", 'access' => 'access ucms content overview', 'base_query' => [], ], 'local' => [ 'title' => "Local", 'access' => 'access ucms content overview', 'base_query' => [ 'is_global' => 0, ], ], 'global' => [ 'title' => "Global", 'access' => 'content manage global', 'base_query' => [ 'is_global' => 1, 'is_corporate' => 0, ], ], 'flagged' => [ 'title' => "Flagged", 'access' => 'content manage global', 'base_query' => [ 'is_flagged' => 1 ], ], 'starred' => [ 'title' => "Starred", 'access' => 'content manage global', 'base_query' => [ 'is_starred' => 1 ], ], ]; } // This will be re-used as is without any transformation into // the ucms_contrib_menu() implementation to build node admin // pages. Configuration implementation, in theory, validated // and normalized the input so it's safe to proceed. $container->setParameter('ucms_contrib.admin_pages', $config['admin_pages']); } }
php
public function load(array $configs, ContainerBuilder $container) { $configuration = $this->getConfiguration($configs, $container); // From the configured pages, build services foreach ($configs as $config) { // Do not process everything at once, it will erase array keys // of all pages definitions except those from the very first config // file, and break all our services identifiers $config = $this->processConfiguration($configuration, [$config]); if (empty($config['admin_pages'])) { // If any (one or more) module, extension or app config itself // provided pages, we drop defaults, but in case none did, we // must provide something to the user. // All strings will be translated automatically at runtime. $config['admin_pages'] = [ 'mine' => [ 'title' => "My content", 'access' => 'access ucms content overview', 'base_query' => [], ], 'local' => [ 'title' => "Local", 'access' => 'access ucms content overview', 'base_query' => [ 'is_global' => 0, ], ], 'global' => [ 'title' => "Global", 'access' => 'content manage global', 'base_query' => [ 'is_global' => 1, 'is_corporate' => 0, ], ], 'flagged' => [ 'title' => "Flagged", 'access' => 'content manage global', 'base_query' => [ 'is_flagged' => 1 ], ], 'starred' => [ 'title' => "Starred", 'access' => 'content manage global', 'base_query' => [ 'is_starred' => 1 ], ], ]; } // This will be re-used as is without any transformation into // the ucms_contrib_menu() implementation to build node admin // pages. Configuration implementation, in theory, validated // and normalized the input so it's safe to proceed. $container->setParameter('ucms_contrib.admin_pages', $config['admin_pages']); } }
[ "public", "function", "load", "(", "array", "$", "configs", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "configuration", "=", "$", "this", "->", "getConfiguration", "(", "$", "configs", ",", "$", "container", ")", ";", "// From the configured pag...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_contrib/src/DependencyInjection/ContribExtension.php#L26-L86
makinacorpus/drupal-ucms
ucms_user/src/Form/UserEnable.php
UserEnable.buildForm
public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = null) { if ($user === null) { return []; } $form_state->setTemporaryValue('user', $user); if ($user->isBlocked() && ((int) $user->getLastAccessedTime() === 0)) { $form['explanation'] = [ '#type' => 'item', '#markup' => $this->t("This user has never been connected. You have to define a password and pass it on to the user by yourself."), ]; $form['password'] = [ '#type' => 'password_confirm', '#size' => 20, '#required' => true, '#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' => $this->t('Enable'), ]; return $form; } else { $question = $this->t("Do you really want to enable the user @name?", ['@name' => $user->name]); return confirm_form($form, $question, 'admin/dashboard/user', ''); } }
php
public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = null) { if ($user === null) { return []; } $form_state->setTemporaryValue('user', $user); if ($user->isBlocked() && ((int) $user->getLastAccessedTime() === 0)) { $form['explanation'] = [ '#type' => 'item', '#markup' => $this->t("This user has never been connected. You have to define a password and pass it on to the user by yourself."), ]; $form['password'] = [ '#type' => 'password_confirm', '#size' => 20, '#required' => true, '#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' => $this->t('Enable'), ]; return $form; } else { $question = $this->t("Do you really want to enable the user @name?", ['@name' => $user->name]); return confirm_form($form, $question, 'admin/dashboard/user', ''); } }
[ "public", "function", "buildForm", "(", "array", "$", "form", ",", "FormStateInterface", "$", "form_state", ",", "UserInterface", "$", "user", "=", "null", ")", "{", "if", "(", "$", "user", "===", "null", ")", "{", "return", "[", "]", ";", "}", "$", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_user/src/Form/UserEnable.php#L65-L98
makinacorpus/drupal-ucms
ucms_user/src/Form/UserEnable.php
UserEnable.validateForm
public function validateForm(array &$form, FormStateInterface $form_state) { /* @var $user UserInterface */ $user = $form_state->getTemporaryValue('user'); if ( $user->isBlocked() && ((int) $user->getLastAccessedTime() === 0) && (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) { /* @var $user UserInterface */ $user = $form_state->getTemporaryValue('user'); if ( $user->isBlocked() && ((int) $user->getLastAccessedTime() === 0) && (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", ")", "{", "/* @var $user UserInterface */", "$", "user", "=", "$", "form_state", "->", "getTemporaryValue", "(", "'user'", ")", ";", "if", "(", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_user/src/Form/UserEnable.php#L104-L116
makinacorpus/drupal-ucms
ucms_user/src/Form/UserEnable.php
UserEnable.submitForm
public function submitForm(array &$form, FormStateInterface $form_state) { /* @var $user UserInterface */ $user = $form_state->getTemporaryValue('user'); $user->status = 1; if ($user->isBlocked() && ((int) $user->getLastAccessedTime() === 0)) { require_once DRUPAL_ROOT . '/includes/password.inc'; $user->pass = user_hash_password($form_state->getValue('password')); } if ($this->entityManager->getStorage('user')->save($user)) { drupal_set_message($this->t("User @name has been enabled.", array('@name' => $user->getDisplayName()))); $this->dispatcher->dispatch('user:enable', new UserEvent($user->id(), $this->currentUser()->id())); } 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) { /* @var $user UserInterface */ $user = $form_state->getTemporaryValue('user'); $user->status = 1; if ($user->isBlocked() && ((int) $user->getLastAccessedTime() === 0)) { require_once DRUPAL_ROOT . '/includes/password.inc'; $user->pass = user_hash_password($form_state->getValue('password')); } if ($this->entityManager->getStorage('user')->save($user)) { drupal_set_message($this->t("User @name has been enabled.", array('@name' => $user->getDisplayName()))); $this->dispatcher->dispatch('user:enable', new UserEvent($user->id(), $this->currentUser()->id())); } 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", ")", "{", "/* @var $user UserInterface */", "$", "user", "=", "$", "form_state", "->", "getTemporaryValue", "(", "'user'", ")", ";", "$", "user", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_user/src/Form/UserEnable.php#L122-L141
makinacorpus/drupal-ucms
ucms_site/src/Action/AbstractWebmasterActionProvider.php
AbstractWebmasterActionProvider.createDeleteAction
protected function createDeleteAction(SiteAccessRecord $item) { $path = $this->buildWebmasterUri($item, 'delete'); return new Action($this->t("Delete from this site"), $path, 'dialog', 'remove', 100, true, true); }
php
protected function createDeleteAction(SiteAccessRecord $item) { $path = $this->buildWebmasterUri($item, 'delete'); return new Action($this->t("Delete from this site"), $path, 'dialog', 'remove', 100, true, true); }
[ "protected", "function", "createDeleteAction", "(", "SiteAccessRecord", "$", "item", ")", "{", "$", "path", "=", "$", "this", "->", "buildWebmasterUri", "(", "$", "item", ",", "'delete'", ")", ";", "return", "new", "Action", "(", "$", "this", "->", "t", ...
Creates the action to delete a user from a site. @param SiteAccessRecord $item @return Action
[ "Creates", "the", "action", "to", "delete", "a", "user", "from", "a", "site", "." ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Action/AbstractWebmasterActionProvider.php#L66-L70
makinacorpus/drupal-ucms
ucms_site/src/Form/SiteRequest.php
SiteRequest.buildForm
public function buildForm(array $form, FormStateInterface $form_state) { $form['#form_horizontal'] = true; $formData = &$form_state->getStorage(); if (empty($formData['site'])) { $site = $formData['site'] = new Site(); $site->uid = $this->currentUser()->uid; } else { $site = $formData['site']; } $form['#site'] = $site; // This is used in *_form_alter() if (empty($formData['step'])) { $step = $formData['step'] = 'a'; } else { $step = $formData['step']; } switch ($step) { case 'a': // Basic information about site return $this->buildStepA($form, $form_state, $site); break; case 'b': // Information about template and theme return $this->buildStepB($form, $form_state, $site); break; } // This is an error... $this->logger('form')->critical("Invalid step @step", ['@step' => $step]); return $form; }
php
public function buildForm(array $form, FormStateInterface $form_state) { $form['#form_horizontal'] = true; $formData = &$form_state->getStorage(); if (empty($formData['site'])) { $site = $formData['site'] = new Site(); $site->uid = $this->currentUser()->uid; } else { $site = $formData['site']; } $form['#site'] = $site; // This is used in *_form_alter() if (empty($formData['step'])) { $step = $formData['step'] = 'a'; } else { $step = $formData['step']; } switch ($step) { case 'a': // Basic information about site return $this->buildStepA($form, $form_state, $site); break; case 'b': // Information about template and theme return $this->buildStepB($form, $form_state, $site); break; } // This is an error... $this->logger('form')->critical("Invalid step @step", ['@step' => $step]); return $form; }
[ "public", "function", "buildForm", "(", "array", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "$", "form", "[", "'#form_horizontal'", "]", "=", "true", ";", "$", "formData", "=", "&", "$", "form_state", "->", "getStorage", "(", ")",...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Form/SiteRequest.php#L58-L95
makinacorpus/drupal-ucms
ucms_site/src/Form/SiteRequest.php
SiteRequest.buildStepA
private function buildStepA(array $form, FormStateInterface $form_state, Site $site) { $form['title'] = [ '#title' => $this->t("Name"), '#type' => 'textfield', '#default_value' => $site->title, '#attributes' => ['placeholder' => $this->t("Martin's blog")], '#description' => $this->t("This will appear as the site's title on the frontoffice."), '#required' => true, ]; $form['title_admin'] = [ '#title' => $this->t("Administrative title"), '#type' => 'textfield', '#default_value' => $site->title_admin, '#attributes' => ['placeholder' => $this->t("Martin's blog")], '#description' => $this->t("This will be the site's title for the backoffice."), '#maxlength' => 255, '#required' => true, ]; $form['http_host'] = [ '#title' => $this->t("Host name"), '#type' => 'textfield', '#field_prefix' => "http://", '#default_value' => $site->http_host, '#attributes' => ['placeholder' => "martin-blog.fr"], '#description' => $this->t("Type here the site URL"), '#element_validate' => ['::validateHttpHost'], '#required' => true, ]; $form['allowed_protocols'] = [ '#title' => $this->t("Allowed protocols"), '#type' => 'select', '#options' => [ Site::ALLOWED_PROTOCOL_HTTPS => $this->t("Secure HTTPS only"), Site::ALLOWED_PROTOCOL_HTTP => $this->t("Unsecure HTTP only"), Site::ALLOWED_PROTOCOL_ALL => $this->t("Both secure HTTPS and unsecure HTTP"), Site::ALLOWED_PROTOCOL_PASS => $this->t("Let Drupal decide depending on the environment") ], '#default_value' => $site->allowed_protocols, '#description' => $this->t("This is a technical setting that depends on the web server configuration, the technical administrators might change it."), '#required' => true, ]; $form['replacement_of'] = [ '#title' => $this->t("Replaces"), '#type' => 'textarea', '#default_value' => $site->replacement_of, '#attributes' => ['placeholder' => "martin-blog.fr"], '#description' => $this->t("If the new site aims to replace an existing site, please copy/paste the site URI into this textarea, you may write more than one URI or any useful textual information."), '#required' => false, '#rows' => 2, ]; $form['http_redirects'] = [ '#title' => $this->t("Host name redirects"), '#type' => 'textarea', '#default_value' => $site->http_redirects, '#attributes' => ['placeholder' => "www.martin-blog.fr, martinblog.com"], '#description' => $this->t("List of domain names that should redirect on this site, this is, you may write more than one URI or any useful textual information."), '#required' => false, '#rows' => 2, ]; $form['is_public'] = [ '#title' => $this->t("Public site"), '#type' => 'checkbox', '#description' => $this->t("Uncheck this field to limit access to the site."), '#default_value' => ($site->getId() == null) ? 1 : $site->is_public, ]; // @todo Missing site type $form['actions']['#type'] = 'actions'; $form['actions']['continue'] = [ '#type' => 'submit', '#value' => $this->t("Continue"), '#submit' => ['::submitStepA'], ]; $form['actions']['cancel'] = [ '#markup' => l( $this->t("Cancel"), isset($_GET['destination']) ? $_GET['destination'] : 'admin/dashboard/site', ['attributes' => ['class' => ['btn', 'btn-danger']]] ), ]; return $form; }
php
private function buildStepA(array $form, FormStateInterface $form_state, Site $site) { $form['title'] = [ '#title' => $this->t("Name"), '#type' => 'textfield', '#default_value' => $site->title, '#attributes' => ['placeholder' => $this->t("Martin's blog")], '#description' => $this->t("This will appear as the site's title on the frontoffice."), '#required' => true, ]; $form['title_admin'] = [ '#title' => $this->t("Administrative title"), '#type' => 'textfield', '#default_value' => $site->title_admin, '#attributes' => ['placeholder' => $this->t("Martin's blog")], '#description' => $this->t("This will be the site's title for the backoffice."), '#maxlength' => 255, '#required' => true, ]; $form['http_host'] = [ '#title' => $this->t("Host name"), '#type' => 'textfield', '#field_prefix' => "http://", '#default_value' => $site->http_host, '#attributes' => ['placeholder' => "martin-blog.fr"], '#description' => $this->t("Type here the site URL"), '#element_validate' => ['::validateHttpHost'], '#required' => true, ]; $form['allowed_protocols'] = [ '#title' => $this->t("Allowed protocols"), '#type' => 'select', '#options' => [ Site::ALLOWED_PROTOCOL_HTTPS => $this->t("Secure HTTPS only"), Site::ALLOWED_PROTOCOL_HTTP => $this->t("Unsecure HTTP only"), Site::ALLOWED_PROTOCOL_ALL => $this->t("Both secure HTTPS and unsecure HTTP"), Site::ALLOWED_PROTOCOL_PASS => $this->t("Let Drupal decide depending on the environment") ], '#default_value' => $site->allowed_protocols, '#description' => $this->t("This is a technical setting that depends on the web server configuration, the technical administrators might change it."), '#required' => true, ]; $form['replacement_of'] = [ '#title' => $this->t("Replaces"), '#type' => 'textarea', '#default_value' => $site->replacement_of, '#attributes' => ['placeholder' => "martin-blog.fr"], '#description' => $this->t("If the new site aims to replace an existing site, please copy/paste the site URI into this textarea, you may write more than one URI or any useful textual information."), '#required' => false, '#rows' => 2, ]; $form['http_redirects'] = [ '#title' => $this->t("Host name redirects"), '#type' => 'textarea', '#default_value' => $site->http_redirects, '#attributes' => ['placeholder' => "www.martin-blog.fr, martinblog.com"], '#description' => $this->t("List of domain names that should redirect on this site, this is, you may write more than one URI or any useful textual information."), '#required' => false, '#rows' => 2, ]; $form['is_public'] = [ '#title' => $this->t("Public site"), '#type' => 'checkbox', '#description' => $this->t("Uncheck this field to limit access to the site."), '#default_value' => ($site->getId() == null) ? 1 : $site->is_public, ]; // @todo Missing site type $form['actions']['#type'] = 'actions'; $form['actions']['continue'] = [ '#type' => 'submit', '#value' => $this->t("Continue"), '#submit' => ['::submitStepA'], ]; $form['actions']['cancel'] = [ '#markup' => l( $this->t("Cancel"), isset($_GET['destination']) ? $_GET['destination'] : 'admin/dashboard/site', ['attributes' => ['class' => ['btn', 'btn-danger']]] ), ]; return $form; }
[ "private", "function", "buildStepA", "(", "array", "$", "form", ",", "FormStateInterface", "$", "form_state", ",", "Site", "$", "site", ")", "{", "$", "form", "[", "'title'", "]", "=", "[", "'#title'", "=>", "$", "this", "->", "t", "(", "\"Name\"", ")"...
Step A form builder
[ "Step", "A", "form", "builder" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Form/SiteRequest.php#L100-L189
makinacorpus/drupal-ucms
ucms_site/src/Form/SiteRequest.php
SiteRequest.validateHttpHost
public function validateHttpHost(&$element, FormStateInterface $form_state, &$complete_form) { $value = $form_state->getValue($element['#parents']); if (empty($value)) { $form_state->setError($element, $this->t("Host name cannot be empty")); return; } if ($this->manager->getStorage()->findByHostname($value)) { $form_state->setError($element, $this->t("Host name already exists")); } // Validate host name format $regex = '@^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])$@i'; if (!preg_match($regex, $value)) { $form_state->setError($element, $this->t("Host name contains invalid characters or has a wrong format")); } }
php
public function validateHttpHost(&$element, FormStateInterface $form_state, &$complete_form) { $value = $form_state->getValue($element['#parents']); if (empty($value)) { $form_state->setError($element, $this->t("Host name cannot be empty")); return; } if ($this->manager->getStorage()->findByHostname($value)) { $form_state->setError($element, $this->t("Host name already exists")); } // Validate host name format $regex = '@^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])$@i'; if (!preg_match($regex, $value)) { $form_state->setError($element, $this->t("Host name contains invalid characters or has a wrong format")); } }
[ "public", "function", "validateHttpHost", "(", "&", "$", "element", ",", "FormStateInterface", "$", "form_state", ",", "&", "$", "complete_form", ")", "{", "$", "value", "=", "$", "form_state", "->", "getValue", "(", "$", "element", "[", "'#parents'", "]", ...
Validate HTTP host (must be unique and valid)
[ "Validate", "HTTP", "host", "(", "must", "be", "unique", "and", "valid", ")" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Form/SiteRequest.php#L194-L212
makinacorpus/drupal-ucms
ucms_site/src/Form/SiteRequest.php
SiteRequest.submitStepA
public function submitStepA(array $form, FormStateInterface $form_state) { $formData = &$form_state->getStorage(); $values = &$form_state->getValues(); /** @var $site Site */ $site = $formData['site']; $site->title = $values['title']; $site->title_admin = $values['title_admin']; $site->http_host = $values['http_host']; $site->allowed_protocols = $values['allowed_protocols']; $site->http_redirects = $values['http_redirects']; $site->replacement_of = $values['replacement_of']; $site->is_public = $values['is_public']; $formData['step'] = 'b'; $form_state->setRebuild(true); }
php
public function submitStepA(array $form, FormStateInterface $form_state) { $formData = &$form_state->getStorage(); $values = &$form_state->getValues(); /** @var $site Site */ $site = $formData['site']; $site->title = $values['title']; $site->title_admin = $values['title_admin']; $site->http_host = $values['http_host']; $site->allowed_protocols = $values['allowed_protocols']; $site->http_redirects = $values['http_redirects']; $site->replacement_of = $values['replacement_of']; $site->is_public = $values['is_public']; $formData['step'] = 'b'; $form_state->setRebuild(true); }
[ "public", "function", "submitStepA", "(", "array", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "$", "formData", "=", "&", "$", "form_state", "->", "getStorage", "(", ")", ";", "$", "values", "=", "&", "$", "form_state", "->", "ge...
Step B form submit
[ "Step", "B", "form", "submit" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Form/SiteRequest.php#L227-L244
makinacorpus/drupal-ucms
ucms_site/src/Form/SiteRequest.php
SiteRequest.buildStepB
private function buildStepB(array $form, FormStateInterface $form_state, Site $site) { // @todo Form stuff // WARNING I won't fetch the whole Drupal 8 API in the sf_dic module, // this has to stop at some point, so I'll use only Drupal 7 API to // handle themes, this will need porting. $themes = list_themes(); $options = []; foreach ($this->manager->getAllowedThemes() as $theme) { if (!isset($themes[$theme])) { $this->logger('default')->alert(sprintf("Theme '%s' does not exist but is referenced into sites possible selection", $theme)); continue; } if (!$themes[$theme]->status) { $this->logger('default')->alert(sprintf("Theme '%s' is not enabled but is referenced into sites possible selection", $theme)); continue; } if (isset($themes[$theme]) && file_exists($themes[$theme]->info['screenshot'])) { $text = theme('image', [ 'path' => $themes[$theme]->info['screenshot'], 'alt' => $this->t('Screenshot for !theme theme', ['!theme' => $themes[$theme]->info['name']]), 'attributes' => ['class' => ['screenshot']], ]); $text .= '<p>'. $themes[$theme]->info['name'] . '</p>'; } else { $text = $themes[$theme]->info['name']; } $options[$theme] = $text; } $defaultTheme = null; if ($site->theme) { $defaultTheme = $site->theme; } elseif (count($options) == 1) { reset($options); $defaultTheme = key($options); } $form['theme'] = [ '#title' => $this->t("Theme"), '#type' => 'radios', '#options' => $options, '#default_value' => $defaultTheme, '#required' => true, '#disabled' => (count($options) == 1), ]; // Is template site $currentUser = $this->currentUser(); $canManage = ( $currentUser->hasPermission(Access::PERM_SITE_MANAGE_ALL) || $currentUser->hasPermission(Access::PERM_SITE_GOD) ); $form['is_template'] = [ '#title' => $this->t("Is template site?"), '#type' => 'radios', '#options' => [1 => $this->t("Yes"), 0 => $this->t("No")], '#access' => $canManage, '#default_value' => $site->is_template, ]; // Template site (which will be duplicated) $templateList = $this->manager->getTemplateList(); if ($canManage) { array_unshift($templateList, $this->t('- None -')); } $defaultTemplate = null; if ($site->template_id) { $defaultTemplate = $site->template_id; } elseif (count($templateList) == 1) { reset($templateList); $defaultTemplate = key($templateList); } $form['template_id'] = [ '#title' => $this->t("Template site"), '#type' => 'radios', '#options' => $templateList, '#default_value' => $defaultTemplate, '#required' => !$canManage, '#disabled' => (count($templateList) == 1), ]; if ($form['is_template']['#access']) { $form['template_id']['#states'] = [ 'visible' => [':input[name="is_template"]' => ['value' => 0]], ]; } $form['attributes']['#tree'] = true; $form['actions']['#type'] = 'actions'; $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t("Request"), ]; $form['actions']['back'] = [ '#type' => 'submit', '#value' => $this->t("Go back"), '#submit' => ['::submitStepABack'], ]; return $form; }
php
private function buildStepB(array $form, FormStateInterface $form_state, Site $site) { // @todo Form stuff // WARNING I won't fetch the whole Drupal 8 API in the sf_dic module, // this has to stop at some point, so I'll use only Drupal 7 API to // handle themes, this will need porting. $themes = list_themes(); $options = []; foreach ($this->manager->getAllowedThemes() as $theme) { if (!isset($themes[$theme])) { $this->logger('default')->alert(sprintf("Theme '%s' does not exist but is referenced into sites possible selection", $theme)); continue; } if (!$themes[$theme]->status) { $this->logger('default')->alert(sprintf("Theme '%s' is not enabled but is referenced into sites possible selection", $theme)); continue; } if (isset($themes[$theme]) && file_exists($themes[$theme]->info['screenshot'])) { $text = theme('image', [ 'path' => $themes[$theme]->info['screenshot'], 'alt' => $this->t('Screenshot for !theme theme', ['!theme' => $themes[$theme]->info['name']]), 'attributes' => ['class' => ['screenshot']], ]); $text .= '<p>'. $themes[$theme]->info['name'] . '</p>'; } else { $text = $themes[$theme]->info['name']; } $options[$theme] = $text; } $defaultTheme = null; if ($site->theme) { $defaultTheme = $site->theme; } elseif (count($options) == 1) { reset($options); $defaultTheme = key($options); } $form['theme'] = [ '#title' => $this->t("Theme"), '#type' => 'radios', '#options' => $options, '#default_value' => $defaultTheme, '#required' => true, '#disabled' => (count($options) == 1), ]; // Is template site $currentUser = $this->currentUser(); $canManage = ( $currentUser->hasPermission(Access::PERM_SITE_MANAGE_ALL) || $currentUser->hasPermission(Access::PERM_SITE_GOD) ); $form['is_template'] = [ '#title' => $this->t("Is template site?"), '#type' => 'radios', '#options' => [1 => $this->t("Yes"), 0 => $this->t("No")], '#access' => $canManage, '#default_value' => $site->is_template, ]; // Template site (which will be duplicated) $templateList = $this->manager->getTemplateList(); if ($canManage) { array_unshift($templateList, $this->t('- None -')); } $defaultTemplate = null; if ($site->template_id) { $defaultTemplate = $site->template_id; } elseif (count($templateList) == 1) { reset($templateList); $defaultTemplate = key($templateList); } $form['template_id'] = [ '#title' => $this->t("Template site"), '#type' => 'radios', '#options' => $templateList, '#default_value' => $defaultTemplate, '#required' => !$canManage, '#disabled' => (count($templateList) == 1), ]; if ($form['is_template']['#access']) { $form['template_id']['#states'] = [ 'visible' => [':input[name="is_template"]' => ['value' => 0]], ]; } $form['attributes']['#tree'] = true; $form['actions']['#type'] = 'actions'; $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t("Request"), ]; $form['actions']['back'] = [ '#type' => 'submit', '#value' => $this->t("Go back"), '#submit' => ['::submitStepABack'], ]; return $form; }
[ "private", "function", "buildStepB", "(", "array", "$", "form", ",", "FormStateInterface", "$", "form_state", ",", "Site", "$", "site", ")", "{", "// @todo Form stuff", "// WARNING I won't fetch the whole Drupal 8 API in the sf_dic module,", "// this has to stop at some point, ...
Step B form builder
[ "Step", "B", "form", "builder" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Form/SiteRequest.php#L249-L361
makinacorpus/drupal-ucms
ucms_site/src/Form/SiteRequest.php
SiteRequest.submitStepABack
public function submitStepABack(array $form, FormStateInterface $form_state) { $formData = &$form_state->getStorage(); /** @var $site Site */ $site = $formData['site']; $site->state = SiteState::REQUESTED; $site->theme = $form_state->getValue('theme'); $site->ts_created = $site->ts_changed = new \DateTime(); $site->template_id = $form_state->getValue('is_template') ? 0 : $form_state->getValue('template_id'); $site->is_template = $form_state->getValue('is_template'); $formData['step'] = 'a'; $form_state->setRebuild(true); }
php
public function submitStepABack(array $form, FormStateInterface $form_state) { $formData = &$form_state->getStorage(); /** @var $site Site */ $site = $formData['site']; $site->state = SiteState::REQUESTED; $site->theme = $form_state->getValue('theme'); $site->ts_created = $site->ts_changed = new \DateTime(); $site->template_id = $form_state->getValue('is_template') ? 0 : $form_state->getValue('template_id'); $site->is_template = $form_state->getValue('is_template'); $formData['step'] = 'a'; $form_state->setRebuild(true); }
[ "public", "function", "submitStepABack", "(", "array", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "$", "formData", "=", "&", "$", "form_state", "->", "getStorage", "(", ")", ";", "/** @var $site Site */", "$", "site", "=", "$", "for...
Step B form go back submit
[ "Step", "B", "form", "go", "back", "submit" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Form/SiteRequest.php#L366-L380
makinacorpus/drupal-ucms
ucms_site/src/Form/SiteRequest.php
SiteRequest.submitForm
public function submitForm(array &$form, FormStateInterface $form_state) { $formData = &$form_state->getStorage(); /** @var $site Site */ $site = $formData['site']; $site->state = SiteState::REQUESTED; $site->theme = $form_state->getValue('theme'); $site->template_id = $form_state->getValue('is_template') ? 0 : $form_state->getValue('template_id'); $site->is_template = $form_state->getValue('is_template'); $attributes = $form_state->getValue('attributes', []); foreach ($attributes as $name => $attribute) { $site->setAttribute($name, $attribute); } if ($site->template_id) { $site->type = $this->manager->getStorage()->findOne($site->template_id)->type; } $this->manager->getStorage()->save($site); drupal_set_message($this->t("Your site creation request has been submitted")); $this->dispatcher->dispatch('site:request', new SiteEvent($site, $this->currentUser()->uid)); $form_state->setRedirect('admin/dashboard/site'); }
php
public function submitForm(array &$form, FormStateInterface $form_state) { $formData = &$form_state->getStorage(); /** @var $site Site */ $site = $formData['site']; $site->state = SiteState::REQUESTED; $site->theme = $form_state->getValue('theme'); $site->template_id = $form_state->getValue('is_template') ? 0 : $form_state->getValue('template_id'); $site->is_template = $form_state->getValue('is_template'); $attributes = $form_state->getValue('attributes', []); foreach ($attributes as $name => $attribute) { $site->setAttribute($name, $attribute); } if ($site->template_id) { $site->type = $this->manager->getStorage()->findOne($site->template_id)->type; } $this->manager->getStorage()->save($site); drupal_set_message($this->t("Your site creation request has been submitted")); $this->dispatcher->dispatch('site:request', new SiteEvent($site, $this->currentUser()->uid)); $form_state->setRedirect('admin/dashboard/site'); }
[ "public", "function", "submitForm", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "$", "formData", "=", "&", "$", "form_state", "->", "getStorage", "(", ")", ";", "/** @var $site Site */", "$", "site", "=", "$", "f...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/Form/SiteRequest.php#L385-L410
runcmf/runbb
src/RunBB/Helpers/Menu/MenuManager.php
MenuManager.generateUrl
protected function generateUrl($urlpath) { $baseUrl = $this->sc->get('request')->getUri()->getBasePath(); // $baseUrl = trim($baseUrl, '/'); // $urlpath = trim($urlpath, '/'); return $baseUrl . $urlpath; }
php
protected function generateUrl($urlpath) { $baseUrl = $this->sc->get('request')->getUri()->getBasePath(); // $baseUrl = trim($baseUrl, '/'); // $urlpath = trim($urlpath, '/'); return $baseUrl . $urlpath; }
[ "protected", "function", "generateUrl", "(", "$", "urlpath", ")", "{", "$", "baseUrl", "=", "$", "this", "->", "sc", "->", "get", "(", "'request'", ")", "->", "getUri", "(", ")", "->", "getBasePath", "(", ")", ";", "// $baseUrl = trim($baseUrl, '/');"...
generate base URL
[ "generate", "base", "URL" ]
train
https://github.com/runcmf/runbb/blob/d4f4098bcece48b78ea2d1ae5eeead7ac9a8b463/src/RunBB/Helpers/Menu/MenuManager.php#L126-L132
accompli/accompli
src/Utility/ProcessUtility.php
ProcessUtility.escapeArguments
public static function escapeArguments(array $arguments, $command = null) { $processedArguments = array(); foreach ($arguments as $key => $value) { if (is_string($key) && substr($key, 0, 1) === '-') { if (is_array($value) === false) { $value = array($value); } foreach ($value as $optionValue) { if ($optionValue === null) { $processedArguments[] = $key; } elseif (is_string($optionValue)) { $processedArguments[] = trim(sprintf('%s=%s', $key, $optionValue)); } } } elseif (is_scalar($value)) { $processedArguments[] = $value; } } if ($command !== null) { array_unshift($processedArguments, $command); } return implode(' ', array_map(array(__CLASS__, 'escapeArgument'), $processedArguments)); }
php
public static function escapeArguments(array $arguments, $command = null) { $processedArguments = array(); foreach ($arguments as $key => $value) { if (is_string($key) && substr($key, 0, 1) === '-') { if (is_array($value) === false) { $value = array($value); } foreach ($value as $optionValue) { if ($optionValue === null) { $processedArguments[] = $key; } elseif (is_string($optionValue)) { $processedArguments[] = trim(sprintf('%s=%s', $key, $optionValue)); } } } elseif (is_scalar($value)) { $processedArguments[] = $value; } } if ($command !== null) { array_unshift($processedArguments, $command); } return implode(' ', array_map(array(__CLASS__, 'escapeArgument'), $processedArguments)); }
[ "public", "static", "function", "escapeArguments", "(", "array", "$", "arguments", ",", "$", "command", "=", "null", ")", "{", "$", "processedArguments", "=", "array", "(", ")", ";", "foreach", "(", "$", "arguments", "as", "$", "key", "=>", "$", "value",...
Returns a string with escaped option values and arguments from the supplied arguments array. @param array $arguments @param string|null $command @return string
[ "Returns", "a", "string", "with", "escaped", "option", "values", "and", "arguments", "from", "the", "supplied", "arguments", "array", "." ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Utility/ProcessUtility.php#L20-L46
accompli/accompli
src/Utility/ProcessUtility.php
ProcessUtility.isSurroundedBy
private static function isSurroundedBy($argument, $character) { return 2 < strlen($argument) && $character === $argument[0] && $character === $argument[strlen($argument) - 1]; }
php
private static function isSurroundedBy($argument, $character) { return 2 < strlen($argument) && $character === $argument[0] && $character === $argument[strlen($argument) - 1]; }
[ "private", "static", "function", "isSurroundedBy", "(", "$", "argument", ",", "$", "character", ")", "{", "return", "2", "<", "strlen", "(", "$", "argument", ")", "&&", "$", "character", "===", "$", "argument", "[", "0", "]", "&&", "$", "character", "=...
Returns true when the argument is surrounded by character. @param string $argument @param string $character @return bool
[ "Returns", "true", "when", "the", "argument", "is", "surrounded", "by", "character", "." ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/Utility/ProcessUtility.php#L89-L92
makinacorpus/drupal-ucms
ucms_site/src/ACL/GroupEntryCollector.php
GroupEntryCollector.collectEntryLists
public function collectEntryLists(EntryListBuilder $builder) { $resource = $builder->getResource(); $groupId = $resource->getId(); $builder->add(Access::PROFILE_GROUP_GOD, Access::ID_ALL, [Permission::VIEW, Permission::UPDATE, Permission::DELETE, Access::ACL_PERM_MANAGE_USERS]); $builder->add(Access::PROFILE_GROUP_ADMIN, $groupId, [Permission::VIEW, Access::ACL_PERM_MANAGE_USERS]); $builder->add(Access::PROFILE_GROUP_MEMBER, $groupId, [Permission::VIEW]); }
php
public function collectEntryLists(EntryListBuilder $builder) { $resource = $builder->getResource(); $groupId = $resource->getId(); $builder->add(Access::PROFILE_GROUP_GOD, Access::ID_ALL, [Permission::VIEW, Permission::UPDATE, Permission::DELETE, Access::ACL_PERM_MANAGE_USERS]); $builder->add(Access::PROFILE_GROUP_ADMIN, $groupId, [Permission::VIEW, Access::ACL_PERM_MANAGE_USERS]); $builder->add(Access::PROFILE_GROUP_MEMBER, $groupId, [Permission::VIEW]); }
[ "public", "function", "collectEntryLists", "(", "EntryListBuilder", "$", "builder", ")", "{", "$", "resource", "=", "$", "builder", "->", "getResource", "(", ")", ";", "$", "groupId", "=", "$", "resource", "->", "getId", "(", ")", ";", "$", "builder", "-...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/ACL/GroupEntryCollector.php#L58-L66
makinacorpus/drupal-ucms
ucms_site/src/ACL/GroupEntryCollector.php
GroupEntryCollector.collectProfiles
public function collectProfiles(ProfileSetBuilder $builder) { $account = $builder->getObject(); if (!$account instanceof AccountInterface) { return; } if ($account->hasPermission(Access::PERM_GROUP_MANAGE_ALL)) { $builder->add(Access::PROFILE_GROUP_GOD, Access::ID_ALL); } foreach ($this->groupManager->getUserGroups($account) as $access) { $groupId = $access->getGroupId(); $builder->add(Access::PROFILE_GROUP_MEMBER, $groupId); if ($access->isGroupAdmin()) { $builder->add(Access::PROFILE_GROUP_ADMIN, $groupId); } } }
php
public function collectProfiles(ProfileSetBuilder $builder) { $account = $builder->getObject(); if (!$account instanceof AccountInterface) { return; } if ($account->hasPermission(Access::PERM_GROUP_MANAGE_ALL)) { $builder->add(Access::PROFILE_GROUP_GOD, Access::ID_ALL); } foreach ($this->groupManager->getUserGroups($account) as $access) { $groupId = $access->getGroupId(); $builder->add(Access::PROFILE_GROUP_MEMBER, $groupId); if ($access->isGroupAdmin()) { $builder->add(Access::PROFILE_GROUP_ADMIN, $groupId); } } }
[ "public", "function", "collectProfiles", "(", "ProfileSetBuilder", "$", "builder", ")", "{", "$", "account", "=", "$", "builder", "->", "getObject", "(", ")", ";", "if", "(", "!", "$", "account", "instanceof", "AccountInterface", ")", "{", "return", ";", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_site/src/ACL/GroupEntryCollector.php#L71-L89
makinacorpus/drupal-ucms
ucms_seo/src/Path/Redirect.php
Redirect.expiresAt
public function expiresAt() { if ($this->expires && !$this->expiresAt) { $this->expiresAt = \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $this->expires); } return $this->expiresAt; }
php
public function expiresAt() { if ($this->expires && !$this->expiresAt) { $this->expiresAt = \DateTimeImmutable::createFromFormat('Y-m-d H:i:s', $this->expires); } return $this->expiresAt; }
[ "public", "function", "expiresAt", "(", ")", "{", "if", "(", "$", "this", "->", "expires", "&&", "!", "$", "this", "->", "expiresAt", ")", "{", "$", "this", "->", "expiresAt", "=", "\\", "DateTimeImmutable", "::", "createFromFormat", "(", "'Y-m-d H:i:s'", ...
Get expiry date @return null|\DateTimeImmutable
[ "Get", "expiry", "date" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_seo/src/Path/Redirect.php#L84-L91
makinacorpus/drupal-ucms
ucms_extranet/src/Form/MemberRejectionForm.php
MemberRejectionForm.buildForm
public function buildForm(array $form, FormStateInterface $formState, Site $site = null, UserInterface $account = null) { if (null === $site || null === $account) { return []; } $formState->setTemporaryValue('site', $site); $formState->setTemporaryValue('account', $account); return confirm_form( $form, $this->t("Reject the registration of !name?", ['!name' => $account->getDisplayName()]), 'admin/dashboard/site/' . $site->getId() . '/webmaster', '' ); }
php
public function buildForm(array $form, FormStateInterface $formState, Site $site = null, UserInterface $account = null) { if (null === $site || null === $account) { return []; } $formState->setTemporaryValue('site', $site); $formState->setTemporaryValue('account', $account); return confirm_form( $form, $this->t("Reject the registration of !name?", ['!name' => $account->getDisplayName()]), 'admin/dashboard/site/' . $site->getId() . '/webmaster', '' ); }
[ "public", "function", "buildForm", "(", "array", "$", "form", ",", "FormStateInterface", "$", "formState", ",", "Site", "$", "site", "=", "null", ",", "UserInterface", "$", "account", "=", "null", ")", "{", "if", "(", "null", "===", "$", "site", "||", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_extranet/src/Form/MemberRejectionForm.php#L65-L80
makinacorpus/drupal-ucms
ucms_extranet/src/Form/MemberRejectionForm.php
MemberRejectionForm.submitForm
public function submitForm(array &$form, FormStateInterface $formState) { /** @var $site Site */ $site = $formState->getTemporaryValue('site'); /** @var $account UserInterface */ $account = $formState->getTemporaryValue('account'); $this->entityManager->getStorage('user')->delete([$account]); drupal_set_message($this->t("Registration of !name has been rejected.", ['!name' => $account->getDisplayName()])); $event = new ExtranetMemberEvent($account, $site, ['name' => $account->getDisplayName()]); $this->dispatcher->dispatch(ExtranetMemberEvent::EVENT_REJECT, $event); }
php
public function submitForm(array &$form, FormStateInterface $formState) { /** @var $site Site */ $site = $formState->getTemporaryValue('site'); /** @var $account UserInterface */ $account = $formState->getTemporaryValue('account'); $this->entityManager->getStorage('user')->delete([$account]); drupal_set_message($this->t("Registration of !name has been rejected.", ['!name' => $account->getDisplayName()])); $event = new ExtranetMemberEvent($account, $site, ['name' => $account->getDisplayName()]); $this->dispatcher->dispatch(ExtranetMemberEvent::EVENT_REJECT, $event); }
[ "public", "function", "submitForm", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "formState", ")", "{", "/** @var $site Site */", "$", "site", "=", "$", "formState", "->", "getTemporaryValue", "(", "'site'", ")", ";", "/** @var $account UserInte...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_extranet/src/Form/MemberRejectionForm.php#L86-L99
qloog/yaf-library
src/Caches/Redis.php
Redis.get
public function get($key, $default = null) { $ret = $this->redis->get($key); if (is_numeric($ret)) { return $ret; } return $ret === false ? false : json_decode($ret, true); }
php
public function get($key, $default = null) { $ret = $this->redis->get($key); if (is_numeric($ret)) { return $ret; } return $ret === false ? false : json_decode($ret, true); }
[ "public", "function", "get", "(", "$", "key", ",", "$", "default", "=", "null", ")", "{", "$", "ret", "=", "$", "this", "->", "redis", "->", "get", "(", "$", "key", ")", ";", "if", "(", "is_numeric", "(", "$", "ret", ")", ")", "{", "return", ...
获取缓存 @param string $key @param null $default @return mixed
[ "获取缓存" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Caches/Redis.php#L36-L44
qloog/yaf-library
src/Caches/Redis.php
Redis.set
public function set($key, $val, $expire = 0) { if (!is_numeric($val)) { $val = json_encode($val); } if ($expire) { return $this->redis->setex($key, $expire, $val); } return $this->redis->set($key, $val); }
php
public function set($key, $val, $expire = 0) { if (!is_numeric($val)) { $val = json_encode($val); } if ($expire) { return $this->redis->setex($key, $expire, $val); } return $this->redis->set($key, $val); }
[ "public", "function", "set", "(", "$", "key", ",", "$", "val", ",", "$", "expire", "=", "0", ")", "{", "if", "(", "!", "is_numeric", "(", "$", "val", ")", ")", "{", "$", "val", "=", "json_encode", "(", "$", "val", ")", ";", "}", "if", "(", ...
设置缓存 @param string $key 缓存Key @param mixed $val 缓存的值,自动编码 @param int $expire 有效期, 0为不过期 @return bool 成功返回true, 失败false
[ "设置缓存" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Caches/Redis.php#L54-L65
qloog/yaf-library
src/Caches/Redis.php
Redis.getMultiple
public function getMultiple($keys, $default = null) { if (!is_array($keys)) { throw new InvalidArgumentException(sprintf('Cache keys must be array, "%s" given', is_object($keys) ? get_class($keys) : gettype($keys))); } $ret = $this->redis->mget($keys); foreach ($ret as & $v) { $v = json_decode($v, true); } return $ret; }
php
public function getMultiple($keys, $default = null) { if (!is_array($keys)) { throw new InvalidArgumentException(sprintf('Cache keys must be array, "%s" given', is_object($keys) ? get_class($keys) : gettype($keys))); } $ret = $this->redis->mget($keys); foreach ($ret as & $v) { $v = json_decode($v, true); } return $ret; }
[ "public", "function", "getMultiple", "(", "$", "keys", ",", "$", "default", "=", "null", ")", "{", "if", "(", "!", "is_array", "(", "$", "keys", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Cache keys must be array, \"%s\...
批量读取缓存 @param array $keys 要读取的缓存Key列表 @param null $default @return array Key到值的Map
[ "批量读取缓存" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Caches/Redis.php#L85-L97
qloog/yaf-library
src/Caches/Redis.php
Redis.setMultiple
public function setMultiple($data, $expire = 0) { if (!is_array($data)) { throw new InvalidArgumentException(sprintf('Cache keys must be array, "%s" given', is_object($data) ? get_class($data) : gettype($data))); } foreach ($data as &$d) { if (!is_numeric($d)) { $d = json_encode($d); } } $retFlag = $this->redis->mset($data); if ($expire > 0) { foreach ($data as $key => $value) { $this->redis->expire($key, $expire); } } return $retFlag; }
php
public function setMultiple($data, $expire = 0) { if (!is_array($data)) { throw new InvalidArgumentException(sprintf('Cache keys must be array, "%s" given', is_object($data) ? get_class($data) : gettype($data))); } foreach ($data as &$d) { if (!is_numeric($d)) { $d = json_encode($d); } } $retFlag = $this->redis->mset($data); if ($expire > 0) { foreach ($data as $key => $value) { $this->redis->expire($key, $expire); } } return $retFlag; }
[ "public", "function", "setMultiple", "(", "$", "data", ",", "$", "expire", "=", "0", ")", "{", "if", "(", "!", "is_array", "(", "$", "data", ")", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Cache keys must be array, \"%s\" gi...
批量设置缓存 @param array $data 要设置的缓存,键为缓存的Key @param int $expire 有效期, 0为不过期 @return bool Key到值的Map
[ "批量设置缓存" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Caches/Redis.php#L107-L127
qloog/yaf-library
src/Caches/Redis.php
Redis.expiresAt
public function expiresAt($key, $time = 0) { $expire = $time - time(); return $this->redis->expire($key, $expire); }
php
public function expiresAt($key, $time = 0) { $expire = $time - time(); return $this->redis->expire($key, $expire); }
[ "public", "function", "expiresAt", "(", "$", "key", ",", "$", "time", "=", "0", ")", "{", "$", "expire", "=", "$", "time", "-", "time", "(", ")", ";", "return", "$", "this", "->", "redis", "->", "expire", "(", "$", "key", ",", "$", "expire", ")...
设置缓存有效期到某个时间为止 @param string $key 缓存Key @param int $time 有效期,时间戳 @return bool 成功返回true, 失败false
[ "设置缓存有效期到某个时间为止" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Caches/Redis.php#L160-L165
accompli/accompli
src/EventDispatcher/Subscriber/DataCollectorSubscriber.php
DataCollectorSubscriber.onEvent
public function onEvent(Event $event, $eventName) { foreach ($this->dataCollectors as $dataCollector) { $dataCollector->collect($event, $eventName); } }
php
public function onEvent(Event $event, $eventName) { foreach ($this->dataCollectors as $dataCollector) { $dataCollector->collect($event, $eventName); } }
[ "public", "function", "onEvent", "(", "Event", "$", "event", ",", "$", "eventName", ")", "{", "foreach", "(", "$", "this", "->", "dataCollectors", "as", "$", "dataCollector", ")", "{", "$", "dataCollector", "->", "collect", "(", "$", "event", ",", "$", ...
Calls the collect method on all registered data collectors. @param Event $event @param string $eventName
[ "Calls", "the", "collect", "method", "on", "all", "registered", "data", "collectors", "." ]
train
https://github.com/accompli/accompli/blob/618f28377448d8caa90d63bfa5865a3ee15e49e7/src/EventDispatcher/Subscriber/DataCollectorSubscriber.php#L65-L70
someline/starter-framework
src/Someline/Support/Middleware/LocaleMiddleware.php
LocaleMiddleware.handle
public function handle($request, Closure $next) { // get supported locales $supportedLocales = LaravelLocalization::getSupportedLocales(); // 1. get current locale $locale = LaravelLocalization::getCurrentLocale(); // 2. check from session $sessionLocale = session('someline-locale'); if (!empty($sessionLocale)) { // if supported if (is_array($supportedLocales) && isset($supportedLocales[$sessionLocale])) { $locale = $sessionLocale; } } // 3. check from lang $lang = $request->get('lang'); if (!empty($lang)) { // if supported if (is_array($supportedLocales) && isset($supportedLocales[$lang])) { $locale = $lang; } } // set locale LaravelLocalization::setLocale($locale); // set carbon locale Carbon::setLocale($locale); return $next($request); }
php
public function handle($request, Closure $next) { // get supported locales $supportedLocales = LaravelLocalization::getSupportedLocales(); // 1. get current locale $locale = LaravelLocalization::getCurrentLocale(); // 2. check from session $sessionLocale = session('someline-locale'); if (!empty($sessionLocale)) { // if supported if (is_array($supportedLocales) && isset($supportedLocales[$sessionLocale])) { $locale = $sessionLocale; } } // 3. check from lang $lang = $request->get('lang'); if (!empty($lang)) { // if supported if (is_array($supportedLocales) && isset($supportedLocales[$lang])) { $locale = $lang; } } // set locale LaravelLocalization::setLocale($locale); // set carbon locale Carbon::setLocale($locale); return $next($request); }
[ "public", "function", "handle", "(", "$", "request", ",", "Closure", "$", "next", ")", "{", "// get supported locales", "$", "supportedLocales", "=", "LaravelLocalization", "::", "getSupportedLocales", "(", ")", ";", "// 1. get current locale", "$", "locale", "=", ...
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
[ "Handle", "an", "incoming", "request", "." ]
train
https://github.com/someline/starter-framework/blob/38d3e97ca75dadb05bdc9020f73c78653dbecf15/src/Someline/Support/Middleware/LocaleMiddleware.php#L18-L52
makinacorpus/drupal-ucms
ucms_tree/src/Form/TreeEditForm.php
TreeEditForm.buildForm
public function buildForm(array $form, FormStateInterface $form_state, Menu $menu = null) { $form['#form_horizontal'] = true; $isCreation = false; if (!$menu) { $isCreation = true; $menu = new Menu(); } $form['name'] = [ '#type' => 'textfield', '#attributes' => ['placeholder' => 'site-42-main'], '#description' => $this->t("Leave this field empty for auto-generation"), '#default_value' => $menu->getName(), '#maxlength' => 255, '#disabled' => !$isCreation, ]; $form['is_creation'] = ['#type' => 'value', '#value' => $isCreation]; if ($roles = variable_get('umenu_allowed_roles', [])) { $form['role'] = [ '#type' => 'select', '#title' => $this->t("Role"), '#options' => $roles, '#default_value' => $menu->getRole(), '#empty_option' => $this->t("None"), '#maxlength' => 255, ]; } $form['title'] = [ '#type' => 'textfield', '#title' => $this->t("Title"), '#attributes' => ['placeholder' => $this->t("Main, Footer, ...")], '#default_value' => $menu->getTitle(), '#required' => true, '#maxlength' => 255, ]; $form['description'] = [ '#type' => 'textfield', '#title' => $this->t("Description"), '#attributes' => ['placeholder' => $this->t("Something about this menu...")], '#default_value' => $menu->getDescription(), '#maxlength' => 1024, ]; $allowedRoles = ucms_tree_role_list(); if ($allowedRoles) { $form['role'] = [ '#type' => 'select', '#title' => $this->t("Menu role in site"), '#empty_option' => $this->t("None"), '#options' => $allowedRoles, '#default_value' => $menu->getRole(), ]; } $form['is_main'] = [ '#type' => 'checkbox', '#title' => $this->t("Set as the site main menu?"), '#default_value' => $menu->isSiteMain(), '#description' => $this->t("If the site already has a main menu, this choice will change it."), ]; $form['actions']['#type'] = 'actions'; $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Save'), ]; return $form; }
php
public function buildForm(array $form, FormStateInterface $form_state, Menu $menu = null) { $form['#form_horizontal'] = true; $isCreation = false; if (!$menu) { $isCreation = true; $menu = new Menu(); } $form['name'] = [ '#type' => 'textfield', '#attributes' => ['placeholder' => 'site-42-main'], '#description' => $this->t("Leave this field empty for auto-generation"), '#default_value' => $menu->getName(), '#maxlength' => 255, '#disabled' => !$isCreation, ]; $form['is_creation'] = ['#type' => 'value', '#value' => $isCreation]; if ($roles = variable_get('umenu_allowed_roles', [])) { $form['role'] = [ '#type' => 'select', '#title' => $this->t("Role"), '#options' => $roles, '#default_value' => $menu->getRole(), '#empty_option' => $this->t("None"), '#maxlength' => 255, ]; } $form['title'] = [ '#type' => 'textfield', '#title' => $this->t("Title"), '#attributes' => ['placeholder' => $this->t("Main, Footer, ...")], '#default_value' => $menu->getTitle(), '#required' => true, '#maxlength' => 255, ]; $form['description'] = [ '#type' => 'textfield', '#title' => $this->t("Description"), '#attributes' => ['placeholder' => $this->t("Something about this menu...")], '#default_value' => $menu->getDescription(), '#maxlength' => 1024, ]; $allowedRoles = ucms_tree_role_list(); if ($allowedRoles) { $form['role'] = [ '#type' => 'select', '#title' => $this->t("Menu role in site"), '#empty_option' => $this->t("None"), '#options' => $allowedRoles, '#default_value' => $menu->getRole(), ]; } $form['is_main'] = [ '#type' => 'checkbox', '#title' => $this->t("Set as the site main menu?"), '#default_value' => $menu->isSiteMain(), '#description' => $this->t("If the site already has a main menu, this choice will change it."), ]; $form['actions']['#type'] = 'actions'; $form['actions']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Save'), ]; return $form; }
[ "public", "function", "buildForm", "(", "array", "$", "form", ",", "FormStateInterface", "$", "form_state", ",", "Menu", "$", "menu", "=", "null", ")", "{", "$", "form", "[", "'#form_horizontal'", "]", "=", "true", ";", "$", "isCreation", "=", "false", "...
{@inheritDoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_tree/src/Form/TreeEditForm.php#L57-L132
makinacorpus/drupal-ucms
ucms_tree/src/Form/TreeEditForm.php
TreeEditForm.submitForm
public function submitForm(array &$form, FormStateInterface $form_state) { try { $tx = $this->db->startTransaction(); $storage = $this->treeManager->getMenuStorage(); $name = $form_state->getValue('name'); $values = [ 'title' => $form_state->getValue('title'), 'description' => $form_state->getValue('description'), 'role' => $form_state->getValue('role'), ]; if ($this->siteManager->hasContext()) { $siteId = $this->siteManager->getContext()->getId(); $values['site_id'] = $siteId; if (!$name) { // Auto-generation for name $name = \URLify::filter('site-' . $siteId . '-' . $values['title'], UCMS_SEO_SEGMENT_TRIM_LENGTH); } } else if (!$name) { // Auto-generation for name $name = \URLify::filter($values['title'], UCMS_SEO_SEGMENT_TRIM_LENGTH); } if ($form_state->getValue('is_creation')) { $storage->create($name, $values); } else { $storage->update($name, $values); } $storage->toggleMainStatus($name, (bool)$form_state->getValue('is_main')); unset($tx); drupal_set_message($this->t("Tree has been saved")); } catch (\Exception $e) { if ($tx) { try { $tx->rollback(); } catch (\Exception $e2) { watchdog_exception('ucms_tree', $e2); } watchdog_exception('ucms_tree', $e); drupal_set_message($this->t("Could not save tree"), 'error'); } } }
php
public function submitForm(array &$form, FormStateInterface $form_state) { try { $tx = $this->db->startTransaction(); $storage = $this->treeManager->getMenuStorage(); $name = $form_state->getValue('name'); $values = [ 'title' => $form_state->getValue('title'), 'description' => $form_state->getValue('description'), 'role' => $form_state->getValue('role'), ]; if ($this->siteManager->hasContext()) { $siteId = $this->siteManager->getContext()->getId(); $values['site_id'] = $siteId; if (!$name) { // Auto-generation for name $name = \URLify::filter('site-' . $siteId . '-' . $values['title'], UCMS_SEO_SEGMENT_TRIM_LENGTH); } } else if (!$name) { // Auto-generation for name $name = \URLify::filter($values['title'], UCMS_SEO_SEGMENT_TRIM_LENGTH); } if ($form_state->getValue('is_creation')) { $storage->create($name, $values); } else { $storage->update($name, $values); } $storage->toggleMainStatus($name, (bool)$form_state->getValue('is_main')); unset($tx); drupal_set_message($this->t("Tree has been saved")); } catch (\Exception $e) { if ($tx) { try { $tx->rollback(); } catch (\Exception $e2) { watchdog_exception('ucms_tree', $e2); } watchdog_exception('ucms_tree', $e); drupal_set_message($this->t("Could not save tree"), 'error'); } } }
[ "public", "function", "submitForm", "(", "array", "&", "$", "form", ",", "FormStateInterface", "$", "form_state", ")", "{", "try", "{", "$", "tx", "=", "$", "this", "->", "db", "->", "startTransaction", "(", ")", ";", "$", "storage", "=", "$", "this", ...
{@inheritDoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_tree/src/Form/TreeEditForm.php#L137-L188
dilsonjlrjr/slim3-auth
src/SlimAuth/SlimAuthFacade.php
SlimAuthFacade.auth
public function auth() { try { $this->authResponse = $this->authAdapterInterface->authenticate(); } catch (\Exception $ex) { throw $ex; } $message = $this->authResponse->getMessage(); if ($message->getCode() == AuthResponse::AUTHRESPONSE_SUCCESS) { $this->session->set($message->getKeysession(), $message->getAttrsession()); } return; }
php
public function auth() { try { $this->authResponse = $this->authAdapterInterface->authenticate(); } catch (\Exception $ex) { throw $ex; } $message = $this->authResponse->getMessage(); if ($message->getCode() == AuthResponse::AUTHRESPONSE_SUCCESS) { $this->session->set($message->getKeysession(), $message->getAttrsession()); } return; }
[ "public", "function", "auth", "(", ")", "{", "try", "{", "$", "this", "->", "authResponse", "=", "$", "this", "->", "authAdapterInterface", "->", "authenticate", "(", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "ex", ")", "{", "throw", "$", ...
Auth method @throws \Exception
[ "Auth", "method" ]
train
https://github.com/dilsonjlrjr/slim3-auth/blob/e9a78cd49e76b9d3fbc306374becd2805eac2728/src/SlimAuth/SlimAuthFacade.php#L41-L56
saxulum/saxulum-elasticsearch-querybuilder
src/Node/IntNode.php
IntNode.create
public static function create(int $value = null, bool $allowSerializeEmpty = false): IntNode { $node = new self(); $node->value = $value; $node->allowSerializeEmpty = $allowSerializeEmpty; return $node; }
php
public static function create(int $value = null, bool $allowSerializeEmpty = false): IntNode { $node = new self(); $node->value = $value; $node->allowSerializeEmpty = $allowSerializeEmpty; return $node; }
[ "public", "static", "function", "create", "(", "int", "$", "value", "=", "null", ",", "bool", "$", "allowSerializeEmpty", "=", "false", ")", ":", "IntNode", "{", "$", "node", "=", "new", "self", "(", ")", ";", "$", "node", "->", "value", "=", "$", ...
@param int|null $value @param bool $allowSerializeEmpty @return IntNode
[ "@param", "int|null", "$value", "@param", "bool", "$allowSerializeEmpty" ]
train
https://github.com/saxulum/saxulum-elasticsearch-querybuilder/blob/2f5a15925f3f3afe6a8efabf1f2c9af42f81d9b1/src/Node/IntNode.php#L20-L27
andkirby/multi-repo-composer
src/Repository/VcsNamespaceRepository.php
VcsNamespaceRepository.getTypes
public static function getTypes() { return [ self::TYPE_VCS, self::TYPE_GIT, self::TYPE_GIT_BITBACKET, self::TYPE_GITHUB, self::TYPE_GITLAB, ]; }
php
public static function getTypes() { return [ self::TYPE_VCS, self::TYPE_GIT, self::TYPE_GIT_BITBACKET, self::TYPE_GITHUB, self::TYPE_GITLAB, ]; }
[ "public", "static", "function", "getTypes", "(", ")", "{", "return", "[", "self", "::", "TYPE_VCS", ",", "self", "::", "TYPE_GIT", ",", "self", "::", "TYPE_GIT_BITBACKET", ",", "self", "::", "TYPE_GITHUB", ",", "self", "::", "TYPE_GITLAB", ",", "]", ";", ...
Get "namespaced" types @return array
[ "Get", "namespaced", "types" ]
train
https://github.com/andkirby/multi-repo-composer/blob/2d9fed02edf7601f56f2998f9d99e646b713aef6/src/Repository/VcsNamespaceRepository.php#L88-L97
andkirby/multi-repo-composer
src/Repository/VcsNamespaceRepository.php
VcsNamespaceRepository.initialize
protected function initialize() { ArrayRepository::initialize(); $verbose = $this->verbose; /** @var VcsDriver $driver */ $driver = $this->getDriver(); if (!$driver) { throw new \InvalidArgumentException('No driver found to handle VCS repository '.$this->url); } $this->versionParser = new VersionParser(); if (!$this->loader) { $this->loader = new ArrayLoader($this->versionParser); } try { if ($driver->hasComposerFile($driver->getRootIdentifier())) { $data = $driver->getComposerInformation($driver->getRootIdentifier()); $this->packageName = !empty($data['name']) ? $data['name'] : null; } } catch (\Exception $e) { if ($verbose) { $this->io->write('<error>Skipped parsing '.$driver->getRootIdentifier().', '.$e->getMessage().'</error>'); } } foreach ($driver->getTags() as $tag => $identifier) { $msg = 'Reading composer.json of <info>' . ($this->packageName ?: $this->url) . '</info> (<comment>' . $tag . '</comment>)'; if ($verbose) { $this->io->write($msg); } else { $this->io->overwrite($msg, false); } // strip the release- prefix from tags if present $tag = str_replace('release-', '', $tag); if (!$parsedTag = $this->validateTag($tag)) { if ($verbose) { $this->io->write('<warning>Skipped tag '.$tag.', invalid tag name</warning>'); } continue; } try { if (!$data = $driver->getComposerInformation($identifier)) { if ($verbose) { $this->io->write('<warning>Skipped tag '.$tag.', no composer file</warning>'); } continue; } // manually versioned package if (isset($data['version'])) { $data['version_normalized'] = $this->versionParser->normalize($data['version']); } else { // auto-versioned package, read value from tag //set version without namespace $data['version'] = $this->_getBranchWithoutNamespace($tag); $data['version_normalized'] = $parsedTag; } //set package namespace to generate package name based upon repository name $data['namespace'] = isset($data['namespace']) ? $data['namespace'] : $this->_getBranchNamespace($tag); // make sure tag packages have no -dev flag $data['version'] = preg_replace('{[.-]?dev$}i', '', $data['version']); $data['version_normalized'] = preg_replace('{(^dev-|[.-]?dev$)}i', '', $data['version_normalized']); // broken package, version doesn't match tag if ($data['version_normalized'] !== $parsedTag) { if ($verbose) { $this->io->write('<warning>Skipped tag '.$tag.', tag ('.$parsedTag.') does not match version ('.$data['version_normalized'].') in composer.json</warning>'); } continue; } if ($verbose) { $this->io->write('Importing tag '.$tag.' ('.$data['version_normalized'].')'); } $this->addPackage($this->loader->load($this->preProcess($driver, $data, $identifier))); } catch (\Exception $e) { if ($verbose) { $this->io->write('<warning>Skipped tag '.$tag.', '.($e instanceof TransportException ? 'no composer file was found' : $e->getMessage()).'</warning>'); } continue; } } if (!$verbose) { $this->io->overwrite('', false); } foreach ($driver->getBranches() as $branch => $identifier) { $msg = 'Reading composer.json of <info>' . ($this->packageName ?: $this->url) . '</info> (<comment>' . $branch . '</comment>)'; if ($verbose) { $this->io->write($msg); } else { $this->io->overwrite($msg, false); } if (!$parsedBranch = $this->validateBranch($branch)) { if ($verbose) { $this->io->write('<warning>Skipped branch '.$branch.', invalid name</warning>'); } continue; } try { if (!$data = $driver->getComposerInformation($identifier)) { if ($verbose) { $this->io->write('<warning>Skipped branch '.$branch.', no composer file</warning>'); } continue; } // branches are always auto-versioned, read value from branch name // set branch name without package namespace $data['version'] = $this->_getBranchWithoutNamespace($branch); //set package namespace to generate package name based upon repository name $data['namespace'] = isset($data['namespace']) ? $data['namespace'] : $this->_getBranchNamespace($branch); $data['version_normalized'] = $parsedBranch; // make sure branch packages have a dev flag if ('dev-' === substr($parsedBranch, 0, 4) || '9999999-dev' === $parsedBranch) { $data['version'] = 'dev-' . $data['version']; } else { $data['version'] = preg_replace('{(\.9{7})+}', '.x', $parsedBranch); } if ($verbose) { $this->io->write('Importing branch '.$branch.' ('.$data['version'].')'); } $packageData = $this->preProcess($driver, $data, $identifier); $package = $this->loader->load($packageData); if ($this->loader instanceof ValidatingArrayLoader && $this->loader->getWarnings()) { throw new InvalidPackageException($this->loader->getErrors(), $this->loader->getWarnings(), $packageData); } $this->addPackage($package); } catch (TransportException $e) { if ($verbose) { $this->io->write('<warning>Skipped branch '.$branch.', no composer file was found</warning>'); } continue; } catch (\Exception $e) { if (!$verbose) { $this->io->write(''); } $this->branchErrorOccurred = true; $this->io->write('<error>Skipped branch '.$branch.', '.$e->getMessage().'</error>'); $this->io->write(''); continue; } } $driver->cleanup(); if (!$verbose) { $this->io->overwrite('', false); } if (!$this->getPackages()) { throw new InvalidRepositoryException('No valid composer.json was found in any branch or tag of '.$this->url.', could not load a package from it.'); } }
php
protected function initialize() { ArrayRepository::initialize(); $verbose = $this->verbose; /** @var VcsDriver $driver */ $driver = $this->getDriver(); if (!$driver) { throw new \InvalidArgumentException('No driver found to handle VCS repository '.$this->url); } $this->versionParser = new VersionParser(); if (!$this->loader) { $this->loader = new ArrayLoader($this->versionParser); } try { if ($driver->hasComposerFile($driver->getRootIdentifier())) { $data = $driver->getComposerInformation($driver->getRootIdentifier()); $this->packageName = !empty($data['name']) ? $data['name'] : null; } } catch (\Exception $e) { if ($verbose) { $this->io->write('<error>Skipped parsing '.$driver->getRootIdentifier().', '.$e->getMessage().'</error>'); } } foreach ($driver->getTags() as $tag => $identifier) { $msg = 'Reading composer.json of <info>' . ($this->packageName ?: $this->url) . '</info> (<comment>' . $tag . '</comment>)'; if ($verbose) { $this->io->write($msg); } else { $this->io->overwrite($msg, false); } // strip the release- prefix from tags if present $tag = str_replace('release-', '', $tag); if (!$parsedTag = $this->validateTag($tag)) { if ($verbose) { $this->io->write('<warning>Skipped tag '.$tag.', invalid tag name</warning>'); } continue; } try { if (!$data = $driver->getComposerInformation($identifier)) { if ($verbose) { $this->io->write('<warning>Skipped tag '.$tag.', no composer file</warning>'); } continue; } // manually versioned package if (isset($data['version'])) { $data['version_normalized'] = $this->versionParser->normalize($data['version']); } else { // auto-versioned package, read value from tag //set version without namespace $data['version'] = $this->_getBranchWithoutNamespace($tag); $data['version_normalized'] = $parsedTag; } //set package namespace to generate package name based upon repository name $data['namespace'] = isset($data['namespace']) ? $data['namespace'] : $this->_getBranchNamespace($tag); // make sure tag packages have no -dev flag $data['version'] = preg_replace('{[.-]?dev$}i', '', $data['version']); $data['version_normalized'] = preg_replace('{(^dev-|[.-]?dev$)}i', '', $data['version_normalized']); // broken package, version doesn't match tag if ($data['version_normalized'] !== $parsedTag) { if ($verbose) { $this->io->write('<warning>Skipped tag '.$tag.', tag ('.$parsedTag.') does not match version ('.$data['version_normalized'].') in composer.json</warning>'); } continue; } if ($verbose) { $this->io->write('Importing tag '.$tag.' ('.$data['version_normalized'].')'); } $this->addPackage($this->loader->load($this->preProcess($driver, $data, $identifier))); } catch (\Exception $e) { if ($verbose) { $this->io->write('<warning>Skipped tag '.$tag.', '.($e instanceof TransportException ? 'no composer file was found' : $e->getMessage()).'</warning>'); } continue; } } if (!$verbose) { $this->io->overwrite('', false); } foreach ($driver->getBranches() as $branch => $identifier) { $msg = 'Reading composer.json of <info>' . ($this->packageName ?: $this->url) . '</info> (<comment>' . $branch . '</comment>)'; if ($verbose) { $this->io->write($msg); } else { $this->io->overwrite($msg, false); } if (!$parsedBranch = $this->validateBranch($branch)) { if ($verbose) { $this->io->write('<warning>Skipped branch '.$branch.', invalid name</warning>'); } continue; } try { if (!$data = $driver->getComposerInformation($identifier)) { if ($verbose) { $this->io->write('<warning>Skipped branch '.$branch.', no composer file</warning>'); } continue; } // branches are always auto-versioned, read value from branch name // set branch name without package namespace $data['version'] = $this->_getBranchWithoutNamespace($branch); //set package namespace to generate package name based upon repository name $data['namespace'] = isset($data['namespace']) ? $data['namespace'] : $this->_getBranchNamespace($branch); $data['version_normalized'] = $parsedBranch; // make sure branch packages have a dev flag if ('dev-' === substr($parsedBranch, 0, 4) || '9999999-dev' === $parsedBranch) { $data['version'] = 'dev-' . $data['version']; } else { $data['version'] = preg_replace('{(\.9{7})+}', '.x', $parsedBranch); } if ($verbose) { $this->io->write('Importing branch '.$branch.' ('.$data['version'].')'); } $packageData = $this->preProcess($driver, $data, $identifier); $package = $this->loader->load($packageData); if ($this->loader instanceof ValidatingArrayLoader && $this->loader->getWarnings()) { throw new InvalidPackageException($this->loader->getErrors(), $this->loader->getWarnings(), $packageData); } $this->addPackage($package); } catch (TransportException $e) { if ($verbose) { $this->io->write('<warning>Skipped branch '.$branch.', no composer file was found</warning>'); } continue; } catch (\Exception $e) { if (!$verbose) { $this->io->write(''); } $this->branchErrorOccurred = true; $this->io->write('<error>Skipped branch '.$branch.', '.$e->getMessage().'</error>'); $this->io->write(''); continue; } } $driver->cleanup(); if (!$verbose) { $this->io->overwrite('', false); } if (!$this->getPackages()) { throw new InvalidRepositoryException('No valid composer.json was found in any branch or tag of '.$this->url.', could not load a package from it.'); } }
[ "protected", "function", "initialize", "(", ")", "{", "ArrayRepository", "::", "initialize", "(", ")", ";", "$", "verbose", "=", "$", "this", "->", "verbose", ";", "/** @var VcsDriver $driver */", "$", "driver", "=", "$", "this", "->", "getDriver", "(", ")",...
Implemented package namespace usage @see VcsRepository::initialize() @throws InvalidRepositoryException
[ "Implemented", "package", "namespace", "usage" ]
train
https://github.com/andkirby/multi-repo-composer/blob/2d9fed02edf7601f56f2998f9d99e646b713aef6/src/Repository/VcsNamespaceRepository.php#L105-L274
andkirby/multi-repo-composer
src/Repository/VcsNamespaceRepository.php
VcsNamespaceRepository.preProcess
protected function preProcess(VcsDriverInterface $driver, array $data, $identifier) { // keep the name of the main identifier for all packages if ($this->packageName != $this->url) { $namespace = preg_replace('/([a-z0-9])([A-Z])/', '$1_$2', $data['namespace']); $namespace = strtolower($namespace); $data['name'] = $this->packageName . '-' . $namespace; } if (!isset($data['dist'])) { $data['dist'] = $driver->getDist($identifier); } if (!isset($data['source'])) { $data['source'] = $driver->getSource($identifier); $data['source']['type'] = $this->repoConfig['type']; } return $data; }
php
protected function preProcess(VcsDriverInterface $driver, array $data, $identifier) { // keep the name of the main identifier for all packages if ($this->packageName != $this->url) { $namespace = preg_replace('/([a-z0-9])([A-Z])/', '$1_$2', $data['namespace']); $namespace = strtolower($namespace); $data['name'] = $this->packageName . '-' . $namespace; } if (!isset($data['dist'])) { $data['dist'] = $driver->getDist($identifier); } if (!isset($data['source'])) { $data['source'] = $driver->getSource($identifier); $data['source']['type'] = $this->repoConfig['type']; } return $data; }
[ "protected", "function", "preProcess", "(", "VcsDriverInterface", "$", "driver", ",", "array", "$", "data", ",", "$", "identifier", ")", "{", "// keep the name of the main identifier for all packages", "if", "(", "$", "this", "->", "packageName", "!=", "$", "this", ...
Make proper package data @param VcsDriverInterface $driver @param array $data @param string $identifier @return array
[ "Make", "proper", "package", "data" ]
train
https://github.com/andkirby/multi-repo-composer/blob/2d9fed02edf7601f56f2998f9d99e646b713aef6/src/Repository/VcsNamespaceRepository.php#L284-L302
andkirby/multi-repo-composer
src/Repository/VcsNamespaceRepository.php
VcsNamespaceRepository.validateTag
protected function validateTag($version) { try { if (!strpos($version, '/')) { return false; } return $this->versionParser->normalize( $this->_getBranchWithoutNamespace($version) ); } catch (\Exception $e) { return false; } }
php
protected function validateTag($version) { try { if (!strpos($version, '/')) { return false; } return $this->versionParser->normalize( $this->_getBranchWithoutNamespace($version) ); } catch (\Exception $e) { return false; } }
[ "protected", "function", "validateTag", "(", "$", "version", ")", "{", "try", "{", "if", "(", "!", "strpos", "(", "$", "version", ",", "'/'", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "versionParser", "->", "normalize", ...
Get normalized tag name It will return an empty result if it's not valid @param string $version @return bool
[ "Get", "normalized", "tag", "name" ]
train
https://github.com/andkirby/multi-repo-composer/blob/2d9fed02edf7601f56f2998f9d99e646b713aef6/src/Repository/VcsNamespaceRepository.php#L312-L324
andkirby/multi-repo-composer
src/Repository/VcsNamespaceRepository.php
VcsNamespaceRepository.validateBranch
protected function validateBranch($branch) { try { if (!strpos($branch, '/')) { return false; } return $this->versionParser->normalizeBranch( $this->_getBranchWithoutNamespace($branch) ); } catch (\Exception $e) { return false; } }
php
protected function validateBranch($branch) { try { if (!strpos($branch, '/')) { return false; } return $this->versionParser->normalizeBranch( $this->_getBranchWithoutNamespace($branch) ); } catch (\Exception $e) { return false; } }
[ "protected", "function", "validateBranch", "(", "$", "branch", ")", "{", "try", "{", "if", "(", "!", "strpos", "(", "$", "branch", ",", "'/'", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "versionParser", "->", "normalizeBra...
Get normalized branch name It will return an empty result if it's not valid @param string $branch @return bool
[ "Get", "normalized", "branch", "name" ]
train
https://github.com/andkirby/multi-repo-composer/blob/2d9fed02edf7601f56f2998f9d99e646b713aef6/src/Repository/VcsNamespaceRepository.php#L334-L346
makinacorpus/drupal-ucms
ucms_search/src/IndexStorage.php
IndexStorage.getIndexRealname
public function getIndexRealname($index) { if (isset($this->indexAliasMap[$index])) { return $this->indexAliasMap[$index]; } return $index; }
php
public function getIndexRealname($index) { if (isset($this->indexAliasMap[$index])) { return $this->indexAliasMap[$index]; } return $index; }
[ "public", "function", "getIndexRealname", "(", "$", "index", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "indexAliasMap", "[", "$", "index", "]", ")", ")", "{", "return", "$", "this", "->", "indexAliasMap", "[", "$", "index", "]", ";", "}",...
Get index real name for Elastic Search @param string $index @return string
[ "Get", "index", "real", "name", "for", "Elastic", "Search" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/IndexStorage.php#L135-L142
makinacorpus/drupal-ucms
ucms_search/src/IndexStorage.php
IndexStorage.indexer
public function indexer($index = null) { if (empty($this->nodeIndexerChain)) { $list = []; foreach ($this->keys() as $existing) { $list[$existing] = new NodeIndexer( $existing, $this->client, $this->db, $this->entityManager, $this->moduleHandler, $this->eventDispatcher, $this->getIndexRealname($existing), $this->preventBulkUsage ); } $this->nodeIndexerChain = new NodeIndexerChain($list); } if ($index) { return $this->nodeIndexerChain->getIndexer($index); } return $this->nodeIndexerChain; }
php
public function indexer($index = null) { if (empty($this->nodeIndexerChain)) { $list = []; foreach ($this->keys() as $existing) { $list[$existing] = new NodeIndexer( $existing, $this->client, $this->db, $this->entityManager, $this->moduleHandler, $this->eventDispatcher, $this->getIndexRealname($existing), $this->preventBulkUsage ); } $this->nodeIndexerChain = new NodeIndexerChain($list); } if ($index) { return $this->nodeIndexerChain->getIndexer($index); } return $this->nodeIndexerChain; }
[ "public", "function", "indexer", "(", "$", "index", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "nodeIndexerChain", ")", ")", "{", "$", "list", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "keys", "(", ")", "as", ...
Get node indexer for the given index @param string $index If none is given, a passthru implementation that will work internally on all indices at once will be given @return NodeIndexerInterface
[ "Get", "node", "indexer", "for", "the", "given", "index" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/IndexStorage.php#L153-L177
makinacorpus/drupal-ucms
ucms_search/src/IndexStorage.php
IndexStorage.save
public function save($index, $name, $param, $force = false) { $updated = false; $existing = $this->load($index); // Directly compare array structures, should be enough if (!$existing || $force || $param !== $existing) { // This was updated, then we really need to save it $updated = true; } // Adds 'node_access' table ACL system replica into elastic index // mapping so that we can query it later, this will only replicate // grants for the view operation, here is the process: // - it identifies each (realm, gid) group for the node as a raw // string such as "REALM:GID" // - it stores a string term vector of those // - of course, it only stores those with 1 as value for grant_view // - in all queries, a nice alteration will be done to force it to // have a filter query that does a term exact match in the vector // for all user grants $param['mapping']['node']['properties']['node_access']['type'] = 'string'; $this ->db ->merge('ucms_search_index') ->key(['index_key' => $index]) ->fields(['name' => $name, 'data' => serialize($param)]) ->execute() ; $this->clearDefinitionCache(); $this->moduleHandler->invokeAll(self::HOOK_DEF_SAVE, [$index, $param, $updated, !$existing]); $this->indexer(); $this->nodeIndexerChain->addIndexer( $index, new NodeIndexer( $index, $this->client, $this->db, $this->entityManager, $this->moduleHandler, $this->eventDispatcher, $this->getIndexRealname($index), $this->preventBulkUsage )); if ($updated) { $this->clear($index); } }
php
public function save($index, $name, $param, $force = false) { $updated = false; $existing = $this->load($index); // Directly compare array structures, should be enough if (!$existing || $force || $param !== $existing) { // This was updated, then we really need to save it $updated = true; } // Adds 'node_access' table ACL system replica into elastic index // mapping so that we can query it later, this will only replicate // grants for the view operation, here is the process: // - it identifies each (realm, gid) group for the node as a raw // string such as "REALM:GID" // - it stores a string term vector of those // - of course, it only stores those with 1 as value for grant_view // - in all queries, a nice alteration will be done to force it to // have a filter query that does a term exact match in the vector // for all user grants $param['mapping']['node']['properties']['node_access']['type'] = 'string'; $this ->db ->merge('ucms_search_index') ->key(['index_key' => $index]) ->fields(['name' => $name, 'data' => serialize($param)]) ->execute() ; $this->clearDefinitionCache(); $this->moduleHandler->invokeAll(self::HOOK_DEF_SAVE, [$index, $param, $updated, !$existing]); $this->indexer(); $this->nodeIndexerChain->addIndexer( $index, new NodeIndexer( $index, $this->client, $this->db, $this->entityManager, $this->moduleHandler, $this->eventDispatcher, $this->getIndexRealname($index), $this->preventBulkUsage )); if ($updated) { $this->clear($index); } }
[ "public", "function", "save", "(", "$", "index", ",", "$", "name", ",", "$", "param", ",", "$", "force", "=", "false", ")", "{", "$", "updated", "=", "false", ";", "$", "existing", "=", "$", "this", "->", "load", "(", "$", "index", ")", ";", "/...
Create or update index definition @param string $index Index key @param string $name Human readable title @param array $param This must contain the exact replica of the 'body' key that will be sent to ElasticSearch indices()::create() array @param boolean $force Force index to be refreshed
[ "Create", "or", "update", "index", "definition" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/IndexStorage.php#L192-L243
makinacorpus/drupal-ucms
ucms_search/src/IndexStorage.php
IndexStorage.names
public function names() { if ($this->indexListCache) { return $this->indexListCache; } // Attempt to have a zero SQL Drupal $doCache = variable_get('ucms_search_cache_list', true); if ($doCache && ($cached = $this->cache->get(self::CID_LIST))) { $this->indexListCache = $cached->data; } else { $this->indexListCache = $this ->db ->query( "SELECT index_key, name FROM {ucms_search_index}" ) ->fetchAllKeyed() ; if ($doCache) { $this->cache->set(self::CID_LIST, $this->indexListCache); } } return $this->indexListCache; }
php
public function names() { if ($this->indexListCache) { return $this->indexListCache; } // Attempt to have a zero SQL Drupal $doCache = variable_get('ucms_search_cache_list', true); if ($doCache && ($cached = $this->cache->get(self::CID_LIST))) { $this->indexListCache = $cached->data; } else { $this->indexListCache = $this ->db ->query( "SELECT index_key, name FROM {ucms_search_index}" ) ->fetchAllKeyed() ; if ($doCache) { $this->cache->set(self::CID_LIST, $this->indexListCache); } } return $this->indexListCache; }
[ "public", "function", "names", "(", ")", "{", "if", "(", "$", "this", "->", "indexListCache", ")", "{", "return", "$", "this", "->", "indexListCache", ";", "}", "// Attempt to have a zero SQL Drupal", "$", "doCache", "=", "variable_get", "(", "'ucms_search_cache...
Get indices names @return string[] Keys are indices machine names while values are human readables names
[ "Get", "indices", "names" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/IndexStorage.php#L276-L303
makinacorpus/drupal-ucms
ucms_search/src/IndexStorage.php
IndexStorage.load
public function load($index) { // Minor optimization, avoid lookups for unknow indexes if (!$this->exists($index)) { return; } // Can be null if index does not exists if (array_key_exists($index, $this->indexDefinitionCache)) { return $this->indexDefinitionCache[$index]; } $param = $this ->db ->query( "SELECT data FROM {ucms_search_index} WHERE index_key = :index", ['index' => $index] ) ->fetchField() ; if ($param) { $param = unserialize($param); } return $this->indexDefinitionCache[$index] = $param; }
php
public function load($index) { // Minor optimization, avoid lookups for unknow indexes if (!$this->exists($index)) { return; } // Can be null if index does not exists if (array_key_exists($index, $this->indexDefinitionCache)) { return $this->indexDefinitionCache[$index]; } $param = $this ->db ->query( "SELECT data FROM {ucms_search_index} WHERE index_key = :index", ['index' => $index] ) ->fetchField() ; if ($param) { $param = unserialize($param); } return $this->indexDefinitionCache[$index] = $param; }
[ "public", "function", "load", "(", "$", "index", ")", "{", "// Minor optimization, avoid lookups for unknow indexes", "if", "(", "!", "$", "this", "->", "exists", "(", "$", "index", ")", ")", "{", "return", ";", "}", "// Can be null if index does not exists", "if"...
Load an index definition This is uncached, never use it during normal runtime @param string $index @return array This must contain the exact replica of the 'body' key that will be sent to ElasticSearch indices()::create() array.
[ "Load", "an", "index", "definition" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/IndexStorage.php#L316-L342
makinacorpus/drupal-ucms
ucms_search/src/IndexStorage.php
IndexStorage.delete
public function delete($index) { $this ->db ->delete('ucms_search_index') ->condition('index_key', $index) ->execute() ; $this->indexer(); $this->nodeIndexerChain->removeIndexer($index); $this->clearDefinitionCache(); $this->moduleHandler->invokeAll(self::HOOK_DEF_DELETE, [$index]); $this->deleteInClient($index); }
php
public function delete($index) { $this ->db ->delete('ucms_search_index') ->condition('index_key', $index) ->execute() ; $this->indexer(); $this->nodeIndexerChain->removeIndexer($index); $this->clearDefinitionCache(); $this->moduleHandler->invokeAll(self::HOOK_DEF_DELETE, [$index]); $this->deleteInClient($index); }
[ "public", "function", "delete", "(", "$", "index", ")", "{", "$", "this", "->", "db", "->", "delete", "(", "'ucms_search_index'", ")", "->", "condition", "(", "'index_key'", ",", "$", "index", ")", "->", "execute", "(", ")", ";", "$", "this", "->", "...
Delete an index definition @param string $index
[ "Delete", "an", "index", "definition" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/IndexStorage.php#L349-L366
makinacorpus/drupal-ucms
ucms_search/src/IndexStorage.php
IndexStorage.clear
public function clear($index) { $this->deleteInClient($index); $this->createInClient($index); $this->indexer(); $this->nodeIndexerChain->getIndexer($index)->bulkMarkForReindex(); }
php
public function clear($index) { $this->deleteInClient($index); $this->createInClient($index); $this->indexer(); $this->nodeIndexerChain->getIndexer($index)->bulkMarkForReindex(); }
[ "public", "function", "clear", "(", "$", "index", ")", "{", "$", "this", "->", "deleteInClient", "(", "$", "index", ")", ";", "$", "this", "->", "createInClient", "(", "$", "index", ")", ";", "$", "this", "->", "indexer", "(", ")", ";", "$", "this"...
Clear an index. @param string $index
[ "Clear", "an", "index", "." ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/IndexStorage.php#L373-L380
makinacorpus/drupal-ucms
ucms_search/src/IndexStorage.php
IndexStorage.createInClient
protected function createInClient($index) { $param = $this->load($index); if (!$param) { throw new \InvalidArgumentException(sprintf("'%s' index definition does not exist", $index)); } $namespace = $this->client->indices(); $indexRealname = $this->getIndexRealname($index); if (!$namespace->exists(['index' => $indexRealname])) { $namespace->create([ 'index' => $indexRealname, 'body' => $param, ]); } }
php
protected function createInClient($index) { $param = $this->load($index); if (!$param) { throw new \InvalidArgumentException(sprintf("'%s' index definition does not exist", $index)); } $namespace = $this->client->indices(); $indexRealname = $this->getIndexRealname($index); if (!$namespace->exists(['index' => $indexRealname])) { $namespace->create([ 'index' => $indexRealname, 'body' => $param, ]); } }
[ "protected", "function", "createInClient", "(", "$", "index", ")", "{", "$", "param", "=", "$", "this", "->", "load", "(", "$", "index", ")", ";", "if", "(", "!", "$", "param", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "sprintf",...
Ensure index exists @param string $index
[ "Ensure", "index", "exists" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/IndexStorage.php#L387-L404
makinacorpus/drupal-ucms
ucms_search/src/IndexStorage.php
IndexStorage.deleteInClient
protected function deleteInClient($index) { $namespace = $this->client->indices(); $indexRealname = $this->getIndexRealname($index); if ($namespace->exists(['index' => $indexRealname])) { $namespace->delete(['index' => $indexRealname]); } }
php
protected function deleteInClient($index) { $namespace = $this->client->indices(); $indexRealname = $this->getIndexRealname($index); if ($namespace->exists(['index' => $indexRealname])) { $namespace->delete(['index' => $indexRealname]); } }
[ "protected", "function", "deleteInClient", "(", "$", "index", ")", "{", "$", "namespace", "=", "$", "this", "->", "client", "->", "indices", "(", ")", ";", "$", "indexRealname", "=", "$", "this", "->", "getIndexRealname", "(", "$", "index", ")", ";", "...
Delete an index on Elastic client without removing the Drupal definition @param string $index
[ "Delete", "an", "index", "on", "Elastic", "client", "without", "removing", "the", "Drupal", "definition" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/IndexStorage.php#L411-L419
makinacorpus/drupal-ucms
ucms_search/src/IndexStorage.php
IndexStorage.clearDefinitionCache
protected function clearDefinitionCache() { $this->indexDefinitionCache = []; $this->indexListCache = []; $this->cache->delete(self::CID_LIST); }
php
protected function clearDefinitionCache() { $this->indexDefinitionCache = []; $this->indexListCache = []; $this->cache->delete(self::CID_LIST); }
[ "protected", "function", "clearDefinitionCache", "(", ")", "{", "$", "this", "->", "indexDefinitionCache", "=", "[", "]", ";", "$", "this", "->", "indexListCache", "=", "[", "]", ";", "$", "this", "->", "cache", "->", "delete", "(", "self", "::", "CID_LI...
Clear all index definition related cache
[ "Clear", "all", "index", "definition", "related", "cache" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_search/src/IndexStorage.php#L424-L429
qloog/yaf-library
src/Http/Cookies.php
Cookies.getConfig
public static function getConfig() { if (static::$config !== null) { return static::$config; } $configs = Registry::get('config'); return static::$config = isset($configs['cookie']) ? $configs['cookie'] : []; }
php
public static function getConfig() { if (static::$config !== null) { return static::$config; } $configs = Registry::get('config'); return static::$config = isset($configs['cookie']) ? $configs['cookie'] : []; }
[ "public", "static", "function", "getConfig", "(", ")", "{", "if", "(", "static", "::", "$", "config", "!==", "null", ")", "{", "return", "static", "::", "$", "config", ";", "}", "$", "configs", "=", "Registry", "::", "get", "(", "'config'", ")", ";",...
获取配置 @return array
[ "获取配置" ]
train
https://github.com/qloog/yaf-library/blob/8e7dc276ffb335adfb298dffce9c0b533e14bd93/src/Http/Cookies.php#L56-L65
makinacorpus/drupal-ucms
ucms_group/src/Datasource/GroupMemberAdminDatasource.php
GroupMemberAdminDatasource.getItems
public function getItems(Query $query) { $q = $this ->database ->select('ucms_group_access', 'gu') ->fields('gu', ['group_id', 'user_id', 'role']) ->fields('u', ['name', 'mail', 'status']) ->addTag('ucms_group_access') //->groupBy('gu.user_id') ; $q->join('users', 'u', "u.uid = gu.user_id"); if ($query->has('group')) { $q->condition('gu.group_id', $query->has('group')); } if ($query->has('uid')) { $q->condition('gu.user_id', $query->get('uid')); } if ($query->hasSortField()) { $q->orderBy($query->getSortField(), $query->getSortOrder()); } $q->orderBy('u.name', $query->getSortOrder()); $search = $query->getSearchString(); if ($search) { $q->condition( (new \DatabaseCondition('OR')) ->condition('u.name', '%' . db_like($search) . '%', 'LIKE') ->condition('u.mail', '%' . db_like($search) . '%', 'LIKE') ); } /** @var \MakinaCorpus\Drupal\Calista\Datasource\QueryExtender\DrupalPager $pager */ $pager = $q->extend(DrupalPager::class)->setDatasourceQuery($query); $r = $pager->execute(); $r->setFetchMode(\PDO::FETCH_CLASS, GroupMember::class); $items = $r->fetchAll(); return $this->createResult($items, $pager->getTotalCount()); }
php
public function getItems(Query $query) { $q = $this ->database ->select('ucms_group_access', 'gu') ->fields('gu', ['group_id', 'user_id', 'role']) ->fields('u', ['name', 'mail', 'status']) ->addTag('ucms_group_access') //->groupBy('gu.user_id') ; $q->join('users', 'u', "u.uid = gu.user_id"); if ($query->has('group')) { $q->condition('gu.group_id', $query->has('group')); } if ($query->has('uid')) { $q->condition('gu.user_id', $query->get('uid')); } if ($query->hasSortField()) { $q->orderBy($query->getSortField(), $query->getSortOrder()); } $q->orderBy('u.name', $query->getSortOrder()); $search = $query->getSearchString(); if ($search) { $q->condition( (new \DatabaseCondition('OR')) ->condition('u.name', '%' . db_like($search) . '%', 'LIKE') ->condition('u.mail', '%' . db_like($search) . '%', 'LIKE') ); } /** @var \MakinaCorpus\Drupal\Calista\Datasource\QueryExtender\DrupalPager $pager */ $pager = $q->extend(DrupalPager::class)->setDatasourceQuery($query); $r = $pager->execute(); $r->setFetchMode(\PDO::FETCH_CLASS, GroupMember::class); $items = $r->fetchAll(); return $this->createResult($items, $pager->getTotalCount()); }
[ "public", "function", "getItems", "(", "Query", "$", "query", ")", "{", "$", "q", "=", "$", "this", "->", "database", "->", "select", "(", "'ucms_group_access'", ",", "'gu'", ")", "->", "fields", "(", "'gu'", ",", "[", "'group_id'", ",", "'user_id'", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/makinacorpus/drupal-ucms/blob/6b8a84305472d2cad816102672f10274b3bbb535/ucms_group/src/Datasource/GroupMemberAdminDatasource.php#L57-L99
anlutro/laravel-validation
src/Validator.php
Validator.replace
public function replace($key, $value) { $key = (string) $key; $value = (string) $value; if ($value === null) { unset($this->replace[$key]); } else { $this->replace[$key] = $value; } }
php
public function replace($key, $value) { $key = (string) $key; $value = (string) $value; if ($value === null) { unset($this->replace[$key]); } else { $this->replace[$key] = $value; } }
[ "public", "function", "replace", "(", "$", "key", ",", "$", "value", ")", "{", "$", "key", "=", "(", "string", ")", "$", "key", ";", "$", "value", "=", "(", "string", ")", "$", "value", ";", "if", "(", "$", "value", "===", "null", ")", "{", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/anlutro/laravel-validation/blob/fb653cf29f230bf53beda4b35a4e1042d52faaeb/src/Validator.php#L74-L84
anlutro/laravel-validation
src/Validator.php
Validator.valid
public function valid($action, array $attributes, $merge = null) { $rules = $this->prepareRules($this->getRules($action, $merge), $attributes); $rules = $this->replaceRuleVariables($rules, $attributes); $this->validator = $this->makeValidator($rules, $attributes); if ($this->throwExceptions) { if ($this->validator->passes()) { return true; } else { throw new ValidationException($this->validator->getMessageBag(), $rules, $attributes, $action); } } else { return $this->validator->passes(); } }
php
public function valid($action, array $attributes, $merge = null) { $rules = $this->prepareRules($this->getRules($action, $merge), $attributes); $rules = $this->replaceRuleVariables($rules, $attributes); $this->validator = $this->makeValidator($rules, $attributes); if ($this->throwExceptions) { if ($this->validator->passes()) { return true; } else { throw new ValidationException($this->validator->getMessageBag(), $rules, $attributes, $action); } } else { return $this->validator->passes(); } }
[ "public", "function", "valid", "(", "$", "action", ",", "array", "$", "attributes", ",", "$", "merge", "=", "null", ")", "{", "$", "rules", "=", "$", "this", "->", "prepareRules", "(", "$", "this", "->", "getRules", "(", "$", "action", ",", "$", "m...
{@inheritdoc}
[ "{" ]
train
https://github.com/anlutro/laravel-validation/blob/fb653cf29f230bf53beda4b35a4e1042d52faaeb/src/Validator.php#L105-L121
anlutro/laravel-validation
src/Validator.php
Validator.getRules
protected function getRules($action, $merge = null) { $method = 'get' . ucfirst($action) . 'Rules'; if (method_exists($this, $method)) { $rules = $this->$method(); } else { $rules = []; } if ($merge === null) { $merge = $this->merge; } if ($merge) { $rules = array_merge_recursive($this->getCommonRules(), $rules); } return $rules; }
php
protected function getRules($action, $merge = null) { $method = 'get' . ucfirst($action) . 'Rules'; if (method_exists($this, $method)) { $rules = $this->$method(); } else { $rules = []; } if ($merge === null) { $merge = $this->merge; } if ($merge) { $rules = array_merge_recursive($this->getCommonRules(), $rules); } return $rules; }
[ "protected", "function", "getRules", "(", "$", "action", ",", "$", "merge", "=", "null", ")", "{", "$", "method", "=", "'get'", ".", "ucfirst", "(", "$", "action", ")", ".", "'Rules'", ";", "if", "(", "method_exists", "(", "$", "this", ",", "$", "m...
Get the rules for an action. @param string $action @param boolean $merge Whether or not to merge with common rules. Leave the parameter out to default to $this->merge @return array
[ "Get", "the", "rules", "for", "an", "action", "." ]
train
https://github.com/anlutro/laravel-validation/blob/fb653cf29f230bf53beda4b35a4e1042d52faaeb/src/Validator.php#L132-L151
anlutro/laravel-validation
src/Validator.php
Validator.replaceRuleVariables
protected function replaceRuleVariables(array $rules, array $attributes) { array_walk_recursive($rules, function(&$item, $key) use($attributes) { // don't mess with regex rules if (substr($item, 0, 6) === 'regex:') return; // replace explicit variables foreach ($this->replace as $key => $value) { if (strpos($item, "<$key>") !== false) { $item = str_replace("<$key>", $value, $item); } } // replace input variables foreach ($attributes as $key => $value) { if (strpos($item, "[$key]") !== false) { $item = str_replace("[$key]", $value, $item); } } }); return $rules; }
php
protected function replaceRuleVariables(array $rules, array $attributes) { array_walk_recursive($rules, function(&$item, $key) use($attributes) { // don't mess with regex rules if (substr($item, 0, 6) === 'regex:') return; // replace explicit variables foreach ($this->replace as $key => $value) { if (strpos($item, "<$key>") !== false) { $item = str_replace("<$key>", $value, $item); } } // replace input variables foreach ($attributes as $key => $value) { if (strpos($item, "[$key]") !== false) { $item = str_replace("[$key]", $value, $item); } } }); return $rules; }
[ "protected", "function", "replaceRuleVariables", "(", "array", "$", "rules", ",", "array", "$", "attributes", ")", "{", "array_walk_recursive", "(", "$", "rules", ",", "function", "(", "&", "$", "item", ",", "$", "key", ")", "use", "(", "$", "attributes", ...
Dynamically replace variables in the rules. @param array $rules @param array $attributes @return array
[ "Dynamically", "replace", "variables", "in", "the", "rules", "." ]
train
https://github.com/anlutro/laravel-validation/blob/fb653cf29f230bf53beda4b35a4e1042d52faaeb/src/Validator.php#L174-L196
anlutro/laravel-validation
src/Validator.php
Validator.makeValidator
protected function makeValidator(array $rules, array $attributes) { $validator = $this->factory->make($attributes, $rules); $this->prepareValidator($this->validator); return $validator; }
php
protected function makeValidator(array $rules, array $attributes) { $validator = $this->factory->make($attributes, $rules); $this->prepareValidator($this->validator); return $validator; }
[ "protected", "function", "makeValidator", "(", "array", "$", "rules", ",", "array", "$", "attributes", ")", "{", "$", "validator", "=", "$", "this", "->", "factory", "->", "make", "(", "$", "attributes", ",", "$", "rules", ")", ";", "$", "this", "->", ...
Make a new validator instance. @param array $rules @param array $attributes @return \Illuminate\Validation\Validator
[ "Make", "a", "new", "validator", "instance", "." ]
train
https://github.com/anlutro/laravel-validation/blob/fb653cf29f230bf53beda4b35a4e1042d52faaeb/src/Validator.php#L220-L225
ARCANEDEV/Settings
src/Stores/DatabaseStore.php
DatabaseStore.setConstraint
public function setConstraint(Closure $callback) { $this->data = []; $this->loaded = false; $this->queryConstraint = $callback; return $this; }
php
public function setConstraint(Closure $callback) { $this->data = []; $this->loaded = false; $this->queryConstraint = $callback; return $this; }
[ "public", "function", "setConstraint", "(", "Closure", "$", "callback", ")", "{", "$", "this", "->", "data", "=", "[", "]", ";", "$", "this", "->", "loaded", "=", "false", ";", "$", "this", "->", "queryConstraint", "=", "$", "callback", ";", "return", ...
Set the query constraint. @param \Closure $callback @return self
[ "Set", "the", "query", "constraint", "." ]
train
https://github.com/ARCANEDEV/Settings/blob/8e08dadc29d5a47c64099454696100babb356530/src/Stores/DatabaseStore.php#L94-L101
ARCANEDEV/Settings
src/Stores/DatabaseStore.php
DatabaseStore.read
protected function read() { $results = []; foreach ($this->model()->get() as $setting) { /** @var Setting $setting */ Arr::set($results, $setting->key, $setting->value); } return $results; }
php
protected function read() { $results = []; foreach ($this->model()->get() as $setting) { /** @var Setting $setting */ Arr::set($results, $setting->key, $setting->value); } return $results; }
[ "protected", "function", "read", "(", ")", "{", "$", "results", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "model", "(", ")", "->", "get", "(", ")", "as", "$", "setting", ")", "{", "/** @var Setting $setting */", "Arr", "::", "set", "(", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/ARCANEDEV/Settings/blob/8e08dadc29d5a47c64099454696100babb356530/src/Stores/DatabaseStore.php#L154-L164
ARCANEDEV/Settings
src/Stores/DatabaseStore.php
DatabaseStore.write
protected function write(array $data) { list($inserts, $updates, $deletes) = $this->prepareData($data); $this->updateSettings($updates); $this->insertSettings($inserts); $this->deleteSettings($deletes); }
php
protected function write(array $data) { list($inserts, $updates, $deletes) = $this->prepareData($data); $this->updateSettings($updates); $this->insertSettings($inserts); $this->deleteSettings($deletes); }
[ "protected", "function", "write", "(", "array", "$", "data", ")", "{", "list", "(", "$", "inserts", ",", "$", "updates", ",", "$", "deletes", ")", "=", "$", "this", "->", "prepareData", "(", "$", "data", ")", ";", "$", "this", "->", "updateSettings",...
{@inheritdoc}
[ "{" ]
train
https://github.com/ARCANEDEV/Settings/blob/8e08dadc29d5a47c64099454696100babb356530/src/Stores/DatabaseStore.php#L169-L176
ARCANEDEV/Settings
src/Stores/DatabaseStore.php
DatabaseStore.prepareData
private function prepareData(array $data) { $inserts = array_dot($data); $updates = []; $deletes = []; foreach ($this->model()->lists('key') as $key) { if (isset($inserts[$key])) $updates[$key] = $inserts[$key]; else $deletes[] = $key; unset($inserts[$key]); } return [$inserts, $updates, $deletes]; }
php
private function prepareData(array $data) { $inserts = array_dot($data); $updates = []; $deletes = []; foreach ($this->model()->lists('key') as $key) { if (isset($inserts[$key])) $updates[$key] = $inserts[$key]; else $deletes[] = $key; unset($inserts[$key]); } return [$inserts, $updates, $deletes]; }
[ "private", "function", "prepareData", "(", "array", "$", "data", ")", "{", "$", "inserts", "=", "array_dot", "(", "$", "data", ")", ";", "$", "updates", "=", "[", "]", ";", "$", "deletes", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "m...
Prepare settings data. @param array $data @return array
[ "Prepare", "settings", "data", "." ]
train
https://github.com/ARCANEDEV/Settings/blob/8e08dadc29d5a47c64099454696100babb356530/src/Stores/DatabaseStore.php#L189-L205
ARCANEDEV/Settings
src/Stores/DatabaseStore.php
DatabaseStore.updateSettings
private function updateSettings($updates) { foreach ($updates as $key => $value) { $this->model()->where('key', $key)->update(compact('value')); } }
php
private function updateSettings($updates) { foreach ($updates as $key => $value) { $this->model()->where('key', $key)->update(compact('value')); } }
[ "private", "function", "updateSettings", "(", "$", "updates", ")", "{", "foreach", "(", "$", "updates", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "this", "->", "model", "(", ")", "->", "where", "(", "'key'", ",", "$", "key", ")", "->", ...
Update settings data. @param array $updates
[ "Update", "settings", "data", "." ]
train
https://github.com/ARCANEDEV/Settings/blob/8e08dadc29d5a47c64099454696100babb356530/src/Stores/DatabaseStore.php#L212-L217
ARCANEDEV/Settings
src/Stores/DatabaseStore.php
DatabaseStore.insertSettings
private function insertSettings(array $inserts) { if (empty($inserts)) { return; } $dbData = []; foreach ($inserts as $key => $value) { $data = compact('key', 'value'); $dbData[] = empty($this->extraColumns) ? $data : array_merge($this->extraColumns, $data); } $this->model(true)->insert($dbData); }
php
private function insertSettings(array $inserts) { if (empty($inserts)) { return; } $dbData = []; foreach ($inserts as $key => $value) { $data = compact('key', 'value'); $dbData[] = empty($this->extraColumns) ? $data : array_merge($this->extraColumns, $data); } $this->model(true)->insert($dbData); }
[ "private", "function", "insertSettings", "(", "array", "$", "inserts", ")", "{", "if", "(", "empty", "(", "$", "inserts", ")", ")", "{", "return", ";", "}", "$", "dbData", "=", "[", "]", ";", "foreach", "(", "$", "inserts", "as", "$", "key", "=>", ...
Insert settings data. @param array $inserts
[ "Insert", "settings", "data", "." ]
train
https://github.com/ARCANEDEV/Settings/blob/8e08dadc29d5a47c64099454696100babb356530/src/Stores/DatabaseStore.php#L224-L238
ARCANEDEV/Settings
src/Stores/DatabaseStore.php
DatabaseStore.model
private function model($insert = false) { $model = $this->model; if ($insert === false) { foreach ($this->extraColumns as $key => $value) { $model->where($key, $value); } } if ($this->hasConstraint()) { /** @var Closure $callback */ $callback = $this->queryConstraint; $model = $callback($model, $insert); } return $model; }
php
private function model($insert = false) { $model = $this->model; if ($insert === false) { foreach ($this->extraColumns as $key => $value) { $model->where($key, $value); } } if ($this->hasConstraint()) { /** @var Closure $callback */ $callback = $this->queryConstraint; $model = $callback($model, $insert); } return $model; }
[ "private", "function", "model", "(", "$", "insert", "=", "false", ")", "{", "$", "model", "=", "$", "this", "->", "model", ";", "if", "(", "$", "insert", "===", "false", ")", "{", "foreach", "(", "$", "this", "->", "extraColumns", "as", "$", "key",...
Create a new query builder instance. @param $insert bool Whether the query is an insert or not. @return \Arcanedev\Settings\Models\Setting
[ "Create", "a", "new", "query", "builder", "instance", "." ]
train
https://github.com/ARCANEDEV/Settings/blob/8e08dadc29d5a47c64099454696100babb356530/src/Stores/DatabaseStore.php#L261-L278