repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
list
docstring
stringlengths
3
47.2k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
vanilla/garden-db
src/Drivers/MySqlDb.php
MySqlDb.buildUpsert
protected function buildUpsert($table, array $row, $options = []) { // Build the initial insert statement first. unset($options[Db::OPTION_UPSERT]); $sql = $this->buildInsert($table, $row, $options); // Add the duplicate key stuff. $updates = []; foreach ($row as $key => $value) { $updates[] = $this->escape($key).' = values('.$this->escape($key).')'; } $sql .= "\non duplicate key update ".implode(', ', $updates); return $sql; }
php
protected function buildUpsert($table, array $row, $options = []) { // Build the initial insert statement first. unset($options[Db::OPTION_UPSERT]); $sql = $this->buildInsert($table, $row, $options); // Add the duplicate key stuff. $updates = []; foreach ($row as $key => $value) { $updates[] = $this->escape($key).' = values('.$this->escape($key).')'; } $sql .= "\non duplicate key update ".implode(', ', $updates); return $sql; }
[ "protected", "function", "buildUpsert", "(", "$", "table", ",", "array", "$", "row", ",", "$", "options", "=", "[", "]", ")", "{", "// Build the initial insert statement first.", "unset", "(", "$", "options", "[", "Db", "::", "OPTION_UPSERT", "]", ")", ";", ...
Build an upsert statement. An upsert statement is an insert on duplicate key statement in MySQL. @param string|Identifier $table The name of the table to update. @param array $row The row to insert or update. @param array $options An array of additional query options. @return string Returns the upsert statement as a string.
[ "Build", "an", "upsert", "statement", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Drivers/MySqlDb.php#L536-L549
train
vanilla/garden-db
src/Drivers/MySqlDb.php
MySqlDb.indexDefString
protected function indexDefString($table, array $def) { $indexName = $this->escape($this->buildIndexName($table, $def)); if (empty($def['columns'])) { throw new \DomainException("The `$table`.$indexName index has no columns.", 500); } switch (self::val('type', $def, Db::INDEX_IX)) { case Db::INDEX_IX: return "index $indexName ".$this->bracketList($def['columns'], '`'); case Db::INDEX_UNIQUE: return "unique $indexName ".$this->bracketList($def['columns'], '`'); case Db::INDEX_PK: return "primary key ".$this->bracketList($def['columns'], '`'); } return null; }
php
protected function indexDefString($table, array $def) { $indexName = $this->escape($this->buildIndexName($table, $def)); if (empty($def['columns'])) { throw new \DomainException("The `$table`.$indexName index has no columns.", 500); } switch (self::val('type', $def, Db::INDEX_IX)) { case Db::INDEX_IX: return "index $indexName ".$this->bracketList($def['columns'], '`'); case Db::INDEX_UNIQUE: return "unique $indexName ".$this->bracketList($def['columns'], '`'); case Db::INDEX_PK: return "primary key ".$this->bracketList($def['columns'], '`'); } return null; }
[ "protected", "function", "indexDefString", "(", "$", "table", ",", "array", "$", "def", ")", "{", "$", "indexName", "=", "$", "this", "->", "escape", "(", "$", "this", "->", "buildIndexName", "(", "$", "table", ",", "$", "def", ")", ")", ";", "if", ...
Return the SDL string that defines an index. @param string $table The name of the table that the index is on. @param array $def The index definition. This definition should have the following keys. columns : An array of columns in the index. type : One of "index", "unique", or "primary". @return null|string Returns the index string or null if the index is not correct.
[ "Return", "the", "SDL", "string", "that", "defines", "an", "index", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Drivers/MySqlDb.php#L734-L748
train
vanilla/garden-db
src/Drivers/MySqlDb.php
MySqlDb.forceType
protected function forceType($value, $type) { $type = strtolower($type); if ($type === 'null') { return null; } elseif ($type === 'boolean') { return filter_var($value, FILTER_VALIDATE_BOOLEAN); } elseif (in_array($type, ['int', 'integer', 'tinyint', 'smallint', 'mediumint', 'bigint', 'unsigned big int', 'int2', 'int8', 'boolean'])) { return filter_var($value, FILTER_VALIDATE_INT); } elseif (in_array($type, ['real', 'double', 'double precision', 'float', 'numeric', 'number', 'decimal(10,5)'])) { return filter_var($value, FILTER_VALIDATE_FLOAT); } else { return (string)$value; } }
php
protected function forceType($value, $type) { $type = strtolower($type); if ($type === 'null') { return null; } elseif ($type === 'boolean') { return filter_var($value, FILTER_VALIDATE_BOOLEAN); } elseif (in_array($type, ['int', 'integer', 'tinyint', 'smallint', 'mediumint', 'bigint', 'unsigned big int', 'int2', 'int8', 'boolean'])) { return filter_var($value, FILTER_VALIDATE_INT); } elseif (in_array($type, ['real', 'double', 'double precision', 'float', 'numeric', 'number', 'decimal(10,5)'])) { return filter_var($value, FILTER_VALIDATE_FLOAT); } else { return (string)$value; } }
[ "protected", "function", "forceType", "(", "$", "value", ",", "$", "type", ")", "{", "$", "type", "=", "strtolower", "(", "$", "type", ")", ";", "if", "(", "$", "type", "===", "'null'", ")", "{", "return", "null", ";", "}", "elseif", "(", "$", "t...
Force a value into the appropriate php type based on its SQL type. @param mixed $value The value to force. @param string $type The sqlite type name. @return mixed Returns $value cast to the appropriate type.
[ "Force", "a", "value", "into", "the", "appropriate", "php", "type", "based", "on", "its", "SQL", "type", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Drivers/MySqlDb.php#L817-L833
train
vanilla/garden-db
src/Drivers/MySqlDb.php
MySqlDb.argValue
private function argValue($value) { if (is_bool($value)) { return (int)$value; } elseif ($value instanceof \DateTimeInterface) { return $value->format(self::MYSQL_DATE_FORMAT); } else { return $value; } }
php
private function argValue($value) { if (is_bool($value)) { return (int)$value; } elseif ($value instanceof \DateTimeInterface) { return $value->format(self::MYSQL_DATE_FORMAT); } else { return $value; } }
[ "private", "function", "argValue", "(", "$", "value", ")", "{", "if", "(", "is_bool", "(", "$", "value", ")", ")", "{", "return", "(", "int", ")", "$", "value", ";", "}", "elseif", "(", "$", "value", "instanceof", "\\", "DateTimeInterface", ")", "{",...
Convert a value into something usable as a PDO parameter. @param mixed $value The value to convert. @return mixed Returns the converted value or the value itself if it's fine.
[ "Convert", "a", "value", "into", "something", "usable", "as", "a", "PDO", "parameter", "." ]
2634229fb7a161f649ad371e59a973ccbbe72247
https://github.com/vanilla/garden-db/blob/2634229fb7a161f649ad371e59a973ccbbe72247/src/Drivers/MySqlDb.php#L853-L861
train
helsingborg-stad/broken-link-detector
source/php/InternalDetector.php
InternalDetector.detectChangedPermalink
public function detectChangedPermalink() { // if permalink not changed, return, do nothing more if ($this->permalinkBefore === $this->permalinkAfter && !$this->trashed) { return false; } if ($this->trashed) { App::$externalDetector->lookForBrokenLinks('internal', str_replace('__trashed', '', $this->permalinkBefore)); return true; } // Replace occurances of the old permalink with the new permalink global $wpdb; $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_content = REPLACE(post_content, %s, %s) WHERE post_content LIKE %s", $this->permalinkBefore, $this->permalinkAfter, '%' . $wpdb->esc_like($this->permalinkBefore) . '%' ) ); $this->permalinksUpdated += $wpdb->rows_affected; if ($this->permalinksUpdated > 0) { add_notice(sprintf('%d links to this post was updated to use the new permalink.', $this->permalinksUpdated)); } return true; }
php
public function detectChangedPermalink() { // if permalink not changed, return, do nothing more if ($this->permalinkBefore === $this->permalinkAfter && !$this->trashed) { return false; } if ($this->trashed) { App::$externalDetector->lookForBrokenLinks('internal', str_replace('__trashed', '', $this->permalinkBefore)); return true; } // Replace occurances of the old permalink with the new permalink global $wpdb; $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_content = REPLACE(post_content, %s, %s) WHERE post_content LIKE %s", $this->permalinkBefore, $this->permalinkAfter, '%' . $wpdb->esc_like($this->permalinkBefore) . '%' ) ); $this->permalinksUpdated += $wpdb->rows_affected; if ($this->permalinksUpdated > 0) { add_notice(sprintf('%d links to this post was updated to use the new permalink.', $this->permalinksUpdated)); } return true; }
[ "public", "function", "detectChangedPermalink", "(", ")", "{", "// if permalink not changed, return, do nothing more", "if", "(", "$", "this", "->", "permalinkBefore", "===", "$", "this", "->", "permalinkAfter", "&&", "!", "$", "this", "->", "trashed", ")", "{", "...
Detect and repair @return void
[ "Detect", "and", "repair" ]
f7ddc4a7258235b67dbfabe994de7335e7bcb73b
https://github.com/helsingborg-stad/broken-link-detector/blob/f7ddc4a7258235b67dbfabe994de7335e7bcb73b/source/php/InternalDetector.php#L66-L99
train
Eden-PHP/Path
src/Index.php
Index.absolute
public function absolute($root = null) { //argument 1 must be a string or null Argument::i()->test(1, 'string', 'null'); //if path is a directory or file if (is_dir($this->data) || is_file($this->data)) { return $this; } //if root is null if (is_null($root)) { //assume the root is doc root $root = $_SERVER['DOCUMENT_ROOT']; } //get the absolute path $absolute = $this->format($this->format($root).$this->data); //if absolute is a directory or file if (is_dir($absolute) || is_file($absolute)) { $this->data = $absolute; return $this; } //if we are here then it means that no path was found so we should throw an exception Exception::i() ->setMessage(self::ERROR_FULL_PATH_NOT_FOUND) ->addVariable($this->data) ->addVariable($absolute) ->trigger(); }
php
public function absolute($root = null) { //argument 1 must be a string or null Argument::i()->test(1, 'string', 'null'); //if path is a directory or file if (is_dir($this->data) || is_file($this->data)) { return $this; } //if root is null if (is_null($root)) { //assume the root is doc root $root = $_SERVER['DOCUMENT_ROOT']; } //get the absolute path $absolute = $this->format($this->format($root).$this->data); //if absolute is a directory or file if (is_dir($absolute) || is_file($absolute)) { $this->data = $absolute; return $this; } //if we are here then it means that no path was found so we should throw an exception Exception::i() ->setMessage(self::ERROR_FULL_PATH_NOT_FOUND) ->addVariable($this->data) ->addVariable($absolute) ->trigger(); }
[ "public", "function", "absolute", "(", "$", "root", "=", "null", ")", "{", "//argument 1 must be a string or null", "Argument", "::", "i", "(", ")", "->", "test", "(", "1", ",", "'string'", ",", "'null'", ")", ";", "//if path is a directory or file", "if", "("...
Attempts to get the full absolute path as described on the server. The path given must exist. @param string|null $root The root path @return Eden\Path\Index
[ "Attempts", "to", "get", "the", "full", "absolute", "path", "as", "described", "on", "the", "server", ".", "The", "path", "given", "must", "exist", "." ]
d2b2c8ac8722fac6ccc1f01d8b14365e8a7ad9b6
https://github.com/Eden-PHP/Path/blob/d2b2c8ac8722fac6ccc1f01d8b14365e8a7ad9b6/src/Index.php#L61-L92
train
Eden-PHP/Path
src/Index.php
Index.append
public function append($path) { //argument 1 must be a string $argument = Argument::i()->test(1, 'string'); //each argument will be a path $paths = func_get_args(); //for each path foreach ($paths as $i => $path) { //check for type errors $argument->test($i + 1, $path, 'string'); //add to path $this->data .= $this->format($path); } return $this; }
php
public function append($path) { //argument 1 must be a string $argument = Argument::i()->test(1, 'string'); //each argument will be a path $paths = func_get_args(); //for each path foreach ($paths as $i => $path) { //check for type errors $argument->test($i + 1, $path, 'string'); //add to path $this->data .= $this->format($path); } return $this; }
[ "public", "function", "append", "(", "$", "path", ")", "{", "//argument 1 must be a string", "$", "argument", "=", "Argument", "::", "i", "(", ")", "->", "test", "(", "1", ",", "'string'", ")", ";", "//each argument will be a path", "$", "paths", "=", "func_...
Adds a path to the existing one @param *string $path The extra path to append @return Eden\Path\Index
[ "Adds", "a", "path", "to", "the", "existing", "one" ]
d2b2c8ac8722fac6ccc1f01d8b14365e8a7ad9b6
https://github.com/Eden-PHP/Path/blob/d2b2c8ac8722fac6ccc1f01d8b14365e8a7ad9b6/src/Index.php#L101-L118
train
Eden-PHP/Path
src/Index.php
Index.prepend
public function prepend($path) { //argument 1 must be a string $error = Argument::i()->test(1, 'string'); //each argument will be a path $paths = func_get_args(); //for each path foreach ($paths as $i => $path) { //check for type errors $error->test($i + 1, $path, 'string'); //add to path $this->data = $this->format($path).$this->data; } return $this; }
php
public function prepend($path) { //argument 1 must be a string $error = Argument::i()->test(1, 'string'); //each argument will be a path $paths = func_get_args(); //for each path foreach ($paths as $i => $path) { //check for type errors $error->test($i + 1, $path, 'string'); //add to path $this->data = $this->format($path).$this->data; } return $this; }
[ "public", "function", "prepend", "(", "$", "path", ")", "{", "//argument 1 must be a string", "$", "error", "=", "Argument", "::", "i", "(", ")", "->", "test", "(", "1", ",", "'string'", ")", ";", "//each argument will be a path", "$", "paths", "=", "func_ge...
Adds a path before the existing one @param *string $path The path to prepend @return Eden\Path\Index
[ "Adds", "a", "path", "before", "the", "existing", "one" ]
d2b2c8ac8722fac6ccc1f01d8b14365e8a7ad9b6
https://github.com/Eden-PHP/Path/blob/d2b2c8ac8722fac6ccc1f01d8b14365e8a7ad9b6/src/Index.php#L220-L237
train
Eden-PHP/Path
src/Index.php
Index.pop
public function pop() { //get the path array $pathArray = $this->getArray(); //remove the last $path = array_pop($pathArray); //set path $this->data = implode('/', $pathArray); return $path; }
php
public function pop() { //get the path array $pathArray = $this->getArray(); //remove the last $path = array_pop($pathArray); //set path $this->data = implode('/', $pathArray); return $path; }
[ "public", "function", "pop", "(", ")", "{", "//get the path array", "$", "pathArray", "=", "$", "this", "->", "getArray", "(", ")", ";", "//remove the last", "$", "path", "=", "array_pop", "(", "$", "pathArray", ")", ";", "//set path", "$", "this", "->", ...
Remove the last path @return Eden\Path\Index
[ "Remove", "the", "last", "path" ]
d2b2c8ac8722fac6ccc1f01d8b14365e8a7ad9b6
https://github.com/Eden-PHP/Path/blob/d2b2c8ac8722fac6ccc1f01d8b14365e8a7ad9b6/src/Index.php#L244-L256
train
Eden-PHP/Path
src/Index.php
Index.replace
public function replace($path) { //argument 1 must be a string Argument::i()->test(1, 'string'); //get the path array $pathArray = $this->getArray(); //pop out the last array_pop($pathArray); //push in the new $pathArray[] = $path; //assign back to path $this->data = implode('/', $pathArray); return $this; }
php
public function replace($path) { //argument 1 must be a string Argument::i()->test(1, 'string'); //get the path array $pathArray = $this->getArray(); //pop out the last array_pop($pathArray); //push in the new $pathArray[] = $path; //assign back to path $this->data = implode('/', $pathArray); return $this; }
[ "public", "function", "replace", "(", "$", "path", ")", "{", "//argument 1 must be a string", "Argument", "::", "i", "(", ")", "->", "test", "(", "1", ",", "'string'", ")", ";", "//get the path array", "$", "pathArray", "=", "$", "this", "->", "getArray", ...
Replaces the last path with this one @param *string $path replaces the last path with this @return Eden\Path\Index
[ "Replaces", "the", "last", "path", "with", "this", "one" ]
d2b2c8ac8722fac6ccc1f01d8b14365e8a7ad9b6
https://github.com/Eden-PHP/Path/blob/d2b2c8ac8722fac6ccc1f01d8b14365e8a7ad9b6/src/Index.php#L265-L283
train
Eden-PHP/Path
src/Index.php
Index.format
protected function format($path) { //replace back slash with forward $path = str_replace('\\', '/', $path); //replace double forward slash with 1 forward slash $path = str_replace('//', '/', $path); //if there is a last forward slash if (substr($path, -1, 1) == '/') { //remove it $path = substr($path, 0, -1); } //if the path does not start with a foward slash //and the path does not have a colon //(this is a test for windows) if (substr($path, 0, 1) != '/' && !preg_match("/^[A-Za-z]+\:/", $path)) { //it's safe to add a slash $path = '/'.$path; } return $path; }
php
protected function format($path) { //replace back slash with forward $path = str_replace('\\', '/', $path); //replace double forward slash with 1 forward slash $path = str_replace('//', '/', $path); //if there is a last forward slash if (substr($path, -1, 1) == '/') { //remove it $path = substr($path, 0, -1); } //if the path does not start with a foward slash //and the path does not have a colon //(this is a test for windows) if (substr($path, 0, 1) != '/' && !preg_match("/^[A-Za-z]+\:/", $path)) { //it's safe to add a slash $path = '/'.$path; } return $path; }
[ "protected", "function", "format", "(", "$", "path", ")", "{", "//replace back slash with forward", "$", "path", "=", "str_replace", "(", "'\\\\'", ",", "'/'", ",", "$", "path", ")", ";", "//replace double forward slash with 1 forward slash", "$", "path", "=", "st...
Formats the path 1. Must start with forward slash 2. Must not end with forward slash 3. Must not have double forward slashes @param *string $path The path to format @return string
[ "Formats", "the", "path", "1", ".", "Must", "start", "with", "forward", "slash", "2", ".", "Must", "not", "end", "with", "forward", "slash", "3", ".", "Must", "not", "have", "double", "forward", "slashes" ]
d2b2c8ac8722fac6ccc1f01d8b14365e8a7ad9b6
https://github.com/Eden-PHP/Path/blob/d2b2c8ac8722fac6ccc1f01d8b14365e8a7ad9b6/src/Index.php#L295-L318
train
unikent/lib-php-readinglists
src/API.php
API.set_campus
public function set_campus($campus) { $campus = !is_array($campus) ? array($campus) : $campus; $this->_campus = array(); foreach ($campus as $c) { $c = strtolower($c); if (!in_array($c, array('canterbury', 'medway'))) { throw new \Exception("Invalid campus: '{$campus}'."); } $this->_campus[] = $c; } }
php
public function set_campus($campus) { $campus = !is_array($campus) ? array($campus) : $campus; $this->_campus = array(); foreach ($campus as $c) { $c = strtolower($c); if (!in_array($c, array('canterbury', 'medway'))) { throw new \Exception("Invalid campus: '{$campus}'."); } $this->_campus[] = $c; } }
[ "public", "function", "set_campus", "(", "$", "campus", ")", "{", "$", "campus", "=", "!", "is_array", "(", "$", "campus", ")", "?", "array", "(", "$", "campus", ")", ":", "$", "campus", ";", "$", "this", "->", "_campus", "=", "array", "(", ")", ...
Set the campus we want lists from. Defaults to all lists. @param string $campus Canterbury or Medway, or an array of both.
[ "Set", "the", "campus", "we", "want", "lists", "from", ".", "Defaults", "to", "all", "lists", "." ]
e14bfaee0ec52319c3f95a0599d01222948b6d76
https://github.com/unikent/lib-php-readinglists/blob/e14bfaee0ec52319c3f95a0599d01222948b6d76/src/API.php#L85-L97
train
unikent/lib-php-readinglists
src/API.php
API.get_item
public function get_item($url) { $raw = $this->curl($url . '.json'); $json = json_decode($raw, true); if (!$json) { return null; } return new Item($this, $url, $json); }
php
public function get_item($url) { $raw = $this->curl($url . '.json'); $json = json_decode($raw, true); if (!$json) { return null; } return new Item($this, $url, $json); }
[ "public", "function", "get_item", "(", "$", "url", ")", "{", "$", "raw", "=", "$", "this", "->", "curl", "(", "$", "url", ".", "'.json'", ")", ";", "$", "json", "=", "json_decode", "(", "$", "raw", ",", "true", ")", ";", "if", "(", "!", "$", ...
Returns a list item, given a URL.
[ "Returns", "a", "list", "item", "given", "a", "URL", "." ]
e14bfaee0ec52319c3f95a0599d01222948b6d76
https://github.com/unikent/lib-php-readinglists/blob/e14bfaee0ec52319c3f95a0599d01222948b6d76/src/API.php#L165-L173
train
unikent/lib-php-readinglists
src/API.php
API.get_list
public function get_list($id, $campus = 'current') { if ($campus == 'current') { $campus = $this->_campus; } if (is_array($campus)) { throw new \Exception("Campus cannot be an array!"); } $url = self::CANTERBURY_URL; if ($campus == 'medway') { $url = self::MEDWAY_URL; } $raw = $this->curl($url . '/sections/' . $id . '.json'); $parser = new Parser($this, $url, $raw); return $parser->get_list($id); }
php
public function get_list($id, $campus = 'current') { if ($campus == 'current') { $campus = $this->_campus; } if (is_array($campus)) { throw new \Exception("Campus cannot be an array!"); } $url = self::CANTERBURY_URL; if ($campus == 'medway') { $url = self::MEDWAY_URL; } $raw = $this->curl($url . '/sections/' . $id . '.json'); $parser = new Parser($this, $url, $raw); return $parser->get_list($id); }
[ "public", "function", "get_list", "(", "$", "id", ",", "$", "campus", "=", "'current'", ")", "{", "if", "(", "$", "campus", "==", "'current'", ")", "{", "$", "campus", "=", "$", "this", "->", "_campus", ";", "}", "if", "(", "is_array", "(", "$", ...
Returns a list, given an ID. @param string $id List ID. @param string $campus Campus.
[ "Returns", "a", "list", "given", "an", "ID", "." ]
e14bfaee0ec52319c3f95a0599d01222948b6d76
https://github.com/unikent/lib-php-readinglists/blob/e14bfaee0ec52319c3f95a0599d01222948b6d76/src/API.php#L181-L198
train
nails/module-auth
src/Api/Controller/AccessToken.php
AccessToken.postIndex
public function postIndex() { $oInput = Factory::service('Input'); $oHttpCodes = Factory::service('HttpCodes'); $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $oAccessTokenModel = Factory::model('UserAccessToken', 'nails/module-auth'); $sIdentifier = $oInput->post('identifier'); $sPassword = $oInput->post('password'); $sScope = $oInput->post('scope'); $sLabel = $oInput->post('label'); $bIsValid = $oAuthModel->verifyCredentials($sIdentifier, $sPassword); if (!$bIsValid) { throw new ApiException( 'Invalid login credentials', $oHttpCodes::STATUS_UNAUTHORIZED ); } /** * User credentials are valid, but a few other tests are still required: * - User is not suspended * - Password is not temporary * - Password is not expired * - @todo: handle 2FA, perhaps? */ $oUserModel = Factory::model('User', 'nails/module-auth'); $oUserPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); $oUser = $oUserModel->getByIdentifier($sIdentifier); $bIsSuspended = $oUser->is_suspended; $bPwIsTemp = $oUser->temp_pw; $bPwIsExpired = $oUserPasswordModel->isExpired($oUser->id); if ($bIsSuspended) { throw new ApiException( 'User account is suspended', $oHttpCodes::STATUS_UNAUTHORIZED ); } elseif ($bPwIsTemp) { throw new ApiException( 'Password is temporary', $oHttpCodes::STATUS_UNAUTHORIZED ); } elseif ($bPwIsExpired) { throw new ApiException( 'Password has expired', $oHttpCodes::STATUS_UNAUTHORIZED ); } $oToken = $oAccessTokenModel->create([ 'user_id' => $oUser->id, 'label' => $sLabel, 'scope' => $sScope, ]); if (!$oToken) { throw new ApiException( 'Failed to generate access token. ' . $oAccessTokenModel->lastError(), $oHttpCodes::STATUS_INTERNAL_SERVER_ERROR ); } return Factory::factory('ApiResponse', 'nails/module-api') ->setData([ 'token' => $oToken->token, 'expires' => $oToken->expires, ]); }
php
public function postIndex() { $oInput = Factory::service('Input'); $oHttpCodes = Factory::service('HttpCodes'); $oAuthModel = Factory::model('Auth', 'nails/module-auth'); $oAccessTokenModel = Factory::model('UserAccessToken', 'nails/module-auth'); $sIdentifier = $oInput->post('identifier'); $sPassword = $oInput->post('password'); $sScope = $oInput->post('scope'); $sLabel = $oInput->post('label'); $bIsValid = $oAuthModel->verifyCredentials($sIdentifier, $sPassword); if (!$bIsValid) { throw new ApiException( 'Invalid login credentials', $oHttpCodes::STATUS_UNAUTHORIZED ); } /** * User credentials are valid, but a few other tests are still required: * - User is not suspended * - Password is not temporary * - Password is not expired * - @todo: handle 2FA, perhaps? */ $oUserModel = Factory::model('User', 'nails/module-auth'); $oUserPasswordModel = Factory::model('UserPassword', 'nails/module-auth'); $oUser = $oUserModel->getByIdentifier($sIdentifier); $bIsSuspended = $oUser->is_suspended; $bPwIsTemp = $oUser->temp_pw; $bPwIsExpired = $oUserPasswordModel->isExpired($oUser->id); if ($bIsSuspended) { throw new ApiException( 'User account is suspended', $oHttpCodes::STATUS_UNAUTHORIZED ); } elseif ($bPwIsTemp) { throw new ApiException( 'Password is temporary', $oHttpCodes::STATUS_UNAUTHORIZED ); } elseif ($bPwIsExpired) { throw new ApiException( 'Password has expired', $oHttpCodes::STATUS_UNAUTHORIZED ); } $oToken = $oAccessTokenModel->create([ 'user_id' => $oUser->id, 'label' => $sLabel, 'scope' => $sScope, ]); if (!$oToken) { throw new ApiException( 'Failed to generate access token. ' . $oAccessTokenModel->lastError(), $oHttpCodes::STATUS_INTERNAL_SERVER_ERROR ); } return Factory::factory('ApiResponse', 'nails/module-api') ->setData([ 'token' => $oToken->token, 'expires' => $oToken->expires, ]); }
[ "public", "function", "postIndex", "(", ")", "{", "$", "oInput", "=", "Factory", "::", "service", "(", "'Input'", ")", ";", "$", "oHttpCodes", "=", "Factory", "::", "service", "(", "'HttpCodes'", ")", ";", "$", "oAuthModel", "=", "Factory", "::", "model"...
Retrieves an access token for a user @return ApiResponse
[ "Retrieves", "an", "access", "token", "for", "a", "user" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Api/Controller/AccessToken.php#L25-L94
train
nails/module-auth
src/Api/Controller/AccessToken.php
AccessToken.postRevoke
public function postRevoke() { $oHttpCodes = Factory::service('HttpCodes'); $oAccessTokenModel = Factory::model('UserAccessToken', 'nails/module-auth'); if (!isLoggedIn()) { throw new ApiException( 'You must be logged in', $oHttpCodes::STATUS_UNAUTHORIZED ); } $oInput = Factory::service('Input'); $sAccessToken = $oInput->post('access_token'); if (empty($sAccessToken)) { throw new ApiException( 'An access token to revoke must be provided', $oHttpCodes::STATUS_BAD_REQUEST ); } if (!$oAccessTokenModel->revoke(activeUser('id'), $sAccessToken)) { throw new ApiException( 'Failed to revoke access token. ' . $oAccessTokenModel->lastError(), $oHttpCodes::STATUS_INTERNAL_SERVER_ERROR ); } return Factory::factory('ApiResponse', 'nails/module-api'); }
php
public function postRevoke() { $oHttpCodes = Factory::service('HttpCodes'); $oAccessTokenModel = Factory::model('UserAccessToken', 'nails/module-auth'); if (!isLoggedIn()) { throw new ApiException( 'You must be logged in', $oHttpCodes::STATUS_UNAUTHORIZED ); } $oInput = Factory::service('Input'); $sAccessToken = $oInput->post('access_token'); if (empty($sAccessToken)) { throw new ApiException( 'An access token to revoke must be provided', $oHttpCodes::STATUS_BAD_REQUEST ); } if (!$oAccessTokenModel->revoke(activeUser('id'), $sAccessToken)) { throw new ApiException( 'Failed to revoke access token. ' . $oAccessTokenModel->lastError(), $oHttpCodes::STATUS_INTERNAL_SERVER_ERROR ); } return Factory::factory('ApiResponse', 'nails/module-api'); }
[ "public", "function", "postRevoke", "(", ")", "{", "$", "oHttpCodes", "=", "Factory", "::", "service", "(", "'HttpCodes'", ")", ";", "$", "oAccessTokenModel", "=", "Factory", "::", "model", "(", "'UserAccessToken'", ",", "'nails/module-auth'", ")", ";", "if", ...
Revoke an access token for the authenticated user @return ApiResponse
[ "Revoke", "an", "access", "token", "for", "the", "authenticated", "user" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Api/Controller/AccessToken.php#L102-L132
train
nails/module-auth
src/Model/User.php
User.init
public function init() { $oInput = Factory::service('Input'); $iTestingAsUser = $oInput->header(Testing::TEST_HEADER_USER_NAME); if (Environment::not(Environment::ENV_PROD) && $iTestingAsUser) { $oUser = $this->getById($iTestingAsUser); if (empty($oUser)) { set_status_header(500); ErrorHandler::halt('Not a valid user ID'); } $this->setLoginData($oUser->id); } else { // Refresh user's session $this->refreshSession(); // If no user is logged in, see if there's a remembered user to be logged in if (!$this->isLoggedIn()) { $this->loginRememberedUser(); } } }
php
public function init() { $oInput = Factory::service('Input'); $iTestingAsUser = $oInput->header(Testing::TEST_HEADER_USER_NAME); if (Environment::not(Environment::ENV_PROD) && $iTestingAsUser) { $oUser = $this->getById($iTestingAsUser); if (empty($oUser)) { set_status_header(500); ErrorHandler::halt('Not a valid user ID'); } $this->setLoginData($oUser->id); } else { // Refresh user's session $this->refreshSession(); // If no user is logged in, see if there's a remembered user to be logged in if (!$this->isLoggedIn()) { $this->loginRememberedUser(); } } }
[ "public", "function", "init", "(", ")", "{", "$", "oInput", "=", "Factory", "::", "service", "(", "'Input'", ")", ";", "$", "iTestingAsUser", "=", "$", "oInput", "->", "header", "(", "Testing", "::", "TEST_HEADER_USER_NAME", ")", ";", "if", "(", "Environ...
Initialise the generic user model @return void
[ "Initialise", "the", "generic", "user", "model" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L93-L117
train
nails/module-auth
src/Model/User.php
User.loginRememberedUser
protected function loginRememberedUser() { // Is remember me functionality enabled? $oConfig = Factory::service('Config'); $oConfig->load('auth/auth'); if (!$oConfig->item('authEnableRememberMe')) { return false; } // -------------------------------------------------------------------------- // Get the credentials from the cookie set earlier $remember = get_cookie($this->sRememberCookie); if ($remember) { $remember = explode('|', $remember); $email = isset($remember[0]) ? $remember[0] : null; $code = isset($remember[1]) ? $remember[1] : null; if ($email && $code) { // Look up the user so we can cross-check the codes $user = $this->getByEmail($email); if ($user && $code === $user->remember_code) { // User was validated, log them in! $this->setLoginData($user->id); $this->me = $user->id; } } } return true; }
php
protected function loginRememberedUser() { // Is remember me functionality enabled? $oConfig = Factory::service('Config'); $oConfig->load('auth/auth'); if (!$oConfig->item('authEnableRememberMe')) { return false; } // -------------------------------------------------------------------------- // Get the credentials from the cookie set earlier $remember = get_cookie($this->sRememberCookie); if ($remember) { $remember = explode('|', $remember); $email = isset($remember[0]) ? $remember[0] : null; $code = isset($remember[1]) ? $remember[1] : null; if ($email && $code) { // Look up the user so we can cross-check the codes $user = $this->getByEmail($email); if ($user && $code === $user->remember_code) { // User was validated, log them in! $this->setLoginData($user->id); $this->me = $user->id; } } } return true; }
[ "protected", "function", "loginRememberedUser", "(", ")", "{", "// Is remember me functionality enabled?", "$", "oConfig", "=", "Factory", "::", "service", "(", "'Config'", ")", ";", "$", "oConfig", "->", "load", "(", "'auth/auth'", ")", ";", "if", "(", "!", ...
Log in a previously logged in user @return boolean
[ "Log", "in", "a", "previously", "logged", "in", "user" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L126-L161
train
nails/module-auth
src/Model/User.php
User.activeUser
public function activeUser($sKeys = '', $sDelimiter = ' ') { // Only look for a value if we're logged in if (!$this->isLoggedIn()) { return false; } // -------------------------------------------------------------------------- // If $sKeys is false just return the user object in its entirety if (empty($sKeys)) { return $this->activeUser; } // -------------------------------------------------------------------------- // If only one key is being requested then don't do anything fancy if (strpos($sKeys, ',') === false) { $val = isset($this->activeUser->{trim($sKeys)}) ? $this->activeUser->{trim($sKeys)} : null; } else { // More than one key $aKeys = explode(',', $sKeys); $aKeys = array_filter($aKeys); $aOut = []; foreach ($aKeys as $sKey) { // If something is found, use that. if (isset($this->activeUser->{trim($sKey)})) { $aOut[] = $this->activeUser->{trim($sKey)}; } } // If nothing was found, just return null if (empty($aOut)) { $val = null; } else { $val = implode($sDelimiter, $aOut); } } return $val; }
php
public function activeUser($sKeys = '', $sDelimiter = ' ') { // Only look for a value if we're logged in if (!$this->isLoggedIn()) { return false; } // -------------------------------------------------------------------------- // If $sKeys is false just return the user object in its entirety if (empty($sKeys)) { return $this->activeUser; } // -------------------------------------------------------------------------- // If only one key is being requested then don't do anything fancy if (strpos($sKeys, ',') === false) { $val = isset($this->activeUser->{trim($sKeys)}) ? $this->activeUser->{trim($sKeys)} : null; } else { // More than one key $aKeys = explode(',', $sKeys); $aKeys = array_filter($aKeys); $aOut = []; foreach ($aKeys as $sKey) { // If something is found, use that. if (isset($this->activeUser->{trim($sKey)})) { $aOut[] = $this->activeUser->{trim($sKey)}; } } // If nothing was found, just return null if (empty($aOut)) { $val = null; } else { $val = implode($sDelimiter, $aOut); } } return $val; }
[ "public", "function", "activeUser", "(", "$", "sKeys", "=", "''", ",", "$", "sDelimiter", "=", "' '", ")", "{", "// Only look for a value if we're logged in", "if", "(", "!", "$", "this", "->", "isLoggedIn", "(", ")", ")", "{", "return", "false", ";", "}"...
Fetches a value from the active user's session data @param string $sKeys The key to look up in activeUser @param string $sDelimiter If multiple fields are requested they'll be joined by this string @return mixed
[ "Fetches", "a", "value", "from", "the", "active", "user", "s", "session", "data" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L173-L218
train
nails/module-auth
src/Model/User.php
User.setActiveUser
public function setActiveUser($oUser) { $this->activeUser = $oUser; $oDateTimeService = Factory::service('DateTime'); // Set the user's date/time formats $sFormatDate = $this->activeUser('pref_date_format'); $sFormatDate = $sFormatDate ? $sFormatDate : $oDateTimeService->getDateFormatDefaultSlug(); $sFormatTime = $this->activeUser('pref_time_format'); $sFormatTime = $sFormatTime ? $sFormatTime : $oDateTimeService->getTimeFormatDefaultSlug(); $oDateTimeService->setFormats($sFormatDate, $sFormatTime); }
php
public function setActiveUser($oUser) { $this->activeUser = $oUser; $oDateTimeService = Factory::service('DateTime'); // Set the user's date/time formats $sFormatDate = $this->activeUser('pref_date_format'); $sFormatDate = $sFormatDate ? $sFormatDate : $oDateTimeService->getDateFormatDefaultSlug(); $sFormatTime = $this->activeUser('pref_time_format'); $sFormatTime = $sFormatTime ? $sFormatTime : $oDateTimeService->getTimeFormatDefaultSlug(); $oDateTimeService->setFormats($sFormatDate, $sFormatTime); }
[ "public", "function", "setActiveUser", "(", "$", "oUser", ")", "{", "$", "this", "->", "activeUser", "=", "$", "oUser", ";", "$", "oDateTimeService", "=", "Factory", "::", "service", "(", "'DateTime'", ")", ";", "// Set the user's date/time formats", "$", "sF...
Set the active user @param \stdClass $oUser The user object to set
[ "Set", "the", "active", "user" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L227-L240
train
nails/module-auth
src/Model/User.php
User.setLoginData
public function setLoginData($mIdEmail, $bSetSessionData = true) { // Valid user? if (is_numeric($mIdEmail)) { $oUser = $this->getById($mIdEmail); $sError = 'Invalid User ID.'; } elseif (is_string($mIdEmail)) { Factory::helper('email'); if (valid_email($mIdEmail)) { $oUser = $this->getByEmail($mIdEmail); $sError = 'Invalid User email.'; } else { $this->setError('Invalid User email.'); return false; } } else { $this->setError('Invalid user ID or email.'); return false; } // -------------------------------------------------------------------------- // Test user if (!$oUser) { $this->setError($sError); return false; } elseif ($oUser->is_suspended) { $this->setError('User is suspended.'); return false; } else { // Set the flag $this->bIsLoggedIn = true; // Set session variables if ($bSetSessionData) { $oSession = Factory::service('Session', 'nails/module-auth'); $oSession->setUserData([ 'id' => $oUser->id, 'email' => $oUser->email, 'group_id' => $oUser->group_id, ]); } // Set the active user $this->setActiveUser($oUser); return true; } }
php
public function setLoginData($mIdEmail, $bSetSessionData = true) { // Valid user? if (is_numeric($mIdEmail)) { $oUser = $this->getById($mIdEmail); $sError = 'Invalid User ID.'; } elseif (is_string($mIdEmail)) { Factory::helper('email'); if (valid_email($mIdEmail)) { $oUser = $this->getByEmail($mIdEmail); $sError = 'Invalid User email.'; } else { $this->setError('Invalid User email.'); return false; } } else { $this->setError('Invalid user ID or email.'); return false; } // -------------------------------------------------------------------------- // Test user if (!$oUser) { $this->setError($sError); return false; } elseif ($oUser->is_suspended) { $this->setError('User is suspended.'); return false; } else { // Set the flag $this->bIsLoggedIn = true; // Set session variables if ($bSetSessionData) { $oSession = Factory::service('Session', 'nails/module-auth'); $oSession->setUserData([ 'id' => $oUser->id, 'email' => $oUser->email, 'group_id' => $oUser->group_id, ]); } // Set the active user $this->setActiveUser($oUser); return true; } }
[ "public", "function", "setLoginData", "(", "$", "mIdEmail", ",", "$", "bSetSessionData", "=", "true", ")", "{", "// Valid user?", "if", "(", "is_numeric", "(", "$", "mIdEmail", ")", ")", "{", "$", "oUser", "=", "$", "this", "->", "getById", "(", "$", ...
Set the user's login data @param mixed $mIdEmail The user's ID or email address @param boolean $bSetSessionData Whether to set the session data or not @return boolean
[ "Set", "the", "user", "s", "login", "data" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L264-L322
train
nails/module-auth
src/Model/User.php
User.clearLoginData
public function clearLoginData() { // Clear the session $oSession = Factory::service('Session', 'nails/module-auth'); $oSession->unsetUserData('id'); $oSession->unsetUserData('email'); $oSession->unsetUserData('group_id'); // Set the flag $this->bIsLoggedIn = false; // Reset the activeUser $this->clearActiveUser(); // Remove any remember me cookie $this->clearRememberCookie(); }
php
public function clearLoginData() { // Clear the session $oSession = Factory::service('Session', 'nails/module-auth'); $oSession->unsetUserData('id'); $oSession->unsetUserData('email'); $oSession->unsetUserData('group_id'); // Set the flag $this->bIsLoggedIn = false; // Reset the activeUser $this->clearActiveUser(); // Remove any remember me cookie $this->clearRememberCookie(); }
[ "public", "function", "clearLoginData", "(", ")", "{", "// Clear the session", "$", "oSession", "=", "Factory", "::", "service", "(", "'Session'", ",", "'nails/module-auth'", ")", ";", "$", "oSession", "->", "unsetUserData", "(", "'id'", ")", ";", "$", "oSess...
Clears the login data for a user @return void
[ "Clears", "the", "login", "data", "for", "a", "user" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L331-L347
train
nails/module-auth
src/Model/User.php
User.bIsRemembered
public function bIsRemembered() { // Deja vu? if (!is_null($this->bIsRemembered)) { return $this->bIsRemembered; } // -------------------------------------------------------------------------- /** * Look for the remember me cookie and explode it, if we're landed with a 2 * part array then it's likely this is a valid cookie - however, this test * is, obviously, not gonna detect a spoof. */ $cookie = get_cookie($this->sRememberCookie); $cookie = explode('|', $cookie); $this->bIsRemembered = count($cookie) == 2 ? true : false; return $this->bIsRemembered; }
php
public function bIsRemembered() { // Deja vu? if (!is_null($this->bIsRemembered)) { return $this->bIsRemembered; } // -------------------------------------------------------------------------- /** * Look for the remember me cookie and explode it, if we're landed with a 2 * part array then it's likely this is a valid cookie - however, this test * is, obviously, not gonna detect a spoof. */ $cookie = get_cookie($this->sRememberCookie); $cookie = explode('|', $cookie); $this->bIsRemembered = count($cookie) == 2 ? true : false; return $this->bIsRemembered; }
[ "public", "function", "bIsRemembered", "(", ")", "{", "// Deja vu?", "if", "(", "!", "is_null", "(", "$", "this", "->", "bIsRemembered", ")", ")", "{", "return", "$", "this", "->", "bIsRemembered", ";", "}", "// ---------------------------------------------------...
Determines whether the active user is to be remembered @return bool
[ "Determines", "whether", "the", "active", "user", "is", "to", "be", "remembered" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L368-L389
train
nails/module-auth
src/Model/User.php
User.setAdminRecoveryData
public function setAdminRecoveryData($loggingInAs, $returnTo = '') { $oSession = Factory::service('Session', 'nails/module-auth'); $oInput = Factory::service('Input'); // Look for existing Recovery Data $existingRecoveryData = $oSession->getUserData($this->sAdminRecoveryField); if (empty($existingRecoveryData)) { $existingRecoveryData = []; } // Prepare the new element $adminRecoveryData = new \stdClass(); $adminRecoveryData->oldUserId = activeUser('id'); $adminRecoveryData->newUserId = $loggingInAs; $adminRecoveryData->hash = md5(activeUser('password')); $adminRecoveryData->name = activeUser('first_name,last_name'); $adminRecoveryData->email = activeUser('email'); $adminRecoveryData->returnTo = empty($returnTo) ? $oInput->server('REQUEST_URI') : $returnTo; $adminRecoveryData->loginUrl = 'auth/override/login_as/'; $adminRecoveryData->loginUrl .= md5($adminRecoveryData->oldUserId) . '/' . $adminRecoveryData->hash; $adminRecoveryData->loginUrl .= '?returningAdmin=1'; $adminRecoveryData->loginUrl = site_url($adminRecoveryData->loginUrl); // Put the new session onto the stack and save to the session $existingRecoveryData[] = $adminRecoveryData; $oSession->setUserData($this->sAdminRecoveryField, $existingRecoveryData); }
php
public function setAdminRecoveryData($loggingInAs, $returnTo = '') { $oSession = Factory::service('Session', 'nails/module-auth'); $oInput = Factory::service('Input'); // Look for existing Recovery Data $existingRecoveryData = $oSession->getUserData($this->sAdminRecoveryField); if (empty($existingRecoveryData)) { $existingRecoveryData = []; } // Prepare the new element $adminRecoveryData = new \stdClass(); $adminRecoveryData->oldUserId = activeUser('id'); $adminRecoveryData->newUserId = $loggingInAs; $adminRecoveryData->hash = md5(activeUser('password')); $adminRecoveryData->name = activeUser('first_name,last_name'); $adminRecoveryData->email = activeUser('email'); $adminRecoveryData->returnTo = empty($returnTo) ? $oInput->server('REQUEST_URI') : $returnTo; $adminRecoveryData->loginUrl = 'auth/override/login_as/'; $adminRecoveryData->loginUrl .= md5($adminRecoveryData->oldUserId) . '/' . $adminRecoveryData->hash; $adminRecoveryData->loginUrl .= '?returningAdmin=1'; $adminRecoveryData->loginUrl = site_url($adminRecoveryData->loginUrl); // Put the new session onto the stack and save to the session $existingRecoveryData[] = $adminRecoveryData; $oSession->setUserData($this->sAdminRecoveryField, $existingRecoveryData); }
[ "public", "function", "setAdminRecoveryData", "(", "$", "loggingInAs", ",", "$", "returnTo", "=", "''", ")", "{", "$", "oSession", "=", "Factory", "::", "service", "(", "'Session'", ",", "'nails/module-auth'", ")", ";", "$", "oInput", "=", "Factory", "::", ...
Adds to the admin recovery array, allowing suers to login as other users multiple times, and come back @param integer $loggingInAs The ID of the user who is being imitated @param string $returnTo Where to redirect the user when they log back in
[ "Adds", "to", "the", "admin", "recovery", "array", "allowing", "suers", "to", "login", "as", "other", "users", "multiple", "times", "and", "come", "back" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L428-L458
train
nails/module-auth
src/Model/User.php
User.getAdminRecoveryData
public function getAdminRecoveryData() { $oSession = Factory::service('Session', 'nails/module-auth'); $existingRecoveryData = $oSession->getUserData($this->sAdminRecoveryField); if (empty($existingRecoveryData)) { return []; } else { return end($existingRecoveryData); } }
php
public function getAdminRecoveryData() { $oSession = Factory::service('Session', 'nails/module-auth'); $existingRecoveryData = $oSession->getUserData($this->sAdminRecoveryField); if (empty($existingRecoveryData)) { return []; } else { return end($existingRecoveryData); } }
[ "public", "function", "getAdminRecoveryData", "(", ")", "{", "$", "oSession", "=", "Factory", "::", "service", "(", "'Session'", ",", "'nails/module-auth'", ")", ";", "$", "existingRecoveryData", "=", "$", "oSession", "->", "getUserData", "(", "$", "this", "->...
Returns the recovery data at the bottom of the stack, i.e the most recently added @return array|\stdClass
[ "Returns", "the", "recovery", "data", "at", "the", "bottom", "of", "the", "stack", "i", ".", "e", "the", "most", "recently", "added" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L467-L477
train
nails/module-auth
src/Model/User.php
User.unsetAdminRecoveryData
public function unsetAdminRecoveryData() { $oSession = Factory::service('Session', 'nails/module-auth'); $aExistingRecoveryData = $oSession->getUserData($this->sAdminRecoveryField); if (empty($aExistingRecoveryData)) { $aExistingRecoveryData = []; } else { array_pop($aExistingRecoveryData); } $oSession->setUserData($this->sAdminRecoveryField, $aExistingRecoveryData); }
php
public function unsetAdminRecoveryData() { $oSession = Factory::service('Session', 'nails/module-auth'); $aExistingRecoveryData = $oSession->getUserData($this->sAdminRecoveryField); if (empty($aExistingRecoveryData)) { $aExistingRecoveryData = []; } else { array_pop($aExistingRecoveryData); } $oSession->setUserData($this->sAdminRecoveryField, $aExistingRecoveryData); }
[ "public", "function", "unsetAdminRecoveryData", "(", ")", "{", "$", "oSession", "=", "Factory", "::", "service", "(", "'Session'", ",", "'nails/module-auth'", ")", ";", "$", "aExistingRecoveryData", "=", "$", "oSession", "->", "getUserData", "(", "$", "this", ...
Removes the most recently added recovery data from the stack @return void
[ "Removes", "the", "most", "recently", "added", "recovery", "data", "from", "the", "stack" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L486-L498
train
nails/module-auth
src/Model/User.php
User.hasPermission
public function hasPermission($sSearch, $mUser = null) { // Fetch the correct ACL if (is_numeric($mUser)) { $oUser = $this->getById($mUser); if (isset($oUser->acl)) { $aAcl = $oUser->acl; unset($oUser); } else { return false; } } elseif (isset($mUser->acl)) { $aAcl = $mUser->acl; } else { $aAcl = (array) $this->activeUser('acl'); } // -------------------------------------------------------------------------- // Super users or CLI users can do anything their heart desires $oInput = Factory::service('Input'); if (in_array('admin:superuser', $aAcl) || $oInput::isCli()) { return true; } // -------------------------------------------------------------------------- /** * Test the ACL * We're going to use regular expressions here so we can allow for some * flexibility in the search, i.e admin:* would return true if the user has * access to any of admin. */ $bHasPermission = false; /** * Replace :* with :.* - this is a common mistake when using the permission * system (i.e., assuming that star on it's own will match) */ $sSearch = strtolower(preg_replace('/:\*/', ':.*', $sSearch)); foreach ($aAcl as $sPermission) { $sPattern = '/^' . $sSearch . '$/'; $bMatch = preg_match($sPattern, $sPermission); if ($bMatch) { $bHasPermission = true; break; } } return $bHasPermission; }
php
public function hasPermission($sSearch, $mUser = null) { // Fetch the correct ACL if (is_numeric($mUser)) { $oUser = $this->getById($mUser); if (isset($oUser->acl)) { $aAcl = $oUser->acl; unset($oUser); } else { return false; } } elseif (isset($mUser->acl)) { $aAcl = $mUser->acl; } else { $aAcl = (array) $this->activeUser('acl'); } // -------------------------------------------------------------------------- // Super users or CLI users can do anything their heart desires $oInput = Factory::service('Input'); if (in_array('admin:superuser', $aAcl) || $oInput::isCli()) { return true; } // -------------------------------------------------------------------------- /** * Test the ACL * We're going to use regular expressions here so we can allow for some * flexibility in the search, i.e admin:* would return true if the user has * access to any of admin. */ $bHasPermission = false; /** * Replace :* with :.* - this is a common mistake when using the permission * system (i.e., assuming that star on it's own will match) */ $sSearch = strtolower(preg_replace('/:\*/', ':.*', $sSearch)); foreach ($aAcl as $sPermission) { $sPattern = '/^' . $sSearch . '$/'; $bMatch = preg_match($sPattern, $sPermission); if ($bMatch) { $bHasPermission = true; break; } } return $bHasPermission; }
[ "public", "function", "hasPermission", "(", "$", "sSearch", ",", "$", "mUser", "=", "null", ")", "{", "// Fetch the correct ACL", "if", "(", "is_numeric", "(", "$", "mUser", ")", ")", "{", "$", "oUser", "=", "$", "this", "->", "getById", "(", "$", "mU...
Determines whether the specified user has a certain ACL permission @param string $sSearch The permission to check for @param mixed $mUser The user to check for; if null uses activeUser, if numeric, fetches user, if object uses that object @return boolean
[ "Determines", "whether", "the", "specified", "user", "has", "a", "certain", "ACL", "permission" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L526-L584
train
nails/module-auth
src/Model/User.php
User.getUserColumns
protected function getUserColumns($sPrefix = '', $aCols = []) { if ($this->aUserColumns === null) { $oDb = Factory::service('Database'); $aResult = $oDb->query('DESCRIBE `' . $this->table . '`')->result(); $this->aUserColumns = []; foreach ($aResult as $oResult) { $this->aUserColumns[] = $oResult->Field; } } $aCols = array_merge($aCols, $this->aUserColumns); return $this->prepareDbColumns($sPrefix, $aCols); }
php
protected function getUserColumns($sPrefix = '', $aCols = []) { if ($this->aUserColumns === null) { $oDb = Factory::service('Database'); $aResult = $oDb->query('DESCRIBE `' . $this->table . '`')->result(); $this->aUserColumns = []; foreach ($aResult as $oResult) { $this->aUserColumns[] = $oResult->Field; } } $aCols = array_merge($aCols, $this->aUserColumns); return $this->prepareDbColumns($sPrefix, $aCols); }
[ "protected", "function", "getUserColumns", "(", "$", "sPrefix", "=", "''", ",", "$", "aCols", "=", "[", "]", ")", "{", "if", "(", "$", "this", "->", "aUserColumns", "===", "null", ")", "{", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database...
Defines the list of columns in the `user` table @param string $sPrefix The prefix to add to the columns @param array $aCols Any additional columns to add @return array
[ "Defines", "the", "list", "of", "columns", "in", "the", "user", "table" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L650-L666
train
nails/module-auth
src/Model/User.php
User.getMetaColumns
protected function getMetaColumns($sPrefix = '', $aCols = []) { if ($this->aMetaColumns === null) { $oDb = Factory::service('Database'); $aResult = $oDb->query('DESCRIBE `' . $this->tableMeta . '`')->result(); $this->aMetaColumns = []; foreach ($aResult as $oResult) { if ($oResult->Field !== 'user_id') { $this->aMetaColumns[] = $oResult->Field; } } } $aCols = array_merge($aCols, $this->aMetaColumns); return $this->prepareDbColumns($sPrefix, $aCols); }
php
protected function getMetaColumns($sPrefix = '', $aCols = []) { if ($this->aMetaColumns === null) { $oDb = Factory::service('Database'); $aResult = $oDb->query('DESCRIBE `' . $this->tableMeta . '`')->result(); $this->aMetaColumns = []; foreach ($aResult as $oResult) { if ($oResult->Field !== 'user_id') { $this->aMetaColumns[] = $oResult->Field; } } } $aCols = array_merge($aCols, $this->aMetaColumns); return $this->prepareDbColumns($sPrefix, $aCols); }
[ "protected", "function", "getMetaColumns", "(", "$", "sPrefix", "=", "''", ",", "$", "aCols", "=", "[", "]", ")", "{", "if", "(", "$", "this", "->", "aMetaColumns", "===", "null", ")", "{", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database...
Defines the list of columns in the meta table @param string $sPrefix The prefix to add to the columns @param array $aCols Any additional columns to add @return array
[ "Defines", "the", "list", "of", "columns", "in", "the", "meta", "table" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L678-L696
train
nails/module-auth
src/Model/User.php
User.prepareDbColumns
protected function prepareDbColumns($sPrefix = '', $aCols = []) { // Clean up $aCols = array_unique($aCols); $aCols = array_filter($aCols); // Prefix all the values, if needed if ($sPrefix) { foreach ($aCols as $key => &$value) { $value = $sPrefix . '.' . $value; } } return $aCols; }
php
protected function prepareDbColumns($sPrefix = '', $aCols = []) { // Clean up $aCols = array_unique($aCols); $aCols = array_filter($aCols); // Prefix all the values, if needed if ($sPrefix) { foreach ($aCols as $key => &$value) { $value = $sPrefix . '.' . $value; } } return $aCols; }
[ "protected", "function", "prepareDbColumns", "(", "$", "sPrefix", "=", "''", ",", "$", "aCols", "=", "[", "]", ")", "{", "// Clean up", "$", "aCols", "=", "array_unique", "(", "$", "aCols", ")", ";", "$", "aCols", "=", "array_filter", "(", "$", "aCols...
Filter out duplicates and prefix column names if necessary @param string $sPrefix @param array $aCols @return array
[ "Filter", "out", "duplicates", "and", "prefix", "column", "names", "if", "necessary" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L708-L722
train
nails/module-auth
src/Model/User.php
User.getByIdentifier
public function getByIdentifier($identifier) { switch (APP_NATIVE_LOGIN_USING) { case 'EMAIL': $user = $this->getByEmail($identifier); break; case 'USERNAME': $user = $this->getByUsername($identifier); break; default: Factory::helper('email'); if (valid_email($identifier)) { $user = $this->getByEmail($identifier); } else { $user = $this->getByUsername($identifier); } break; } return $user; }
php
public function getByIdentifier($identifier) { switch (APP_NATIVE_LOGIN_USING) { case 'EMAIL': $user = $this->getByEmail($identifier); break; case 'USERNAME': $user = $this->getByUsername($identifier); break; default: Factory::helper('email'); if (valid_email($identifier)) { $user = $this->getByEmail($identifier); } else { $user = $this->getByUsername($identifier); } break; } return $user; }
[ "public", "function", "getByIdentifier", "(", "$", "identifier", ")", "{", "switch", "(", "APP_NATIVE_LOGIN_USING", ")", "{", "case", "'EMAIL'", ":", "$", "user", "=", "$", "this", "->", "getByEmail", "(", "$", "identifier", ")", ";", "break", ";", "case",...
Look up a user by their identifier @param string $identifier The user's identifier, either an email address or a username @return mixed false on failure, stdClass on success
[ "Look", "up", "a", "user", "by", "their", "identifier" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L733-L756
train
nails/module-auth
src/Model/User.php
User.getByEmail
public function getByEmail($email) { if (!is_string($email)) { return false; } // -------------------------------------------------------------------------- // Look up the email, and if we find an ID then fetch that user $oDb = Factory::service('Database'); $oDb->select('user_id'); $oDb->where('email', trim($email)); $user = $oDb->get($this->tableEmail)->row(); return $user ? $this->getById($user->user_id) : false; }
php
public function getByEmail($email) { if (!is_string($email)) { return false; } // -------------------------------------------------------------------------- // Look up the email, and if we find an ID then fetch that user $oDb = Factory::service('Database'); $oDb->select('user_id'); $oDb->where('email', trim($email)); $user = $oDb->get($this->tableEmail)->row(); return $user ? $this->getById($user->user_id) : false; }
[ "public", "function", "getByEmail", "(", "$", "email", ")", "{", "if", "(", "!", "is_string", "(", "$", "email", ")", ")", "{", "return", "false", ";", "}", "// --------------------------------------------------------------------------", "// Look up the email, and if w...
Get a user by their email address @param string $email The user's email address @return mixed stdClass on success, false on failure
[ "Get", "a", "user", "by", "their", "email", "address" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L767-L782
train
nails/module-auth
src/Model/User.php
User.getByUsername
public function getByUsername($username) { if (!is_string($username)) { return false; } $data = [ 'where' => [ [ 'column' => $this->tableAlias . '.username', 'value' => $username, ], ], ]; $user = $this->getAll(null, null, $data); return empty($user) ? false : $user[0]; }
php
public function getByUsername($username) { if (!is_string($username)) { return false; } $data = [ 'where' => [ [ 'column' => $this->tableAlias . '.username', 'value' => $username, ], ], ]; $user = $this->getAll(null, null, $data); return empty($user) ? false : $user[0]; }
[ "public", "function", "getByUsername", "(", "$", "username", ")", "{", "if", "(", "!", "is_string", "(", "$", "username", ")", ")", "{", "return", "false", ";", "}", "$", "data", "=", "[", "'where'", "=>", "[", "[", "'column'", "=>", "$", "this", "...
Get a user by their username @param string $username The user's username @return mixed stdClass on success, false on failure
[ "Get", "a", "user", "by", "their", "username" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L793-L811
train
nails/module-auth
src/Model/User.php
User.getByHashes
public function getByHashes($md5Id, $md5Pw) { if (empty($md5Id) || empty($md5Pw)) { return false; } $data = [ 'where' => [ [ 'column' => $this->tableAlias . '.id_md5', 'value' => $md5Id, ], [ 'column' => $this->tableAlias . '.password_md5', 'value' => $md5Pw, ], ], ]; $user = $this->getAll(null, null, $data); return empty($user) ? false : $user[0]; }
php
public function getByHashes($md5Id, $md5Pw) { if (empty($md5Id) || empty($md5Pw)) { return false; } $data = [ 'where' => [ [ 'column' => $this->tableAlias . '.id_md5', 'value' => $md5Id, ], [ 'column' => $this->tableAlias . '.password_md5', 'value' => $md5Pw, ], ], ]; $user = $this->getAll(null, null, $data); return empty($user) ? false : $user[0]; }
[ "public", "function", "getByHashes", "(", "$", "md5Id", ",", "$", "md5Pw", ")", "{", "if", "(", "empty", "(", "$", "md5Id", ")", "||", "empty", "(", "$", "md5Pw", ")", ")", "{", "return", "false", ";", "}", "$", "data", "=", "[", "'where'", "=>",...
Get a specific user by a MD5 hash of their ID and password @param string $md5Id The MD5 hash of their ID @param string $md5Pw The MD5 hash of their password @return mixed stdClass on success, false on failure
[ "Get", "a", "specific", "user", "by", "a", "MD5", "hash", "of", "their", "ID", "and", "password" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L823-L845
train
nails/module-auth
src/Model/User.php
User.getByReferral
public function getByReferral($referralCode) { if (!is_string($referralCode)) { return false; } $data = [ 'where' => [ [ 'column' => $this->tableAlias . '.referral', 'value' => $referralCode, ], ], ]; $user = $this->getAll(null, null, $data); return empty($user) ? false : $user[0]; }
php
public function getByReferral($referralCode) { if (!is_string($referralCode)) { return false; } $data = [ 'where' => [ [ 'column' => $this->tableAlias . '.referral', 'value' => $referralCode, ], ], ]; $user = $this->getAll(null, null, $data); return empty($user) ? false : $user[0]; }
[ "public", "function", "getByReferral", "(", "$", "referralCode", ")", "{", "if", "(", "!", "is_string", "(", "$", "referralCode", ")", ")", "{", "return", "false", ";", "}", "$", "data", "=", "[", "'where'", "=>", "[", "[", "'column'", "=>", "$", "th...
Get a user by their referral code @param string $referralCode The user's referral code @return mixed stdClass on success, false on failure
[ "Get", "a", "user", "by", "their", "referral", "code" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L856-L874
train
nails/module-auth
src/Model/User.php
User.getEmailsForUser
public function getEmailsForUser($id) { $oDb = Factory::service('Database'); $oDb->where('user_id', $id); $oDb->order_by('date_added'); $oDb->order_by('email', 'ASC'); return $oDb->get($this->tableEmail)->result(); }
php
public function getEmailsForUser($id) { $oDb = Factory::service('Database'); $oDb->where('user_id', $id); $oDb->order_by('date_added'); $oDb->order_by('email', 'ASC'); return $oDb->get($this->tableEmail)->result(); }
[ "public", "function", "getEmailsForUser", "(", "$", "id", ")", "{", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "oDb", "->", "where", "(", "'user_id'", ",", "$", "id", ")", ";", "$", "oDb", "->", "order_by", "(", ...
Get all the email addresses which are registered to a particular user ID @param integer $id The user's ID @return array
[ "Get", "all", "the", "email", "addresses", "which", "are", "registered", "to", "a", "particular", "user", "ID" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L885-L892
train
nails/module-auth
src/Model/User.php
User.setCacheUser
public function setCacheUser($iUserId, $aData = []) { $this->unsetCacheUser($iUserId); $oUser = $this->getById($iUserId); if (empty($oUser)) { return false; } $this->setCache( $this->prepareCacheKey($this->tableIdColumn, $oUser->id, $aData), $oUser ); return true; }
php
public function setCacheUser($iUserId, $aData = []) { $this->unsetCacheUser($iUserId); $oUser = $this->getById($iUserId); if (empty($oUser)) { return false; } $this->setCache( $this->prepareCacheKey($this->tableIdColumn, $oUser->id, $aData), $oUser ); return true; }
[ "public", "function", "setCacheUser", "(", "$", "iUserId", ",", "$", "aData", "=", "[", "]", ")", "{", "$", "this", "->", "unsetCacheUser", "(", "$", "iUserId", ")", ";", "$", "oUser", "=", "$", "this", "->", "getById", "(", "$", "iUserId", ")", ";...
Saves a user object to the persistent cache @param integer $iUserId The user ID to cache @param array $aData The data array @return boolean
[ "Saves", "a", "user", "object", "to", "the", "persistent", "cache" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L1241-L1256
train
nails/module-auth
src/Model/User.php
User.emailAddSendVerify
public function emailAddSendVerify($email_id, $iUserId = null) { // Fetch the email and the user's group $oDb = Factory::service('Database'); $oDb->select( [ $this->tableEmailAlias . '.id', $this->tableEmailAlias . '.code', $this->tableEmailAlias . '.is_verified', $this->tableEmailAlias . '.user_id', $this->tableAlias . '.group_id', ] ); if (is_numeric($email_id)) { $oDb->where($this->tableEmailAlias . '.id', $email_id); } else { $oDb->where($this->tableEmailAlias . '.email', $email_id); } if (!empty($iUserId)) { $oDb->where($this->tableEmailAlias . '.user_id', $iUserId); } $oDb->join( $this->table . ' ' . $this->tableAlias, $this->tableAlias . '.id = ' . $this->tableEmailAlias . '.user_id' ); $oEmailRow = $oDb->get($this->tableEmail . ' ' . $this->tableEmailAlias)->row(); if (!$oEmailRow) { $this->setError('Invalid Email.'); return false; } if ($oEmailRow->is_verified) { $this->setError('Email is already verified.'); return false; } // -------------------------------------------------------------------------- $oEmailer = Factory::service('Emailer', 'nails/module-email'); $oEmail = new \stdClass(); $oEmail->type = 'verify_email_' . $oEmailRow->group_id; $oEmail->to_id = $oEmailRow->user_id; $oEmail->data = new \stdClass(); $oEmail->data->verifyUrl = site_url('email/verify/' . $oEmailRow->user_id . '/' . $oEmailRow->code); if (!$oEmailer->send($oEmail, true)) { // Failed to send using the group email, try using the generic email template $oEmail->type = 'verify_email'; if (!$oEmailer->send($oEmail, true)) { // Email failed to send, for now, do nothing. $this->setError('The verification email failed to send.'); return false; } } return true; }
php
public function emailAddSendVerify($email_id, $iUserId = null) { // Fetch the email and the user's group $oDb = Factory::service('Database'); $oDb->select( [ $this->tableEmailAlias . '.id', $this->tableEmailAlias . '.code', $this->tableEmailAlias . '.is_verified', $this->tableEmailAlias . '.user_id', $this->tableAlias . '.group_id', ] ); if (is_numeric($email_id)) { $oDb->where($this->tableEmailAlias . '.id', $email_id); } else { $oDb->where($this->tableEmailAlias . '.email', $email_id); } if (!empty($iUserId)) { $oDb->where($this->tableEmailAlias . '.user_id', $iUserId); } $oDb->join( $this->table . ' ' . $this->tableAlias, $this->tableAlias . '.id = ' . $this->tableEmailAlias . '.user_id' ); $oEmailRow = $oDb->get($this->tableEmail . ' ' . $this->tableEmailAlias)->row(); if (!$oEmailRow) { $this->setError('Invalid Email.'); return false; } if ($oEmailRow->is_verified) { $this->setError('Email is already verified.'); return false; } // -------------------------------------------------------------------------- $oEmailer = Factory::service('Emailer', 'nails/module-email'); $oEmail = new \stdClass(); $oEmail->type = 'verify_email_' . $oEmailRow->group_id; $oEmail->to_id = $oEmailRow->user_id; $oEmail->data = new \stdClass(); $oEmail->data->verifyUrl = site_url('email/verify/' . $oEmailRow->user_id . '/' . $oEmailRow->code); if (!$oEmailer->send($oEmail, true)) { // Failed to send using the group email, try using the generic email template $oEmail->type = 'verify_email'; if (!$oEmailer->send($oEmail, true)) { // Email failed to send, for now, do nothing. $this->setError('The verification email failed to send.'); return false; } } return true; }
[ "public", "function", "emailAddSendVerify", "(", "$", "email_id", ",", "$", "iUserId", "=", "null", ")", "{", "// Fetch the email and the user's group", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "oDb", "->", "select", "(",...
Send, or resend, the verify email for a particular email address @param integer $email_id The email's ID @param integer $iUserId The user's ID @return boolean
[ "Send", "or", "resend", "the", "verify", "email", "for", "a", "particular", "email", "address" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L1414-L1477
train
nails/module-auth
src/Model/User.php
User.emailMakePrimary
public function emailMakePrimary($mIdEmail, $iUserId = null) { // Fetch email $oDb = Factory::service('Database'); $oDb->select('id,user_id,email'); if (is_numeric($mIdEmail)) { $oDb->where('id', $mIdEmail); } else { $oDb->where('email', $mIdEmail); } if (!is_null($iUserId)) { $oDb->where('user_id', $iUserId); } $oEmail = $oDb->get($this->tableEmail)->row(); if (empty($oEmail)) { return false; } // Update $oDb->trans_begin(); try { $oDb->set('is_primary', false); $oDb->where('user_id', $oEmail->user_id); $oDb->update($this->tableEmail); $oDb->set('is_primary', true); $oDb->where('id', $oEmail->id); $oDb->update($this->tableEmail); $this->unsetCacheUser($oEmail->user_id); // Update the activeUser if ($oEmail->user_id == $this->activeUser('id')) { $oDate = Factory::factory('DateTime'); $this->activeUser->last_update = $oDate->format('Y-m-d H:i:s'); // @todo: update the rest of the activeUser } $oDb->trans_commit(); return true; } catch (\Exception $e) { $this->setError('Failed to set primary email. ' . $e->getMessage()); $oDb->trans_rollback(); return false; } }
php
public function emailMakePrimary($mIdEmail, $iUserId = null) { // Fetch email $oDb = Factory::service('Database'); $oDb->select('id,user_id,email'); if (is_numeric($mIdEmail)) { $oDb->where('id', $mIdEmail); } else { $oDb->where('email', $mIdEmail); } if (!is_null($iUserId)) { $oDb->where('user_id', $iUserId); } $oEmail = $oDb->get($this->tableEmail)->row(); if (empty($oEmail)) { return false; } // Update $oDb->trans_begin(); try { $oDb->set('is_primary', false); $oDb->where('user_id', $oEmail->user_id); $oDb->update($this->tableEmail); $oDb->set('is_primary', true); $oDb->where('id', $oEmail->id); $oDb->update($this->tableEmail); $this->unsetCacheUser($oEmail->user_id); // Update the activeUser if ($oEmail->user_id == $this->activeUser('id')) { $oDate = Factory::factory('DateTime'); $this->activeUser->last_update = $oDate->format('Y-m-d H:i:s'); // @todo: update the rest of the activeUser } $oDb->trans_commit(); return true; } catch (\Exception $e) { $this->setError('Failed to set primary email. ' . $e->getMessage()); $oDb->trans_rollback(); return false; } }
[ "public", "function", "emailMakePrimary", "(", "$", "mIdEmail", ",", "$", "iUserId", "=", "null", ")", "{", "// Fetch email", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "oDb", "->", "select", "(", "'id,user_id,email'", ...
Sets an email address as the primary email address for that user. @param mixed $mIdEmail The numeric ID of the email address, or the email address itself @param integer $iUserId Specify the user ID which this should apply to @return boolean
[ "Sets", "an", "email", "address", "as", "the", "primary", "email", "address", "for", "that", "user", "." ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L1597-L1650
train
nails/module-auth
src/Model/User.php
User.incrementFailedLogin
public function incrementFailedLogin($iUserId, $expires = 300) { $oDate = Factory::factory('DateTime'); $oDate->add(new \DateInterval('PT' . $expires . 'S')); $oDb = Factory::service('Database'); $oDb->set('failed_login_count', '`failed_login_count`+1', false); $oDb->set('failed_login_expires', $oDate->format('Y-m-d H:i:s')); return $this->update($iUserId); }
php
public function incrementFailedLogin($iUserId, $expires = 300) { $oDate = Factory::factory('DateTime'); $oDate->add(new \DateInterval('PT' . $expires . 'S')); $oDb = Factory::service('Database'); $oDb->set('failed_login_count', '`failed_login_count`+1', false); $oDb->set('failed_login_expires', $oDate->format('Y-m-d H:i:s')); return $this->update($iUserId); }
[ "public", "function", "incrementFailedLogin", "(", "$", "iUserId", ",", "$", "expires", "=", "300", ")", "{", "$", "oDate", "=", "Factory", "::", "factory", "(", "'DateTime'", ")", ";", "$", "oDate", "->", "add", "(", "new", "\\", "DateInterval", "(", ...
Increment the user's failed logins @param integer $iUserId The user ID to increment @param integer $expires How long till the block, if the threshold is reached, expires. @return boolean
[ "Increment", "the", "user", "s", "failed", "logins" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L1662-L1671
train
nails/module-auth
src/Model/User.php
User.resetFailedLogin
public function resetFailedLogin($iUserId) { $oDb = Factory::service('Database'); $oDb->set('failed_login_count', 0); $oDb->set('failed_login_expires', 'null', false); return $this->update($iUserId); }
php
public function resetFailedLogin($iUserId) { $oDb = Factory::service('Database'); $oDb->set('failed_login_count', 0); $oDb->set('failed_login_expires', 'null', false); return $this->update($iUserId); }
[ "public", "function", "resetFailedLogin", "(", "$", "iUserId", ")", "{", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "oDb", "->", "set", "(", "'failed_login_count'", ",", "0", ")", ";", "$", "oDb", "->", "set", "(", ...
Reset a user's failed login @param integer $iUserId The user ID to reset @return boolean
[ "Reset", "a", "user", "s", "failed", "login" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L1682-L1688
train
nails/module-auth
src/Model/User.php
User.setRememberCookie
public function setRememberCookie($iId = null, $sPassword = null, $sEmail = null) { // Is remember me functionality enabled? $oConfig = Factory::service('Config'); $oConfig->load('auth/auth'); if (!$oConfig->item('authEnableRememberMe')) { return false; } // -------------------------------------------------------------------------- if (empty($iId) || empty($sPassword) || empty($sEmail)) { if (!activeUser('id') || !activeUser('password') || !activeUser('email')) { return false; } else { $iId = $this->activeUser('id'); $sPassword = $this->activeUser('password'); $sEmail = $this->activeUser('email'); } } // -------------------------------------------------------------------------- // Generate a code to remember the user by and save it to the DB $oEncrypt = Factory::service('Encrypt'); $sSalt = $oEncrypt->encode(sha1($iId . $sPassword . $sEmail . APP_PRIVATE_KEY . time())); $oDb = Factory::service('Database'); $oDb->set('remember_code', $sSalt); $oDb->where('id', $iId); $oDb->update($this->table); // -------------------------------------------------------------------------- // Set the cookie set_cookie([ 'name' => $this->sRememberCookie, 'value' => $sEmail . '|' . $sSalt, 'expire' => 1209600, // 2 weeks ]); // -------------------------------------------------------------------------- // Update the flag $this->bIsRemembered = true; return true; }
php
public function setRememberCookie($iId = null, $sPassword = null, $sEmail = null) { // Is remember me functionality enabled? $oConfig = Factory::service('Config'); $oConfig->load('auth/auth'); if (!$oConfig->item('authEnableRememberMe')) { return false; } // -------------------------------------------------------------------------- if (empty($iId) || empty($sPassword) || empty($sEmail)) { if (!activeUser('id') || !activeUser('password') || !activeUser('email')) { return false; } else { $iId = $this->activeUser('id'); $sPassword = $this->activeUser('password'); $sEmail = $this->activeUser('email'); } } // -------------------------------------------------------------------------- // Generate a code to remember the user by and save it to the DB $oEncrypt = Factory::service('Encrypt'); $sSalt = $oEncrypt->encode(sha1($iId . $sPassword . $sEmail . APP_PRIVATE_KEY . time())); $oDb = Factory::service('Database'); $oDb->set('remember_code', $sSalt); $oDb->where('id', $iId); $oDb->update($this->table); // -------------------------------------------------------------------------- // Set the cookie set_cookie([ 'name' => $this->sRememberCookie, 'value' => $sEmail . '|' . $sSalt, 'expire' => 1209600, // 2 weeks ]); // -------------------------------------------------------------------------- // Update the flag $this->bIsRemembered = true; return true; }
[ "public", "function", "setRememberCookie", "(", "$", "iId", "=", "null", ",", "$", "sPassword", "=", "null", ",", "$", "sEmail", "=", "null", ")", "{", "// Is remember me functionality enabled?", "$", "oConfig", "=", "Factory", "::", "service", "(", "'Config'...
Set the user's 'rememberMe' cookie, nom nom nom @param integer $iId The User's ID @param string $sPassword The user's password, hashed @param string $sEmail The user's email\ @return boolean
[ "Set", "the", "user", "s", "rememberMe", "cookie", "nom", "nom", "nom" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L1718-L1769
train
nails/module-auth
src/Model/User.php
User.refreshSession
protected function refreshSession() { // Get the user; be wary of admin's logged in as other people $oSession = Factory::service('Session', 'nails/module-auth'); if ($this->wasAdmin()) { $recoveryData = $this->getAdminRecoveryData(); if (!empty($recoveryData->newUserId)) { $me = $recoveryData->newUserId; } else { $me = $oSession->getUserData('id'); } } else { $me = $oSession->getUserData('id'); } // Is anybody home? Hello...? if (!$me) { $me = $this->me; if (!$me) { return false; } } $me = $this->getById($me); // -------------------------------------------------------------------------- /** * If the user is isn't found (perhaps deleted) or has been suspended then * obviously don't proceed with the log in */ if (!$me || !empty($me->is_suspended)) { $this->clearRememberCookie(); $this->clearActiveUser(); $this->clearLoginData(); $this->bIsLoggedIn = false; return false; } // -------------------------------------------------------------------------- // Store this entire user in memory $this->setActiveUser($me); // -------------------------------------------------------------------------- // Set the user's logged in flag $this->bIsLoggedIn = true; // -------------------------------------------------------------------------- // Update user's `last_seen` and `last_ip` properties $oDb = Factory::service('Database'); $oInput = Factory::service('Input'); $oDb->set('last_seen', 'NOW()', false); $oDb->set('last_ip', $oInput->ipAddress()); $oDb->where('id', $me->id); $oDb->update($this->table); return true; }
php
protected function refreshSession() { // Get the user; be wary of admin's logged in as other people $oSession = Factory::service('Session', 'nails/module-auth'); if ($this->wasAdmin()) { $recoveryData = $this->getAdminRecoveryData(); if (!empty($recoveryData->newUserId)) { $me = $recoveryData->newUserId; } else { $me = $oSession->getUserData('id'); } } else { $me = $oSession->getUserData('id'); } // Is anybody home? Hello...? if (!$me) { $me = $this->me; if (!$me) { return false; } } $me = $this->getById($me); // -------------------------------------------------------------------------- /** * If the user is isn't found (perhaps deleted) or has been suspended then * obviously don't proceed with the log in */ if (!$me || !empty($me->is_suspended)) { $this->clearRememberCookie(); $this->clearActiveUser(); $this->clearLoginData(); $this->bIsLoggedIn = false; return false; } // -------------------------------------------------------------------------- // Store this entire user in memory $this->setActiveUser($me); // -------------------------------------------------------------------------- // Set the user's logged in flag $this->bIsLoggedIn = true; // -------------------------------------------------------------------------- // Update user's `last_seen` and `last_ip` properties $oDb = Factory::service('Database'); $oInput = Factory::service('Input'); $oDb->set('last_seen', 'NOW()', false); $oDb->set('last_ip', $oInput->ipAddress()); $oDb->where('id', $me->id); $oDb->update($this->table); return true; }
[ "protected", "function", "refreshSession", "(", ")", "{", "// Get the user; be wary of admin's logged in as other people", "$", "oSession", "=", "Factory", "::", "service", "(", "'Session'", ",", "'nails/module-auth'", ")", ";", "if", "(", "$", "this", "->", "wasAdmi...
Refresh the user's session from the database @return boolean
[ "Refresh", "the", "user", "s", "session", "from", "the", "database" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L1793-L1858
train
nails/module-auth
src/Model/User.php
User.generateReferral
protected function generateReferral() { Factory::helper('string'); $oDb = Factory::service('Database'); $sReferral = ''; while (1 > 0) { $sReferral = random_string('alnum', 8); $oQuery = $oDb->get_where($this->table, ['referral' => $sReferral]); if ($oQuery->num_rows() == 0) { break; } } return $sReferral; }
php
protected function generateReferral() { Factory::helper('string'); $oDb = Factory::service('Database'); $sReferral = ''; while (1 > 0) { $sReferral = random_string('alnum', 8); $oQuery = $oDb->get_where($this->table, ['referral' => $sReferral]); if ($oQuery->num_rows() == 0) { break; } } return $sReferral; }
[ "protected", "function", "generateReferral", "(", ")", "{", "Factory", "::", "helper", "(", "'string'", ")", ";", "$", "oDb", "=", "Factory", "::", "service", "(", "'Database'", ")", ";", "$", "sReferral", "=", "''", ";", "while", "(", "1", ">", "0", ...
Generates a valid referral code @return string
[ "Generates", "a", "valid", "referral", "code" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L2222-L2239
train
nails/module-auth
src/Model/User.php
User.isValidUsername
public function isValidUsername($username, $checkDb = false, $ignoreUserId = null) { /** * Check username doesn't contain invalid characters - we're actively looking * for characters which are invalid so we can say "Hey! The following * characters are invalid" rather than making the user guess, y'know, 'cause * we're good guys. */ $invalidChars = '/[^a-zA-Z0-9\-_\.]/'; // Minimum length of the username $minLength = 2; // -------------------------------------------------------------------------- // Check for illegal characters $containsInvalidChars = preg_match($invalidChars, $username); if ($containsInvalidChars) { $msg = 'Username can only contain alpha numeric characters, underscores, periods and dashes (no spaces).'; $this->setError($msg); return false; } // -------------------------------------------------------------------------- // Check length if (strlen($username) < $minLength) { $this->setError('Usernames must be at least ' . $minLength . ' characters long.'); return false; } // -------------------------------------------------------------------------- if ($checkDb) { $oDb = Factory::service('Database'); $oDb->where('username', $username); if (!empty($ignoreUserId)) { $oDb->where('id !=', $ignoreUserId); } if ($oDb->count_all_results($this->table)) { $this->setError('Username is already in use.'); return false; } } return true; }
php
public function isValidUsername($username, $checkDb = false, $ignoreUserId = null) { /** * Check username doesn't contain invalid characters - we're actively looking * for characters which are invalid so we can say "Hey! The following * characters are invalid" rather than making the user guess, y'know, 'cause * we're good guys. */ $invalidChars = '/[^a-zA-Z0-9\-_\.]/'; // Minimum length of the username $minLength = 2; // -------------------------------------------------------------------------- // Check for illegal characters $containsInvalidChars = preg_match($invalidChars, $username); if ($containsInvalidChars) { $msg = 'Username can only contain alpha numeric characters, underscores, periods and dashes (no spaces).'; $this->setError($msg); return false; } // -------------------------------------------------------------------------- // Check length if (strlen($username) < $minLength) { $this->setError('Usernames must be at least ' . $minLength . ' characters long.'); return false; } // -------------------------------------------------------------------------- if ($checkDb) { $oDb = Factory::service('Database'); $oDb->where('username', $username); if (!empty($ignoreUserId)) { $oDb->where('id !=', $ignoreUserId); } if ($oDb->count_all_results($this->table)) { $this->setError('Username is already in use.'); return false; } } return true; }
[ "public", "function", "isValidUsername", "(", "$", "username", ",", "$", "checkDb", "=", "false", ",", "$", "ignoreUserId", "=", "null", ")", "{", "/**\n * Check username doesn't contain invalid characters - we're actively looking\n * for characters which are inva...
Checks whether a username is valid @param string $username The username to check @param boolean $checkDb Whether to test against the database @param mixed $ignoreUserId The ID of a user to ignore when checking the database @return boolean
[ "Checks", "whether", "a", "username", "is", "valid" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L2295-L2348
train
nails/module-auth
src/Model/User.php
User.describeFields
public function describeFields($sTable = null) { $aFields = parent::describeFields($sTable); $aMetaFields = parent::describeFields($this->tableMeta); unset($aMetaFields['user_id']); return array_merge($aFields, $aMetaFields); }
php
public function describeFields($sTable = null) { $aFields = parent::describeFields($sTable); $aMetaFields = parent::describeFields($this->tableMeta); unset($aMetaFields['user_id']); return array_merge($aFields, $aMetaFields); }
[ "public", "function", "describeFields", "(", "$", "sTable", "=", "null", ")", "{", "$", "aFields", "=", "parent", "::", "describeFields", "(", "$", "sTable", ")", ";", "$", "aMetaFields", "=", "parent", "::", "describeFields", "(", "$", "this", "->", "ta...
Describes the fields for this model @param string $sTable The database table to query @return array
[ "Describes", "the", "fields", "for", "this", "model" ]
f9b0b554c1e06399fa8042dd94c5acf86bac5548
https://github.com/nails/module-auth/blob/f9b0b554c1e06399fa8042dd94c5acf86bac5548/src/Model/User.php#L2532-L2538
train
krixon/datetime
src/ProvidesDateTimeInformation.php
ProvidesDateTimeInformation.dayOfWeekLocal
public function dayOfWeekLocal(string $locale = null) : int { $calendar = $this->createCalendar($locale); return $calendar->get(\IntlCalendar::FIELD_DOW_LOCAL); }
php
public function dayOfWeekLocal(string $locale = null) : int { $calendar = $this->createCalendar($locale); return $calendar->get(\IntlCalendar::FIELD_DOW_LOCAL); }
[ "public", "function", "dayOfWeekLocal", "(", "string", "$", "locale", "=", "null", ")", ":", "int", "{", "$", "calendar", "=", "$", "this", "->", "createCalendar", "(", "$", "locale", ")", ";", "return", "$", "calendar", "->", "get", "(", "\\", "IntlCa...
Returns the day of the week for the specified locale. 1 is the first day of the week, 2 the second etc. For example, for en_GB a Monday would be 1 but for en_US a Monday would be 2 as the first day of the week is Sunday in that locale. @param string|null $locale @return int
[ "Returns", "the", "day", "of", "the", "week", "for", "the", "specified", "locale", "." ]
9a39084119bbfae2cf6e22d794aa04dd79344ce0
https://github.com/krixon/datetime/blob/9a39084119bbfae2cf6e22d794aa04dd79344ce0/src/ProvidesDateTimeInformation.php#L88-L93
train
locomotivemtl/charcoal-attachment
src/Charcoal/Admin/Widget/AttachmentWidget.php
AttachmentWidget.attachmentTypes
public function attachmentTypes() { $attachableObjects = $this->attachableObjects(); $out = []; if (!$attachableObjects) { return $out; } $i = 0; foreach ($attachableObjects as $attType => $attMeta) { $i++; $label = $attMeta['label']; $out[] = [ 'id' => (isset($attMeta['att_id']) ? $attMeta['att_id'] : null), 'ident' => $this->createIdent($attType), 'skipForm' => $attMeta['skipForm'], 'formIdent' => $attMeta['formIdent'], 'quickFormIdent' => $attMeta['quickFormIdent'], 'hasFaIcon' => !!$attMeta['faIcon'], 'faIcon' => $attMeta['faIcon'], 'label' => $label, 'val' => $attType, 'locked' => $attMeta['locked'], 'active' => ($i == 1) ]; } return $out; }
php
public function attachmentTypes() { $attachableObjects = $this->attachableObjects(); $out = []; if (!$attachableObjects) { return $out; } $i = 0; foreach ($attachableObjects as $attType => $attMeta) { $i++; $label = $attMeta['label']; $out[] = [ 'id' => (isset($attMeta['att_id']) ? $attMeta['att_id'] : null), 'ident' => $this->createIdent($attType), 'skipForm' => $attMeta['skipForm'], 'formIdent' => $attMeta['formIdent'], 'quickFormIdent' => $attMeta['quickFormIdent'], 'hasFaIcon' => !!$attMeta['faIcon'], 'faIcon' => $attMeta['faIcon'], 'label' => $label, 'val' => $attType, 'locked' => $attMeta['locked'], 'active' => ($i == 1) ]; } return $out; }
[ "public", "function", "attachmentTypes", "(", ")", "{", "$", "attachableObjects", "=", "$", "this", "->", "attachableObjects", "(", ")", ";", "$", "out", "=", "[", "]", ";", "if", "(", "!", "$", "attachableObjects", ")", "{", "return", "$", "out", ";",...
Retrieve the attachment types with their collections. @return array
[ "Retrieve", "the", "attachment", "types", "with", "their", "collections", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Admin/Widget/AttachmentWidget.php#L167-L198
train
locomotivemtl/charcoal-attachment
src/Charcoal/Admin/Widget/AttachmentWidget.php
AttachmentWidget.attachments
public function attachments() { $attachableObjects = $this->attachableObjects(); $attachments = $this->obj()->getAttachments([ 'group' => $this->group() ]); foreach ($attachments as $attachment) { $GLOBALS['widget_template'] = (string)$attachment->rawPreview(); if (isset($attachableObjects[$attachment->objType()])) { $attachment->attachmentType = $attachableObjects[$attachment->objType()]; } else { continue; } yield $attachment; $GLOBALS['widget_template'] = ''; } }
php
public function attachments() { $attachableObjects = $this->attachableObjects(); $attachments = $this->obj()->getAttachments([ 'group' => $this->group() ]); foreach ($attachments as $attachment) { $GLOBALS['widget_template'] = (string)$attachment->rawPreview(); if (isset($attachableObjects[$attachment->objType()])) { $attachment->attachmentType = $attachableObjects[$attachment->objType()]; } else { continue; } yield $attachment; $GLOBALS['widget_template'] = ''; } }
[ "public", "function", "attachments", "(", ")", "{", "$", "attachableObjects", "=", "$", "this", "->", "attachableObjects", "(", ")", ";", "$", "attachments", "=", "$", "this", "->", "obj", "(", ")", "->", "getAttachments", "(", "[", "'group'", "=>", "$",...
Attachment by groups. @return \Generator
[ "Attachment", "by", "groups", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Admin/Widget/AttachmentWidget.php#L205-L225
train
locomotivemtl/charcoal-attachment
src/Charcoal/Admin/Widget/AttachmentWidget.php
AttachmentWidget.setData
public function setData(array $data) { $this->isMergingData = true; /** * @todo Kinda hacky, but works with the concept of form. * Should work embeded in a form group or in a dashboard. */ $data = array_merge($_GET, $data); parent::setData($data); /** Merge any available presets */ $data = $this->mergePresets($data); parent::setData($data); $this->isMergingData = false; if ($this->lang()) { $this->translator()->setLocale($this->lang()); } return $this; }
php
public function setData(array $data) { $this->isMergingData = true; /** * @todo Kinda hacky, but works with the concept of form. * Should work embeded in a form group or in a dashboard. */ $data = array_merge($_GET, $data); parent::setData($data); /** Merge any available presets */ $data = $this->mergePresets($data); parent::setData($data); $this->isMergingData = false; if ($this->lang()) { $this->translator()->setLocale($this->lang()); } return $this; }
[ "public", "function", "setData", "(", "array", "$", "data", ")", "{", "$", "this", "->", "isMergingData", "=", "true", ";", "/**\n * @todo Kinda hacky, but works with the concept of form.\n * Should work embeded in a form group or in a dashboard.\n */", ...
Set the widget's data. @param array $data The widget data. @return self
[ "Set", "the", "widget", "s", "data", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Admin/Widget/AttachmentWidget.php#L352-L375
train
locomotivemtl/charcoal-attachment
src/Charcoal/Admin/Widget/AttachmentWidget.php
AttachmentWidget.setAttachmentOptions
public function setAttachmentOptions(array $settings) { $this->attachmentOptions = array_merge( $this->defaultAttachmentOptions(), $this->parseAttachmentOptions($settings) ); return $this; }
php
public function setAttachmentOptions(array $settings) { $this->attachmentOptions = array_merge( $this->defaultAttachmentOptions(), $this->parseAttachmentOptions($settings) ); return $this; }
[ "public", "function", "setAttachmentOptions", "(", "array", "$", "settings", ")", "{", "$", "this", "->", "attachmentOptions", "=", "array_merge", "(", "$", "this", "->", "defaultAttachmentOptions", "(", ")", ",", "$", "this", "->", "parseAttachmentOptions", "("...
Set the attachment widget settings. @param array $settings Attachments options array. @return self
[ "Set", "the", "attachment", "widget", "settings", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Admin/Widget/AttachmentWidget.php#L405-L413
train
locomotivemtl/charcoal-attachment
src/Charcoal/Admin/Widget/AttachmentWidget.php
AttachmentWidget.setGroup
public function setGroup($group) { if (!is_string($group) && $group !== null) { throw new InvalidArgumentException(sprintf( 'Attachment group must be string, received %s', is_object($group) ? get_class($group) : gettype($group) )); } $this->group = $group; return $this; }
php
public function setGroup($group) { if (!is_string($group) && $group !== null) { throw new InvalidArgumentException(sprintf( 'Attachment group must be string, received %s', is_object($group) ? get_class($group) : gettype($group) )); } $this->group = $group; return $this; }
[ "public", "function", "setGroup", "(", "$", "group", ")", "{", "if", "(", "!", "is_string", "(", "$", "group", ")", "&&", "$", "group", "!==", "null", ")", "{", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Attachment group must be strin...
Set the widget's attachment grouping. Prevents the relationship from deleting all non related attachments. @param string $group The group identifier. @throws InvalidArgumentException If the group key is invalid. @return self
[ "Set", "the", "widget", "s", "attachment", "grouping", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Admin/Widget/AttachmentWidget.php#L424-L436
train
locomotivemtl/charcoal-attachment
src/Charcoal/Admin/Widget/AttachmentWidget.php
AttachmentWidget.attachmentOptions
public function attachmentOptions() { if ($this->attachmentOptions === null) { $this->attachmentOptions = $this->defaultAttachmentOptions(); } return $this->attachmentOptions; }
php
public function attachmentOptions() { if ($this->attachmentOptions === null) { $this->attachmentOptions = $this->defaultAttachmentOptions(); } return $this->attachmentOptions; }
[ "public", "function", "attachmentOptions", "(", ")", "{", "if", "(", "$", "this", "->", "attachmentOptions", "===", "null", ")", "{", "$", "this", "->", "attachmentOptions", "=", "$", "this", "->", "defaultAttachmentOptions", "(", ")", ";", "}", "return", ...
Retrieve the attachment options. @return array
[ "Retrieve", "the", "attachment", "options", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Admin/Widget/AttachmentWidget.php#L694-L701
train
locomotivemtl/charcoal-attachment
src/Charcoal/Admin/Widget/AttachmentWidget.php
AttachmentWidget.widgetOptions
public function widgetOptions() { $options = [ 'obj_type' => $this->obj()->objType(), 'obj_id' => $this->obj()->id(), 'group' => $this->group(), 'attachment_options' => $this->attachmentOptions(), 'attachable_objects' => $this->attachableObjects(), 'title' => $this->title(), 'lang' => $this->translator()->getLocale() ]; return json_encode($options, true); }
php
public function widgetOptions() { $options = [ 'obj_type' => $this->obj()->objType(), 'obj_id' => $this->obj()->id(), 'group' => $this->group(), 'attachment_options' => $this->attachmentOptions(), 'attachable_objects' => $this->attachableObjects(), 'title' => $this->title(), 'lang' => $this->translator()->getLocale() ]; return json_encode($options, true); }
[ "public", "function", "widgetOptions", "(", ")", "{", "$", "options", "=", "[", "'obj_type'", "=>", "$", "this", "->", "obj", "(", ")", "->", "objType", "(", ")", ",", "'obj_id'", "=>", "$", "this", "->", "obj", "(", ")", "->", "id", "(", ")", ",...
Retrieve the current widget's options as a JSON object. @return string A JSON string.
[ "Retrieve", "the", "current", "widget", "s", "options", "as", "a", "JSON", "object", "." ]
82963e414483e7a0fc75e30894db0bba376dbd2d
https://github.com/locomotivemtl/charcoal-attachment/blob/82963e414483e7a0fc75e30894db0bba376dbd2d/src/Charcoal/Admin/Widget/AttachmentWidget.php#L742-L755
train
merk/Dough
lib/Dough/Money/MultiCurrencyMoney.php
MultiCurrencyMoney.equals
public function equals(Money $money) { if (!$money instanceof MultiCurrencyMoney) { return false; } return $money->currency == $this->currency && $money->getAmount() == $this->getAmount(); }
php
public function equals(Money $money) { if (!$money instanceof MultiCurrencyMoney) { return false; } return $money->currency == $this->currency && $money->getAmount() == $this->getAmount(); }
[ "public", "function", "equals", "(", "Money", "$", "money", ")", "{", "if", "(", "!", "$", "money", "instanceof", "MultiCurrencyMoney", ")", "{", "return", "false", ";", "}", "return", "$", "money", "->", "currency", "==", "$", "this", "->", "currency", ...
Tests if two objects are of equal value. TODO: optionally supply a bank object to do a currency conversion for an equals check? @param Money $money @return bool
[ "Tests", "if", "two", "objects", "are", "of", "equal", "value", "." ]
af36775564fbaf46a8018acc4f1fd993530c1a96
https://github.com/merk/Dough/blob/af36775564fbaf46a8018acc4f1fd993530c1a96/lib/Dough/Money/MultiCurrencyMoney.php#L57-L64
train
merk/Dough
lib/Dough/Money/MultiCurrencyMoney.php
MultiCurrencyMoney.reduce
public function reduce(BankInterface $bank = null, $toCurrency = null) { if (null === $bank) { $bank = static::getBank(); } if (!$bank instanceof MultiCurrencyBankInterface) { throw new \InvalidArgumentException('The supplied bank must implement MultiCurrencyBankInterface'); } $rate = $bank->getRate($this->currency, $toCurrency); $rounder = $bank->getRounder(); $amount = bcmul($this->getAmount(), $rate, $rounder->getPrecision() + 1); return $bank->createMoney($rounder->round($amount, $toCurrency), $toCurrency); }
php
public function reduce(BankInterface $bank = null, $toCurrency = null) { if (null === $bank) { $bank = static::getBank(); } if (!$bank instanceof MultiCurrencyBankInterface) { throw new \InvalidArgumentException('The supplied bank must implement MultiCurrencyBankInterface'); } $rate = $bank->getRate($this->currency, $toCurrency); $rounder = $bank->getRounder(); $amount = bcmul($this->getAmount(), $rate, $rounder->getPrecision() + 1); return $bank->createMoney($rounder->round($amount, $toCurrency), $toCurrency); }
[ "public", "function", "reduce", "(", "BankInterface", "$", "bank", "=", "null", ",", "$", "toCurrency", "=", "null", ")", "{", "if", "(", "null", "===", "$", "bank", ")", "{", "$", "bank", "=", "static", "::", "getBank", "(", ")", ";", "}", "if", ...
Reduces the value of this object to the supplied currency. @param \Dough\Bank\BankInterface $bank @param string $toCurrency @return MultiCurrencyMoneyInterface @throws \InvalidArgumentException when the supplied $bank does not support currency conversion.
[ "Reduces", "the", "value", "of", "this", "object", "to", "the", "supplied", "currency", "." ]
af36775564fbaf46a8018acc4f1fd993530c1a96
https://github.com/merk/Dough/blob/af36775564fbaf46a8018acc4f1fd993530c1a96/lib/Dough/Money/MultiCurrencyMoney.php#L100-L116
train
s9e/RegexpBuilder
src/Builder.php
Builder.build
public function build(array $strings) { $strings = array_unique($strings); sort($strings); if ($this->isEmpty($strings)) { return ''; } $strings = $this->splitStrings($strings); $strings = $this->meta->replaceMeta($strings); $strings = $this->runner->run($strings); return $this->serializer->serializeStrings($strings); }
php
public function build(array $strings) { $strings = array_unique($strings); sort($strings); if ($this->isEmpty($strings)) { return ''; } $strings = $this->splitStrings($strings); $strings = $this->meta->replaceMeta($strings); $strings = $this->runner->run($strings); return $this->serializer->serializeStrings($strings); }
[ "public", "function", "build", "(", "array", "$", "strings", ")", "{", "$", "strings", "=", "array_unique", "(", "$", "strings", ")", ";", "sort", "(", "$", "strings", ")", ";", "if", "(", "$", "this", "->", "isEmpty", "(", "$", "strings", ")", ")"...
Build and return a regular expression that matches all of the given strings @param string[] $strings Literal strings to be matched @return string Regular expression (without delimiters)
[ "Build", "and", "return", "a", "regular", "expression", "that", "matches", "all", "of", "the", "given", "strings" ]
59d0167a909659d718f53964f7653d2c83a5f8fe
https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/Builder.php#L68-L82
train
mirko-pagliai/me-cms
src/View/View/AdminView.php
AdminView.render
public function render($view = null, $layout = null) { //Sets some view vars $this->set('priorities', [ '1' => sprintf('1 - %s', __d('me_cms', 'Very low')), '2' => sprintf('2 - %s', __d('me_cms', 'Low')), '3' => sprintf('3 - %s', __d('me_cms', 'Normal')), '4' => sprintf('4 - %s', __d('me_cms', 'High')), '5' => sprintf('5 - %s', __d('me_cms', 'Very high')) ]); return parent::render($view, $layout); }
php
public function render($view = null, $layout = null) { //Sets some view vars $this->set('priorities', [ '1' => sprintf('1 - %s', __d('me_cms', 'Very low')), '2' => sprintf('2 - %s', __d('me_cms', 'Low')), '3' => sprintf('3 - %s', __d('me_cms', 'Normal')), '4' => sprintf('4 - %s', __d('me_cms', 'High')), '5' => sprintf('5 - %s', __d('me_cms', 'Very high')) ]); return parent::render($view, $layout); }
[ "public", "function", "render", "(", "$", "view", "=", "null", ",", "$", "layout", "=", "null", ")", "{", "//Sets some view vars", "$", "this", "->", "set", "(", "'priorities'", ",", "[", "'1'", "=>", "sprintf", "(", "'1 - %s'", ",", "__d", "(", "'me_c...
Renders view for given template file and layout @param string|null $view Name of view file to use @param string|null $layout Layout to use @return Rendered content or null if content already rendered and returned earlier @see http://api.cakephp.org/3.4/class-Cake.View.View.html#_render
[ "Renders", "view", "for", "given", "template", "file", "and", "layout" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/View/AdminView.php#L51-L63
train
gregorybesson/PlaygroundUser
src/Service/User.php
User.updateAddress
public function updateAddress(array $data, $user) { $this->getEventManager()->trigger('updateInfo.pre', $this, array('user' => $user, 'data' => $data)); $form = $this->getServiceManager()->get('playgrounduser_address_form'); $form->bind($user); $form->setData($data); $filter = $user->getInputFilter(); $filter->remove('password'); $filter->remove('passwordVerify'); $filter->remove('dob'); $form->setInputFilter($filter); if ($form->isValid()) { $user = $this->getUserMapper()->update($user); $this->getEventManager()->trigger('updateInfo.post', $this, array('user' => $user, 'data' => $data)); if ($user) { return $user; } } return false; }
php
public function updateAddress(array $data, $user) { $this->getEventManager()->trigger('updateInfo.pre', $this, array('user' => $user, 'data' => $data)); $form = $this->getServiceManager()->get('playgrounduser_address_form'); $form->bind($user); $form->setData($data); $filter = $user->getInputFilter(); $filter->remove('password'); $filter->remove('passwordVerify'); $filter->remove('dob'); $form->setInputFilter($filter); if ($form->isValid()) { $user = $this->getUserMapper()->update($user); $this->getEventManager()->trigger('updateInfo.post', $this, array('user' => $user, 'data' => $data)); if ($user) { return $user; } } return false; }
[ "public", "function", "updateAddress", "(", "array", "$", "data", ",", "$", "user", ")", "{", "$", "this", "->", "getEventManager", "(", ")", "->", "trigger", "(", "'updateInfo.pre'", ",", "$", "this", ",", "array", "(", "'user'", "=>", "$", "user", ",...
Update user address informations @param array $data @param \PlaygroundUser\Entity\UserInterface $user
[ "Update", "user", "address", "informations" ]
b07c9969b5da1c173001fbba343f0a006d87eb8e
https://github.com/gregorybesson/PlaygroundUser/blob/b07c9969b5da1c173001fbba343f0a006d87eb8e/src/Service/User.php#L707-L732
train
gregorybesson/PlaygroundUser
src/Service/User.php
User.getCSV
public function getCSV($array) { ob_start(); // buffer the output ... $out = fopen('php://output', 'w'); fputcsv($out, array_keys($array[0]), ";"); array_shift($array); foreach ($array as $line) { fputcsv($out, $line, ";"); } fclose($out); return ob_get_clean(); // ... then return it as a string! }
php
public function getCSV($array) { ob_start(); // buffer the output ... $out = fopen('php://output', 'w'); fputcsv($out, array_keys($array[0]), ";"); array_shift($array); foreach ($array as $line) { fputcsv($out, $line, ";"); } fclose($out); return ob_get_clean(); // ... then return it as a string! }
[ "public", "function", "getCSV", "(", "$", "array", ")", "{", "ob_start", "(", ")", ";", "// buffer the output ...", "$", "out", "=", "fopen", "(", "'php://output'", ",", "'w'", ")", ";", "fputcsv", "(", "$", "out", ",", "array_keys", "(", "$", "array", ...
getCSV creates lines of CSV and returns it.
[ "getCSV", "creates", "lines", "of", "CSV", "and", "returns", "it", "." ]
b07c9969b5da1c173001fbba343f0a006d87eb8e
https://github.com/gregorybesson/PlaygroundUser/blob/b07c9969b5da1c173001fbba343f0a006d87eb8e/src/Service/User.php#L1004-L1015
train
gregorybesson/PlaygroundUser
src/Service/User.php
User.getProviderService
public function getProviderService() { if ($this->providerService == null) { $this->setProviderService($this->getServiceManager()->get('playgrounduser_provider_service')); } return $this->providerService; }
php
public function getProviderService() { if ($this->providerService == null) { $this->setProviderService($this->getServiceManager()->get('playgrounduser_provider_service')); } return $this->providerService; }
[ "public", "function", "getProviderService", "(", ")", "{", "if", "(", "$", "this", "->", "providerService", "==", "null", ")", "{", "$", "this", "->", "setProviderService", "(", "$", "this", "->", "getServiceManager", "(", ")", "->", "get", "(", "'playgrou...
retourne le service provider @return
[ "retourne", "le", "service", "provider" ]
b07c9969b5da1c173001fbba343f0a006d87eb8e
https://github.com/gregorybesson/PlaygroundUser/blob/b07c9969b5da1c173001fbba343f0a006d87eb8e/src/Service/User.php#L1189-L1196
train
mirko-pagliai/me-cms
src/Command/VersionUpdatesCommand.php
VersionUpdatesCommand.addEnableCommentsField
public function addEnableCommentsField() { Cache::clear(false, '_cake_model_'); foreach (['Pages', 'Posts'] as $table) { $Table = $this->loadModel('MeCms.' . $table); if (!$Table->getSchema()->hasColumn('enable_comments')) { $Table->getConnection()->execute(sprintf('ALTER TABLE `%s` ADD `enable_comments` BOOLEAN NOT NULL DEFAULT TRUE AFTER `preview`', $Table->getTable())); } } }
php
public function addEnableCommentsField() { Cache::clear(false, '_cake_model_'); foreach (['Pages', 'Posts'] as $table) { $Table = $this->loadModel('MeCms.' . $table); if (!$Table->getSchema()->hasColumn('enable_comments')) { $Table->getConnection()->execute(sprintf('ALTER TABLE `%s` ADD `enable_comments` BOOLEAN NOT NULL DEFAULT TRUE AFTER `preview`', $Table->getTable())); } } }
[ "public", "function", "addEnableCommentsField", "(", ")", "{", "Cache", "::", "clear", "(", "false", ",", "'_cake_model_'", ")", ";", "foreach", "(", "[", "'Pages'", ",", "'Posts'", "]", "as", "$", "table", ")", "{", "$", "Table", "=", "$", "this", "->...
Adds the `enable_comments` field to `Pages` and `Posts` tables @return void @since 2.26.3
[ "Adds", "the", "enable_comments", "field", "to", "Pages", "and", "Posts", "tables" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Command/VersionUpdatesCommand.php#L42-L53
train
mirko-pagliai/me-cms
src/Command/VersionUpdatesCommand.php
VersionUpdatesCommand.alterTagColumnSize
public function alterTagColumnSize() { $Tags = $this->loadModel('MeCms.Tags'); if ($Tags->getSchema()->getColumn('tag')['length'] < 255) { $Tags->getConnection()->execute('ALTER TABLE tags MODIFY tag varchar(255) NOT NULL'); } }
php
public function alterTagColumnSize() { $Tags = $this->loadModel('MeCms.Tags'); if ($Tags->getSchema()->getColumn('tag')['length'] < 255) { $Tags->getConnection()->execute('ALTER TABLE tags MODIFY tag varchar(255) NOT NULL'); } }
[ "public", "function", "alterTagColumnSize", "(", ")", "{", "$", "Tags", "=", "$", "this", "->", "loadModel", "(", "'MeCms.Tags'", ")", ";", "if", "(", "$", "Tags", "->", "getSchema", "(", ")", "->", "getColumn", "(", "'tag'", ")", "[", "'length'", "]",...
Alter the length of the `tag` column of the `tags` table @return void
[ "Alter", "the", "length", "of", "the", "tag", "column", "of", "the", "tags", "table" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Command/VersionUpdatesCommand.php#L59-L66
train
mirko-pagliai/me-cms
src/Command/VersionUpdatesCommand.php
VersionUpdatesCommand.execute
public function execute(Arguments $args, ConsoleIo $io) { $this->addEnableCommentsField(); $this->alterTagColumnSize(); $this->deleteOldDirectories(); return null; }
php
public function execute(Arguments $args, ConsoleIo $io) { $this->addEnableCommentsField(); $this->alterTagColumnSize(); $this->deleteOldDirectories(); return null; }
[ "public", "function", "execute", "(", "Arguments", "$", "args", ",", "ConsoleIo", "$", "io", ")", "{", "$", "this", "->", "addEnableCommentsField", "(", ")", ";", "$", "this", "->", "alterTagColumnSize", "(", ")", ";", "$", "this", "->", "deleteOldDirector...
Performs some updates to the database or files needed for versioning @param Arguments $args The command arguments @param ConsoleIo $io The console io @return null|int The exit code or null for success @uses addEnableCommentsField() @uses alterTagColumnSize() @uses deleteOldDirectories()
[ "Performs", "some", "updates", "to", "the", "database", "or", "files", "needed", "for", "versioning" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Command/VersionUpdatesCommand.php#L87-L94
train
au-research/ANDS-DOI-Service
src/Validator/XMLValidator.php
XMLValidator.getSchemaVersion
public static function getSchemaVersion($xml) { $doiXML = new \DOMDocument(); $doiXML->loadXML($xml); $resources = $doiXML->getElementsByTagName('resource'); $theSchema = 'unknown'; if ($resources->length > 0) { if (isset($resources->item(0)->attributes->item(0)->name)) { $theSchema = substr($resources->item(0)->attributes->item(0)->nodeValue, strpos($resources->item(0)->attributes->item(0)->nodeValue, "/meta/kernel") + 5); } } return $theSchema; }
php
public static function getSchemaVersion($xml) { $doiXML = new \DOMDocument(); $doiXML->loadXML($xml); $resources = $doiXML->getElementsByTagName('resource'); $theSchema = 'unknown'; if ($resources->length > 0) { if (isset($resources->item(0)->attributes->item(0)->name)) { $theSchema = substr($resources->item(0)->attributes->item(0)->nodeValue, strpos($resources->item(0)->attributes->item(0)->nodeValue, "/meta/kernel") + 5); } } return $theSchema; }
[ "public", "static", "function", "getSchemaVersion", "(", "$", "xml", ")", "{", "$", "doiXML", "=", "new", "\\", "DOMDocument", "(", ")", ";", "$", "doiXML", "->", "loadXML", "(", "$", "xml", ")", ";", "$", "resources", "=", "$", "doiXML", "->", "getE...
determines datacite xml schema version xsd @param $xml @return string
[ "determines", "datacite", "xml", "schema", "version", "xsd" ]
c8e2cc98eca23a0c550af9a45b5c5dee230da1c9
https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/Validator/XMLValidator.php#L69-L85
train
au-research/ANDS-DOI-Service
src/Validator/XMLValidator.php
XMLValidator.replaceDOIValue
public static function replaceDOIValue($doiValue, $xml) { $doiXML = new \DOMDocument(); $doiXML->loadXML($xml); // remove the current identifier $currentIdentifier = $doiXML->getElementsByTagName('identifier'); for ($i = 0; $i < $currentIdentifier->length; $i++) { $doiXML ->getElementsByTagName('resource') ->item(0) ->removeChild($currentIdentifier->item($i)); } // add new identifier to the DOM $newIdentifier = $doiXML->createElement('identifier', $doiValue); $newIdentifier->setAttribute('identifierType', "DOI"); $doiXML ->getElementsByTagName('resource') ->item(0) ->insertBefore( $newIdentifier, $doiXML->getElementsByTagName('resource')->item(0)->firstChild ); return $doiXML->saveXML(); }
php
public static function replaceDOIValue($doiValue, $xml) { $doiXML = new \DOMDocument(); $doiXML->loadXML($xml); // remove the current identifier $currentIdentifier = $doiXML->getElementsByTagName('identifier'); for ($i = 0; $i < $currentIdentifier->length; $i++) { $doiXML ->getElementsByTagName('resource') ->item(0) ->removeChild($currentIdentifier->item($i)); } // add new identifier to the DOM $newIdentifier = $doiXML->createElement('identifier', $doiValue); $newIdentifier->setAttribute('identifierType', "DOI"); $doiXML ->getElementsByTagName('resource') ->item(0) ->insertBefore( $newIdentifier, $doiXML->getElementsByTagName('resource')->item(0)->firstChild ); return $doiXML->saveXML(); }
[ "public", "static", "function", "replaceDOIValue", "(", "$", "doiValue", ",", "$", "xml", ")", "{", "$", "doiXML", "=", "new", "\\", "DOMDocument", "(", ")", ";", "$", "doiXML", "->", "loadXML", "(", "$", "xml", ")", ";", "// remove the current identifier"...
Replaces the DOI Identifier value in the provided XML @param $doiValue @param $xml @return string
[ "Replaces", "the", "DOI", "Identifier", "value", "in", "the", "provided", "XML" ]
c8e2cc98eca23a0c550af9a45b5c5dee230da1c9
https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/Validator/XMLValidator.php#L96-L122
train
au-research/ANDS-DOI-Service
src/Validator/XMLValidator.php
XMLValidator.getDOIValue
public static function getDOIValue($xml) { $doiXML = new \DOMDocument(); $doiXML->loadXML($xml); // get the current identifier $currentIdentifier = $doiXML->getElementsByTagName('identifier'); return $currentIdentifier->item(0)->nodeValue; }
php
public static function getDOIValue($xml) { $doiXML = new \DOMDocument(); $doiXML->loadXML($xml); // get the current identifier $currentIdentifier = $doiXML->getElementsByTagName('identifier'); return $currentIdentifier->item(0)->nodeValue; }
[ "public", "static", "function", "getDOIValue", "(", "$", "xml", ")", "{", "$", "doiXML", "=", "new", "\\", "DOMDocument", "(", ")", ";", "$", "doiXML", "->", "loadXML", "(", "$", "xml", ")", ";", "// get the current identifier", "$", "currentIdentifier", "...
Gets the DOI Identifier value in the provided XML @param $xml @return string
[ "Gets", "the", "DOI", "Identifier", "value", "in", "the", "provided", "XML" ]
c8e2cc98eca23a0c550af9a45b5c5dee230da1c9
https://github.com/au-research/ANDS-DOI-Service/blob/c8e2cc98eca23a0c550af9a45b5c5dee230da1c9/src/Validator/XMLValidator.php#L132-L141
train
PitonCMS/Engine
app/Controllers/AdminUserController.php
AdminUserController.showUsers
public function showUsers() { // Get dependencies $userMapper = ($this->container->dataMapper)('UserMapper'); // Fetch users $users = $userMapper->find(); return $this->render('users.html', $users); }
php
public function showUsers() { // Get dependencies $userMapper = ($this->container->dataMapper)('UserMapper'); // Fetch users $users = $userMapper->find(); return $this->render('users.html', $users); }
[ "public", "function", "showUsers", "(", ")", "{", "// Get dependencies", "$", "userMapper", "=", "(", "$", "this", "->", "container", "->", "dataMapper", ")", "(", "'UserMapper'", ")", ";", "// Fetch users", "$", "users", "=", "$", "userMapper", "->", "find"...
Show All Users
[ "Show", "All", "Users" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminUserController.php#L22-L31
train
mirko-pagliai/me-cms
src/Utility/Checkups/Plugin.php
Plugin.versions
public function versions() { $Plugin = new BasePlugin; $plugins['me_cms'] = trim(file_get_contents($Plugin->path('MeCms', 'version'))); foreach ($Plugin->all(['exclude' => 'MeCms']) as $plugin) { $file = $Plugin->path($plugin, 'version', true); $plugins['others'][$plugin] = __d('me_cms', 'n.a.'); if ($file) { $plugins['others'][$plugin] = trim(file_get_contents($file)); } } return $plugins; }
php
public function versions() { $Plugin = new BasePlugin; $plugins['me_cms'] = trim(file_get_contents($Plugin->path('MeCms', 'version'))); foreach ($Plugin->all(['exclude' => 'MeCms']) as $plugin) { $file = $Plugin->path($plugin, 'version', true); $plugins['others'][$plugin] = __d('me_cms', 'n.a.'); if ($file) { $plugins['others'][$plugin] = trim(file_get_contents($file)); } } return $plugins; }
[ "public", "function", "versions", "(", ")", "{", "$", "Plugin", "=", "new", "BasePlugin", ";", "$", "plugins", "[", "'me_cms'", "]", "=", "trim", "(", "file_get_contents", "(", "$", "Plugin", "->", "path", "(", "'MeCms'", ",", "'version'", ")", ")", ")...
Returns the version number for each plugin @return array @uses MeCms\Core\Plugin::all() @uses MeCms\Core\Plugin::path()
[ "Returns", "the", "version", "number", "for", "each", "plugin" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Utility/Checkups/Plugin.php#L30-L46
train
mirko-pagliai/me-cms
src/Utility/Checkups/AbstractCheckup.php
AbstractCheckup._isWriteable
protected function _isWriteable($paths) { foreach ((array)$paths as $path) { $result[$path] = is_writable_resursive($path); } return $result; }
php
protected function _isWriteable($paths) { foreach ((array)$paths as $path) { $result[$path] = is_writable_resursive($path); } return $result; }
[ "protected", "function", "_isWriteable", "(", "$", "paths", ")", "{", "foreach", "(", "(", "array", ")", "$", "paths", "as", "$", "path", ")", "{", "$", "result", "[", "$", "path", "]", "=", "is_writable_resursive", "(", "$", "path", ")", ";", "}", ...
Checks if each path is writeable @param array $paths Paths to check @return array Array with paths as keys and boolean as value
[ "Checks", "if", "each", "path", "is", "writeable" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Utility/Checkups/AbstractCheckup.php#L28-L35
train
yawik/settings
src/Form/Element/DisableElementsCapableFormSettings.php
DisableElementsCapableFormSettings.setForm
public function setForm($formOrContainer) { if (!$formOrContainer instanceof FormInterface && !$formOrContainer instanceof Container ) { throw new \InvalidArgumentException('Parameter must be either of type "\Zend\Form\FormInterface" or "\Core\Form\Container"'); } $this->form = $formOrContainer; $this->generateCheckboxes(); return $this; }
php
public function setForm($formOrContainer) { if (!$formOrContainer instanceof FormInterface && !$formOrContainer instanceof Container ) { throw new \InvalidArgumentException('Parameter must be either of type "\Zend\Form\FormInterface" or "\Core\Form\Container"'); } $this->form = $formOrContainer; $this->generateCheckboxes(); return $this; }
[ "public", "function", "setForm", "(", "$", "formOrContainer", ")", "{", "if", "(", "!", "$", "formOrContainer", "instanceof", "FormInterface", "&&", "!", "$", "formOrContainer", "instanceof", "Container", ")", "{", "throw", "new", "\\", "InvalidArgumentException",...
Sets the target form or form container. @param \Zend\Form\FormInterface|\Core\Form\Container $formOrContainer @return self @throws \InvalidArgumentException if invalid form type is passed.
[ "Sets", "the", "target", "form", "or", "form", "container", "." ]
fc49d14a5eec21fcc074ce29b1428d91191efecf
https://github.com/yawik/settings/blob/fc49d14a5eec21fcc074ce29b1428d91191efecf/src/Form/Element/DisableElementsCapableFormSettings.php#L148-L160
train
yawik/settings
src/Form/Element/DisableElementsCapableFormSettings.php
DisableElementsCapableFormSettings.prepareCheckboxes
protected function prepareCheckboxes(array $boxes, $prefix) { foreach ($boxes as $box) { if (is_array($box)) { $this->prepareCheckboxes($box, $prefix); } else { /* @var $box Checkbox */ $box->setName($prefix . $box->getName()); } } }
php
protected function prepareCheckboxes(array $boxes, $prefix) { foreach ($boxes as $box) { if (is_array($box)) { $this->prepareCheckboxes($box, $prefix); } else { /* @var $box Checkbox */ $box->setName($prefix . $box->getName()); } } }
[ "protected", "function", "prepareCheckboxes", "(", "array", "$", "boxes", ",", "$", "prefix", ")", "{", "foreach", "(", "$", "boxes", "as", "$", "box", ")", "{", "if", "(", "is_array", "(", "$", "box", ")", ")", "{", "$", "this", "->", "prepareCheckb...
Prepares the checkboxes prior to the rendering. @internal This method is called recursivly for each array level. @param array $boxes @param $prefix
[ "Prepares", "the", "checkboxes", "prior", "to", "the", "rendering", "." ]
fc49d14a5eec21fcc074ce29b1428d91191efecf
https://github.com/yawik/settings/blob/fc49d14a5eec21fcc074ce29b1428d91191efecf/src/Form/Element/DisableElementsCapableFormSettings.php#L190-L200
train
yawik/settings
src/Form/Element/DisableElementsCapableFormSettings.php
DisableElementsCapableFormSettings.createCheckbox
protected function createCheckbox($name, $options) { $box = new Checkbox($name, $options); $box->setAttribute('checked', true) ->setAttribute( 'id', preg_replace( array('~\[~', '~\]~', '~--+~', '~-$~'), array('-', '', '-', ''), $name ) ); return $box; }
php
protected function createCheckbox($name, $options) { $box = new Checkbox($name, $options); $box->setAttribute('checked', true) ->setAttribute( 'id', preg_replace( array('~\[~', '~\]~', '~--+~', '~-$~'), array('-', '', '-', ''), $name ) ); return $box; }
[ "protected", "function", "createCheckbox", "(", "$", "name", ",", "$", "options", ")", "{", "$", "box", "=", "new", "Checkbox", "(", "$", "name", ",", "$", "options", ")", ";", "$", "box", "->", "setAttribute", "(", "'checked'", ",", "true", ")", "->...
Creates a toggle checkbox. @param string $name @param array $options @return Checkbox
[ "Creates", "a", "toggle", "checkbox", "." ]
fc49d14a5eec21fcc074ce29b1428d91191efecf
https://github.com/yawik/settings/blob/fc49d14a5eec21fcc074ce29b1428d91191efecf/src/Form/Element/DisableElementsCapableFormSettings.php#L273-L287
train
mirko-pagliai/me-cms
src/View/Helper/MenuBuilderHelper.php
MenuBuilderHelper.buildLinks
protected function buildLinks($links, array $linksOptions = []) { return array_map(function ($link) use ($linksOptions) { return $this->Html->link($link[0], $link[1], $linksOptions); }, $links); }
php
protected function buildLinks($links, array $linksOptions = []) { return array_map(function ($link) use ($linksOptions) { return $this->Html->link($link[0], $link[1], $linksOptions); }, $links); }
[ "protected", "function", "buildLinks", "(", "$", "links", ",", "array", "$", "linksOptions", "=", "[", "]", ")", "{", "return", "array_map", "(", "function", "(", "$", "link", ")", "use", "(", "$", "linksOptions", ")", "{", "return", "$", "this", "->",...
Internal method to build links, converting them from array to html @param array $links Array of links parameters @param array $linksOptions Array of options and HTML attributes @return array
[ "Internal", "method", "to", "build", "links", "converting", "them", "from", "array", "to", "html" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/Helper/MenuBuilderHelper.php#L40-L45
train
mirko-pagliai/me-cms
src/View/Helper/MenuBuilderHelper.php
MenuBuilderHelper.getMenuMethods
protected function getMenuMethods($plugin) { //Gets all methods from `$PLUGIN\View\Helper\MenuHelper` $methods = get_child_methods(sprintf('\%s\View\Helper\MenuHelper', $plugin)); //Filters invalid name methods and returns return $methods ? array_values(preg_grep('/^(?!_).+$/', $methods)) : []; }
php
protected function getMenuMethods($plugin) { //Gets all methods from `$PLUGIN\View\Helper\MenuHelper` $methods = get_child_methods(sprintf('\%s\View\Helper\MenuHelper', $plugin)); //Filters invalid name methods and returns return $methods ? array_values(preg_grep('/^(?!_).+$/', $methods)) : []; }
[ "protected", "function", "getMenuMethods", "(", "$", "plugin", ")", "{", "//Gets all methods from `$PLUGIN\\View\\Helper\\MenuHelper`", "$", "methods", "=", "get_child_methods", "(", "sprintf", "(", "'\\%s\\View\\Helper\\MenuHelper'", ",", "$", "plugin", ")", ")", ";", ...
Internal method to get all menu methods names from a plugin @param string $plugin Plugin name @return array
[ "Internal", "method", "to", "get", "all", "menu", "methods", "names", "from", "a", "plugin" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/Helper/MenuBuilderHelper.php#L52-L59
train
mirko-pagliai/me-cms
src/View/Helper/MenuBuilderHelper.php
MenuBuilderHelper.generate
public function generate($plugin) { //Gets all menu name methods $methods = $this->getMenuMethods($plugin); if (empty($methods)) { return []; } $className = sprintf('%s.Menu', $plugin); //Loads the helper $helper = $this->_View->loadHelper($className, compact('className')); $menus = []; //Calls dynamically each method foreach ($methods as $method) { list($links, $title, $titleOptions) = call_user_func([$helper, $method]); if (empty($links) || empty($title)) { continue; } $menus[sprintf('%s.%s', $plugin, $method)] = compact('links', 'title', 'titleOptions'); } return $menus; }
php
public function generate($plugin) { //Gets all menu name methods $methods = $this->getMenuMethods($plugin); if (empty($methods)) { return []; } $className = sprintf('%s.Menu', $plugin); //Loads the helper $helper = $this->_View->loadHelper($className, compact('className')); $menus = []; //Calls dynamically each method foreach ($methods as $method) { list($links, $title, $titleOptions) = call_user_func([$helper, $method]); if (empty($links) || empty($title)) { continue; } $menus[sprintf('%s.%s', $plugin, $method)] = compact('links', 'title', 'titleOptions'); } return $menus; }
[ "public", "function", "generate", "(", "$", "plugin", ")", "{", "//Gets all menu name methods", "$", "methods", "=", "$", "this", "->", "getMenuMethods", "(", "$", "plugin", ")", ";", "if", "(", "empty", "(", "$", "methods", ")", ")", "{", "return", "[",...
Generates all menus for a plugin @param string $plugin Plugin name @return string|null Html code @uses getMenuMethods()
[ "Generates", "all", "menus", "for", "a", "plugin" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/Helper/MenuBuilderHelper.php#L67-L95
train
mirko-pagliai/me-cms
src/View/Helper/MenuBuilderHelper.php
MenuBuilderHelper.renderAsCollapse
public function renderAsCollapse($plugin) { return implode(PHP_EOL, array_map(function ($menu) { //Sets the collapse name $collapseName = 'collapse-' . strtolower(Text::slug($menu['title'])); $titleOptions = optionsParser($menu['titleOptions'], [ 'aria-controls' => $collapseName, 'aria-expanded' => 'false', 'class' => 'collapsed', 'data-toggle' => 'collapse', ]); $mainLink = $this->Html->link($menu['title'], '#' . $collapseName, $titleOptions->toArray()); $links = $this->Html->div('collapse', $this->buildLinks($menu['links']), ['id' => $collapseName]); return $this->Html->div('card', $mainLink . PHP_EOL . $links); }, $this->generate($plugin))); }
php
public function renderAsCollapse($plugin) { return implode(PHP_EOL, array_map(function ($menu) { //Sets the collapse name $collapseName = 'collapse-' . strtolower(Text::slug($menu['title'])); $titleOptions = optionsParser($menu['titleOptions'], [ 'aria-controls' => $collapseName, 'aria-expanded' => 'false', 'class' => 'collapsed', 'data-toggle' => 'collapse', ]); $mainLink = $this->Html->link($menu['title'], '#' . $collapseName, $titleOptions->toArray()); $links = $this->Html->div('collapse', $this->buildLinks($menu['links']), ['id' => $collapseName]); return $this->Html->div('card', $mainLink . PHP_EOL . $links); }, $this->generate($plugin))); }
[ "public", "function", "renderAsCollapse", "(", "$", "plugin", ")", "{", "return", "implode", "(", "PHP_EOL", ",", "array_map", "(", "function", "(", "$", "menu", ")", "{", "//Sets the collapse name", "$", "collapseName", "=", "'collapse-'", ".", "strtolower", ...
Renders a menu as "collapse" @param string $plugin Plugin name @return string @uses buildLinks() @uses generate()
[ "Renders", "a", "menu", "as", "collapse" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/Helper/MenuBuilderHelper.php#L104-L120
train
mirko-pagliai/me-cms
src/View/Helper/MenuBuilderHelper.php
MenuBuilderHelper.renderAsDropdown
public function renderAsDropdown($plugin, array $titleOptions = []) { return array_map(function ($menu) use ($titleOptions) { $titleOptions = optionsParser($menu['titleOptions'], $titleOptions); $links = $this->buildLinks($menu['links'], ['class' => 'dropdown-item']); return $this->Dropdown->menu($menu['title'], $links, $titleOptions->toArray()); }, $this->generate($plugin)); }
php
public function renderAsDropdown($plugin, array $titleOptions = []) { return array_map(function ($menu) use ($titleOptions) { $titleOptions = optionsParser($menu['titleOptions'], $titleOptions); $links = $this->buildLinks($menu['links'], ['class' => 'dropdown-item']); return $this->Dropdown->menu($menu['title'], $links, $titleOptions->toArray()); }, $this->generate($plugin)); }
[ "public", "function", "renderAsDropdown", "(", "$", "plugin", ",", "array", "$", "titleOptions", "=", "[", "]", ")", "{", "return", "array_map", "(", "function", "(", "$", "menu", ")", "use", "(", "$", "titleOptions", ")", "{", "$", "titleOptions", "=", ...
Renders a menu as "dropdown" @param string $plugin Plugin name @param array $titleOptions HTML attributes of the title @return array @uses buildLinks() @uses generate()
[ "Renders", "a", "menu", "as", "dropdown" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/View/Helper/MenuBuilderHelper.php#L130-L138
train
PitonCMS/Engine
app/Controllers/FrontBaseController.php
FrontBaseController.buildElementsByBlock
protected function buildElementsByBlock($elements) { if (empty($elements)) { return $elements; } $output = []; foreach ($elements as $element) { $output[$element->block_key][] = $element; } return $output; }
php
protected function buildElementsByBlock($elements) { if (empty($elements)) { return $elements; } $output = []; foreach ($elements as $element) { $output[$element->block_key][] = $element; } return $output; }
[ "protected", "function", "buildElementsByBlock", "(", "$", "elements", ")", "{", "if", "(", "empty", "(", "$", "elements", ")", ")", "{", "return", "$", "elements", ";", "}", "$", "output", "=", "[", "]", ";", "foreach", "(", "$", "elements", "as", "...
Build Page Elements by Block Takes array of page elements and changes keys to use block->key as array keys @param array $elements Array of page element domain models @return array
[ "Build", "Page", "Elements", "by", "Block" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/FrontBaseController.php#L37-L49
train
PitonCMS/Engine
app/Controllers/FrontBaseController.php
FrontBaseController.buildPageSettings
protected function buildPageSettings($settings) { if (empty($settings)) { return $settings; } $output = []; foreach ($settings as $setting) { $output[$setting->setting_key] = $setting->setting_value; } return $output; }
php
protected function buildPageSettings($settings) { if (empty($settings)) { return $settings; } $output = []; foreach ($settings as $setting) { $output[$setting->setting_key] = $setting->setting_value; } return $output; }
[ "protected", "function", "buildPageSettings", "(", "$", "settings", ")", "{", "if", "(", "empty", "(", "$", "settings", ")", ")", "{", "return", "$", "settings", ";", "}", "$", "output", "=", "[", "]", ";", "foreach", "(", "$", "settings", "as", "$",...
Build Page Settings Takes array of page settings and changes keys to use setting->key as array keys @param array $settings Array of page settings @return array
[ "Build", "Page", "Settings" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/FrontBaseController.php#L58-L70
train
PitonCMS/Engine
app/Library/Handlers/Email.php
Email.setFrom
public function setFrom($address, $name = null) : EmailInterface { // When using mail/sendmail, we need to set the PHPMailer "auto" flag to false // https://github.com/PHPMailer/PHPMailer/issues/1634 $this->mailer->setFrom($address, $name, false); return $this; }
php
public function setFrom($address, $name = null) : EmailInterface { // When using mail/sendmail, we need to set the PHPMailer "auto" flag to false // https://github.com/PHPMailer/PHPMailer/issues/1634 $this->mailer->setFrom($address, $name, false); return $this; }
[ "public", "function", "setFrom", "(", "$", "address", ",", "$", "name", "=", "null", ")", ":", "EmailInterface", "{", "// When using mail/sendmail, we need to set the PHPMailer \"auto\" flag to false", "// https://github.com/PHPMailer/PHPMailer/issues/1634", "$", "this", "->", ...
Set From Address @param string $address From email address @param string $name Sender name, optional @return object $this EmailInterface
[ "Set", "From", "Address" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Handlers/Email.php#L68-L75
train
PitonCMS/Engine
app/Library/Handlers/Email.php
Email.setTo
public function setTo($address, $name = null) : EmailInterface { $this->mailer->addAddress($address, $name); return $this; }
php
public function setTo($address, $name = null) : EmailInterface { $this->mailer->addAddress($address, $name); return $this; }
[ "public", "function", "setTo", "(", "$", "address", ",", "$", "name", "=", "null", ")", ":", "EmailInterface", "{", "$", "this", "->", "mailer", "->", "addAddress", "(", "$", "address", ",", "$", "name", ")", ";", "return", "$", "this", ";", "}" ]
Set Recipient To Address Can be called multiple times to add additional recipients @param string $address To email address @param string $name Recipient name, optiona @return object $this EmailInterface
[ "Set", "Recipient", "To", "Address" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Handlers/Email.php#L85-L90
train
PitonCMS/Engine
app/Controllers/AdminBaseController.php
AdminBaseController.mergeSettings
public function mergeSettings(array $savedSettings, array $definedSettings) { // Test if the saved settings are for site or page. Only site settings have the category key $pageSetting = isset($savedSettings[0]->category) ? false : true; // Make index of saved setting keys to setting array for easy lookup $settingIndex = array_combine(array_column($savedSettings, 'setting_key'), array_keys($savedSettings)); // Loop through defined settings and update with saved values and meta info foreach ($definedSettings as $defKey => $setting) { if (isset($settingIndex[$setting->key])) { $definedSettings[$defKey]->id = $savedSettings[$settingIndex[$setting->key]]->id; $definedSettings[$defKey]->setting_value = $savedSettings[$settingIndex[$setting->key]]->setting_value; $definedSettings[$defKey]->created_by = $savedSettings[$settingIndex[$setting->key]]->created_by; $definedSettings[$defKey]->created_date = $savedSettings[$settingIndex[$setting->key]]->created_date; $definedSettings[$defKey]->updated_by = $savedSettings[$settingIndex[$setting->key]]->updated_by; $definedSettings[$defKey]->updated_date = $savedSettings[$settingIndex[$setting->key]]->updated_date; // Remove saved setting from array parameter now that we have updated the setting definition unset($savedSettings[$settingIndex[$setting->key]]); } else { // If a matching saved setting was NOT found, then set default value $definedSettings[$defKey]->setting_value = $definedSettings[$defKey]->value; } // Amend setting keys to what is expected in template $definedSettings[$defKey]->setting_key = $setting->key; $definedSettings[$defKey]->input_type = $definedSettings[$defKey]->inputType; // Include select options array if ($definedSettings[$defKey]->inputType === 'select') { $definedSettings[$defKey]->options = array_column($definedSettings[$defKey]->options, 'name', 'value'); } // Add setting catagory. Not needed for page settings, but not in the way either $definedSettings[$defKey]->category = 'custom'; // Remove JSON keys to avoid confusion in template unset($definedSettings[$defKey]->key); unset($definedSettings[$defKey]->value); unset($definedSettings[$defKey]->inputType); } // Check remaining saved settings for orphaned settings. array_walk($savedSettings, function(&$row) use ($pageSetting) { if ($pageSetting || (isset($row->category) && $row->category === 'custom')) { $row->orphaned = true; } }); // Append defined settings to end of saved settings array and return return array_merge($savedSettings, $definedSettings); }
php
public function mergeSettings(array $savedSettings, array $definedSettings) { // Test if the saved settings are for site or page. Only site settings have the category key $pageSetting = isset($savedSettings[0]->category) ? false : true; // Make index of saved setting keys to setting array for easy lookup $settingIndex = array_combine(array_column($savedSettings, 'setting_key'), array_keys($savedSettings)); // Loop through defined settings and update with saved values and meta info foreach ($definedSettings as $defKey => $setting) { if (isset($settingIndex[$setting->key])) { $definedSettings[$defKey]->id = $savedSettings[$settingIndex[$setting->key]]->id; $definedSettings[$defKey]->setting_value = $savedSettings[$settingIndex[$setting->key]]->setting_value; $definedSettings[$defKey]->created_by = $savedSettings[$settingIndex[$setting->key]]->created_by; $definedSettings[$defKey]->created_date = $savedSettings[$settingIndex[$setting->key]]->created_date; $definedSettings[$defKey]->updated_by = $savedSettings[$settingIndex[$setting->key]]->updated_by; $definedSettings[$defKey]->updated_date = $savedSettings[$settingIndex[$setting->key]]->updated_date; // Remove saved setting from array parameter now that we have updated the setting definition unset($savedSettings[$settingIndex[$setting->key]]); } else { // If a matching saved setting was NOT found, then set default value $definedSettings[$defKey]->setting_value = $definedSettings[$defKey]->value; } // Amend setting keys to what is expected in template $definedSettings[$defKey]->setting_key = $setting->key; $definedSettings[$defKey]->input_type = $definedSettings[$defKey]->inputType; // Include select options array if ($definedSettings[$defKey]->inputType === 'select') { $definedSettings[$defKey]->options = array_column($definedSettings[$defKey]->options, 'name', 'value'); } // Add setting catagory. Not needed for page settings, but not in the way either $definedSettings[$defKey]->category = 'custom'; // Remove JSON keys to avoid confusion in template unset($definedSettings[$defKey]->key); unset($definedSettings[$defKey]->value); unset($definedSettings[$defKey]->inputType); } // Check remaining saved settings for orphaned settings. array_walk($savedSettings, function(&$row) use ($pageSetting) { if ($pageSetting || (isset($row->category) && $row->category === 'custom')) { $row->orphaned = true; } }); // Append defined settings to end of saved settings array and return return array_merge($savedSettings, $definedSettings); }
[ "public", "function", "mergeSettings", "(", "array", "$", "savedSettings", ",", "array", "$", "definedSettings", ")", "{", "// Test if the saved settings are for site or page. Only site settings have the category key", "$", "pageSetting", "=", "isset", "(", "$", "savedSetting...
Merge Saved Settings with Defined Settings Merge saved settings with those from page JSON definition file @param array $savedSettings Saved settings array @param array $definedSettings Defined settings in JSON definition file @return array
[ "Merge", "Saved", "Settings", "with", "Defined", "Settings" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminBaseController.php#L78-L130
train
PitonCMS/Engine
app/Controllers/AdminBaseController.php
AdminBaseController.getPageTemplates
public function getPageTemplates(string $templateType = null) { $toolbox = $this->container->toolbox; $json = $this->container->json; // Validate inputs if ($templateType !== null && !in_array($templateType, ['page','collection'])) { throw new Exception("PitonCMS Unexpected $templateType paramter. Expecting 'page' or 'collection'"); } $jsonPath = ROOT_DIR . "structure/definitions/pages/"; $templates = []; foreach ($toolbox->getDirectoryFiles($jsonPath) as $row) { // Get definition files if (null === $definition = $json->getJson($jsonPath . $row['filename'], 'page')) { $this->setAlert('danger', 'Page JSON Definition Error', $json->getErrorMessages()); break; } if ($templateType !== null && $definition->templateType !== $templateType) { continue; } $templates[] = [ 'filename' => $row['filename'], 'name' => $definition->templateName, 'description' => $definition->templateDescription ]; } return $templates; }
php
public function getPageTemplates(string $templateType = null) { $toolbox = $this->container->toolbox; $json = $this->container->json; // Validate inputs if ($templateType !== null && !in_array($templateType, ['page','collection'])) { throw new Exception("PitonCMS Unexpected $templateType paramter. Expecting 'page' or 'collection'"); } $jsonPath = ROOT_DIR . "structure/definitions/pages/"; $templates = []; foreach ($toolbox->getDirectoryFiles($jsonPath) as $row) { // Get definition files if (null === $definition = $json->getJson($jsonPath . $row['filename'], 'page')) { $this->setAlert('danger', 'Page JSON Definition Error', $json->getErrorMessages()); break; } if ($templateType !== null && $definition->templateType !== $templateType) { continue; } $templates[] = [ 'filename' => $row['filename'], 'name' => $definition->templateName, 'description' => $definition->templateDescription ]; } return $templates; }
[ "public", "function", "getPageTemplates", "(", "string", "$", "templateType", "=", "null", ")", "{", "$", "toolbox", "=", "$", "this", "->", "container", "->", "toolbox", ";", "$", "json", "=", "$", "this", "->", "container", "->", "json", ";", "// Valid...
Get Page or Collection Templates Get available templates from JSON files. If no param is provided, then all templates are returned @param string $templateType 'page' | 'collection' | null @return array Array of page templates
[ "Get", "Page", "or", "Collection", "Templates" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminBaseController.php#L139-L171
train
PitonCMS/Engine
app/Library/Twig/Admin.php
Admin.getThemes
public function getThemes() { $json = $this->container->json; if (null === $definition = $json->getJson(ROOT_DIR . 'structure/definitions/themes.json', 'themes')) { throw new Exception('PitonCMS: Get themes exception: ' . implode($json->getErrorMessages(), ',')); } return array_column($definition->themes, 'name', 'value'); }
php
public function getThemes() { $json = $this->container->json; if (null === $definition = $json->getJson(ROOT_DIR . 'structure/definitions/themes.json', 'themes')) { throw new Exception('PitonCMS: Get themes exception: ' . implode($json->getErrorMessages(), ',')); } return array_column($definition->themes, 'name', 'value'); }
[ "public", "function", "getThemes", "(", ")", "{", "$", "json", "=", "$", "this", "->", "container", "->", "json", ";", "if", "(", "null", "===", "$", "definition", "=", "$", "json", "->", "getJson", "(", "ROOT_DIR", ".", "'structure/definitions/themes.json...
Get Array of Themes @param none @return array
[ "Get", "Array", "of", "Themes" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Twig/Admin.php#L99-L108
train
PitonCMS/Engine
app/Library/Twig/Admin.php
Admin.getAlert
public function getAlert($context, $key = null) { $session = $this->container->sessionHandler; // Get alert notices from page context, or failing that then session flash data $alert = (isset($context['alert'])) ? $context['alert'] : $session->getFlashData('alert'); if ($key === null) { return $alert; } if (isset($alert[$key])) { if ($key === 'message' ) { return '<ul><li>' . implode('</li><li>', $alert['message']) . '</ul>'; } return $alert[$key]; } return null; }
php
public function getAlert($context, $key = null) { $session = $this->container->sessionHandler; // Get alert notices from page context, or failing that then session flash data $alert = (isset($context['alert'])) ? $context['alert'] : $session->getFlashData('alert'); if ($key === null) { return $alert; } if (isset($alert[$key])) { if ($key === 'message' ) { return '<ul><li>' . implode('</li><li>', $alert['message']) . '</ul>'; } return $alert[$key]; } return null; }
[ "public", "function", "getAlert", "(", "$", "context", ",", "$", "key", "=", "null", ")", "{", "$", "session", "=", "$", "this", "->", "container", "->", "sessionHandler", ";", "// Get alert notices from page context, or failing that then session flash data", "$", "...
Get Alert Messages Get alert data. Returns null if no alert found. @param array $context Twig context, includes controller alert array @param string $key Alert keys: severity|heading|message @return mixed array|string|null
[ "Get", "Alert", "Messages" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Twig/Admin.php#L130-L150
train
PitonCMS/Engine
app/Library/Twig/Admin.php
Admin.getCollections
public function getCollections() { if ($this->collections) { return $this->collections; } $collectionMapper = ($this->container->dataMapper)('CollectionMapper'); return $this->collections = $collectionMapper->find(); }
php
public function getCollections() { if ($this->collections) { return $this->collections; } $collectionMapper = ($this->container->dataMapper)('CollectionMapper'); return $this->collections = $collectionMapper->find(); }
[ "public", "function", "getCollections", "(", ")", "{", "if", "(", "$", "this", "->", "collections", ")", "{", "return", "$", "this", "->", "collections", ";", "}", "$", "collectionMapper", "=", "(", "$", "this", "->", "container", "->", "dataMapper", ")"...
Get Collection Options Get all collection summary rows @param void @return mixed Array | null
[ "Get", "Collection", "Options" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Twig/Admin.php#L184-L193
train
PitonCMS/Engine
app/Library/Twig/Admin.php
Admin.getGalleries
public function getGalleries() { if ($this->galleries) { return $this->galleries; } $mediaCategoryMapper = ($this->container->dataMapper)('MediaCategoryMapper'); return $this->galleries = $mediaCategoryMapper->findCategories(); }
php
public function getGalleries() { if ($this->galleries) { return $this->galleries; } $mediaCategoryMapper = ($this->container->dataMapper)('MediaCategoryMapper'); return $this->galleries = $mediaCategoryMapper->findCategories(); }
[ "public", "function", "getGalleries", "(", ")", "{", "if", "(", "$", "this", "->", "galleries", ")", "{", "return", "$", "this", "->", "galleries", ";", "}", "$", "mediaCategoryMapper", "=", "(", "$", "this", "->", "container", "->", "dataMapper", ")", ...
Get Gallery Options Get all gallery media categories @param void @return mixed Array | null
[ "Get", "Gallery", "Options" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Twig/Admin.php#L202-L211
train
PitonCMS/Engine
app/Library/Twig/Admin.php
Admin.getUnreadMessageCount
public function getUnreadMessageCount() { $messageMapper = ($this->container->dataMapper)('MessageMapper'); $count = $messageMapper->findUnreadCount(); return ($count === 0) ? null : $count; }
php
public function getUnreadMessageCount() { $messageMapper = ($this->container->dataMapper)('MessageMapper'); $count = $messageMapper->findUnreadCount(); return ($count === 0) ? null : $count; }
[ "public", "function", "getUnreadMessageCount", "(", ")", "{", "$", "messageMapper", "=", "(", "$", "this", "->", "container", "->", "dataMapper", ")", "(", "'MessageMapper'", ")", ";", "$", "count", "=", "$", "messageMapper", "->", "findUnreadCount", "(", ")...
Get Unread Message Count Gets count of unread messages @param void @return mixed
[ "Get", "Unread", "Message", "Count" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Library/Twig/Admin.php#L252-L258
train
flipboxfactory/craft-integration
src/services/IntegrationCache.php
IntegrationCache.loadOverrides
protected function loadOverrides() { if ($this->overrides === null) { $this->overrides = []; if ($this->overrideFile !== null) { $this->overrides = Craft::$app->getConfig()->getConfigFromFile($this->overrideFile); } } }
php
protected function loadOverrides() { if ($this->overrides === null) { $this->overrides = []; if ($this->overrideFile !== null) { $this->overrides = Craft::$app->getConfig()->getConfigFromFile($this->overrideFile); } } }
[ "protected", "function", "loadOverrides", "(", ")", "{", "if", "(", "$", "this", "->", "overrides", "===", "null", ")", "{", "$", "this", "->", "overrides", "=", "[", "]", ";", "if", "(", "$", "this", "->", "overrideFile", "!==", "null", ")", "{", ...
Load override cache configurations
[ "Load", "override", "cache", "configurations" ]
ec19fc1b78a8f6e726fc75156924f548351e6b71
https://github.com/flipboxfactory/craft-integration/blob/ec19fc1b78a8f6e726fc75156924f548351e6b71/src/services/IntegrationCache.php#L84-L93
train
mirko-pagliai/me-cms
src/Mailer/ContactUsMailer.php
ContactUsMailer.contactUsMail
public function contactUsMail($data) { //Checks that all required data is present key_exists_or_fail(['email', 'first_name', 'last_name', 'message'], $data); $this->viewBuilder()->setTemplate('MeCms.Systems/contact_us'); $this->setSender($data['email'], sprintf('%s %s', $data['first_name'], $data['last_name'])) ->setReplyTo($data['email'], sprintf('%s %s', $data['first_name'], $data['last_name'])) ->setTo(getConfigOrFail('email.webmaster')) ->setSubject(__d('me_cms', 'Email from {0}', getConfigOrFail('main.title'))) ->setViewVars([ 'email' => $data['email'], 'firstName' => $data['first_name'], 'lastName' => $data['last_name'], 'message' => $data['message'], ]); }
php
public function contactUsMail($data) { //Checks that all required data is present key_exists_or_fail(['email', 'first_name', 'last_name', 'message'], $data); $this->viewBuilder()->setTemplate('MeCms.Systems/contact_us'); $this->setSender($data['email'], sprintf('%s %s', $data['first_name'], $data['last_name'])) ->setReplyTo($data['email'], sprintf('%s %s', $data['first_name'], $data['last_name'])) ->setTo(getConfigOrFail('email.webmaster')) ->setSubject(__d('me_cms', 'Email from {0}', getConfigOrFail('main.title'))) ->setViewVars([ 'email' => $data['email'], 'firstName' => $data['first_name'], 'lastName' => $data['last_name'], 'message' => $data['message'], ]); }
[ "public", "function", "contactUsMail", "(", "$", "data", ")", "{", "//Checks that all required data is present", "key_exists_or_fail", "(", "[", "'email'", ",", "'first_name'", ",", "'last_name'", ",", "'message'", "]", ",", "$", "data", ")", ";", "$", "this", "...
Email for the "contact us" form. The `$data` array must contain the `email`, `first_name`, `last_name` and `message` keys. @param array $data Form data @return void
[ "Email", "for", "the", "contact", "us", "form", "." ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Mailer/ContactUsMailer.php#L32-L48
train
PitonCMS/Engine
app/Controllers/AdminCollectionController.php
AdminCollectionController.showCollections
public function showCollections() { // Get dependencies $collectionMapper = ($this->container->dataMapper)('CollectionMapper'); $pageMapper = ($this->container->dataMapper)('PageMapper'); // Fetch collection pages, and chuck pages into sub-array by collection ID with meta info $collectionPages = $pageMapper->findCollectionPages(); foreach ($collectionPages as $col) { if (!isset($data['collectionPages'][$col->collection_id])) { $data['collectionPages'][$col->collection_id]['collection_id'] = $col->collection_id; $data['collectionPages'][$col->collection_id]['collection_title'] = $col->collection_title; $data['collectionPages'][$col->collection_id]['collection_slug'] = $col->collection_slug; } $data['collectionPages'][$col->collection_id]['pages'][] = $col; } // Get available templates and collection groups $data['templates'] = $this->getPageTemplates('collection'); $data['collections'] = $collectionMapper->find(); // Enrich collections array with matching description from templates array $templateArray = array_column($data['templates'], 'filename'); array_walk($data['collections'], function (&$collect) use ($data, $templateArray) { // Find matching collection template key for reference in $templateArray $key = array_search($collect->definition, $templateArray); $collect->templateName = $data['templates'][$key]['name']; $collect->templateDescription = $data['templates'][$key]['description']; }); return $this->render('collections.html', $data); }
php
public function showCollections() { // Get dependencies $collectionMapper = ($this->container->dataMapper)('CollectionMapper'); $pageMapper = ($this->container->dataMapper)('PageMapper'); // Fetch collection pages, and chuck pages into sub-array by collection ID with meta info $collectionPages = $pageMapper->findCollectionPages(); foreach ($collectionPages as $col) { if (!isset($data['collectionPages'][$col->collection_id])) { $data['collectionPages'][$col->collection_id]['collection_id'] = $col->collection_id; $data['collectionPages'][$col->collection_id]['collection_title'] = $col->collection_title; $data['collectionPages'][$col->collection_id]['collection_slug'] = $col->collection_slug; } $data['collectionPages'][$col->collection_id]['pages'][] = $col; } // Get available templates and collection groups $data['templates'] = $this->getPageTemplates('collection'); $data['collections'] = $collectionMapper->find(); // Enrich collections array with matching description from templates array $templateArray = array_column($data['templates'], 'filename'); array_walk($data['collections'], function (&$collect) use ($data, $templateArray) { // Find matching collection template key for reference in $templateArray $key = array_search($collect->definition, $templateArray); $collect->templateName = $data['templates'][$key]['name']; $collect->templateDescription = $data['templates'][$key]['description']; }); return $this->render('collections.html', $data); }
[ "public", "function", "showCollections", "(", ")", "{", "// Get dependencies", "$", "collectionMapper", "=", "(", "$", "this", "->", "container", "->", "dataMapper", ")", "(", "'CollectionMapper'", ")", ";", "$", "pageMapper", "=", "(", "$", "this", "->", "c...
Show Collections and Collection Pages Show all collection groups, collection templates, and collection pages
[ "Show", "Collections", "and", "Collection", "Pages" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminCollectionController.php#L21-L53
train
PitonCMS/Engine
app/Controllers/AdminCollectionController.php
AdminCollectionController.editCollection
public function editCollection($args) { // Get dependencies $collectionMapper = ($this->container->dataMapper)('CollectionMapper'); $json = $this->container->json; $toolbox = $this->container->toolbox; // Fetch collection group, or create new collection group if (isset($args['id']) && is_numeric($args['id'])) { $collection = $collectionMapper->findById($args['id']); } else { $definionParam = $this->request->getQueryParam('definition'); // Validate that we have a proper definition file name if (null === $definionParam || 1 !== preg_match('/^[a-zA-Z0-9]+\.json$/', $definionParam)) { throw new Exception("PitonCMS: Invalid query parameter for 'definition': $definionParam"); } // Create new collection and set template JSON file $collection = $collectionMapper->make(); $collection->definition = $definionParam; } return $this->render('editCollection.html', $collection); }
php
public function editCollection($args) { // Get dependencies $collectionMapper = ($this->container->dataMapper)('CollectionMapper'); $json = $this->container->json; $toolbox = $this->container->toolbox; // Fetch collection group, or create new collection group if (isset($args['id']) && is_numeric($args['id'])) { $collection = $collectionMapper->findById($args['id']); } else { $definionParam = $this->request->getQueryParam('definition'); // Validate that we have a proper definition file name if (null === $definionParam || 1 !== preg_match('/^[a-zA-Z0-9]+\.json$/', $definionParam)) { throw new Exception("PitonCMS: Invalid query parameter for 'definition': $definionParam"); } // Create new collection and set template JSON file $collection = $collectionMapper->make(); $collection->definition = $definionParam; } return $this->render('editCollection.html', $collection); }
[ "public", "function", "editCollection", "(", "$", "args", ")", "{", "// Get dependencies", "$", "collectionMapper", "=", "(", "$", "this", "->", "container", "->", "dataMapper", ")", "(", "'CollectionMapper'", ")", ";", "$", "json", "=", "$", "this", "->", ...
Edit Collection Group Create new collection group, or edit collection group
[ "Edit", "Collection", "Group" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminCollectionController.php#L60-L84
train
PitonCMS/Engine
app/Controllers/AdminCollectionController.php
AdminCollectionController.confirmDeleteCollection
public function confirmDeleteCollection($args) { // Get dependencies $collectionMapper = ($this->container->dataMapper)('CollectionMapper'); $pageMapper = ($this->container->dataMapper)('PageMapper'); $data = $collectionMapper->findById($args['id']); $data->pages = $pageMapper->findCollectionPagesById($args['id'], false); return $this->render('confirmDeleteCollection.html', $data); }
php
public function confirmDeleteCollection($args) { // Get dependencies $collectionMapper = ($this->container->dataMapper)('CollectionMapper'); $pageMapper = ($this->container->dataMapper)('PageMapper'); $data = $collectionMapper->findById($args['id']); $data->pages = $pageMapper->findCollectionPagesById($args['id'], false); return $this->render('confirmDeleteCollection.html', $data); }
[ "public", "function", "confirmDeleteCollection", "(", "$", "args", ")", "{", "// Get dependencies", "$", "collectionMapper", "=", "(", "$", "this", "->", "container", "->", "dataMapper", ")", "(", "'CollectionMapper'", ")", ";", "$", "pageMapper", "=", "(", "$...
Confirm Delete Collection Shows all pages to be deleted
[ "Confirm", "Delete", "Collection" ]
51622658cbd21946757abc27f6928cb482384659
https://github.com/PitonCMS/Engine/blob/51622658cbd21946757abc27f6928cb482384659/app/Controllers/AdminCollectionController.php#L114-L124
train
bright-components/services
src/Traits/CallsServices.php
CallsServices.call
public function call(string $service, ...$params) { return Container::getInstance()->make(ServiceCaller::class)->call($service, ...$params); }
php
public function call(string $service, ...$params) { return Container::getInstance()->make(ServiceCaller::class)->call($service, ...$params); }
[ "public", "function", "call", "(", "string", "$", "service", ",", "...", "$", "params", ")", "{", "return", "Container", "::", "getInstance", "(", ")", "->", "make", "(", "ServiceCaller", "::", "class", ")", "->", "call", "(", "$", "service", ",", "......
Call a service. @param string $service @param mixed ...$params @return mixed
[ "Call", "a", "service", "." ]
c8f1c4a578a1fc805fd36cae8d3625fd95c11cdc
https://github.com/bright-components/services/blob/c8f1c4a578a1fc805fd36cae8d3625fd95c11cdc/src/Traits/CallsServices.php#L18-L21
train
s9e/RegexpBuilder
src/Passes/AbstractPass.php
AbstractPass.beforeRun
protected function beforeRun(array $strings) { $this->isOptional = (isset($strings[0]) && $strings[0] === []); if ($this->isOptional) { array_shift($strings); } return $strings; }
php
protected function beforeRun(array $strings) { $this->isOptional = (isset($strings[0]) && $strings[0] === []); if ($this->isOptional) { array_shift($strings); } return $strings; }
[ "protected", "function", "beforeRun", "(", "array", "$", "strings", ")", "{", "$", "this", "->", "isOptional", "=", "(", "isset", "(", "$", "strings", "[", "0", "]", ")", "&&", "$", "strings", "[", "0", "]", "===", "[", "]", ")", ";", "if", "(", ...
Prepare the list of strings before the pass is run @param array[] $strings @return array[]
[ "Prepare", "the", "list", "of", "strings", "before", "the", "pass", "is", "run" ]
59d0167a909659d718f53964f7653d2c83a5f8fe
https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/Passes/AbstractPass.php#L54-L63
train
s9e/RegexpBuilder
src/Passes/AbstractPass.php
AbstractPass.isSingleCharStringList
protected function isSingleCharStringList(array $strings) { foreach ($strings as $string) { if (!$this->isSingleCharString($string)) { return false; } } return true; }
php
protected function isSingleCharStringList(array $strings) { foreach ($strings as $string) { if (!$this->isSingleCharString($string)) { return false; } } return true; }
[ "protected", "function", "isSingleCharStringList", "(", "array", "$", "strings", ")", "{", "foreach", "(", "$", "strings", "as", "$", "string", ")", "{", "if", "(", "!", "$", "this", "->", "isSingleCharString", "(", "$", "string", ")", ")", "{", "return"...
Test whether given list of strings contains nothing but single-char strings @param array[] $strings @return bool
[ "Test", "whether", "given", "list", "of", "strings", "contains", "nothing", "but", "single", "-", "char", "strings" ]
59d0167a909659d718f53964f7653d2c83a5f8fe
https://github.com/s9e/RegexpBuilder/blob/59d0167a909659d718f53964f7653d2c83a5f8fe/src/Passes/AbstractPass.php#L136-L147
train
gregorybesson/PlaygroundUser
src/Authentication/Adapter/Cookie.php
Cookie.logout
public function logout() { $authService = $this->getServiceManager()->get('zfcuser_auth_service'); $user = $authService->getIdentity(); $cookie = explode("\n", $this->getRememberMeService()->getCookie()); if ($cookie[0] !== '' && $user !== null) { $this->getRememberMeService()->removeSerie($user->getId(), $cookie[1]); $this->getRememberMeService()->removeCookie(); } }
php
public function logout() { $authService = $this->getServiceManager()->get('zfcuser_auth_service'); $user = $authService->getIdentity(); $cookie = explode("\n", $this->getRememberMeService()->getCookie()); if ($cookie[0] !== '' && $user !== null) { $this->getRememberMeService()->removeSerie($user->getId(), $cookie[1]); $this->getRememberMeService()->removeCookie(); } }
[ "public", "function", "logout", "(", ")", "{", "$", "authService", "=", "$", "this", "->", "getServiceManager", "(", ")", "->", "get", "(", "'zfcuser_auth_service'", ")", ";", "$", "user", "=", "$", "authService", "->", "getIdentity", "(", ")", ";", "$",...
Hack to use getStorage to clear cookie on logout @return Storage\StorageInterface
[ "Hack", "to", "use", "getStorage", "to", "clear", "cookie", "on", "logout" ]
b07c9969b5da1c173001fbba343f0a006d87eb8e
https://github.com/gregorybesson/PlaygroundUser/blob/b07c9969b5da1c173001fbba343f0a006d87eb8e/src/Authentication/Adapter/Cookie.php#L171-L182
train
mirko-pagliai/me-cms
src/Plugin.php
Plugin.middleware
public function middleware($middleware) { $key = Configure::read('Security.cookieKey', md5(Configure::read('Security.salt'))); return $middleware->add(new EncryptedCookieMiddleware(['login'], $key)); }
php
public function middleware($middleware) { $key = Configure::read('Security.cookieKey', md5(Configure::read('Security.salt'))); return $middleware->add(new EncryptedCookieMiddleware(['login'], $key)); }
[ "public", "function", "middleware", "(", "$", "middleware", ")", "{", "$", "key", "=", "Configure", "::", "read", "(", "'Security.cookieKey'", ",", "md5", "(", "Configure", "::", "read", "(", "'Security.salt'", ")", ")", ")", ";", "return", "$", "middlewar...
Adds middleware for the plugin @param Cake\Http\MiddlewareQueue $middleware The middleware queue to update @return Cake\Http\MiddlewareQueue @since 2.26.4
[ "Adds", "middleware", "for", "the", "plugin" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Plugin.php#L134-L139
train
mirko-pagliai/me-cms
src/Plugin.php
Plugin.setVendorLinks
protected function setVendorLinks() { $links = array_unique(array_merge(Configure::read('VENDOR_LINKS', []), [ 'npm-asset' . DS . 'js-cookie' . DS . 'src' => 'js-cookie', 'sunhater' . DS . 'kcfinder' => 'kcfinder', 'enyo' . DS . 'dropzone' . DS . 'dist' => 'dropzone', ])); return Configure::write('VENDOR_LINKS', $links) ? $links : false; }
php
protected function setVendorLinks() { $links = array_unique(array_merge(Configure::read('VENDOR_LINKS', []), [ 'npm-asset' . DS . 'js-cookie' . DS . 'src' => 'js-cookie', 'sunhater' . DS . 'kcfinder' => 'kcfinder', 'enyo' . DS . 'dropzone' . DS . 'dist' => 'dropzone', ])); return Configure::write('VENDOR_LINKS', $links) ? $links : false; }
[ "protected", "function", "setVendorLinks", "(", ")", "{", "$", "links", "=", "array_unique", "(", "array_merge", "(", "Configure", "::", "read", "(", "'VENDOR_LINKS'", ",", "[", "]", ")", ",", "[", "'npm-asset'", ".", "DS", ".", "'js-cookie'", ".", "DS", ...
Sets symbolic links for vendor assets to be created @return array
[ "Sets", "symbolic", "links", "for", "vendor", "assets", "to", "be", "created" ]
df668ad8e3ee221497c47578d474e487f24ce92a
https://github.com/mirko-pagliai/me-cms/blob/df668ad8e3ee221497c47578d474e487f24ce92a/src/Plugin.php#L145-L154
train