repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
PHPIDS/PHPIDS
lib/IDS/Filter/Storage.php
Storage.getFilterFromXML
public function getFilterFromXML() { if (extension_loaded('SimpleXML')) { /* * See if filters are already available in the cache */ $filters = $this->isCached(); /* * If they aren't, parse the source file */ if (!$filters) { if (!file_exists($this->source)) { throw new \InvalidArgumentException( sprintf('Invalid config: %s doesn\'t exist.', $this->source) ); } if (LIBXML_VERSION >= 20621) { $filters = simplexml_load_file($this->source, null, LIBXML_COMPACT); } else { $filters = simplexml_load_file($this->source); } } /* * In case we still don't have any filters loaded and exception * will be thrown */ if (empty($filters)) { throw new \RuntimeException( 'XML data could not be loaded.' . ' Make sure you specified the correct path.' ); } /* * Now the storage will be filled with IDS_Filter objects */ $nocache = $filters instanceof \SimpleXMLElement; if ($nocache) { // build filters and cache them for re-use on next run $data = array(); $filters = $filters->filter; foreach ($filters as $filter) { $id = (string) $filter->id; $rule = (string) $filter->rule; $impact = (string) $filter->impact; $tags = array_values((array) $filter->tags); $description = (string) $filter->description; $this->addFilter( new \IDS\Filter( $id, $rule, $description, (array) $tags[0], (int) $impact ) ); $data[] = array( 'id' => $id, 'rule' => $rule, 'impact' => $impact, 'tags' => $tags, 'description' => $description ); } /* * If caching is enabled, the fetched data will be cached */ if ($this->cacheSettings) { $this->cache->setCache($data); } } else { // build filters from cached content $this->addFiltersFromArray($filters); } return $this; } throw new \RuntimeException('SimpleXML is not loaded.'); }
php
public function getFilterFromXML() { if (extension_loaded('SimpleXML')) { /* * See if filters are already available in the cache */ $filters = $this->isCached(); /* * If they aren't, parse the source file */ if (!$filters) { if (!file_exists($this->source)) { throw new \InvalidArgumentException( sprintf('Invalid config: %s doesn\'t exist.', $this->source) ); } if (LIBXML_VERSION >= 20621) { $filters = simplexml_load_file($this->source, null, LIBXML_COMPACT); } else { $filters = simplexml_load_file($this->source); } } /* * In case we still don't have any filters loaded and exception * will be thrown */ if (empty($filters)) { throw new \RuntimeException( 'XML data could not be loaded.' . ' Make sure you specified the correct path.' ); } /* * Now the storage will be filled with IDS_Filter objects */ $nocache = $filters instanceof \SimpleXMLElement; if ($nocache) { // build filters and cache them for re-use on next run $data = array(); $filters = $filters->filter; foreach ($filters as $filter) { $id = (string) $filter->id; $rule = (string) $filter->rule; $impact = (string) $filter->impact; $tags = array_values((array) $filter->tags); $description = (string) $filter->description; $this->addFilter( new \IDS\Filter( $id, $rule, $description, (array) $tags[0], (int) $impact ) ); $data[] = array( 'id' => $id, 'rule' => $rule, 'impact' => $impact, 'tags' => $tags, 'description' => $description ); } /* * If caching is enabled, the fetched data will be cached */ if ($this->cacheSettings) { $this->cache->setCache($data); } } else { // build filters from cached content $this->addFiltersFromArray($filters); } return $this; } throw new \RuntimeException('SimpleXML is not loaded.'); }
[ "public", "function", "getFilterFromXML", "(", ")", "{", "if", "(", "extension_loaded", "(", "'SimpleXML'", ")", ")", "{", "/*\n * See if filters are already available in the cache\n */", "$", "filters", "=", "$", "this", "->", "isCached", "(", "...
Loads filters from XML using SimpleXML This function parses the provided source file and stores the result. If caching mode is enabled the result will be cached to increase the performance. @throws \InvalidArgumentException if source file doesn't exist @throws \RuntimeException if problems with fetching the XML data occur @return object $this
[ "Loads", "filters", "from", "XML", "using", "SimpleXML" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Filter/Storage.php#L187-L279
PHPIDS/PHPIDS
lib/IDS/Filter/Storage.php
Storage.getFilterFromJson
public function getFilterFromJson() { if (extension_loaded('Json')) { /* * See if filters are already available in the cache */ $filters = $this->isCached(); /* * If they aren't, parse the source file */ if (!$filters) { if (!file_exists($this->source)) { throw new \InvalidArgumentException( sprintf('Invalid config: %s doesn\'t exist.', $this->source) ); } $filters = json_decode(file_get_contents($this->source)); } if (!$filters) { throw new \RuntimeException('JSON data could not be loaded. Make sure you specified the correct path.'); } /* * Now the storage will be filled with IDS_Filter objects */ $nocache = !is_array($filters); if ($nocache) { // build filters and cache them for re-use on next run $data = array(); $filters = $filters->filters->filter; foreach ($filters as $filter) { $id = (string) $filter->id; $rule = (string) $filter->rule; $impact = (string) $filter->impact; $tags = array_values((array) $filter->tags); $description = (string) $filter->description; $this->addFilter( new \IDS\Filter( $id, $rule, $description, (array) $tags[0], (int) $impact ) ); $data[] = array( 'id' => $id, 'rule' => $rule, 'impact' => $impact, 'tags' => $tags, 'description' => $description ); } /* * If caching is enabled, the fetched data will be cached */ if ($this->cacheSettings) { $this->cache->setCache($data); } } else { // build filters from cached content $this->addFiltersFromArray($filters); } return $this; } throw new \RuntimeException('json extension is not loaded.'); }
php
public function getFilterFromJson() { if (extension_loaded('Json')) { /* * See if filters are already available in the cache */ $filters = $this->isCached(); /* * If they aren't, parse the source file */ if (!$filters) { if (!file_exists($this->source)) { throw new \InvalidArgumentException( sprintf('Invalid config: %s doesn\'t exist.', $this->source) ); } $filters = json_decode(file_get_contents($this->source)); } if (!$filters) { throw new \RuntimeException('JSON data could not be loaded. Make sure you specified the correct path.'); } /* * Now the storage will be filled with IDS_Filter objects */ $nocache = !is_array($filters); if ($nocache) { // build filters and cache them for re-use on next run $data = array(); $filters = $filters->filters->filter; foreach ($filters as $filter) { $id = (string) $filter->id; $rule = (string) $filter->rule; $impact = (string) $filter->impact; $tags = array_values((array) $filter->tags); $description = (string) $filter->description; $this->addFilter( new \IDS\Filter( $id, $rule, $description, (array) $tags[0], (int) $impact ) ); $data[] = array( 'id' => $id, 'rule' => $rule, 'impact' => $impact, 'tags' => $tags, 'description' => $description ); } /* * If caching is enabled, the fetched data will be cached */ if ($this->cacheSettings) { $this->cache->setCache($data); } } else { // build filters from cached content $this->addFiltersFromArray($filters); } return $this; } throw new \RuntimeException('json extension is not loaded.'); }
[ "public", "function", "getFilterFromJson", "(", ")", "{", "if", "(", "extension_loaded", "(", "'Json'", ")", ")", "{", "/*\n * See if filters are already available in the cache\n */", "$", "filters", "=", "$", "this", "->", "isCached", "(", ")", ...
Loads filters from Json file using ext/Json This function parses the provided source file and stores the result. If caching mode is enabled the result will be cached to increase the performance. @throws \RuntimeException if problems with fetching the JSON data occur @return object $this
[ "Loads", "filters", "from", "Json", "file", "using", "ext", "/", "Json" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Filter/Storage.php#L291-L372
PHPIDS/PHPIDS
lib/IDS/Filter/Storage.php
Storage.addFiltersFromArray
private function addFiltersFromArray(array $filters) { foreach ($filters as $filter) { $id = $filter['id']; $rule = $filter['rule']; $impact = $filter['impact']; $tags = $filter['tags']; $description = $filter['description']; $this->addFilter( new \IDS\Filter( $id, $rule, $description, (array) $tags[0], (int) $impact ) ); } }
php
private function addFiltersFromArray(array $filters) { foreach ($filters as $filter) { $id = $filter['id']; $rule = $filter['rule']; $impact = $filter['impact']; $tags = $filter['tags']; $description = $filter['description']; $this->addFilter( new \IDS\Filter( $id, $rule, $description, (array) $tags[0], (int) $impact ) ); } }
[ "private", "function", "addFiltersFromArray", "(", "array", "$", "filters", ")", "{", "foreach", "(", "$", "filters", "as", "$", "filter", ")", "{", "$", "id", "=", "$", "filter", "[", "'id'", "]", ";", "$", "rule", "=", "$", "filter", "[", "'rule'",...
This functions adds an array of filters to the IDS_Storage object. Each entry within the array is expected to be an simple array containing all parts of the filter. @param array $filters
[ "This", "functions", "adds", "an", "array", "of", "filters", "to", "the", "IDS_Storage", "object", ".", "Each", "entry", "within", "the", "array", "is", "expected", "to", "be", "an", "simple", "array", "containing", "all", "parts", "of", "the", "filter", "...
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Filter/Storage.php#L380-L400
PHPIDS/PHPIDS
docs/examples/cakephp/ids.php
IdsComponent.idslog
private function idslog($result, $reaction = 0) { $user = $this->controller ->Session->read('User.id') ? $this->controller->Session->read('User.id') : 0; $ip = ($_SERVER['SERVER_ADDR'] != '127.0.0.1') ? $_SERVER['SERVER_ADDR'] : (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '127.0.0.1'); foreach ($result as $event) { $data = array( 'Intrusion' => array( 'name' => $event->getName(), 'value' => stripslashes($event->getValue()), 'page' => $_SERVER['REQUEST_URI'], 'userid' => $user, 'session' => session_id() ? session_id() : '0', 'ip' => $ip, 'reaction' => $reaction, 'impact' => $result->getImpact() ) ); } loadModel('Intrusion'); $intrusion = new Intrusion; $saveable = array( 'name', 'value', 'page', 'userid', 'session', 'ip', 'reaction', 'impact' ); $intrusion->save($data, false, $saveable); return true; }
php
private function idslog($result, $reaction = 0) { $user = $this->controller ->Session->read('User.id') ? $this->controller->Session->read('User.id') : 0; $ip = ($_SERVER['SERVER_ADDR'] != '127.0.0.1') ? $_SERVER['SERVER_ADDR'] : (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '127.0.0.1'); foreach ($result as $event) { $data = array( 'Intrusion' => array( 'name' => $event->getName(), 'value' => stripslashes($event->getValue()), 'page' => $_SERVER['REQUEST_URI'], 'userid' => $user, 'session' => session_id() ? session_id() : '0', 'ip' => $ip, 'reaction' => $reaction, 'impact' => $result->getImpact() ) ); } loadModel('Intrusion'); $intrusion = new Intrusion; $saveable = array( 'name', 'value', 'page', 'userid', 'session', 'ip', 'reaction', 'impact' ); $intrusion->save($data, false, $saveable); return true; }
[ "private", "function", "idslog", "(", "$", "result", ",", "$", "reaction", "=", "0", ")", "{", "$", "user", "=", "$", "this", "->", "controller", "->", "Session", "->", "read", "(", "'User.id'", ")", "?", "$", "this", "->", "controller", "->", "Sessi...
This function writes an entry about the intrusion to the intrusion database @param array $results @return boolean
[ "This", "function", "writes", "an", "entry", "about", "the", "intrusion", "to", "the", "intrusion", "database" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/docs/examples/cakephp/ids.php#L190-L227
PHPIDS/PHPIDS
docs/examples/cakephp/ids.php
IdsComponent.idsmail
private function idsmail($result) { vendor('phpids/IDS/Log/Email.php'); vendor('phpids/IDS/Log/Composite.php'); $compositeLog = new \IDS\Log\Composite(); $compositeLog->addLogger( \IDS\Log\Email::getInstance( $this->init->config['IDS_Logging']['recipient'], $this->config['IDS_Logging']['subject'], NULL, //optional headers $this->init->config['IDS_Logging']['safemode'], $this->init->config['IDS_Logging']['allowed_rate'], $this->init->config['IDS_Basic']['tmp_path'] ) ); if (!$result->isEmpty()) { $compositeLog->execute($result); } return true; }
php
private function idsmail($result) { vendor('phpids/IDS/Log/Email.php'); vendor('phpids/IDS/Log/Composite.php'); $compositeLog = new \IDS\Log\Composite(); $compositeLog->addLogger( \IDS\Log\Email::getInstance( $this->init->config['IDS_Logging']['recipient'], $this->config['IDS_Logging']['subject'], NULL, //optional headers $this->init->config['IDS_Logging']['safemode'], $this->init->config['IDS_Logging']['allowed_rate'], $this->init->config['IDS_Basic']['tmp_path'] ) ); if (!$result->isEmpty()) { $compositeLog->execute($result); } return true; }
[ "private", "function", "idsmail", "(", "$", "result", ")", "{", "vendor", "(", "'phpids/IDS/Log/Email.php'", ")", ";", "vendor", "(", "'phpids/IDS/Log/Composite.php'", ")", ";", "$", "compositeLog", "=", "new", "\\", "IDS", "\\", "Log", "\\", "Composite", "(",...
This function sends out a mail about the intrusion including the intrusion details @param array $results @return boolean
[ "This", "function", "sends", "out", "a", "mail", "about", "the", "intrusion", "including", "the", "intrusion", "details" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/docs/examples/cakephp/ids.php#L236-L258
PHPIDS/PHPIDS
lib/IDS/Event.php
Event.getImpact
public function getImpact() { if (!$this->impact) { $this->impact = 0; foreach ($this->filters as $filter) { $this->impact += $filter->getImpact(); } } return $this->impact; }
php
public function getImpact() { if (!$this->impact) { $this->impact = 0; foreach ($this->filters as $filter) { $this->impact += $filter->getImpact(); } } return $this->impact; }
[ "public", "function", "getImpact", "(", ")", "{", "if", "(", "!", "$", "this", "->", "impact", ")", "{", "$", "this", "->", "impact", "=", "0", ";", "foreach", "(", "$", "this", "->", "filters", "as", "$", "filter", ")", "{", "$", "this", "->", ...
Returns calculated impact @return integer
[ "Returns", "calculated", "impact" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Event.php#L161-L171
PHPIDS/PHPIDS
lib/IDS/Event.php
Event.getTags
public function getTags() { foreach ($this->getFilters() as $filter) { $this->tags = array_merge($this->tags, $filter->getTags()); } return $this->tags = array_values(array_unique($this->tags)); }
php
public function getTags() { foreach ($this->getFilters() as $filter) { $this->tags = array_merge($this->tags, $filter->getTags()); } return $this->tags = array_values(array_unique($this->tags)); }
[ "public", "function", "getTags", "(", ")", "{", "foreach", "(", "$", "this", "->", "getFilters", "(", ")", "as", "$", "filter", ")", "{", "$", "this", "->", "tags", "=", "array_merge", "(", "$", "this", "->", "tags", ",", "$", "filter", "->", "getT...
Returns affected tags @return string[]|array
[ "Returns", "affected", "tags" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Event.php#L178-L185
PHPIDS/PHPIDS
lib/IDS/Converter.php
Converter.convertFromCommented
public static function convertFromCommented($value) { // check for existing comments if (preg_match('/(?:\<!-|-->|\/\*|\*\/|\/\/\W*\w+\s*$)|(?:--[^-]*-)/ms', $value)) { $pattern = array( '/(?:(?:<!)(?:(?:--(?:[^-]*(?:-[^-]+)*)--\s*)*)(?:>))/ms', '/(?:(?:\/\*\/*[^\/\*]*)+\*\/)/ms', '/(?:--[^-]*-)/ms' ); $converted = preg_replace($pattern, ';', $value); $value .= "\n" . $converted; } //make sure inline comments are detected and converted correctly $value = preg_replace('/(<\w+)\/+(\w+=?)/m', '$1/$2', $value); $value = preg_replace('/[^\\\:]\/\/(.*)$/m', '/**/$1', $value); $value = preg_replace('/([^\-&])#.*[\r\n\v\f]/m', '$1', $value); $value = preg_replace('/([^&\-])#.*\n/m', '$1 ', $value); $value = preg_replace('/^#.*\n/m', ' ', $value); return $value; }
php
public static function convertFromCommented($value) { // check for existing comments if (preg_match('/(?:\<!-|-->|\/\*|\*\/|\/\/\W*\w+\s*$)|(?:--[^-]*-)/ms', $value)) { $pattern = array( '/(?:(?:<!)(?:(?:--(?:[^-]*(?:-[^-]+)*)--\s*)*)(?:>))/ms', '/(?:(?:\/\*\/*[^\/\*]*)+\*\/)/ms', '/(?:--[^-]*-)/ms' ); $converted = preg_replace($pattern, ';', $value); $value .= "\n" . $converted; } //make sure inline comments are detected and converted correctly $value = preg_replace('/(<\w+)\/+(\w+=?)/m', '$1/$2', $value); $value = preg_replace('/[^\\\:]\/\/(.*)$/m', '/**/$1', $value); $value = preg_replace('/([^\-&])#.*[\r\n\v\f]/m', '$1', $value); $value = preg_replace('/([^&\-])#.*\n/m', '$1 ', $value); $value = preg_replace('/^#.*\n/m', ' ', $value); return $value; }
[ "public", "static", "function", "convertFromCommented", "(", "$", "value", ")", "{", "// check for existing comments", "if", "(", "preg_match", "(", "'/(?:\\<!-|-->|\\/\\*|\\*\\/|\\/\\/\\W*\\w+\\s*$)|(?:--[^-]*-)/ms'", ",", "$", "value", ")", ")", "{", "$", "pattern", "...
Check for comments and erases them if available @param string $value the value to convert @static @return string
[ "Check", "for", "comments", "and", "erases", "them", "if", "available" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Converter.php#L86-L109
PHPIDS/PHPIDS
lib/IDS/Converter.php
Converter.convertFromWhiteSpace
public static function convertFromWhiteSpace($value) { //check for inline linebreaks $search = array('\r', '\n', '\f', '\t', '\v'); $value = str_replace($search, ';', $value); // replace replacement characters regular spaces $value = str_replace('�', ' ', $value); //convert real linebreaks return preg_replace('/(?:\n|\r|\v)/m', ' ', $value); }
php
public static function convertFromWhiteSpace($value) { //check for inline linebreaks $search = array('\r', '\n', '\f', '\t', '\v'); $value = str_replace($search, ';', $value); // replace replacement characters regular spaces $value = str_replace('�', ' ', $value); //convert real linebreaks return preg_replace('/(?:\n|\r|\v)/m', ' ', $value); }
[ "public", "static", "function", "convertFromWhiteSpace", "(", "$", "value", ")", "{", "//check for inline linebreaks", "$", "search", "=", "array", "(", "'\\r'", ",", "'\\n'", ",", "'\\f'", ",", "'\\t'", ",", "'\\v'", ")", ";", "$", "value", "=", "str_replac...
Strip newlines @param string $value the value to convert @static @return string
[ "Strip", "newlines" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Converter.php#L119-L130
PHPIDS/PHPIDS
lib/IDS/Converter.php
Converter.convertFromSQLHex
public static function convertFromSQLHex($value) { $matches = array(); if (preg_match_all('/(?:(?:\A|[^\d])0x[a-f\d]{3,}[a-f\d]*)+/im', $value, $matches)) { foreach ($matches[0] as $match) { $converted = ''; foreach (str_split($match, 2) as $hex_index) { if (preg_match('/[a-f\d]{2,3}/i', $hex_index)) { $converted .= chr(hexdec($hex_index)); } } $value = str_replace($match, $converted, $value); } } // take care of hex encoded ctrl chars $value = preg_replace('/0x\d+/m', ' 1 ', $value); return $value; }
php
public static function convertFromSQLHex($value) { $matches = array(); if (preg_match_all('/(?:(?:\A|[^\d])0x[a-f\d]{3,}[a-f\d]*)+/im', $value, $matches)) { foreach ($matches[0] as $match) { $converted = ''; foreach (str_split($match, 2) as $hex_index) { if (preg_match('/[a-f\d]{2,3}/i', $hex_index)) { $converted .= chr(hexdec($hex_index)); } } $value = str_replace($match, $converted, $value); } } // take care of hex encoded ctrl chars $value = preg_replace('/0x\d+/m', ' 1 ', $value); return $value; }
[ "public", "static", "function", "convertFromSQLHex", "(", "$", "value", ")", "{", "$", "matches", "=", "array", "(", ")", ";", "if", "(", "preg_match_all", "(", "'/(?:(?:\\A|[^\\d])0x[a-f\\d]{3,}[a-f\\d]*)+/im'", ",", "$", "value", ",", "$", "matches", ")", ")...
Converts SQLHEX to plain text @param string $value the value to convert @static @return string
[ "Converts", "SQLHEX", "to", "plain", "text" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Converter.php#L271-L289
PHPIDS/PHPIDS
lib/IDS/Converter.php
Converter.convertFromSQLKeywords
public static function convertFromSQLKeywords($value) { $pattern = array( '/(?:is\s+null)|(like\s+null)|' . '(?:(?:^|\W)in[+\s]*\([\s\d"]+[^()]*\))/ims' ); $value = preg_replace($pattern, '"=0', $value); $value = preg_replace('/[^\w\)]+\s*like\s*[^\w\s]+/ims', '1" OR "1"', $value); $value = preg_replace('/null([,"\s])/ims', '0$1', $value); $value = preg_replace('/\d+\./ims', ' 1', $value); $value = preg_replace('/,null/ims', ',0', $value); $value = preg_replace('/(?:between)/ims', 'or', $value); $value = preg_replace('/(?:and\s+\d+\.?\d*)/ims', '', $value); $value = preg_replace('/(?:\s+and\s+)/ims', ' or ', $value); $pattern = array( '/(?:not\s+between)|(?:is\s+not)|(?:not\s+in)|' . '(?:xor|<>|rlike(?:\s+binary)?)|' . '(?:regexp\s+binary)|' . '(?:sounds\s+like)/ims' ); $value = preg_replace($pattern, '!', $value); $value = preg_replace('/"\s+\d/', '"', $value); $value = preg_replace('/(\W)div(\W)/ims', '$1 OR $2', $value); $value = preg_replace('/\/(?:\d+|null)/', null, $value); return $value; }
php
public static function convertFromSQLKeywords($value) { $pattern = array( '/(?:is\s+null)|(like\s+null)|' . '(?:(?:^|\W)in[+\s]*\([\s\d"]+[^()]*\))/ims' ); $value = preg_replace($pattern, '"=0', $value); $value = preg_replace('/[^\w\)]+\s*like\s*[^\w\s]+/ims', '1" OR "1"', $value); $value = preg_replace('/null([,"\s])/ims', '0$1', $value); $value = preg_replace('/\d+\./ims', ' 1', $value); $value = preg_replace('/,null/ims', ',0', $value); $value = preg_replace('/(?:between)/ims', 'or', $value); $value = preg_replace('/(?:and\s+\d+\.?\d*)/ims', '', $value); $value = preg_replace('/(?:\s+and\s+)/ims', ' or ', $value); $pattern = array( '/(?:not\s+between)|(?:is\s+not)|(?:not\s+in)|' . '(?:xor|<>|rlike(?:\s+binary)?)|' . '(?:regexp\s+binary)|' . '(?:sounds\s+like)/ims' ); $value = preg_replace($pattern, '!', $value); $value = preg_replace('/"\s+\d/', '"', $value); $value = preg_replace('/(\W)div(\W)/ims', '$1 OR $2', $value); $value = preg_replace('/\/(?:\d+|null)/', null, $value); return $value; }
[ "public", "static", "function", "convertFromSQLKeywords", "(", "$", "value", ")", "{", "$", "pattern", "=", "array", "(", "'/(?:is\\s+null)|(like\\s+null)|'", ".", "'(?:(?:^|\\W)in[+\\s]*\\([\\s\\d\"]+[^()]*\\))/ims'", ")", ";", "$", "value", "=", "preg_replace", "(", ...
Converts basic SQL keywords and obfuscations @param string $value the value to convert @static @return string
[ "Converts", "basic", "SQL", "keywords", "and", "obfuscations" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Converter.php#L299-L327
PHPIDS/PHPIDS
lib/IDS/Converter.php
Converter.convertFromControlChars
public static function convertFromControlChars($value) { // critical ctrl values $search = array( chr(0), chr(1), chr(2), chr(3), chr(4), chr(5), chr(6), chr(7), chr(8), chr(11), chr(12), chr(14), chr(15), chr(16), chr(17), chr(18), chr(19), chr(24), chr(25), chr(192), chr(193), chr(238), chr(255), '\\0' ); $value = str_replace($search, '%00', $value); //take care for malicious unicode characters $value = urldecode( preg_replace( '/(?:%E(?:2|3)%8(?:0|1)%(?:A|8|9)\w|%EF%BB%BF|%EF%BF%BD)|(?:&#(?:65|8)\d{3};?)/i', null, urlencode($value) ) ); $value = urlencode($value); $value = preg_replace('/(?:%F0%80%BE)/i', '>', $value); $value = preg_replace('/(?:%F0%80%BC)/i', '<', $value); $value = preg_replace('/(?:%F0%80%A2)/i', '"', $value); $value = preg_replace('/(?:%F0%80%A7)/i', '\'', $value); $value = urldecode($value); $value = preg_replace('/(?:%ff1c)/', '<', $value); $value = preg_replace('/(?:&[#x]*(200|820|200|820|zwn?j|lrm|rlm)\w?;?)/i', null, $value); $value = preg_replace( '/(?:&#(?:65|8)\d{3};?)|' . '(?:&#(?:56|7)3\d{2};?)|' . '(?:&#x(?:fe|20)\w{2};?)|' . '(?:&#x(?:d[c-f])\w{2};?)/i', null, $value ); $value = str_replace( array( '«', '〈', '<', '‹', '〈', '⟨' ), '<', $value ); $value = str_replace( array( '»', '〉', '>', '›', '〉', '⟩' ), '>', $value ); return $value; }
php
public static function convertFromControlChars($value) { // critical ctrl values $search = array( chr(0), chr(1), chr(2), chr(3), chr(4), chr(5), chr(6), chr(7), chr(8), chr(11), chr(12), chr(14), chr(15), chr(16), chr(17), chr(18), chr(19), chr(24), chr(25), chr(192), chr(193), chr(238), chr(255), '\\0' ); $value = str_replace($search, '%00', $value); //take care for malicious unicode characters $value = urldecode( preg_replace( '/(?:%E(?:2|3)%8(?:0|1)%(?:A|8|9)\w|%EF%BB%BF|%EF%BF%BD)|(?:&#(?:65|8)\d{3};?)/i', null, urlencode($value) ) ); $value = urlencode($value); $value = preg_replace('/(?:%F0%80%BE)/i', '>', $value); $value = preg_replace('/(?:%F0%80%BC)/i', '<', $value); $value = preg_replace('/(?:%F0%80%A2)/i', '"', $value); $value = preg_replace('/(?:%F0%80%A7)/i', '\'', $value); $value = urldecode($value); $value = preg_replace('/(?:%ff1c)/', '<', $value); $value = preg_replace('/(?:&[#x]*(200|820|200|820|zwn?j|lrm|rlm)\w?;?)/i', null, $value); $value = preg_replace( '/(?:&#(?:65|8)\d{3};?)|' . '(?:&#(?:56|7)3\d{2};?)|' . '(?:&#x(?:fe|20)\w{2};?)|' . '(?:&#x(?:d[c-f])\w{2};?)/i', null, $value ); $value = str_replace( array( '«', '〈', '<', '‹', '〈', '⟨' ), '<', $value ); $value = str_replace( array( '»', '〉', '>', '›', '〉', '⟩' ), '>', $value ); return $value; }
[ "public", "static", "function", "convertFromControlChars", "(", "$", "value", ")", "{", "// critical ctrl values", "$", "search", "=", "array", "(", "chr", "(", "0", ")", ",", "chr", "(", "1", ")", ",", "chr", "(", "2", ")", ",", "chr", "(", "3", ")"...
Detects nullbytes and controls chars via ord() @param string $value the value to convert @static @return string
[ "Detects", "nullbytes", "and", "controls", "chars", "via", "ord", "()" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Converter.php#L337-L401
PHPIDS/PHPIDS
lib/IDS/Converter.php
Converter.convertFromNestedBase64
public static function convertFromNestedBase64($value) { $matches = array(); preg_match_all('/(?:^|[,&?])\s*([a-z0-9]{50,}=*)(?:\W|$)/im', $value, $matches); foreach ($matches[1] as $item) { if (isset($item) && !preg_match('/[a-f0-9]{32}/i', $item)) { $base64_item = base64_decode($item); $value = str_replace($item, $base64_item, $value); } } return $value; }
php
public static function convertFromNestedBase64($value) { $matches = array(); preg_match_all('/(?:^|[,&?])\s*([a-z0-9]{50,}=*)(?:\W|$)/im', $value, $matches); foreach ($matches[1] as $item) { if (isset($item) && !preg_match('/[a-f0-9]{32}/i', $item)) { $base64_item = base64_decode($item); $value = str_replace($item, $base64_item, $value); } } return $value; }
[ "public", "static", "function", "convertFromNestedBase64", "(", "$", "value", ")", "{", "$", "matches", "=", "array", "(", ")", ";", "preg_match_all", "(", "'/(?:^|[,&?])\\s*([a-z0-9]{50,}=*)(?:\\W|$)/im'", ",", "$", "value", ",", "$", "matches", ")", ";", "fore...
This method matches and translates base64 strings and fragments used in data URIs @param string $value the value to convert @static @return string
[ "This", "method", "matches", "and", "translates", "base64", "strings", "and", "fragments", "used", "in", "data", "URIs" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Converter.php#L412-L425
PHPIDS/PHPIDS
lib/IDS/Converter.php
Converter.convertFromOutOfRangeChars
public static function convertFromOutOfRangeChars($value) { $values = str_split($value); foreach ($values as $item) { if (ord($item) >= 127) { $value = str_replace($item, ' ', $value); } } return $value; }
php
public static function convertFromOutOfRangeChars($value) { $values = str_split($value); foreach ($values as $item) { if (ord($item) >= 127) { $value = str_replace($item, ' ', $value); } } return $value; }
[ "public", "static", "function", "convertFromOutOfRangeChars", "(", "$", "value", ")", "{", "$", "values", "=", "str_split", "(", "$", "value", ")", ";", "foreach", "(", "$", "values", "as", "$", "item", ")", "{", "if", "(", "ord", "(", "$", "item", "...
Detects nullbytes and controls chars via ord() @param string $value the value to convert @static @return string
[ "Detects", "nullbytes", "and", "controls", "chars", "via", "ord", "()" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Converter.php#L435-L445
PHPIDS/PHPIDS
lib/IDS/Converter.php
Converter.convertFromXML
public static function convertFromXML($value) { $converted = strip_tags($value); if (!$converted || $converted === $value) { return $value; } else { return $value . "\n" . $converted; } }
php
public static function convertFromXML($value) { $converted = strip_tags($value); if (!$converted || $converted === $value) { return $value; } else { return $value . "\n" . $converted; } }
[ "public", "static", "function", "convertFromXML", "(", "$", "value", ")", "{", "$", "converted", "=", "strip_tags", "(", "$", "value", ")", ";", "if", "(", "!", "$", "converted", "||", "$", "converted", "===", "$", "value", ")", "{", "return", "$", "...
Strip XML patterns @param string $value the value to convert @static @return string
[ "Strip", "XML", "patterns" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Converter.php#L455-L463
PHPIDS/PHPIDS
lib/IDS/Converter.php
Converter.convertFromConcatenated
public static function convertFromConcatenated($value) { //normalize remaining backslashes if ($value != preg_replace('/(\w)\\\/', "$1", $value)) { $value .= preg_replace('/(\w)\\\/', "$1", $value); } $compare = stripslashes($value); $pattern = array( '/(?:<\/\w+>\+<\w+>)/s', '/(?:":\d+[^"[]+")/s', '/(?:"?"\+\w+\+")/s', '/(?:"\s*;[^"]+")|(?:";[^"]+:\s*")/s', '/(?:"\s*(?:;|\+).{8,18}:\s*")/s', '/(?:";\w+=)|(?:!""&&")|(?:~)/s', '/(?:"?"\+""?\+?"?)|(?:;\w+=")|(?:"[|&]{2,})/s', '/(?:"\s*\W+")/s', '/(?:";\w\s*\+=\s*\w?\s*")/s', '/(?:"[|&;]+\s*[^|&\n]*[|&]+\s*"?)/s', '/(?:";\s*\w+\W+\w*\s*[|&]*")/s', '/(?:"\s*"\s*\.)/s', '/(?:\s*new\s+\w+\s*[+",])/', '/(?:(?:^|\s+)(?:do|else)\s+)/', '/(?:[{(]\s*new\s+\w+\s*[)}])/', '/(?:(this|self)\.)/', '/(?:undefined)/', '/(?:in\s+)/' ); // strip out concatenations $converted = preg_replace($pattern, null, $compare); //strip object traversal $converted = preg_replace('/\w(\.\w\()/', "$1", $converted); // normalize obfuscated method calls $converted = preg_replace('/\)\s*\+/', ")", $converted); //convert JS special numbers $converted = preg_replace( '/(?:\(*[.\d]e[+-]*[^a-z\W]+\)*)|(?:NaN|Infinity)\W/ims', 1, $converted ); if ($converted && ($compare != $converted)) { $value .= "\n" . $converted; } return $value; }
php
public static function convertFromConcatenated($value) { //normalize remaining backslashes if ($value != preg_replace('/(\w)\\\/', "$1", $value)) { $value .= preg_replace('/(\w)\\\/', "$1", $value); } $compare = stripslashes($value); $pattern = array( '/(?:<\/\w+>\+<\w+>)/s', '/(?:":\d+[^"[]+")/s', '/(?:"?"\+\w+\+")/s', '/(?:"\s*;[^"]+")|(?:";[^"]+:\s*")/s', '/(?:"\s*(?:;|\+).{8,18}:\s*")/s', '/(?:";\w+=)|(?:!""&&")|(?:~)/s', '/(?:"?"\+""?\+?"?)|(?:;\w+=")|(?:"[|&]{2,})/s', '/(?:"\s*\W+")/s', '/(?:";\w\s*\+=\s*\w?\s*")/s', '/(?:"[|&;]+\s*[^|&\n]*[|&]+\s*"?)/s', '/(?:";\s*\w+\W+\w*\s*[|&]*")/s', '/(?:"\s*"\s*\.)/s', '/(?:\s*new\s+\w+\s*[+",])/', '/(?:(?:^|\s+)(?:do|else)\s+)/', '/(?:[{(]\s*new\s+\w+\s*[)}])/', '/(?:(this|self)\.)/', '/(?:undefined)/', '/(?:in\s+)/' ); // strip out concatenations $converted = preg_replace($pattern, null, $compare); //strip object traversal $converted = preg_replace('/\w(\.\w\()/', "$1", $converted); // normalize obfuscated method calls $converted = preg_replace('/\)\s*\+/', ")", $converted); //convert JS special numbers $converted = preg_replace( '/(?:\(*[.\d]e[+-]*[^a-z\W]+\)*)|(?:NaN|Infinity)\W/ims', 1, $converted ); if ($converted && ($compare != $converted)) { $value .= "\n" . $converted; } return $value; }
[ "public", "static", "function", "convertFromConcatenated", "(", "$", "value", ")", "{", "//normalize remaining backslashes", "if", "(", "$", "value", "!=", "preg_replace", "(", "'/(\\w)\\\\\\/'", ",", "\"$1\"", ",", "$", "value", ")", ")", "{", "$", "value", "...
Converts basic concatenations @param string $value the value to convert @static @return string
[ "Converts", "basic", "concatenations" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Converter.php#L559-L610
PHPIDS/PHPIDS
lib/IDS/Converter.php
Converter.convertFromProprietaryEncodings
public static function convertFromProprietaryEncodings($value) { //Xajax error reportings $value = preg_replace('/<!\[CDATA\[(\W+)\]\]>/im', '$1', $value); //strip false alert triggering apostrophes $value = preg_replace('/(\w)\"(s)/m', '$1$2', $value); //strip quotes within typical search patterns $value = preg_replace('/^"([^"=\\!><~]+)"$/', '$1', $value); //OpenID login tokens $value = preg_replace('/{[\w-]{8,9}\}(?:\{[\w=]{8}\}){2}/', null, $value); //convert Content and \sdo\s to null $value = preg_replace('/Content|\Wdo\s/', null, $value); //strip emoticons $value = preg_replace( '/(?:\s[:;]-[)\/PD]+)|(?:\s;[)PD]+)|(?:\s:[)PD]+)|-\.-|\^\^/m', null, $value ); //normalize separation char repetion $value = preg_replace('/([.+~=*_\-;])\1{2,}/m', '$1', $value); //normalize multiple single quotes $value = preg_replace('/"{2,}/m', '"', $value); //normalize quoted numerical values and asterisks $value = preg_replace('/"(\d+)"/m', '$1', $value); //normalize pipe separated request parameters $value = preg_replace('/\|(\w+=\w+)/m', '&$1', $value); //normalize ampersand listings $value = preg_replace('/(\w\s)&\s(\w)/', '$1$2', $value); //normalize escaped RegExp modifiers $value = preg_replace('/\/\\\(\w)/', '/$1', $value); return $value; }
php
public static function convertFromProprietaryEncodings($value) { //Xajax error reportings $value = preg_replace('/<!\[CDATA\[(\W+)\]\]>/im', '$1', $value); //strip false alert triggering apostrophes $value = preg_replace('/(\w)\"(s)/m', '$1$2', $value); //strip quotes within typical search patterns $value = preg_replace('/^"([^"=\\!><~]+)"$/', '$1', $value); //OpenID login tokens $value = preg_replace('/{[\w-]{8,9}\}(?:\{[\w=]{8}\}){2}/', null, $value); //convert Content and \sdo\s to null $value = preg_replace('/Content|\Wdo\s/', null, $value); //strip emoticons $value = preg_replace( '/(?:\s[:;]-[)\/PD]+)|(?:\s;[)PD]+)|(?:\s:[)PD]+)|-\.-|\^\^/m', null, $value ); //normalize separation char repetion $value = preg_replace('/([.+~=*_\-;])\1{2,}/m', '$1', $value); //normalize multiple single quotes $value = preg_replace('/"{2,}/m', '"', $value); //normalize quoted numerical values and asterisks $value = preg_replace('/"(\d+)"/m', '$1', $value); //normalize pipe separated request parameters $value = preg_replace('/\|(\w+=\w+)/m', '&$1', $value); //normalize ampersand listings $value = preg_replace('/(\w\s)&\s(\w)/', '$1$2', $value); //normalize escaped RegExp modifiers $value = preg_replace('/\/\\\(\w)/', '/$1', $value); return $value; }
[ "public", "static", "function", "convertFromProprietaryEncodings", "(", "$", "value", ")", "{", "//Xajax error reportings", "$", "value", "=", "preg_replace", "(", "'/<!\\[CDATA\\[(\\W+)\\]\\]>/im'", ",", "'$1'", ",", "$", "value", ")", ";", "//strip false alert trigger...
This method collects and decodes proprietary encoding types @param string $value the value to convert @static @return string
[ "This", "method", "collects", "and", "decodes", "proprietary", "encoding", "types" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Converter.php#L620-L663
PHPIDS/PHPIDS
lib/IDS/Converter.php
Converter.convertFromUrlencodeSqlComment
public static function convertFromUrlencodeSqlComment($value) { if (preg_match_all('/(?:\%23.*?\%0a)/im',$value,$matches)){ $converted = $value; foreach($matches[0] as $match){ $converted = str_replace($match,' ',$converted); } $value .= "\n" . $converted; } return $value; }
php
public static function convertFromUrlencodeSqlComment($value) { if (preg_match_all('/(?:\%23.*?\%0a)/im',$value,$matches)){ $converted = $value; foreach($matches[0] as $match){ $converted = str_replace($match,' ',$converted); } $value .= "\n" . $converted; } return $value; }
[ "public", "static", "function", "convertFromUrlencodeSqlComment", "(", "$", "value", ")", "{", "if", "(", "preg_match_all", "(", "'/(?:\\%23.*?\\%0a)/im'", ",", "$", "value", ",", "$", "matches", ")", ")", "{", "$", "converted", "=", "$", "value", ";", "fore...
This method removes encoded sql # comments @param string $value the value to convert @static @return string
[ "This", "method", "removes", "encoded", "sql", "#", "comments" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Converter.php#L673-L683
PHPIDS/PHPIDS
lib/IDS/Converter.php
Converter.runCentrifuge
public static function runCentrifuge($value, Monitor $monitor = null) { $threshold = 3.49; if (strlen($value) > 25) { //strip padding $tmp_value = preg_replace('/\s{4}|==$/m', null, $value); $tmp_value = preg_replace( '/\s{4}|[\p{L}\d\+\-=,.%()]{8,}/m', 'aaa', $tmp_value ); // Check for the attack char ratio $tmp_value = preg_replace('/([*.!?+-])\1{1,}/m', '$1', $tmp_value); $tmp_value = preg_replace('/"[\p{L}\d\s]+"/m', null, $tmp_value); $stripped_length = strlen( preg_replace( '/[\d\s\p{L}\.:,%&\/><\-)!|]+/m', null, $tmp_value ) ); $overall_length = strlen( preg_replace( '/([\d\s\p{L}:,\.]{3,})+/m', 'aaa', preg_replace('/\s{2,}/m', null, $tmp_value) ) ); if ($stripped_length != 0 && $overall_length/$stripped_length <= $threshold) { $monitor->centrifuge['ratio'] = $overall_length / $stripped_length; $monitor->centrifuge['threshold'] =$threshold; $value .= "\n$[!!!]"; } } if (strlen($value) > 40) { // Replace all non-special chars $converted = preg_replace('/[\w\s\p{L},.:!]/', null, $value); // Split string into an array, unify and sort $array = str_split($converted); $array = array_unique($array); asort($array); // Normalize certain tokens $schemes = array( '~' => '+', '^' => '+', '|' => '+', '*' => '+', '%' => '+', '&' => '+', '/' => '+' ); $converted = implode($array); $_keys = array_keys($schemes); $_values = array_values($schemes); $converted = str_replace($_keys, $_values, $converted); $converted = preg_replace('/[+-]\s*\d+/', '+', $converted); $converted = preg_replace('/[()[\]{}]/', '(', $converted); $converted = preg_replace('/[!?:=]/', ':', $converted); $converted = preg_replace('/[^:(+]/', null, stripslashes($converted)); // Sort again and implode $array = str_split($converted); asort($array); $converted = implode($array); if (preg_match('/(?:\({2,}\+{2,}:{2,})|(?:\({2,}\+{2,}:+)|(?:\({3,}\++:{2,})/', $converted)) { $monitor->centrifuge['converted'] = $converted; return $value . "\n" . $converted; } } return $value; }
php
public static function runCentrifuge($value, Monitor $monitor = null) { $threshold = 3.49; if (strlen($value) > 25) { //strip padding $tmp_value = preg_replace('/\s{4}|==$/m', null, $value); $tmp_value = preg_replace( '/\s{4}|[\p{L}\d\+\-=,.%()]{8,}/m', 'aaa', $tmp_value ); // Check for the attack char ratio $tmp_value = preg_replace('/([*.!?+-])\1{1,}/m', '$1', $tmp_value); $tmp_value = preg_replace('/"[\p{L}\d\s]+"/m', null, $tmp_value); $stripped_length = strlen( preg_replace( '/[\d\s\p{L}\.:,%&\/><\-)!|]+/m', null, $tmp_value ) ); $overall_length = strlen( preg_replace( '/([\d\s\p{L}:,\.]{3,})+/m', 'aaa', preg_replace('/\s{2,}/m', null, $tmp_value) ) ); if ($stripped_length != 0 && $overall_length/$stripped_length <= $threshold) { $monitor->centrifuge['ratio'] = $overall_length / $stripped_length; $monitor->centrifuge['threshold'] =$threshold; $value .= "\n$[!!!]"; } } if (strlen($value) > 40) { // Replace all non-special chars $converted = preg_replace('/[\w\s\p{L},.:!]/', null, $value); // Split string into an array, unify and sort $array = str_split($converted); $array = array_unique($array); asort($array); // Normalize certain tokens $schemes = array( '~' => '+', '^' => '+', '|' => '+', '*' => '+', '%' => '+', '&' => '+', '/' => '+' ); $converted = implode($array); $_keys = array_keys($schemes); $_values = array_values($schemes); $converted = str_replace($_keys, $_values, $converted); $converted = preg_replace('/[+-]\s*\d+/', '+', $converted); $converted = preg_replace('/[()[\]{}]/', '(', $converted); $converted = preg_replace('/[!?:=]/', ':', $converted); $converted = preg_replace('/[^:(+]/', null, stripslashes($converted)); // Sort again and implode $array = str_split($converted); asort($array); $converted = implode($array); if (preg_match('/(?:\({2,}\+{2,}:{2,})|(?:\({2,}\+{2,}:+)|(?:\({3,}\++:{2,})/', $converted)) { $monitor->centrifuge['converted'] = $converted; return $value . "\n" . $converted; } } return $value; }
[ "public", "static", "function", "runCentrifuge", "(", "$", "value", ",", "Monitor", "$", "monitor", "=", "null", ")", "{", "$", "threshold", "=", "3.49", ";", "if", "(", "strlen", "(", "$", "value", ")", ">", "25", ")", "{", "//strip padding", "$", "...
This method is the centrifuge prototype @param string $value the value to convert @param Monitor $monitor the monitor object @static @return string
[ "This", "method", "is", "the", "centrifuge", "prototype" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Converter.php#L694-L778
PHPIDS/PHPIDS
lib/IDS/Caching/SessionCache.php
SessionCache.getInstance
public static function getInstance($type, $init) { if (!self::$cachingInstance) { self::$cachingInstance = new SessionCache($type, $init); } return self::$cachingInstance; }
php
public static function getInstance($type, $init) { if (!self::$cachingInstance) { self::$cachingInstance = new SessionCache($type, $init); } return self::$cachingInstance; }
[ "public", "static", "function", "getInstance", "(", "$", "type", ",", "$", "init", ")", "{", "if", "(", "!", "self", "::", "$", "cachingInstance", ")", "{", "self", "::", "$", "cachingInstance", "=", "new", "SessionCache", "(", "$", "type", ",", "$", ...
Returns an instance of this class @param string $type caching type @param object $init the IDS_Init object @return object $this
[ "Returns", "an", "instance", "of", "this", "class" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Caching/SessionCache.php#L95-L103
PHPIDS/PHPIDS
lib/IDS/Caching/SessionCache.php
SessionCache.getCache
public function getCache() { if ($this->type && $_SESSION['PHPIDS'][$this->type]) { return $_SESSION['PHPIDS'][$this->type]; } return false; }
php
public function getCache() { if ($this->type && $_SESSION['PHPIDS'][$this->type]) { return $_SESSION['PHPIDS'][$this->type]; } return false; }
[ "public", "function", "getCache", "(", ")", "{", "if", "(", "$", "this", "->", "type", "&&", "$", "_SESSION", "[", "'PHPIDS'", "]", "[", "$", "this", "->", "type", "]", ")", "{", "return", "$", "_SESSION", "[", "'PHPIDS'", "]", "[", "$", "this", ...
Returns the cached data Note that this method returns false if either type or file cache is not set @return mixed cache data or false
[ "Returns", "the", "cached", "data" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Caching/SessionCache.php#L127-L135
PHPIDS/PHPIDS
lib/IDS/Report.php
Report.addEvent
public function addEvent(Event $event) { $this->clear(); $this->events[$event->getName()] = $event; return $this; }
php
public function addEvent(Event $event) { $this->clear(); $this->events[$event->getName()] = $event; return $this; }
[ "public", "function", "addEvent", "(", "Event", "$", "event", ")", "{", "$", "this", "->", "clear", "(", ")", ";", "$", "this", "->", "events", "[", "$", "event", "->", "getName", "(", ")", "]", "=", "$", "event", ";", "return", "$", "this", ";",...
Adds an IDS_Event object to the report @param Event $event IDS_Event @return self $this
[ "Adds", "an", "IDS_Event", "object", "to", "the", "report" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Report.php#L112-L118
PHPIDS/PHPIDS
lib/IDS/Report.php
Report.getEvent
public function getEvent($name) { if (!is_scalar($name)) { throw new \InvalidArgumentException('Invalid argument type given'); } return $this->hasEvent($name) ? $this->events[$name] : null; }
php
public function getEvent($name) { if (!is_scalar($name)) { throw new \InvalidArgumentException('Invalid argument type given'); } return $this->hasEvent($name) ? $this->events[$name] : null; }
[ "public", "function", "getEvent", "(", "$", "name", ")", "{", "if", "(", "!", "is_scalar", "(", "$", "name", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Invalid argument type given'", ")", ";", "}", "return", "$", "this", "->", ...
Get event by name In most cases an event is identified by the key of the variable that contained maliciously appearing content @param string|integer $name the event name @throws \InvalidArgumentException if argument is invalid @return Event|null IDS_Event object or false if the event does not exist
[ "Get", "event", "by", "name" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Report.php#L131-L138
PHPIDS/PHPIDS
lib/IDS/Report.php
Report.getTags
public function getTags() { if (!$this->tags) { $this->tags = array(); foreach ($this->events as $event) { $this->tags = array_merge($this->tags, $event->getTags()); } $this->tags = array_values(array_unique($this->tags)); } return $this->tags; }
php
public function getTags() { if (!$this->tags) { $this->tags = array(); foreach ($this->events as $event) { $this->tags = array_merge($this->tags, $event->getTags()); } $this->tags = array_values(array_unique($this->tags)); } return $this->tags; }
[ "public", "function", "getTags", "(", ")", "{", "if", "(", "!", "$", "this", "->", "tags", ")", "{", "$", "this", "->", "tags", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "events", "as", "$", "event", ")", "{", "$", "this",...
Returns list of affected tags @return string[]|array
[ "Returns", "list", "of", "affected", "tags" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Report.php#L145-L158
PHPIDS/PHPIDS
lib/IDS/Report.php
Report.getImpact
public function getImpact() { if (!$this->impact) { $this->impact = 0; foreach ($this->events as $event) { $this->impact += $event->getImpact(); } } return $this->impact; }
php
public function getImpact() { if (!$this->impact) { $this->impact = 0; foreach ($this->events as $event) { $this->impact += $event->getImpact(); } } return $this->impact; }
[ "public", "function", "getImpact", "(", ")", "{", "if", "(", "!", "$", "this", "->", "impact", ")", "{", "$", "this", "->", "impact", "=", "0", ";", "foreach", "(", "$", "this", "->", "events", "as", "$", "event", ")", "{", "$", "this", "->", "...
Returns total impact Each stored IDS_Event object and its IDS_Filter sub-object are called to calculate the overall impact level of this request @return integer
[ "Returns", "total", "impact" ]
train
https://github.com/PHPIDS/PHPIDS/blob/dfc1476e4ffe9f1dde72c0954912411082a17597/lib/IDS/Report.php#L168-L178
maxmind/web-service-common-php
src/WebService/Http/CurlRequest.php
CurlRequest.post
public function post($body) { $curl = $this->createCurl(); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $body); return $this->execute($curl); }
php
public function post($body) { $curl = $this->createCurl(); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $body); return $this->execute($curl); }
[ "public", "function", "post", "(", "$", "body", ")", "{", "$", "curl", "=", "$", "this", "->", "createCurl", "(", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_POST", ",", "true", ")", ";", "curl_setopt", "(", "$", "curl", ",", "CURLOPT_PO...
@param $body @return array
[ "@param", "$body" ]
train
https://github.com/maxmind/web-service-common-php/blob/761712da754fd69c145e6a769da2c318da0d97e1/src/WebService/Http/CurlRequest.php#L32-L40
maxmind/web-service-common-php
src/WebService/Client.php
Client.post
public function post($service, $path, $input) { $requestBody = json_encode($input); if ($requestBody === false) { throw new InvalidInputException( 'Error encoding input as JSON: ' . $this->jsonErrorDescription() ); } $request = $this->createRequest( $path, ['Content-Type: application/json'] ); list($statusCode, $contentType, $responseBody) = $request->post($requestBody); return $this->handleResponse( $statusCode, $contentType, $responseBody, $service, $path ); }
php
public function post($service, $path, $input) { $requestBody = json_encode($input); if ($requestBody === false) { throw new InvalidInputException( 'Error encoding input as JSON: ' . $this->jsonErrorDescription() ); } $request = $this->createRequest( $path, ['Content-Type: application/json'] ); list($statusCode, $contentType, $responseBody) = $request->post($requestBody); return $this->handleResponse( $statusCode, $contentType, $responseBody, $service, $path ); }
[ "public", "function", "post", "(", "$", "service", ",", "$", "path", ",", "$", "input", ")", "{", "$", "requestBody", "=", "json_encode", "(", "$", "input", ")", ";", "if", "(", "$", "requestBody", "===", "false", ")", "{", "throw", "new", "InvalidIn...
@param string $service name of the service querying @param string $path the URI path to use @param array $input the data to be posted as JSON @throws InvalidInputException when the request has missing or invalid data @throws AuthenticationException when there is an issue authenticating the request @throws InsufficientFundsException when your account is out of funds @throws InvalidRequestException when the request is invalid for some other reason, e.g., invalid JSON in the POST. @throws HttpException when an unexpected HTTP error occurs @throws WebServiceException when some other error occurs. This also serves as the base class for the above exceptions. @return array The decoded content of a successful response
[ "@param", "string", "$service", "name", "of", "the", "service", "querying", "@param", "string", "$path", "the", "URI", "path", "to", "use", "@param", "array", "$input", "the", "data", "to", "be", "posted", "as", "JSON" ]
train
https://github.com/maxmind/web-service-common-php/blob/761712da754fd69c145e6a769da2c318da0d97e1/src/WebService/Client.php#L101-L125
maxmind/web-service-common-php
src/WebService/Client.php
Client.handleResponse
private function handleResponse( $statusCode, $contentType, $responseBody, $service, $path ) { if ($statusCode >= 400 && $statusCode <= 499) { $this->handle4xx($statusCode, $contentType, $responseBody, $service, $path); } elseif ($statusCode >= 500) { $this->handle5xx($statusCode, $service, $path); } elseif ($statusCode !== 200) { $this->handleUnexpectedStatus($statusCode, $service, $path); } return $this->handleSuccess($responseBody, $service); }
php
private function handleResponse( $statusCode, $contentType, $responseBody, $service, $path ) { if ($statusCode >= 400 && $statusCode <= 499) { $this->handle4xx($statusCode, $contentType, $responseBody, $service, $path); } elseif ($statusCode >= 500) { $this->handle5xx($statusCode, $service, $path); } elseif ($statusCode !== 200) { $this->handleUnexpectedStatus($statusCode, $service, $path); } return $this->handleSuccess($responseBody, $service); }
[ "private", "function", "handleResponse", "(", "$", "statusCode", ",", "$", "contentType", ",", "$", "responseBody", ",", "$", "service", ",", "$", "path", ")", "{", "if", "(", "$", "statusCode", ">=", "400", "&&", "$", "statusCode", "<=", "499", ")", "...
@param int $statusCode the HTTP status code of the response @param string $contentType the Content-Type of the response @param string $responseBody the response body @param string $service the name of the service @param string $path the path used in the request @throws AuthenticationException when there is an issue authenticating the request @throws InsufficientFundsException when your account is out of funds @throws InvalidRequestException when the request is invalid for some other reason, e.g., invalid JSON in the POST. @throws HttpException when an unexpected HTTP error occurs @throws WebServiceException when some other error occurs. This also serves as the base class for the above exceptions @return array The decoded content of a successful response
[ "@param", "int", "$statusCode", "the", "HTTP", "status", "code", "of", "the", "response", "@param", "string", "$contentType", "the", "Content", "-", "Type", "of", "the", "response", "@param", "string", "$responseBody", "the", "response", "body", "@param", "strin...
train
https://github.com/maxmind/web-service-common-php/blob/761712da754fd69c145e6a769da2c318da0d97e1/src/WebService/Client.php#L190-L206
maxmind/web-service-common-php
src/WebService/Client.php
Client.handle4xx
private function handle4xx( $statusCode, $contentType, $body, $service, $path ) { if (\strlen($body) === 0) { throw new HttpException( "Received a $statusCode error for $service with no body", $statusCode, $this->urlFor($path) ); } if (!strstr($contentType, 'json')) { throw new HttpException( "Received a $statusCode error for $service with " . 'the following body: ' . $body, $statusCode, $this->urlFor($path) ); } $message = json_decode($body, true); if ($message === null) { throw new HttpException( "Received a $statusCode error for $service but could " . 'not decode the response as JSON: ' . $this->jsonErrorDescription() . ' Body: ' . $body, $statusCode, $this->urlFor($path) ); } if (!isset($message['code']) || !isset($message['error'])) { throw new HttpException( 'Error response contains JSON but it does not ' . 'specify code or error keys: ' . $body, $statusCode, $this->urlFor($path) ); } $this->handleWebServiceError( $message['error'], $message['code'], $statusCode, $path ); }
php
private function handle4xx( $statusCode, $contentType, $body, $service, $path ) { if (\strlen($body) === 0) { throw new HttpException( "Received a $statusCode error for $service with no body", $statusCode, $this->urlFor($path) ); } if (!strstr($contentType, 'json')) { throw new HttpException( "Received a $statusCode error for $service with " . 'the following body: ' . $body, $statusCode, $this->urlFor($path) ); } $message = json_decode($body, true); if ($message === null) { throw new HttpException( "Received a $statusCode error for $service but could " . 'not decode the response as JSON: ' . $this->jsonErrorDescription() . ' Body: ' . $body, $statusCode, $this->urlFor($path) ); } if (!isset($message['code']) || !isset($message['error'])) { throw new HttpException( 'Error response contains JSON but it does not ' . 'specify code or error keys: ' . $body, $statusCode, $this->urlFor($path) ); } $this->handleWebServiceError( $message['error'], $message['code'], $statusCode, $path ); }
[ "private", "function", "handle4xx", "(", "$", "statusCode", ",", "$", "contentType", ",", "$", "body", ",", "$", "service", ",", "$", "path", ")", "{", "if", "(", "\\", "strlen", "(", "$", "body", ")", "===", "0", ")", "{", "throw", "new", "HttpExc...
@param int $statusCode the HTTP status code @param string $contentType the response content-type @param string $body the response body @param string $service the service name @param string $path the path used in the request @throws AuthenticationException @throws HttpException @throws InsufficientFundsException @throws InvalidRequestException
[ "@param", "int", "$statusCode", "the", "HTTP", "status", "code", "@param", "string", "$contentType", "the", "response", "content", "-", "type", "@param", "string", "$body", "the", "response", "body", "@param", "string", "$service", "the", "service", "name", "@pa...
train
https://github.com/maxmind/web-service-common-php/blob/761712da754fd69c145e6a769da2c318da0d97e1/src/WebService/Client.php#L252-L301
maxmind/web-service-common-php
src/WebService/Client.php
Client.handleWebServiceError
private function handleWebServiceError( $message, $code, $statusCode, $path ) { switch ($code) { case 'IP_ADDRESS_NOT_FOUND': case 'IP_ADDRESS_RESERVED': throw new IpAddressNotFoundException( $message, $code, $statusCode, $this->urlFor($path) ); case 'ACCOUNT_ID_REQUIRED': case 'ACCOUNT_ID_UNKNOWN': case 'AUTHORIZATION_INVALID': case 'LICENSE_KEY_REQUIRED': case 'USER_ID_REQUIRED': case 'USER_ID_UNKNOWN': throw new AuthenticationException( $message, $code, $statusCode, $this->urlFor($path) ); case 'OUT_OF_QUERIES': case 'INSUFFICIENT_FUNDS': throw new InsufficientFundsException( $message, $code, $statusCode, $this->urlFor($path) ); case 'PERMISSION_REQUIRED': throw new PermissionRequiredException( $message, $code, $statusCode, $this->urlFor($path) ); default: throw new InvalidRequestException( $message, $code, $statusCode, $this->urlFor($path) ); } }
php
private function handleWebServiceError( $message, $code, $statusCode, $path ) { switch ($code) { case 'IP_ADDRESS_NOT_FOUND': case 'IP_ADDRESS_RESERVED': throw new IpAddressNotFoundException( $message, $code, $statusCode, $this->urlFor($path) ); case 'ACCOUNT_ID_REQUIRED': case 'ACCOUNT_ID_UNKNOWN': case 'AUTHORIZATION_INVALID': case 'LICENSE_KEY_REQUIRED': case 'USER_ID_REQUIRED': case 'USER_ID_UNKNOWN': throw new AuthenticationException( $message, $code, $statusCode, $this->urlFor($path) ); case 'OUT_OF_QUERIES': case 'INSUFFICIENT_FUNDS': throw new InsufficientFundsException( $message, $code, $statusCode, $this->urlFor($path) ); case 'PERMISSION_REQUIRED': throw new PermissionRequiredException( $message, $code, $statusCode, $this->urlFor($path) ); default: throw new InvalidRequestException( $message, $code, $statusCode, $this->urlFor($path) ); } }
[ "private", "function", "handleWebServiceError", "(", "$", "message", ",", "$", "code", ",", "$", "statusCode", ",", "$", "path", ")", "{", "switch", "(", "$", "code", ")", "{", "case", "'IP_ADDRESS_NOT_FOUND'", ":", "case", "'IP_ADDRESS_RESERVED'", ":", "thr...
@param string $message the error message from the web service @param string $code the error code from the web service @param int $statusCode the HTTP status code @param string $path the path used in the request @throws AuthenticationException @throws InvalidRequestException @throws InsufficientFundsException
[ "@param", "string", "$message", "the", "error", "message", "from", "the", "web", "service", "@param", "string", "$code", "the", "error", "code", "from", "the", "web", "service", "@param", "int", "$statusCode", "the", "HTTP", "status", "code", "@param", "string...
train
https://github.com/maxmind/web-service-common-php/blob/761712da754fd69c145e6a769da2c318da0d97e1/src/WebService/Client.php#L313-L363
maxmind/web-service-common-php
src/WebService/Client.php
Client.handleSuccess
private function handleSuccess($body, $service) { if (\strlen($body) === 0) { throw new WebServiceException( "Received a 200 response for $service but did not " . 'receive a HTTP body.' ); } $decodedContent = json_decode($body, true); if ($decodedContent === null) { throw new WebServiceException( "Received a 200 response for $service but could " . 'not decode the response as JSON: ' . $this->jsonErrorDescription() . ' Body: ' . $body ); } return $decodedContent; }
php
private function handleSuccess($body, $service) { if (\strlen($body) === 0) { throw new WebServiceException( "Received a 200 response for $service but did not " . 'receive a HTTP body.' ); } $decodedContent = json_decode($body, true); if ($decodedContent === null) { throw new WebServiceException( "Received a 200 response for $service but could " . 'not decode the response as JSON: ' . $this->jsonErrorDescription() . ' Body: ' . $body ); } return $decodedContent; }
[ "private", "function", "handleSuccess", "(", "$", "body", ",", "$", "service", ")", "{", "if", "(", "\\", "strlen", "(", "$", "body", ")", "===", "0", ")", "{", "throw", "new", "WebServiceException", "(", "\"Received a 200 response for $service but did not \"", ...
@param string $body the successful request body @param string $service the service name @throws WebServiceException if the request body cannot be decoded as JSON @return array the decoded request body
[ "@param", "string", "$body", "the", "successful", "request", "body", "@param", "string", "$service", "the", "service", "name" ]
train
https://github.com/maxmind/web-service-common-php/blob/761712da754fd69c145e6a769da2c318da0d97e1/src/WebService/Client.php#L407-L426
sonata-project/SonataUserBundle
src/GoogleAuthenticator/Helper.php
Helper.checkCode
public function checkCode(UserInterface $user, $code) { return $this->authenticator->checkCode($user->getTwoStepVerificationCode(), $code); }
php
public function checkCode(UserInterface $user, $code) { return $this->authenticator->checkCode($user->getTwoStepVerificationCode(), $code); }
[ "public", "function", "checkCode", "(", "UserInterface", "$", "user", ",", "$", "code", ")", "{", "return", "$", "this", "->", "authenticator", "->", "checkCode", "(", "$", "user", "->", "getTwoStepVerificationCode", "(", ")", ",", "$", "code", ")", ";", ...
@param UserInterface $user @param $code @return bool
[ "@param", "UserInterface", "$user", "@param", "$code" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/GoogleAuthenticator/Helper.php#L73-L76
sonata-project/SonataUserBundle
src/GoogleAuthenticator/Helper.php
Helper.getUrl
public function getUrl(UserInterface $user) { return $this->authenticator->getUrl($user->getUsername(), $this->server, $user->getTwoStepVerificationCode()); }
php
public function getUrl(UserInterface $user) { return $this->authenticator->getUrl($user->getUsername(), $this->server, $user->getTwoStepVerificationCode()); }
[ "public", "function", "getUrl", "(", "UserInterface", "$", "user", ")", "{", "return", "$", "this", "->", "authenticator", "->", "getUrl", "(", "$", "user", "->", "getUsername", "(", ")", ",", "$", "this", "->", "server", ",", "$", "user", "->", "getTw...
@param UserInterface $user @return string
[ "@param", "UserInterface", "$user" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/GoogleAuthenticator/Helper.php#L83-L86
sonata-project/SonataUserBundle
src/Form/Transformer/RestoreRolesTransformer.php
RestoreRolesTransformer.transform
public function transform($value) { if (null === $value) { return $value; } if (null === $this->originalRoles) { throw new \RuntimeException('Invalid state, originalRoles array is not set'); } return $value; }
php
public function transform($value) { if (null === $value) { return $value; } if (null === $this->originalRoles) { throw new \RuntimeException('Invalid state, originalRoles array is not set'); } return $value; }
[ "public", "function", "transform", "(", "$", "value", ")", "{", "if", "(", "null", "===", "$", "value", ")", "{", "return", "$", "value", ";", "}", "if", "(", "null", "===", "$", "this", "->", "originalRoles", ")", "{", "throw", "new", "\\", "Runti...
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Form/Transformer/RestoreRolesTransformer.php#L50-L61
sonata-project/SonataUserBundle
src/Security/Authorization/Voter/UserAclVoter.php
UserAclVoter.vote
public function vote(TokenInterface $token, $subject, array $attributes) { if (!\is_object($subject) || !$this->supportsClass(\get_class($subject))) { return self::ACCESS_ABSTAIN; } foreach ($attributes as $attribute) { if ($this->supportsAttribute($attribute) && $subject instanceof UserInterface && $token->getUser() instanceof UserInterface) { if ($subject->isSuperAdmin() && !$token->getUser()->isSuperAdmin()) { // deny a non super admin user to edit or delete a super admin user return self::ACCESS_DENIED; } } } // leave the permission voting to the AclVoter that is using the default permission map return self::ACCESS_ABSTAIN; }
php
public function vote(TokenInterface $token, $subject, array $attributes) { if (!\is_object($subject) || !$this->supportsClass(\get_class($subject))) { return self::ACCESS_ABSTAIN; } foreach ($attributes as $attribute) { if ($this->supportsAttribute($attribute) && $subject instanceof UserInterface && $token->getUser() instanceof UserInterface) { if ($subject->isSuperAdmin() && !$token->getUser()->isSuperAdmin()) { // deny a non super admin user to edit or delete a super admin user return self::ACCESS_DENIED; } } } // leave the permission voting to the AclVoter that is using the default permission map return self::ACCESS_ABSTAIN; }
[ "public", "function", "vote", "(", "TokenInterface", "$", "token", ",", "$", "subject", ",", "array", "$", "attributes", ")", "{", "if", "(", "!", "\\", "is_object", "(", "$", "subject", ")", "||", "!", "$", "this", "->", "supportsClass", "(", "\\", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Security/Authorization/Voter/UserAclVoter.php#L42-L59
sonata-project/SonataUserBundle
src/Command/TwoStepVerificationCommand.php
TwoStepVerificationCommand.execute
public function execute(InputInterface $input, OutputInterface $output): void { if (null === $this->helper && !$this->getContainer()->has('sonata.user.google.authenticator.provider')) { throw new \RuntimeException('Two Step Verification process is not enabled'); } if (null === $this->helper) { @trigger_error(sprintf( 'Not providing the $helper argument of "%s::__construct()" is deprecated since 4.x and will no longer be possible in 5.0', __CLASS__ ), E_USER_DEPRECATED); $helper = $this->getContainer()->get('sonata.user.google.authenticator.provider'); \assert($helper instanceof Helper); $this->helper = $helper; } if (null === $this->userManager) { @trigger_error(sprintf( 'Not providing the $userManager argument of "%s::__construct()" is deprecated since 4.x and will no longer be possible in 5.0', __CLASS__ ), E_USER_DEPRECATED); $manager = $this->getContainer()->get('fos_user.user_manager'); \assert($manager instanceof UserManagerInterface); $this->userManager = $manager; } $user = $this->userManager->findUserByUsernameOrEmail($input->getArgument('username')); \assert($user instanceof UserInterface); if (!$user) { throw new \RuntimeException(sprintf('Unable to find the username : %s', $input->getArgument('username'))); } if (!$user->getTwoStepVerificationCode() || $input->getOption('reset')) { $user->setTwoStepVerificationCode($this->helper->generateSecret()); $this->userManager->updateUser($user); } $output->writeln([ sprintf('<info>Username</info> : %s', $input->getArgument('username')), sprintf('<info>Secret</info> : %s', $user->getTwoStepVerificationCode()), sprintf('<info>Url</info> : %s', $this->helper->getUrl($user)), ]); }
php
public function execute(InputInterface $input, OutputInterface $output): void { if (null === $this->helper && !$this->getContainer()->has('sonata.user.google.authenticator.provider')) { throw new \RuntimeException('Two Step Verification process is not enabled'); } if (null === $this->helper) { @trigger_error(sprintf( 'Not providing the $helper argument of "%s::__construct()" is deprecated since 4.x and will no longer be possible in 5.0', __CLASS__ ), E_USER_DEPRECATED); $helper = $this->getContainer()->get('sonata.user.google.authenticator.provider'); \assert($helper instanceof Helper); $this->helper = $helper; } if (null === $this->userManager) { @trigger_error(sprintf( 'Not providing the $userManager argument of "%s::__construct()" is deprecated since 4.x and will no longer be possible in 5.0', __CLASS__ ), E_USER_DEPRECATED); $manager = $this->getContainer()->get('fos_user.user_manager'); \assert($manager instanceof UserManagerInterface); $this->userManager = $manager; } $user = $this->userManager->findUserByUsernameOrEmail($input->getArgument('username')); \assert($user instanceof UserInterface); if (!$user) { throw new \RuntimeException(sprintf('Unable to find the username : %s', $input->getArgument('username'))); } if (!$user->getTwoStepVerificationCode() || $input->getOption('reset')) { $user->setTwoStepVerificationCode($this->helper->generateSecret()); $this->userManager->updateUser($user); } $output->writeln([ sprintf('<info>Username</info> : %s', $input->getArgument('username')), sprintf('<info>Secret</info> : %s', $user->getTwoStepVerificationCode()), sprintf('<info>Url</info> : %s', $this->helper->getUrl($user)), ]); }
[ "public", "function", "execute", "(", "InputInterface", "$", "input", ",", "OutputInterface", "$", "output", ")", ":", "void", "{", "if", "(", "null", "===", "$", "this", "->", "helper", "&&", "!", "$", "this", "->", "getContainer", "(", ")", "->", "ha...
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Command/TwoStepVerificationCommand.php#L74-L117
sonata-project/SonataUserBundle
src/DependencyInjection/SonataUserExtension.php
SonataUserExtension.load
public function load(array $configs, ContainerBuilder $container): void { $processor = new Processor(); $configuration = new Configuration(); $config = $processor->processConfiguration($configuration, $configs); $config = $this->fixImpersonating($config); $bundles = $container->getParameter('kernel.bundles'); $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); if (isset($bundles['SonataAdminBundle'])) { $loader->load('admin.xml'); $loader->load(sprintf('admin_%s.xml', $config['manager_type'])); } $loader->load(sprintf('%s.xml', $config['manager_type'])); $this->aliasManagers($container, $config['manager_type']); $loader->load('form.xml'); if (class_exists('Google\Authenticator\GoogleAuthenticator')) { @trigger_error( 'The \'Google\Authenticator\' namespace is deprecated in sonata-project/GoogleAuthenticator since version 2.1 and will be removed in 3.0.', E_USER_DEPRECATED ); } if (class_exists('Google\Authenticator\GoogleAuthenticator') || class_exists('Sonata\GoogleAuthenticator\GoogleAuthenticator')) { $loader->load('google_authenticator.xml'); } $loader->load('twig.xml'); $loader->load('command.xml'); $loader->load('actions.xml'); $loader->load('mailer.xml'); if ('orm' === $config['manager_type'] && isset( $bundles['FOSRestBundle'], $bundles['NelmioApiDocBundle'], $bundles['JMSSerializerBundle'] )) { $loader->load('serializer.xml'); $loader->load('api_form.xml'); $loader->load('api_controllers.xml'); } if ($config['security_acl']) { $loader->load('security_acl.xml'); } $this->checkManagerTypeToModelTypeMapping($config); $this->registerDoctrineMapping($config); $this->configureAdminClass($config, $container); $this->configureClass($config, $container); $this->configureTranslationDomain($config, $container); $this->configureController($config, $container); $this->configureMailer($config, $container); $container->setParameter('sonata.user.default_avatar', $config['profile']['default_avatar']); $container->setParameter('sonata.user.impersonating', $config['impersonating']); $this->configureGoogleAuthenticator($config, $container); }
php
public function load(array $configs, ContainerBuilder $container): void { $processor = new Processor(); $configuration = new Configuration(); $config = $processor->processConfiguration($configuration, $configs); $config = $this->fixImpersonating($config); $bundles = $container->getParameter('kernel.bundles'); $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); if (isset($bundles['SonataAdminBundle'])) { $loader->load('admin.xml'); $loader->load(sprintf('admin_%s.xml', $config['manager_type'])); } $loader->load(sprintf('%s.xml', $config['manager_type'])); $this->aliasManagers($container, $config['manager_type']); $loader->load('form.xml'); if (class_exists('Google\Authenticator\GoogleAuthenticator')) { @trigger_error( 'The \'Google\Authenticator\' namespace is deprecated in sonata-project/GoogleAuthenticator since version 2.1 and will be removed in 3.0.', E_USER_DEPRECATED ); } if (class_exists('Google\Authenticator\GoogleAuthenticator') || class_exists('Sonata\GoogleAuthenticator\GoogleAuthenticator')) { $loader->load('google_authenticator.xml'); } $loader->load('twig.xml'); $loader->load('command.xml'); $loader->load('actions.xml'); $loader->load('mailer.xml'); if ('orm' === $config['manager_type'] && isset( $bundles['FOSRestBundle'], $bundles['NelmioApiDocBundle'], $bundles['JMSSerializerBundle'] )) { $loader->load('serializer.xml'); $loader->load('api_form.xml'); $loader->load('api_controllers.xml'); } if ($config['security_acl']) { $loader->load('security_acl.xml'); } $this->checkManagerTypeToModelTypeMapping($config); $this->registerDoctrineMapping($config); $this->configureAdminClass($config, $container); $this->configureClass($config, $container); $this->configureTranslationDomain($config, $container); $this->configureController($config, $container); $this->configureMailer($config, $container); $container->setParameter('sonata.user.default_avatar', $config['profile']['default_avatar']); $container->setParameter('sonata.user.impersonating', $config['impersonating']); $this->configureGoogleAuthenticator($config, $container); }
[ "public", "function", "load", "(", "array", "$", "configs", ",", "ContainerBuilder", "$", "container", ")", ":", "void", "{", "$", "processor", "=", "new", "Processor", "(", ")", ";", "$", "configuration", "=", "new", "Configuration", "(", ")", ";", "$",...
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/DependencyInjection/SonataUserExtension.php#L47-L116
sonata-project/SonataUserBundle
src/DependencyInjection/SonataUserExtension.php
SonataUserExtension.fixImpersonating
public function fixImpersonating(array $config) { if (isset($config['impersonating'], $config['impersonating_route'])) { throw new \RuntimeException('you can\'t have `impersonating` and `impersonating_route` keys defined at the same time'); } if (isset($config['impersonating_route'])) { $config['impersonating'] = [ 'route' => $config['impersonating_route'], 'parameters' => [], ]; } if (!isset($config['impersonating']['parameters'])) { $config['impersonating']['parameters'] = []; } if (!isset($config['impersonating']['route'])) { $config['impersonating'] = false; } return $config; }
php
public function fixImpersonating(array $config) { if (isset($config['impersonating'], $config['impersonating_route'])) { throw new \RuntimeException('you can\'t have `impersonating` and `impersonating_route` keys defined at the same time'); } if (isset($config['impersonating_route'])) { $config['impersonating'] = [ 'route' => $config['impersonating_route'], 'parameters' => [], ]; } if (!isset($config['impersonating']['parameters'])) { $config['impersonating']['parameters'] = []; } if (!isset($config['impersonating']['route'])) { $config['impersonating'] = false; } return $config; }
[ "public", "function", "fixImpersonating", "(", "array", "$", "config", ")", "{", "if", "(", "isset", "(", "$", "config", "[", "'impersonating'", "]", ",", "$", "config", "[", "'impersonating_route'", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeExcept...
@throws \RuntimeException @return array
[ "@throws", "\\", "RuntimeException" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/DependencyInjection/SonataUserExtension.php#L123-L145
sonata-project/SonataUserBundle
src/DependencyInjection/SonataUserExtension.php
SonataUserExtension.configureGoogleAuthenticator
public function configureGoogleAuthenticator($config, ContainerBuilder $container) { $container->setParameter('sonata.user.google.authenticator.enabled', $config['google_authenticator']['enabled']); if (!$config['google_authenticator']['enabled']) { $container->removeDefinition('sonata.user.google.authenticator'); $container->removeDefinition('sonata.user.google.authenticator.provider'); $container->removeDefinition('sonata.user.google.authenticator.interactive_login_listener'); $container->removeDefinition('sonata.user.google.authenticator.request_listener'); return; } if (!class_exists('Google\Authenticator\GoogleAuthenticator') && !class_exists('Sonata\GoogleAuthenticator\GoogleAuthenticator')) { throw new \RuntimeException('Please add ``sonata-project/google-authenticator`` package'); } $container->setParameter('sonata.user.google.authenticator.forced_for_role', $config['google_authenticator']['forced_for_role']); $container->setParameter('sonata.user.google.authenticator.ip_white_list', $config['google_authenticator']['ip_white_list']); $container->getDefinition('sonata.user.google.authenticator.provider') ->replaceArgument(0, $config['google_authenticator']['server']); }
php
public function configureGoogleAuthenticator($config, ContainerBuilder $container) { $container->setParameter('sonata.user.google.authenticator.enabled', $config['google_authenticator']['enabled']); if (!$config['google_authenticator']['enabled']) { $container->removeDefinition('sonata.user.google.authenticator'); $container->removeDefinition('sonata.user.google.authenticator.provider'); $container->removeDefinition('sonata.user.google.authenticator.interactive_login_listener'); $container->removeDefinition('sonata.user.google.authenticator.request_listener'); return; } if (!class_exists('Google\Authenticator\GoogleAuthenticator') && !class_exists('Sonata\GoogleAuthenticator\GoogleAuthenticator')) { throw new \RuntimeException('Please add ``sonata-project/google-authenticator`` package'); } $container->setParameter('sonata.user.google.authenticator.forced_for_role', $config['google_authenticator']['forced_for_role']); $container->setParameter('sonata.user.google.authenticator.ip_white_list', $config['google_authenticator']['ip_white_list']); $container->getDefinition('sonata.user.google.authenticator.provider') ->replaceArgument(0, $config['google_authenticator']['server']); }
[ "public", "function", "configureGoogleAuthenticator", "(", "$", "config", ",", "ContainerBuilder", "$", "container", ")", "{", "$", "container", "->", "setParameter", "(", "'sonata.user.google.authenticator.enabled'", ",", "$", "config", "[", "'google_authenticator'", "...
@param array $config @param ContainerBuilder $container @throws \RuntimeException @return mixed
[ "@param", "array", "$config", "@param", "ContainerBuilder", "$container" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/DependencyInjection/SonataUserExtension.php#L155-L178
sonata-project/SonataUserBundle
src/DependencyInjection/SonataUserExtension.php
SonataUserExtension.aliasManagers
protected function aliasManagers(ContainerBuilder $container, $managerType): void { $container->setAlias('sonata.user.user_manager', sprintf('sonata.user.%s.user_manager', $managerType)); $container->setAlias('sonata.user.group_manager', sprintf('sonata.user.%s.group_manager', $managerType)); // NEXT_MAJOR: call setPublic(true) directly, when dropping support for Sf 3.3 $container->getAlias('sonata.user.user_manager')->setPublic(true); $container->getAlias('sonata.user.group_manager')->setPublic(true); }
php
protected function aliasManagers(ContainerBuilder $container, $managerType): void { $container->setAlias('sonata.user.user_manager', sprintf('sonata.user.%s.user_manager', $managerType)); $container->setAlias('sonata.user.group_manager', sprintf('sonata.user.%s.group_manager', $managerType)); // NEXT_MAJOR: call setPublic(true) directly, when dropping support for Sf 3.3 $container->getAlias('sonata.user.user_manager')->setPublic(true); $container->getAlias('sonata.user.group_manager')->setPublic(true); }
[ "protected", "function", "aliasManagers", "(", "ContainerBuilder", "$", "container", ",", "$", "managerType", ")", ":", "void", "{", "$", "container", "->", "setAlias", "(", "'sonata.user.user_manager'", ",", "sprintf", "(", "'sonata.user.%s.user_manager'", ",", "$"...
Adds aliases for user & group managers depending on $managerType. @param ContainerBuilder $container @param string $managerType
[ "Adds", "aliases", "for", "user", "&", "group", "managers", "depending", "on", "$managerType", "." ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/DependencyInjection/SonataUserExtension.php#L269-L277
sonata-project/SonataUserBundle
src/Admin/Model/UserAdmin.php
UserAdmin.getFormBuilder
public function getFormBuilder() { $this->formOptions['data_class'] = $this->getClass(); $options = $this->formOptions; $options['validation_groups'] = (!$this->getSubject() || null === $this->getSubject()->getId()) ? 'Registration' : 'Profile'; $formBuilder = $this->getFormContractor()->getFormBuilder($this->getUniqid(), $options); $this->defineFormBuilder($formBuilder); return $formBuilder; }
php
public function getFormBuilder() { $this->formOptions['data_class'] = $this->getClass(); $options = $this->formOptions; $options['validation_groups'] = (!$this->getSubject() || null === $this->getSubject()->getId()) ? 'Registration' : 'Profile'; $formBuilder = $this->getFormContractor()->getFormBuilder($this->getUniqid(), $options); $this->defineFormBuilder($formBuilder); return $formBuilder; }
[ "public", "function", "getFormBuilder", "(", ")", "{", "$", "this", "->", "formOptions", "[", "'data_class'", "]", "=", "$", "this", "->", "getClass", "(", ")", ";", "$", "options", "=", "$", "this", "->", "formOptions", ";", "$", "options", "[", "'val...
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Admin/Model/UserAdmin.php#L42-L54
sonata-project/SonataUserBundle
src/Admin/Model/UserAdmin.php
UserAdmin.preUpdate
public function preUpdate($user): void { $this->getUserManager()->updateCanonicalFields($user); $this->getUserManager()->updatePassword($user); }
php
public function preUpdate($user): void { $this->getUserManager()->updateCanonicalFields($user); $this->getUserManager()->updatePassword($user); }
[ "public", "function", "preUpdate", "(", "$", "user", ")", ":", "void", "{", "$", "this", "->", "getUserManager", "(", ")", "->", "updateCanonicalFields", "(", "$", "user", ")", ";", "$", "this", "->", "getUserManager", "(", ")", "->", "updatePassword", "...
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Admin/Model/UserAdmin.php#L70-L74
sonata-project/SonataUserBundle
src/Admin/Model/UserAdmin.php
UserAdmin.configureShowFields
protected function configureShowFields(ShowMapper $showMapper): void { $showMapper ->with('General') ->add('username') ->add('email') ->end() ->with('Groups') ->add('groups') ->end() ->with('Profile') ->add('dateOfBirth') ->add('firstname') ->add('lastname') ->add('website') ->add('biography') ->add('gender') ->add('locale') ->add('timezone') ->add('phone') ->end() ->with('Social') ->add('facebookUid') ->add('facebookName') ->add('twitterUid') ->add('twitterName') ->add('gplusUid') ->add('gplusName') ->end() ->with('Security') ->add('token') ->add('twoStepVerificationCode') ->end() ; }
php
protected function configureShowFields(ShowMapper $showMapper): void { $showMapper ->with('General') ->add('username') ->add('email') ->end() ->with('Groups') ->add('groups') ->end() ->with('Profile') ->add('dateOfBirth') ->add('firstname') ->add('lastname') ->add('website') ->add('biography') ->add('gender') ->add('locale') ->add('timezone') ->add('phone') ->end() ->with('Social') ->add('facebookUid') ->add('facebookName') ->add('twitterUid') ->add('twitterName') ->add('gplusUid') ->add('gplusName') ->end() ->with('Security') ->add('token') ->add('twoStepVerificationCode') ->end() ; }
[ "protected", "function", "configureShowFields", "(", "ShowMapper", "$", "showMapper", ")", ":", "void", "{", "$", "showMapper", "->", "with", "(", "'General'", ")", "->", "add", "(", "'username'", ")", "->", "add", "(", "'email'", ")", "->", "end", "(", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Admin/Model/UserAdmin.php#L128-L162
sonata-project/SonataUserBundle
src/Admin/Model/UserAdmin.php
UserAdmin.configureFormFields
protected function configureFormFields(FormMapper $formMapper): void { // define group zoning $formMapper ->tab('User') ->with('Profile', ['class' => 'col-md-6'])->end() ->with('General', ['class' => 'col-md-6'])->end() ->with('Social', ['class' => 'col-md-6'])->end() ->end() ->tab('Security') ->with('Status', ['class' => 'col-md-4'])->end() ->with('Groups', ['class' => 'col-md-4'])->end() ->with('Keys', ['class' => 'col-md-4'])->end() ->with('Roles', ['class' => 'col-md-12'])->end() ->end() ; $now = new \DateTime(); $genderOptions = [ 'choices' => \call_user_func([$this->getUserManager()->getClass(), 'getGenderList']), 'required' => true, 'translation_domain' => $this->getTranslationDomain(), ]; // NEXT_MAJOR: Remove this when dropping support for SF 2.8 if (method_exists(FormTypeInterface::class, 'setDefaultOptions')) { $genderOptions['choices_as_values'] = true; } $formMapper ->tab('User') ->with('General') ->add('username') ->add('email') ->add('plainPassword', TextType::class, [ 'required' => (!$this->getSubject() || null === $this->getSubject()->getId()), ]) ->end() ->with('Profile') ->add('dateOfBirth', DatePickerType::class, [ 'years' => range(1900, $now->format('Y')), 'dp_min_date' => '1-1-1900', 'dp_max_date' => $now->format('c'), 'required' => false, ]) ->add('firstname', null, ['required' => false]) ->add('lastname', null, ['required' => false]) ->add('website', UrlType::class, ['required' => false]) ->add('biography', TextType::class, ['required' => false]) ->add('gender', ChoiceType::class, $genderOptions) ->add('locale', LocaleType::class, ['required' => false]) ->add('timezone', TimezoneType::class, ['required' => false]) ->add('phone', null, ['required' => false]) ->end() ->with('Social') ->add('facebookUid', null, ['required' => false]) ->add('facebookName', null, ['required' => false]) ->add('twitterUid', null, ['required' => false]) ->add('twitterName', null, ['required' => false]) ->add('gplusUid', null, ['required' => false]) ->add('gplusName', null, ['required' => false]) ->end() ->end() ->tab('Security') ->with('Status') ->add('enabled', null, ['required' => false]) ->end() ->with('Groups') ->add('groups', ModelType::class, [ 'required' => false, 'expanded' => true, 'multiple' => true, ]) ->end() ->with('Roles') ->add('realRoles', SecurityRolesType::class, [ 'label' => 'form.label_roles', 'expanded' => true, 'multiple' => true, 'required' => false, ]) ->end() ->with('Keys') ->add('token', null, ['required' => false]) ->add('twoStepVerificationCode', null, ['required' => false]) ->end() ->end() ; }
php
protected function configureFormFields(FormMapper $formMapper): void { // define group zoning $formMapper ->tab('User') ->with('Profile', ['class' => 'col-md-6'])->end() ->with('General', ['class' => 'col-md-6'])->end() ->with('Social', ['class' => 'col-md-6'])->end() ->end() ->tab('Security') ->with('Status', ['class' => 'col-md-4'])->end() ->with('Groups', ['class' => 'col-md-4'])->end() ->with('Keys', ['class' => 'col-md-4'])->end() ->with('Roles', ['class' => 'col-md-12'])->end() ->end() ; $now = new \DateTime(); $genderOptions = [ 'choices' => \call_user_func([$this->getUserManager()->getClass(), 'getGenderList']), 'required' => true, 'translation_domain' => $this->getTranslationDomain(), ]; // NEXT_MAJOR: Remove this when dropping support for SF 2.8 if (method_exists(FormTypeInterface::class, 'setDefaultOptions')) { $genderOptions['choices_as_values'] = true; } $formMapper ->tab('User') ->with('General') ->add('username') ->add('email') ->add('plainPassword', TextType::class, [ 'required' => (!$this->getSubject() || null === $this->getSubject()->getId()), ]) ->end() ->with('Profile') ->add('dateOfBirth', DatePickerType::class, [ 'years' => range(1900, $now->format('Y')), 'dp_min_date' => '1-1-1900', 'dp_max_date' => $now->format('c'), 'required' => false, ]) ->add('firstname', null, ['required' => false]) ->add('lastname', null, ['required' => false]) ->add('website', UrlType::class, ['required' => false]) ->add('biography', TextType::class, ['required' => false]) ->add('gender', ChoiceType::class, $genderOptions) ->add('locale', LocaleType::class, ['required' => false]) ->add('timezone', TimezoneType::class, ['required' => false]) ->add('phone', null, ['required' => false]) ->end() ->with('Social') ->add('facebookUid', null, ['required' => false]) ->add('facebookName', null, ['required' => false]) ->add('twitterUid', null, ['required' => false]) ->add('twitterName', null, ['required' => false]) ->add('gplusUid', null, ['required' => false]) ->add('gplusName', null, ['required' => false]) ->end() ->end() ->tab('Security') ->with('Status') ->add('enabled', null, ['required' => false]) ->end() ->with('Groups') ->add('groups', ModelType::class, [ 'required' => false, 'expanded' => true, 'multiple' => true, ]) ->end() ->with('Roles') ->add('realRoles', SecurityRolesType::class, [ 'label' => 'form.label_roles', 'expanded' => true, 'multiple' => true, 'required' => false, ]) ->end() ->with('Keys') ->add('token', null, ['required' => false]) ->add('twoStepVerificationCode', null, ['required' => false]) ->end() ->end() ; }
[ "protected", "function", "configureFormFields", "(", "FormMapper", "$", "formMapper", ")", ":", "void", "{", "// define group zoning", "$", "formMapper", "->", "tab", "(", "'User'", ")", "->", "with", "(", "'Profile'", ",", "[", "'class'", "=>", "'col-md-6'", ...
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Admin/Model/UserAdmin.php#L167-L256
sonata-project/SonataUserBundle
src/SonataUserBundle.php
SonataUserBundle.build
public function build(ContainerBuilder $container): void { $container->addCompilerPass(new GlobalVariablesCompilerPass()); $container->addCompilerPass(new RolesMatrixCompilerPass()); $this->registerFormMapping(); }
php
public function build(ContainerBuilder $container): void { $container->addCompilerPass(new GlobalVariablesCompilerPass()); $container->addCompilerPass(new RolesMatrixCompilerPass()); $this->registerFormMapping(); }
[ "public", "function", "build", "(", "ContainerBuilder", "$", "container", ")", ":", "void", "{", "$", "container", "->", "addCompilerPass", "(", "new", "GlobalVariablesCompilerPass", "(", ")", ")", ";", "$", "container", "->", "addCompilerPass", "(", "new", "R...
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/SonataUserBundle.php#L27-L33
sonata-project/SonataUserBundle
src/Controller/Api/UserController.php
UserController.getUsersAction
public function getUsersAction(ParamFetcherInterface $paramFetcher) { $supporedCriteria = [ 'enabled' => '', ]; $page = $paramFetcher->get('page'); $limit = $paramFetcher->get('count'); $sort = $paramFetcher->get('orderBy'); $criteria = array_intersect_key($paramFetcher->all(), $supporedCriteria); foreach ($criteria as $key => $value) { if (null === $value) { unset($criteria[$key]); } } if (!$sort) { $sort = []; } elseif (!\is_array($sort)) { $sort = [$sort, 'asc']; } return $this->userManager->getPager($criteria, $page, $limit, $sort); }
php
public function getUsersAction(ParamFetcherInterface $paramFetcher) { $supporedCriteria = [ 'enabled' => '', ]; $page = $paramFetcher->get('page'); $limit = $paramFetcher->get('count'); $sort = $paramFetcher->get('orderBy'); $criteria = array_intersect_key($paramFetcher->all(), $supporedCriteria); foreach ($criteria as $key => $value) { if (null === $value) { unset($criteria[$key]); } } if (!$sort) { $sort = []; } elseif (!\is_array($sort)) { $sort = [$sort, 'asc']; } return $this->userManager->getPager($criteria, $page, $limit, $sort); }
[ "public", "function", "getUsersAction", "(", "ParamFetcherInterface", "$", "paramFetcher", ")", "{", "$", "supporedCriteria", "=", "[", "'enabled'", "=>", "''", ",", "]", ";", "$", "page", "=", "$", "paramFetcher", "->", "get", "(", "'page'", ")", ";", "$"...
Returns a paginated list of users. @ApiDoc( resource=true, output={"class"="Sonata\DatagridBundle\Pager\PagerInterface", "groups"={"sonata_api_read"}} ) @QueryParam(name="page", requirements="\d+", default="1", description="Page for users list pagination (1-indexed)") @QueryParam(name="count", requirements="\d+", default="10", description="Number of users by page") @QueryParam(name="orderBy", map=true, requirements="ASC|DESC", nullable=true, strict=true, description="Query users order by clause (key is field, value is direction") @QueryParam(name="enabled", requirements="0|1", nullable=true, strict=true, description="Enabled/disabled users only?") @View(serializerGroups={"sonata_api_read"}, serializerEnableMaxDepthChecks=true) @param ParamFetcherInterface $paramFetcher @return PagerInterface
[ "Returns", "a", "paginated", "list", "of", "users", "." ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Controller/Api/UserController.php#L83-L107
sonata-project/SonataUserBundle
src/Controller/Api/UserController.php
UserController.deleteUserAction
public function deleteUserAction($id) { $user = $this->getUser($id); $this->userManager->deleteUser($user); return ['deleted' => true]; }
php
public function deleteUserAction($id) { $user = $this->getUser($id); $this->userManager->deleteUser($user); return ['deleted' => true]; }
[ "public", "function", "deleteUserAction", "(", "$", "id", ")", "{", "$", "user", "=", "$", "this", "->", "getUser", "(", "$", "id", ")", ";", "$", "this", "->", "userManager", "->", "deleteUser", "(", "$", "user", ")", ";", "return", "[", "'deleted'"...
Deletes an user. @ApiDoc( requirements={ {"name"="id", "dataType"="integer", "requirement"="\d+", "description"="user identifier"} }, statusCodes={ 200="Returned when user is successfully deleted", 400="Returned when an error has occurred while user deletion", 404="Returned when unable to find user" } ) @param int $id An User identifier @throws NotFoundHttpException @return \FOS\RestBundle\View\View
[ "Deletes", "an", "user", "." ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Controller/Api/UserController.php#L205-L212
sonata-project/SonataUserBundle
src/Controller/Api/UserController.php
UserController.postUserGroupAction
public function postUserGroupAction($userId, $groupId) { $user = $this->getUser($userId); $group = $this->getGroup($groupId); if ($user->hasGroup($group)) { return FOSRestView::create([ 'error' => sprintf('User "%s" already has group "%s"', $userId, $groupId), ], 400); } $user->addGroup($group); $this->userManager->updateUser($user); return ['added' => true]; }
php
public function postUserGroupAction($userId, $groupId) { $user = $this->getUser($userId); $group = $this->getGroup($groupId); if ($user->hasGroup($group)) { return FOSRestView::create([ 'error' => sprintf('User "%s" already has group "%s"', $userId, $groupId), ], 400); } $user->addGroup($group); $this->userManager->updateUser($user); return ['added' => true]; }
[ "public", "function", "postUserGroupAction", "(", "$", "userId", ",", "$", "groupId", ")", "{", "$", "user", "=", "$", "this", "->", "getUser", "(", "$", "userId", ")", ";", "$", "group", "=", "$", "this", "->", "getGroup", "(", "$", "groupId", ")", ...
Attach a group to a user. @ApiDoc( requirements={ {"name"="userId", "dataType"="integer", "requirement"="\d+", "description"="user identifier"}, {"name"="groupId", "dataType"="integer", "requirement"="\d+", "description"="group identifier"} }, output={"class"="Sonata\UserBundle\Model\User", "groups"={"sonata_api_read"}}, statusCodes={ 200="Returned when successful", 400="Returned when an error has occurred while user/group attachment", 404="Returned when unable to find user or group" } ) @param int $userId A User identifier @param int $groupId A Group identifier @throws NotFoundHttpException @throws \RuntimeException @return UserInterface
[ "Attach", "a", "group", "to", "a", "user", "." ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Controller/Api/UserController.php#L238-L253
sonata-project/SonataUserBundle
src/Controller/Api/UserController.php
UserController.deleteUserGroupAction
public function deleteUserGroupAction($userId, $groupId) { $user = $this->getUser($userId); $group = $this->getGroup($groupId); if (!$user->hasGroup($group)) { return FOSRestView::create([ 'error' => sprintf('User "%s" has not group "%s"', $userId, $groupId), ], 400); } $user->removeGroup($group); $this->userManager->updateUser($user); return ['removed' => true]; }
php
public function deleteUserGroupAction($userId, $groupId) { $user = $this->getUser($userId); $group = $this->getGroup($groupId); if (!$user->hasGroup($group)) { return FOSRestView::create([ 'error' => sprintf('User "%s" has not group "%s"', $userId, $groupId), ], 400); } $user->removeGroup($group); $this->userManager->updateUser($user); return ['removed' => true]; }
[ "public", "function", "deleteUserGroupAction", "(", "$", "userId", ",", "$", "groupId", ")", "{", "$", "user", "=", "$", "this", "->", "getUser", "(", "$", "userId", ")", ";", "$", "group", "=", "$", "this", "->", "getGroup", "(", "$", "groupId", ")"...
Detach a group to a user. @ApiDoc( requirements={ {"name"="userId", "dataType"="integer", "requirement"="\d+", "description"="user identifier"}, {"name"="groupId", "dataType"="integer", "requirement"="\d+", "description"="group identifier"} }, output={"class"="Sonata\UserBundle\Model\User", "groups"={"sonata_api_read"}}, statusCodes={ 200="Returned when successful", 400="Returned when an error has occurred while user/group detachment", 404="Returned when unable to find user or group" } ) @param int $userId A User identifier @param int $groupId A Group identifier @throws NotFoundHttpException @throws \RuntimeException @return UserInterface
[ "Detach", "a", "group", "to", "a", "user", "." ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Controller/Api/UserController.php#L279-L294
sonata-project/SonataUserBundle
src/Controller/Api/UserController.php
UserController.getUser
protected function getUser($id) { $user = $this->userManager->findUserBy(['id' => $id]); if (null === $user) { throw new NotFoundHttpException(sprintf('User (%d) not found', $id)); } return $user; }
php
protected function getUser($id) { $user = $this->userManager->findUserBy(['id' => $id]); if (null === $user) { throw new NotFoundHttpException(sprintf('User (%d) not found', $id)); } return $user; }
[ "protected", "function", "getUser", "(", "$", "id", ")", "{", "$", "user", "=", "$", "this", "->", "userManager", "->", "findUserBy", "(", "[", "'id'", "=>", "$", "id", "]", ")", ";", "if", "(", "null", "===", "$", "user", ")", "{", "throw", "new...
Retrieves user with id $id or throws an exception if it doesn't exist. @param $id @throws NotFoundHttpException @return UserInterface
[ "Retrieves", "user", "with", "id", "$id", "or", "throws", "an", "exception", "if", "it", "doesn", "t", "exist", "." ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Controller/Api/UserController.php#L305-L314
sonata-project/SonataUserBundle
src/Controller/Api/UserController.php
UserController.getGroup
protected function getGroup($id) { $group = $this->groupManager->findGroupBy(['id' => $id]); if (null === $group) { throw new NotFoundHttpException(sprintf('Group (%d) not found', $id)); } return $group; }
php
protected function getGroup($id) { $group = $this->groupManager->findGroupBy(['id' => $id]); if (null === $group) { throw new NotFoundHttpException(sprintf('Group (%d) not found', $id)); } return $group; }
[ "protected", "function", "getGroup", "(", "$", "id", ")", "{", "$", "group", "=", "$", "this", "->", "groupManager", "->", "findGroupBy", "(", "[", "'id'", "=>", "$", "id", "]", ")", ";", "if", "(", "null", "===", "$", "group", ")", "{", "throw", ...
Retrieves user with id $id or throws an exception if it doesn't exist. @param $id @throws NotFoundHttpException @return GroupInterface
[ "Retrieves", "user", "with", "id", "$id", "or", "throws", "an", "exception", "if", "it", "doesn", "t", "exist", "." ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Controller/Api/UserController.php#L325-L334
sonata-project/SonataUserBundle
src/Controller/Api/UserController.php
UserController.handleWriteUser
protected function handleWriteUser($request, $id = null) { $user = $id ? $this->getUser($id) : null; $form = $this->formFactory->createNamed(null, 'sonata_user_api_form_user', $user, [ 'csrf_protection' => false, ]); $form->handleRequest($request); if ($form->isValid()) { $user = $form->getData(); $this->userManager->updateUser($user); $context = new Context(); $context->setGroups(['sonata_api_read']); $context->enableMaxDepth(); $view = FOSRestView::create($user); $view->setContext($context); return $view; } return $form; }
php
protected function handleWriteUser($request, $id = null) { $user = $id ? $this->getUser($id) : null; $form = $this->formFactory->createNamed(null, 'sonata_user_api_form_user', $user, [ 'csrf_protection' => false, ]); $form->handleRequest($request); if ($form->isValid()) { $user = $form->getData(); $this->userManager->updateUser($user); $context = new Context(); $context->setGroups(['sonata_api_read']); $context->enableMaxDepth(); $view = FOSRestView::create($user); $view->setContext($context); return $view; } return $form; }
[ "protected", "function", "handleWriteUser", "(", "$", "request", ",", "$", "id", "=", "null", ")", "{", "$", "user", "=", "$", "id", "?", "$", "this", "->", "getUser", "(", "$", "id", ")", ":", "null", ";", "$", "form", "=", "$", "this", "->", ...
Write an User, this method is used by both POST and PUT action methods. @param Request $request Symfony request @param int|null $id An User identifier @return FormInterface
[ "Write", "an", "User", "this", "method", "is", "used", "by", "both", "POST", "and", "PUT", "action", "methods", "." ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Controller/Api/UserController.php#L344-L369
sonata-project/SonataUserBundle
src/DependencyInjection/Configuration.php
Configuration.getConfigTreeBuilder
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('sonata_user'); // Keep compatibility with symfony/config < 4.2 if (!method_exists($treeBuilder, 'getRootNode')) { $rootNode = $treeBuilder->root('sonata_user'); } else { $rootNode = $treeBuilder->getRootNode(); } $supportedManagerTypes = ['orm', 'mongodb']; $rootNode ->children() ->booleanNode('security_acl')->defaultFalse()->end() ->arrayNode('table') ->addDefaultsIfNotSet() ->children() ->scalarNode('user_group')->defaultValue('fos_user_user_group')->end() ->end() ->end() ->scalarNode('impersonating_route')->end() ->arrayNode('impersonating') ->children() ->scalarNode('route')->defaultFalse()->end() ->arrayNode('parameters') ->useAttributeAsKey('id') ->prototype('scalar')->end() ->end() ->end() ->end() ->arrayNode('google_authenticator') ->addDefaultsIfNotSet() ->children() ->scalarNode('server')->cannotBeEmpty()->end() ->scalarNode('enabled')->defaultFalse()->end() ->arrayNode('ip_white_list') ->prototype('scalar')->end() ->defaultValue(['127.0.0.1']) ->info('IPs for which 2FA will be skipped.') ->end() ->arrayNode('forced_for_role') ->prototype('scalar')->end() ->defaultValue(['ROLE_ADMIN']) ->info('User roles for which 2FA is necessary.') ->end() ->end() ->end() ->scalarNode('manager_type') ->defaultValue('orm') ->validate() ->ifNotInArray($supportedManagerTypes) ->thenInvalid('The manager type %s is not supported. Please choose one of '.json_encode($supportedManagerTypes)) ->end() ->end() ->arrayNode('class') ->addDefaultsIfNotSet() ->children() ->scalarNode('group')->cannotBeEmpty()->defaultValue(BaseGroup::class)->end() ->scalarNode('user')->cannotBeEmpty()->defaultValue(BaseUser::class)->end() ->end() ->end() ->arrayNode('admin') ->addDefaultsIfNotSet() ->children() ->arrayNode('group') ->addDefaultsIfNotSet() ->children() ->scalarNode('class')->cannotBeEmpty()->defaultValue(GroupAdmin::class)->end() ->scalarNode('controller')->cannotBeEmpty()->defaultValue('SonataAdminBundle:CRUD')->end() ->scalarNode('translation')->cannotBeEmpty()->defaultValue('SonataUserBundle')->end() ->end() ->end() ->arrayNode('user') ->addDefaultsIfNotSet() ->children() ->scalarNode('class')->cannotBeEmpty()->defaultValue(UserAdmin::class)->end() ->scalarNode('controller')->cannotBeEmpty()->defaultValue('SonataAdminBundle:CRUD')->end() ->scalarNode('translation')->cannotBeEmpty()->defaultValue('SonataUserBundle')->end() ->end() ->end() ->end() ->end() ->arrayNode('profile') ->addDefaultsIfNotSet() ->children() ->scalarNode('default_avatar')->defaultValue('bundles/sonatauser/default_avatar.png')->end() ->end() ->end() ->scalarNode('mailer')->defaultValue('sonata.user.mailer.default')->info('Custom mailer used to send reset password emails')->end() ->end() ; return $treeBuilder; }
php
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('sonata_user'); // Keep compatibility with symfony/config < 4.2 if (!method_exists($treeBuilder, 'getRootNode')) { $rootNode = $treeBuilder->root('sonata_user'); } else { $rootNode = $treeBuilder->getRootNode(); } $supportedManagerTypes = ['orm', 'mongodb']; $rootNode ->children() ->booleanNode('security_acl')->defaultFalse()->end() ->arrayNode('table') ->addDefaultsIfNotSet() ->children() ->scalarNode('user_group')->defaultValue('fos_user_user_group')->end() ->end() ->end() ->scalarNode('impersonating_route')->end() ->arrayNode('impersonating') ->children() ->scalarNode('route')->defaultFalse()->end() ->arrayNode('parameters') ->useAttributeAsKey('id') ->prototype('scalar')->end() ->end() ->end() ->end() ->arrayNode('google_authenticator') ->addDefaultsIfNotSet() ->children() ->scalarNode('server')->cannotBeEmpty()->end() ->scalarNode('enabled')->defaultFalse()->end() ->arrayNode('ip_white_list') ->prototype('scalar')->end() ->defaultValue(['127.0.0.1']) ->info('IPs for which 2FA will be skipped.') ->end() ->arrayNode('forced_for_role') ->prototype('scalar')->end() ->defaultValue(['ROLE_ADMIN']) ->info('User roles for which 2FA is necessary.') ->end() ->end() ->end() ->scalarNode('manager_type') ->defaultValue('orm') ->validate() ->ifNotInArray($supportedManagerTypes) ->thenInvalid('The manager type %s is not supported. Please choose one of '.json_encode($supportedManagerTypes)) ->end() ->end() ->arrayNode('class') ->addDefaultsIfNotSet() ->children() ->scalarNode('group')->cannotBeEmpty()->defaultValue(BaseGroup::class)->end() ->scalarNode('user')->cannotBeEmpty()->defaultValue(BaseUser::class)->end() ->end() ->end() ->arrayNode('admin') ->addDefaultsIfNotSet() ->children() ->arrayNode('group') ->addDefaultsIfNotSet() ->children() ->scalarNode('class')->cannotBeEmpty()->defaultValue(GroupAdmin::class)->end() ->scalarNode('controller')->cannotBeEmpty()->defaultValue('SonataAdminBundle:CRUD')->end() ->scalarNode('translation')->cannotBeEmpty()->defaultValue('SonataUserBundle')->end() ->end() ->end() ->arrayNode('user') ->addDefaultsIfNotSet() ->children() ->scalarNode('class')->cannotBeEmpty()->defaultValue(UserAdmin::class)->end() ->scalarNode('controller')->cannotBeEmpty()->defaultValue('SonataAdminBundle:CRUD')->end() ->scalarNode('translation')->cannotBeEmpty()->defaultValue('SonataUserBundle')->end() ->end() ->end() ->end() ->end() ->arrayNode('profile') ->addDefaultsIfNotSet() ->children() ->scalarNode('default_avatar')->defaultValue('bundles/sonatauser/default_avatar.png')->end() ->end() ->end() ->scalarNode('mailer')->defaultValue('sonata.user.mailer.default')->info('Custom mailer used to send reset password emails')->end() ->end() ; return $treeBuilder; }
[ "public", "function", "getConfigTreeBuilder", "(", ")", "{", "$", "treeBuilder", "=", "new", "TreeBuilder", "(", "'sonata_user'", ")", ";", "// Keep compatibility with symfony/config < 4.2", "if", "(", "!", "method_exists", "(", "$", "treeBuilder", ",", "'getRootNode'...
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/DependencyInjection/Configuration.php#L33-L129
sonata-project/SonataUserBundle
src/Form/Type/RolesMatrixType.php
RolesMatrixType.configureOptions
public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'expanded' => true, 'choices' => function (Options $options, $parentChoices): array { if (!empty($parentChoices)) { return []; } $roles = $this->rolesBuilder->getRoles( $options['choice_translation_domain'], $options['expanded'] ); $roles = array_keys($roles); return array_combine($roles, $roles); }, 'choice_translation_domain' => static function (Options $options, $value): ?string { // if choice_translation_domain is true, then it's the same as translation_domain if (true === $value) { $value = $options['translation_domain']; } if (null === $value) { // no translation domain yet, try to ask sonata admin $admin = null; if (isset($options['sonata_admin'])) { $admin = $options['sonata_admin']; } if (null === $admin && isset($options['sonata_field_description'])) { $admin = $options['sonata_field_description']->getAdmin(); } if (null !== $admin) { $value = $admin->getTranslationDomain(); } } return $value; }, 'data_class' => null, ]); // Symfony 2.8 BC if (method_exists(FormTypeInterface::class, 'setDefaultOptions')) { $resolver->setDefault('choices_as_values', true); } }
php
public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'expanded' => true, 'choices' => function (Options $options, $parentChoices): array { if (!empty($parentChoices)) { return []; } $roles = $this->rolesBuilder->getRoles( $options['choice_translation_domain'], $options['expanded'] ); $roles = array_keys($roles); return array_combine($roles, $roles); }, 'choice_translation_domain' => static function (Options $options, $value): ?string { // if choice_translation_domain is true, then it's the same as translation_domain if (true === $value) { $value = $options['translation_domain']; } if (null === $value) { // no translation domain yet, try to ask sonata admin $admin = null; if (isset($options['sonata_admin'])) { $admin = $options['sonata_admin']; } if (null === $admin && isset($options['sonata_field_description'])) { $admin = $options['sonata_field_description']->getAdmin(); } if (null !== $admin) { $value = $admin->getTranslationDomain(); } } return $value; }, 'data_class' => null, ]); // Symfony 2.8 BC if (method_exists(FormTypeInterface::class, 'setDefaultOptions')) { $resolver->setDefault('choices_as_values', true); } }
[ "public", "function", "configureOptions", "(", "OptionsResolver", "$", "resolver", ")", ":", "void", "{", "$", "resolver", "->", "setDefaults", "(", "[", "'expanded'", "=>", "true", ",", "'choices'", "=>", "function", "(", "Options", "$", "options", ",", "$"...
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Form/Type/RolesMatrixType.php#L41-L87
sonata-project/SonataUserBundle
src/Controller/Api/GroupController.php
GroupController.getGroupsAction
public function getGroupsAction(ParamFetcherInterface $paramFetcher) { $supportedFilters = [ 'enabled' => '', ]; $page = $paramFetcher->get('page'); $limit = $paramFetcher->get('count'); $sort = $paramFetcher->get('orderBy'); $criteria = array_intersect_key($paramFetcher->all(), $supportedFilters); foreach ($criteria as $key => $value) { if (null === $value) { unset($criteria[$key]); } } if (!$sort) { $sort = []; } elseif (!\is_array($sort)) { $sort = [$sort, 'asc']; } return $this->groupManager->getPager($criteria, $page, $limit, $sort); }
php
public function getGroupsAction(ParamFetcherInterface $paramFetcher) { $supportedFilters = [ 'enabled' => '', ]; $page = $paramFetcher->get('page'); $limit = $paramFetcher->get('count'); $sort = $paramFetcher->get('orderBy'); $criteria = array_intersect_key($paramFetcher->all(), $supportedFilters); foreach ($criteria as $key => $value) { if (null === $value) { unset($criteria[$key]); } } if (!$sort) { $sort = []; } elseif (!\is_array($sort)) { $sort = [$sort, 'asc']; } return $this->groupManager->getPager($criteria, $page, $limit, $sort); }
[ "public", "function", "getGroupsAction", "(", "ParamFetcherInterface", "$", "paramFetcher", ")", "{", "$", "supportedFilters", "=", "[", "'enabled'", "=>", "''", ",", "]", ";", "$", "page", "=", "$", "paramFetcher", "->", "get", "(", "'page'", ")", ";", "$...
Returns a paginated list of groups. @ApiDoc( resource=true, output={"class"="Sonata\DatagridBundle\Pager\PagerInterface", "groups"={"sonata_api_read"}} ) @QueryParam(name="page", requirements="\d+", default="1", description="Page for groups list pagination (1-indexed)") @QueryParam(name="count", requirements="\d+", default="10", description="Number of groups by page") @QueryParam(name="orderBy", map=true, requirements="ASC|DESC", nullable=true, strict=true, description="Query groups order by clause (key is field, value is direction") @QueryParam(name="enabled", requirements="0|1", nullable=true, strict=true, description="Enabled/disabled groups only?") @View(serializerGroups={"sonata_api_read"}, serializerEnableMaxDepthChecks=true) @param ParamFetcherInterface $paramFetcher @return PagerInterface
[ "Returns", "a", "paginated", "list", "of", "groups", "." ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Controller/Api/GroupController.php#L74-L98
sonata-project/SonataUserBundle
src/Controller/Api/GroupController.php
GroupController.deleteGroupAction
public function deleteGroupAction($id) { $group = $this->getGroup($id); $this->groupManager->deleteGroup($group); return ['deleted' => true]; }
php
public function deleteGroupAction($id) { $group = $this->getGroup($id); $this->groupManager->deleteGroup($group); return ['deleted' => true]; }
[ "public", "function", "deleteGroupAction", "(", "$", "id", ")", "{", "$", "group", "=", "$", "this", "->", "getGroup", "(", "$", "id", ")", ";", "$", "this", "->", "groupManager", "->", "deleteGroup", "(", "$", "group", ")", ";", "return", "[", "'del...
Deletes a group. @ApiDoc( requirements={ {"name"="id", "dataType"="integer", "requirement"="\d+", "description"="group identifier"} }, statusCodes={ 200="Returned when group is successfully deleted", 400="Returned when an error has occurred while group deletion", 404="Returned when unable to find group" } ) @param int $id A Group identifier @throws NotFoundHttpException @return \FOS\RestBundle\View\View
[ "Deletes", "a", "group", "." ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Controller/Api/GroupController.php#L196-L203
sonata-project/SonataUserBundle
src/Controller/Api/GroupController.php
GroupController.handleWriteGroup
protected function handleWriteGroup($request, $id = null) { $groupClassName = $this->groupManager->getClass(); $group = $id ? $this->getGroup($id) : new $groupClassName(''); $form = $this->formFactory->createNamed(null, 'sonata_user_api_form_group', $group, [ 'csrf_protection' => false, ]); $form->handleRequest($request); if ($form->isValid()) { $group = $form->getData(); $this->groupManager->updateGroup($group); $context = new Context(); $context->setGroups(['sonata_api_read']); $context->enableMaxDepth(); $view = FOSRestView::create($group); $view->setContext($context); return $view; } return $form; }
php
protected function handleWriteGroup($request, $id = null) { $groupClassName = $this->groupManager->getClass(); $group = $id ? $this->getGroup($id) : new $groupClassName(''); $form = $this->formFactory->createNamed(null, 'sonata_user_api_form_group', $group, [ 'csrf_protection' => false, ]); $form->handleRequest($request); if ($form->isValid()) { $group = $form->getData(); $this->groupManager->updateGroup($group); $context = new Context(); $context->setGroups(['sonata_api_read']); $context->enableMaxDepth(); $view = FOSRestView::create($group); $view->setContext($context); return $view; } return $form; }
[ "protected", "function", "handleWriteGroup", "(", "$", "request", ",", "$", "id", "=", "null", ")", "{", "$", "groupClassName", "=", "$", "this", "->", "groupManager", "->", "getClass", "(", ")", ";", "$", "group", "=", "$", "id", "?", "$", "this", "...
Write a Group, this method is used by both POST and PUT action methods. @param Request $request Symfony request @param int|null $id A Group identifier @return FormInterface
[ "Write", "a", "Group", "this", "method", "is", "used", "by", "both", "POST", "and", "PUT", "action", "methods", "." ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Controller/Api/GroupController.php#L213-L239
sonata-project/SonataUserBundle
src/Security/EditableRolesBuilder.php
EditableRolesBuilder.getRoles
public function getRoles($domain = false, $expanded = true) { $roles = []; if (!$this->tokenStorage->getToken()) { return $roles; } $this->iterateAdminRoles(function ($role, $isMaster) use ($domain, &$roles): void { if ($isMaster) { // if the user has the MASTER permission, allow to grant access the admin roles to other users $roles[$role] = $this->translateRole($role, $domain); } }); $isMaster = $this->authorizationChecker->isGranted( $this->pool->getOption('role_super_admin', 'ROLE_SUPER_ADMIN') ); // get roles from the service container foreach ($this->rolesHierarchy as $name => $rolesHierarchy) { if ($this->authorizationChecker->isGranted($name) || $isMaster) { $roles[$name] = $this->translateRole($name, $domain); if ($expanded) { $result = array_map([$this, 'translateRole'], $rolesHierarchy, array_fill(0, \count($rolesHierarchy), $domain)); $roles[$name] .= ': '.implode(', ', $result); } foreach ($rolesHierarchy as $role) { if (!isset($roles[$role])) { $roles[$role] = $this->translateRole($role, $domain); } } } } return $roles; }
php
public function getRoles($domain = false, $expanded = true) { $roles = []; if (!$this->tokenStorage->getToken()) { return $roles; } $this->iterateAdminRoles(function ($role, $isMaster) use ($domain, &$roles): void { if ($isMaster) { // if the user has the MASTER permission, allow to grant access the admin roles to other users $roles[$role] = $this->translateRole($role, $domain); } }); $isMaster = $this->authorizationChecker->isGranted( $this->pool->getOption('role_super_admin', 'ROLE_SUPER_ADMIN') ); // get roles from the service container foreach ($this->rolesHierarchy as $name => $rolesHierarchy) { if ($this->authorizationChecker->isGranted($name) || $isMaster) { $roles[$name] = $this->translateRole($name, $domain); if ($expanded) { $result = array_map([$this, 'translateRole'], $rolesHierarchy, array_fill(0, \count($rolesHierarchy), $domain)); $roles[$name] .= ': '.implode(', ', $result); } foreach ($rolesHierarchy as $role) { if (!isset($roles[$role])) { $roles[$role] = $this->translateRole($role, $domain); } } } } return $roles; }
[ "public", "function", "getRoles", "(", "$", "domain", "=", "false", ",", "$", "expanded", "=", "true", ")", "{", "$", "roles", "=", "[", "]", ";", "if", "(", "!", "$", "this", "->", "tokenStorage", "->", "getToken", "(", ")", ")", "{", "return", ...
@param string|bool|null $domain @param bool $expanded @return array
[ "@param", "string|bool|null", "$domain", "@param", "bool", "$expanded" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Security/EditableRolesBuilder.php#L76-L112
sonata-project/SonataUserBundle
src/Security/EditableRolesBuilder.php
EditableRolesBuilder.getRolesReadOnly
public function getRolesReadOnly($domain = false) { $rolesReadOnly = []; if (!$this->tokenStorage->getToken()) { return $rolesReadOnly; } $this->iterateAdminRoles(function ($role, $isMaster) use ($domain, &$rolesReadOnly): void { if (!$isMaster && $this->authorizationChecker->isGranted($role)) { // although the user has no MASTER permission, allow the currently logged in user to view the role $rolesReadOnly[$role] = $this->translateRole($role, $domain); } }); return $rolesReadOnly; }
php
public function getRolesReadOnly($domain = false) { $rolesReadOnly = []; if (!$this->tokenStorage->getToken()) { return $rolesReadOnly; } $this->iterateAdminRoles(function ($role, $isMaster) use ($domain, &$rolesReadOnly): void { if (!$isMaster && $this->authorizationChecker->isGranted($role)) { // although the user has no MASTER permission, allow the currently logged in user to view the role $rolesReadOnly[$role] = $this->translateRole($role, $domain); } }); return $rolesReadOnly; }
[ "public", "function", "getRolesReadOnly", "(", "$", "domain", "=", "false", ")", "{", "$", "rolesReadOnly", "=", "[", "]", ";", "if", "(", "!", "$", "this", "->", "tokenStorage", "->", "getToken", "(", ")", ")", "{", "return", "$", "rolesReadOnly", ";"...
@param string|bool|null $domain @return array
[ "@param", "string|bool|null", "$domain" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Security/EditableRolesBuilder.php#L119-L135
sonata-project/SonataUserBundle
src/Security/EditableRolesBuilder.php
EditableRolesBuilder.translateRole
private function translateRole($role, $domain) { // translation domain is false, do not translate it, // null is fallback to message domain if (false === $domain || !isset($this->translator)) { return $role; } return $this->translator->trans($role, [], $domain); }
php
private function translateRole($role, $domain) { // translation domain is false, do not translate it, // null is fallback to message domain if (false === $domain || !isset($this->translator)) { return $role; } return $this->translator->trans($role, [], $domain); }
[ "private", "function", "translateRole", "(", "$", "role", ",", "$", "domain", ")", "{", "// translation domain is false, do not translate it,", "// null is fallback to message domain", "if", "(", "false", "===", "$", "domain", "||", "!", "isset", "(", "$", "this", "...
/* @param string $role @param string|bool|null $domain @return string
[ "/", "*", "@param", "string", "$role", "@param", "string|bool|null", "$domain" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Security/EditableRolesBuilder.php#L169-L178
sonata-project/SonataUserBundle
src/Entity/UserManager.php
UserManager.save
public function save($entity, $andFlush = true): void { if (!$entity instanceof UserInterface) { throw new \InvalidArgumentException('Save method expected entity of type UserInterface'); } parent::updateUser($entity, $andFlush); }
php
public function save($entity, $andFlush = true): void { if (!$entity instanceof UserInterface) { throw new \InvalidArgumentException('Save method expected entity of type UserInterface'); } parent::updateUser($entity, $andFlush); }
[ "public", "function", "save", "(", "$", "entity", ",", "$", "andFlush", "=", "true", ")", ":", "void", "{", "if", "(", "!", "$", "entity", "instanceof", "UserInterface", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Save method expected ...
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Entity/UserManager.php#L79-L86
sonata-project/SonataUserBundle
src/Entity/UserManager.php
UserManager.delete
public function delete($entity, $andFlush = true): void { if (!$entity instanceof UserInterface) { throw new \InvalidArgumentException('Save method expected entity of type UserInterface'); } parent::deleteUser($entity); }
php
public function delete($entity, $andFlush = true): void { if (!$entity instanceof UserInterface) { throw new \InvalidArgumentException('Save method expected entity of type UserInterface'); } parent::deleteUser($entity); }
[ "public", "function", "delete", "(", "$", "entity", ",", "$", "andFlush", "=", "true", ")", ":", "void", "{", "if", "(", "!", "$", "entity", "instanceof", "UserInterface", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Save method expecte...
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Entity/UserManager.php#L91-L98
sonata-project/SonataUserBundle
src/Entity/UserManagerProxy.php
UserManagerProxy.findBy
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) { return $this->userManager->findBy($criteria, $orderBy, $limit, $offset); }
php
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) { return $this->userManager->findBy($criteria, $orderBy, $limit, $offset); }
[ "public", "function", "findBy", "(", "array", "$", "criteria", ",", "array", "$", "orderBy", "=", "null", ",", "$", "limit", "=", "null", ",", "$", "offset", "=", "null", ")", "{", "return", "$", "this", "->", "userManager", "->", "findBy", "(", "$",...
{@inheritdoc}
[ "{" ]
train
https://github.com/sonata-project/SonataUserBundle/blob/56d670de000dd0cf8e26e43d4f018eeaa5589bac/src/Entity/UserManagerProxy.php#L65-L68
CharlotteDunois/Yasmin
src/Utils/Snowflake.php
Snowflake.generate
static function generate(int $workerID = 1, int $processID = 0) { if($workerID > 31 || $workerID < 0) { throw new \InvalidArgumentException('Worker ID is out of range'); } if($processID > 31 || $processID < 0) { throw new \InvalidArgumentException('Process ID is out of range'); } $time = \microtime(true); if($time === static::$incrementTime) { static::$incrementIndex++; if(static::$incrementIndex >= 4095) { \usleep(1000); $time = \microtime(true); static::$incrementIndex = 0; } } else { static::$incrementIndex = 0; static::$incrementTime = $time; } $workerID = \str_pad(\decbin($workerID), 5, 0, \STR_PAD_LEFT); $processID = \str_pad(\decbin($processID), 5, 0, \STR_PAD_LEFT); $mtime = \explode('.', ((string) $time)); if(\count($mtime) < 2) { $mtime[1] = '000'; } $time = ((string) (((int) $mtime[0]) - static::EPOCH)).\substr($mtime[1], 0, 3); if(\PHP_INT_SIZE === 4) { $binary = \str_pad(\base_convert($time, 10, 2), 42, 0, \STR_PAD_LEFT).$workerID.$processID.\str_pad(\decbin(static::$incrementIndex), 12, 0, \STR_PAD_LEFT); return \base_convert($binary, 2, 10); } else { $binary = \str_pad(\decbin(((int) $time)), 42, 0, \STR_PAD_LEFT).$workerID.$processID.\str_pad(\decbin(static::$incrementIndex), 12, 0, \STR_PAD_LEFT); return ((string) \bindec($binary)); } }
php
static function generate(int $workerID = 1, int $processID = 0) { if($workerID > 31 || $workerID < 0) { throw new \InvalidArgumentException('Worker ID is out of range'); } if($processID > 31 || $processID < 0) { throw new \InvalidArgumentException('Process ID is out of range'); } $time = \microtime(true); if($time === static::$incrementTime) { static::$incrementIndex++; if(static::$incrementIndex >= 4095) { \usleep(1000); $time = \microtime(true); static::$incrementIndex = 0; } } else { static::$incrementIndex = 0; static::$incrementTime = $time; } $workerID = \str_pad(\decbin($workerID), 5, 0, \STR_PAD_LEFT); $processID = \str_pad(\decbin($processID), 5, 0, \STR_PAD_LEFT); $mtime = \explode('.', ((string) $time)); if(\count($mtime) < 2) { $mtime[1] = '000'; } $time = ((string) (((int) $mtime[0]) - static::EPOCH)).\substr($mtime[1], 0, 3); if(\PHP_INT_SIZE === 4) { $binary = \str_pad(\base_convert($time, 10, 2), 42, 0, \STR_PAD_LEFT).$workerID.$processID.\str_pad(\decbin(static::$incrementIndex), 12, 0, \STR_PAD_LEFT); return \base_convert($binary, 2, 10); } else { $binary = \str_pad(\decbin(((int) $time)), 42, 0, \STR_PAD_LEFT).$workerID.$processID.\str_pad(\decbin(static::$incrementIndex), 12, 0, \STR_PAD_LEFT); return ((string) \bindec($binary)); } }
[ "static", "function", "generate", "(", "int", "$", "workerID", "=", "1", ",", "int", "$", "processID", "=", "0", ")", "{", "if", "(", "$", "workerID", ">", "31", "||", "$", "workerID", "<", "0", ")", "{", "throw", "new", "\\", "InvalidArgumentExcepti...
Generates a new snowflake. @param int $workerID Valid values are in the range of 0-31. @param int $processID Valid values are in the range of 0-31. @return string
[ "Generates", "a", "new", "snowflake", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Utils/Snowflake.php#L111-L153
CharlotteDunois/Yasmin
src/Utils/Snowflake.php
Snowflake.getShardID
function getShardID(int $shardCount) { if(\PHP_INT_SIZE === 4) { $time = \base_convert(\substr($this->binary, 0, 42), 2, 10); $shard = (int) \bcmod($time, ((string) $shardCount)); return $shard; } else { $time = $this->value >> 22; return ($time % $shardCount); } }
php
function getShardID(int $shardCount) { if(\PHP_INT_SIZE === 4) { $time = \base_convert(\substr($this->binary, 0, 42), 2, 10); $shard = (int) \bcmod($time, ((string) $shardCount)); return $shard; } else { $time = $this->value >> 22; return ($time % $shardCount); } }
[ "function", "getShardID", "(", "int", "$", "shardCount", ")", "{", "if", "(", "\\", "PHP_INT_SIZE", "===", "4", ")", "{", "$", "time", "=", "\\", "base_convert", "(", "\\", "substr", "(", "$", "this", "->", "binary", ",", "0", ",", "42", ")", ",", ...
Compute the shard ID from the snowflake. @param int $shardCount @return int
[ "Compute", "the", "shard", "ID", "from", "the", "snowflake", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Utils/Snowflake.php#L160-L170
CharlotteDunois/Yasmin
src/HTTP/APIEndpoints.php
APIEndpoints.getCurrentApplication
function getCurrentApplication() { $url = \CharlotteDunois\Yasmin\HTTP\APIEndpoints::ENDPOINTS['currentOAuthApplication']; return $this->api->makeRequest('GET', $url, array()); }
php
function getCurrentApplication() { $url = \CharlotteDunois\Yasmin\HTTP\APIEndpoints::ENDPOINTS['currentOAuthApplication']; return $this->api->makeRequest('GET', $url, array()); }
[ "function", "getCurrentApplication", "(", ")", "{", "$", "url", "=", "\\", "CharlotteDunois", "\\", "Yasmin", "\\", "HTTP", "\\", "APIEndpoints", "::", "ENDPOINTS", "[", "'currentOAuthApplication'", "]", ";", "return", "$", "this", "->", "api", "->", "makeRequ...
Gets the current OAuth application. @return \React\Promise\ExtendedPromiseInterface
[ "Gets", "the", "current", "OAuth", "application", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/APIEndpoints.php#L124-L127
CharlotteDunois/Yasmin
src/Models/Storage.php
Storage.has
function has($key) { if(\is_array($key) || \is_object($key)) { throw new \InvalidArgumentException('Key can not be an array or object'); } $key = (string) $key; return parent::has($key); }
php
function has($key) { if(\is_array($key) || \is_object($key)) { throw new \InvalidArgumentException('Key can not be an array or object'); } $key = (string) $key; return parent::has($key); }
[ "function", "has", "(", "$", "key", ")", "{", "if", "(", "\\", "is_array", "(", "$", "key", ")", "||", "\\", "is_object", "(", "$", "key", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Key can not be an array or object'", ")", "...
{@inheritdoc} @return bool @throws \InvalidArgumentException
[ "{" ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/Storage.php#L108-L115
CharlotteDunois/Yasmin
src/Models/Storage.php
Storage.get
function get($key) { if(\is_array($key) || \is_object($key)) { throw new \InvalidArgumentException('Key can not be an array or object'); } $key = (string) $key; return parent::get($key); }
php
function get($key) { if(\is_array($key) || \is_object($key)) { throw new \InvalidArgumentException('Key can not be an array or object'); } $key = (string) $key; return parent::get($key); }
[ "function", "get", "(", "$", "key", ")", "{", "if", "(", "\\", "is_array", "(", "$", "key", ")", "||", "\\", "is_object", "(", "$", "key", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Key can not be an array or object'", ")", "...
{@inheritdoc} @return mixed|null @throws \InvalidArgumentException
[ "{" ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/Storage.php#L122-L129
CharlotteDunois/Yasmin
src/Models/Storage.php
Storage.set
function set($key, $value) { if(\is_array($key) || \is_object($key)) { throw new \InvalidArgumentException('Key can not be an array or object'); } $key = (string) $key; return parent::set($key, $value); }
php
function set($key, $value) { if(\is_array($key) || \is_object($key)) { throw new \InvalidArgumentException('Key can not be an array or object'); } $key = (string) $key; return parent::set($key, $value); }
[ "function", "set", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "\\", "is_array", "(", "$", "key", ")", "||", "\\", "is_object", "(", "$", "key", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Key can not be an arra...
{@inheritdoc} @return $this @throws \InvalidArgumentException
[ "{" ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/Storage.php#L136-L143
CharlotteDunois/Yasmin
src/Models/Storage.php
Storage.delete
function delete($key) { if(\is_array($key) || \is_object($key)) { throw new \InvalidArgumentException('Key can not be an array or object'); } $key = (string) $key; return parent::delete($key); }
php
function delete($key) { if(\is_array($key) || \is_object($key)) { throw new \InvalidArgumentException('Key can not be an array or object'); } $key = (string) $key; return parent::delete($key); }
[ "function", "delete", "(", "$", "key", ")", "{", "if", "(", "\\", "is_array", "(", "$", "key", ")", "||", "\\", "is_object", "(", "$", "key", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Key can not be an array or object'", ")", ...
{@inheritdoc} @return $this @throws \InvalidArgumentException
[ "{" ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/Storage.php#L150-L157
CharlotteDunois/Yasmin
src/Models/Storage.php
Storage.filter
function filter(callable $closure) { $args = $this->baseStorageArgs; $args[] = parent::filter($closure)->all(); return (new static(...$args)); }
php
function filter(callable $closure) { $args = $this->baseStorageArgs; $args[] = parent::filter($closure)->all(); return (new static(...$args)); }
[ "function", "filter", "(", "callable", "$", "closure", ")", "{", "$", "args", "=", "$", "this", "->", "baseStorageArgs", ";", "$", "args", "[", "]", "=", "parent", "::", "filter", "(", "$", "closure", ")", "->", "all", "(", ")", ";", "return", "(",...
{@inheritdoc} @param callable $closure @return \CharlotteDunois\Yasmin\Interfaces\StorageInterface
[ "{" ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/Storage.php#L175-L180
CharlotteDunois/Yasmin
src/Models/Storage.php
Storage.sort
function sort(bool $descending = false, int $options = \SORT_REGULAR) { $args = $this->baseStorageArgs; $args[] = parent::sort($descending, $options)->all(); return (new static(...$args)); }
php
function sort(bool $descending = false, int $options = \SORT_REGULAR) { $args = $this->baseStorageArgs; $args[] = parent::sort($descending, $options)->all(); return (new static(...$args)); }
[ "function", "sort", "(", "bool", "$", "descending", "=", "false", ",", "int", "$", "options", "=", "\\", "SORT_REGULAR", ")", "{", "$", "args", "=", "$", "this", "->", "baseStorageArgs", ";", "$", "args", "[", "]", "=", "parent", "::", "sort", "(", ...
{@inheritdoc} @param bool $descending @param int $options @return \CharlotteDunois\Collect\Collection
[ "{" ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/Storage.php#L188-L193
CharlotteDunois/Yasmin
src/Models/Storage.php
Storage.sortCustom
function sortCustom(callable $closure) { $args = $this->baseStorageArgs; $args[] = parent::sortCustom($closure)->all(); return (new static(...$args)); }
php
function sortCustom(callable $closure) { $args = $this->baseStorageArgs; $args[] = parent::sortCustom($closure)->all(); return (new static(...$args)); }
[ "function", "sortCustom", "(", "callable", "$", "closure", ")", "{", "$", "args", "=", "$", "this", "->", "baseStorageArgs", ";", "$", "args", "[", "]", "=", "parent", "::", "sortCustom", "(", "$", "closure", ")", "->", "all", "(", ")", ";", "return"...
{@inheritdoc} @param callable $closure Callback specification: `function ($a, $b): int` @return \CharlotteDunois\Collect\Collection
[ "{" ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/Storage.php#L213-L218
CharlotteDunois/Yasmin
src/Models/Storage.php
Storage.sortCustomKey
function sortCustomKey(callable $closure) { $args = $this->baseStorageArgs; $args[] = parent::sortCustomKey($closure)->all(); return (new static(...$args)); }
php
function sortCustomKey(callable $closure) { $args = $this->baseStorageArgs; $args[] = parent::sortCustomKey($closure)->all(); return (new static(...$args)); }
[ "function", "sortCustomKey", "(", "callable", "$", "closure", ")", "{", "$", "args", "=", "$", "this", "->", "baseStorageArgs", ";", "$", "args", "[", "]", "=", "parent", "::", "sortCustomKey", "(", "$", "closure", ")", "->", "all", "(", ")", ";", "r...
{@inheritDoc} @param callable $closure Callback specification: `function ($a, $b): int` @return \CharlotteDunois\Collect\Collection
[ "{" ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Models/Storage.php#L225-L230
CharlotteDunois/Yasmin
src/HTTP/APIManager.php
APIManager.clear
function clear() { $this->limited = true; $this->resetTime = \INF; while($item = \array_shift($this->queue)) { unset($item); } while($bucket = \array_shift($this->ratelimits)) { unset($bucket); } $this->limited = false; $this->resetTime = 0; }
php
function clear() { $this->limited = true; $this->resetTime = \INF; while($item = \array_shift($this->queue)) { unset($item); } while($bucket = \array_shift($this->ratelimits)) { unset($bucket); } $this->limited = false; $this->resetTime = 0; }
[ "function", "clear", "(", ")", "{", "$", "this", "->", "limited", "=", "true", ";", "$", "this", "->", "resetTime", "=", "\\", "INF", ";", "while", "(", "$", "item", "=", "\\", "array_shift", "(", "$", "this", "->", "queue", ")", ")", "{", "unset...
Clears all buckets and the queue. @return void
[ "Clears", "all", "buckets", "and", "the", "queue", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/APIManager.php#L144-L158
CharlotteDunois/Yasmin
src/HTTP/APIManager.php
APIManager.makeRequest
function makeRequest(string $method, string $endpoint, array $options) { $request = new \CharlotteDunois\Yasmin\HTTP\APIRequest($this, $method, $endpoint, $options); return $this->add($request); }
php
function makeRequest(string $method, string $endpoint, array $options) { $request = new \CharlotteDunois\Yasmin\HTTP\APIRequest($this, $method, $endpoint, $options); return $this->add($request); }
[ "function", "makeRequest", "(", "string", "$", "method", ",", "string", "$", "endpoint", ",", "array", "$", "options", ")", "{", "$", "request", "=", "new", "\\", "CharlotteDunois", "\\", "Yasmin", "\\", "HTTP", "\\", "APIRequest", "(", "$", "this", ",",...
Makes an API request. @param string $method @param string $endpoint @param array $options @return \React\Promise\ExtendedPromiseInterface
[ "Makes", "an", "API", "request", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/APIManager.php#L167-L170
CharlotteDunois/Yasmin
src/HTTP/APIManager.php
APIManager.add
function add(\CharlotteDunois\Yasmin\HTTP\APIRequest $apirequest) { return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($apirequest) { $apirequest->deferred = new \React\Promise\Deferred(); $apirequest->deferred->promise()->done($resolve, $reject); $endpoint = $this->getRatelimitEndpoint($apirequest); if(!empty($endpoint)) { $this->client->emit('debug', 'Adding request "'.$apirequest->getEndpoint().'" to ratelimit bucket'); $bucket = $this->getRatelimitBucket($endpoint); $bucket->push($apirequest); $this->queue[] = $bucket; } else { $this->client->emit('debug', 'Adding request "'.$apirequest->getEndpoint().'" to global queue'); $this->queue[] = $apirequest; } $this->processFuture(); })); }
php
function add(\CharlotteDunois\Yasmin\HTTP\APIRequest $apirequest) { return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($apirequest) { $apirequest->deferred = new \React\Promise\Deferred(); $apirequest->deferred->promise()->done($resolve, $reject); $endpoint = $this->getRatelimitEndpoint($apirequest); if(!empty($endpoint)) { $this->client->emit('debug', 'Adding request "'.$apirequest->getEndpoint().'" to ratelimit bucket'); $bucket = $this->getRatelimitBucket($endpoint); $bucket->push($apirequest); $this->queue[] = $bucket; } else { $this->client->emit('debug', 'Adding request "'.$apirequest->getEndpoint().'" to global queue'); $this->queue[] = $apirequest; } $this->processFuture(); })); }
[ "function", "add", "(", "\\", "CharlotteDunois", "\\", "Yasmin", "\\", "HTTP", "\\", "APIRequest", "$", "apirequest", ")", "{", "return", "(", "new", "\\", "React", "\\", "Promise", "\\", "Promise", "(", "function", "(", "callable", "$", "resolve", ",", ...
Adds an APIRequest to the queue. @param \CharlotteDunois\Yasmin\HTTP\APIRequest $apirequest @return \React\Promise\ExtendedPromiseInterface
[ "Adds", "an", "APIRequest", "to", "the", "queue", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/APIManager.php#L177-L196
CharlotteDunois/Yasmin
src/HTTP/APIManager.php
APIManager.processDelayed
protected function processDelayed() { $offset = (float) $this->client->getOption('http.restTimeOffset', 0.0); if($offset > 0.0) { $this->client->addTimer($offset, function () { $this->process(); }); return; } $this->process(); }
php
protected function processDelayed() { $offset = (float) $this->client->getOption('http.restTimeOffset', 0.0); if($offset > 0.0) { $this->client->addTimer($offset, function () { $this->process(); }); return; } $this->process(); }
[ "protected", "function", "processDelayed", "(", ")", "{", "$", "offset", "=", "(", "float", ")", "$", "this", "->", "client", "->", "getOption", "(", "'http.restTimeOffset'", ",", "0.0", ")", ";", "if", "(", "$", "offset", ">", "0.0", ")", "{", "$", ...
Processes the queue delayed, depends on rest time offset. @return void
[ "Processes", "the", "queue", "delayed", "depends", "on", "rest", "time", "offset", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/APIManager.php#L230-L241
CharlotteDunois/Yasmin
src/HTTP/APIManager.php
APIManager.process
protected function process() { if($this->limited) { if(\microtime(true) < $this->resetTime) { $this->client->addTimer(($this->resetTime - \microtime(true)), function () { $this->process(); }); return; } $this->limited = false; $this->remaining = ($this->limit ? $this->limit : \INF); } if(\count($this->queue) === 0) { return; } $item = \array_shift($this->queue); $this->processItem($item); }
php
protected function process() { if($this->limited) { if(\microtime(true) < $this->resetTime) { $this->client->addTimer(($this->resetTime - \microtime(true)), function () { $this->process(); }); return; } $this->limited = false; $this->remaining = ($this->limit ? $this->limit : \INF); } if(\count($this->queue) === 0) { return; } $item = \array_shift($this->queue); $this->processItem($item); }
[ "protected", "function", "process", "(", ")", "{", "if", "(", "$", "this", "->", "limited", ")", "{", "if", "(", "\\", "microtime", "(", "true", ")", "<", "$", "this", "->", "resetTime", ")", "{", "$", "this", "->", "client", "->", "addTimer", "(",...
Processes the queue. @return void
[ "Processes", "the", "queue", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/APIManager.php#L247-L267
CharlotteDunois/Yasmin
src/HTTP/APIManager.php
APIManager.processItem
protected function processItem($item) { if($item instanceof \CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface) { if($item->isBusy()) { $this->queue[] = $item; foreach($this->queue as $qitem) { if(!($qitem instanceof \CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface) || !$qitem->isBusy()) { $this->processItem($qitem); return; } } return; } $item->setBusy(true); $buckItem = $this->extractFromBucket($item); if(!($buckItem instanceof \React\Promise\ExtendedPromiseInterface)) { $buckItem = \React\Promise\resolve($buckItem); } $buckItem->done(function ($req) use ($item) { $item->setBusy(false); if(!($req instanceof \CharlotteDunois\Yasmin\HTTP\APIRequest)) { return; } $this->execute($req); }, array($this->client, 'handlePromiseRejection')); } else { if(!($item instanceof \CharlotteDunois\Yasmin\HTTP\APIRequest)) { return; } $this->execute($item); } }
php
protected function processItem($item) { if($item instanceof \CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface) { if($item->isBusy()) { $this->queue[] = $item; foreach($this->queue as $qitem) { if(!($qitem instanceof \CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface) || !$qitem->isBusy()) { $this->processItem($qitem); return; } } return; } $item->setBusy(true); $buckItem = $this->extractFromBucket($item); if(!($buckItem instanceof \React\Promise\ExtendedPromiseInterface)) { $buckItem = \React\Promise\resolve($buckItem); } $buckItem->done(function ($req) use ($item) { $item->setBusy(false); if(!($req instanceof \CharlotteDunois\Yasmin\HTTP\APIRequest)) { return; } $this->execute($req); }, array($this->client, 'handlePromiseRejection')); } else { if(!($item instanceof \CharlotteDunois\Yasmin\HTTP\APIRequest)) { return; } $this->execute($item); } }
[ "protected", "function", "processItem", "(", "$", "item", ")", "{", "if", "(", "$", "item", "instanceof", "\\", "CharlotteDunois", "\\", "Yasmin", "\\", "Interfaces", "\\", "RatelimitBucketInterface", ")", "{", "if", "(", "$", "item", "->", "isBusy", "(", ...
Processes a queue item. @param \CharlotteDunois\Yasmin\HTTP\APIRequest|\CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface|null $item @return void
[ "Processes", "a", "queue", "item", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/APIManager.php#L274-L312
CharlotteDunois/Yasmin
src/HTTP/APIManager.php
APIManager.extractFromBucket
protected function extractFromBucket(\CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface $item) { if($item->size() > 0) { $meta = $item->getMeta(); if($meta instanceof \React\Promise\ExtendedPromiseInterface) { return $meta->then(function ($data) use (&$item) { if(!$data['limited']) { $this->client->emit('debug', 'Retrieved item from bucket "'.$item->getEndpoint().'"'); return $item->shift(); } $this->queue[] = $item; $this->client->addTimer(($data['resetTime'] - \microtime(true)), function () { $this->process(); }); }, function ($error) use (&$item) { $this->queue[] = $item; $this->client->emit('error', $error); $this->process(); return false; }); } else { if(!$meta['limited']) { $this->client->emit('debug', 'Retrieved item from bucket "'.$item->getEndpoint().'"'); return $item->shift(); } $this->queue[] = $item; $this->client->addTimer(($meta['resetTime'] - \microtime(true)), function () { $this->process(); }); } } return false; }
php
protected function extractFromBucket(\CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface $item) { if($item->size() > 0) { $meta = $item->getMeta(); if($meta instanceof \React\Promise\ExtendedPromiseInterface) { return $meta->then(function ($data) use (&$item) { if(!$data['limited']) { $this->client->emit('debug', 'Retrieved item from bucket "'.$item->getEndpoint().'"'); return $item->shift(); } $this->queue[] = $item; $this->client->addTimer(($data['resetTime'] - \microtime(true)), function () { $this->process(); }); }, function ($error) use (&$item) { $this->queue[] = $item; $this->client->emit('error', $error); $this->process(); return false; }); } else { if(!$meta['limited']) { $this->client->emit('debug', 'Retrieved item from bucket "'.$item->getEndpoint().'"'); return $item->shift(); } $this->queue[] = $item; $this->client->addTimer(($meta['resetTime'] - \microtime(true)), function () { $this->process(); }); } } return false; }
[ "protected", "function", "extractFromBucket", "(", "\\", "CharlotteDunois", "\\", "Yasmin", "\\", "Interfaces", "\\", "RatelimitBucketInterface", "$", "item", ")", "{", "if", "(", "$", "item", "->", "size", "(", ")", ">", "0", ")", "{", "$", "meta", "=", ...
Extracts an item from a ratelimit bucket. @param \CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface $item @return \CharlotteDunois\Yasmin\HTTP\APIRequest|bool|\React\Promise\ExtendedPromiseInterface
[ "Extracts", "an", "item", "from", "a", "ratelimit", "bucket", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/APIManager.php#L319-L357
CharlotteDunois/Yasmin
src/HTTP/APIManager.php
APIManager.execute
protected function execute(\CharlotteDunois\Yasmin\HTTP\APIRequest $item) { $endpoint = $this->getRatelimitEndpoint($item); $ratelimit = null; if(!empty($endpoint)) { $ratelimit = $this->getRatelimitBucket($endpoint); $ratelimit->setBusy(true); } $this->client->emit('debug', 'Executing item "'.$item->getEndpoint().'"'); $item->execute($ratelimit)->then(function ($data) use ($item) { if($data === 0) { $item->deferred->resolve(); } elseif($data !== -1) { $item->deferred->resolve($data); } }, function ($error) use ($item) { $this->client->emit('debug', 'Request for item "'.$item->getEndpoint().'" failed with '.($error instanceof \Throwable ? 'exception '.\get_class($error) : 'error '.$error)); $item->deferred->reject($error); })->then(null, function ($error) { $this->client->handlePromiseRejection($error); })->done(function () use ($ratelimit, $endpoint) { if($ratelimit instanceof \CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface) { if(isset($this->bucketRatelimitPromises[$endpoint])) { $this->bucketRatelimitPromises[$endpoint]->done(function () use ($ratelimit) { $ratelimit->setBusy(false); $this->processDelayed(); }); } else { $ratelimit->setBusy(false); $this->processDelayed(); } } else { $this->processDelayed(); } }); }
php
protected function execute(\CharlotteDunois\Yasmin\HTTP\APIRequest $item) { $endpoint = $this->getRatelimitEndpoint($item); $ratelimit = null; if(!empty($endpoint)) { $ratelimit = $this->getRatelimitBucket($endpoint); $ratelimit->setBusy(true); } $this->client->emit('debug', 'Executing item "'.$item->getEndpoint().'"'); $item->execute($ratelimit)->then(function ($data) use ($item) { if($data === 0) { $item->deferred->resolve(); } elseif($data !== -1) { $item->deferred->resolve($data); } }, function ($error) use ($item) { $this->client->emit('debug', 'Request for item "'.$item->getEndpoint().'" failed with '.($error instanceof \Throwable ? 'exception '.\get_class($error) : 'error '.$error)); $item->deferred->reject($error); })->then(null, function ($error) { $this->client->handlePromiseRejection($error); })->done(function () use ($ratelimit, $endpoint) { if($ratelimit instanceof \CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface) { if(isset($this->bucketRatelimitPromises[$endpoint])) { $this->bucketRatelimitPromises[$endpoint]->done(function () use ($ratelimit) { $ratelimit->setBusy(false); $this->processDelayed(); }); } else { $ratelimit->setBusy(false); $this->processDelayed(); } } else { $this->processDelayed(); } }); }
[ "protected", "function", "execute", "(", "\\", "CharlotteDunois", "\\", "Yasmin", "\\", "HTTP", "\\", "APIRequest", "$", "item", ")", "{", "$", "endpoint", "=", "$", "this", "->", "getRatelimitEndpoint", "(", "$", "item", ")", ";", "$", "ratelimit", "=", ...
Executes an API Request. @param \CharlotteDunois\Yasmin\HTTP\APIRequest $item @return void
[ "Executes", "an", "API", "Request", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/APIManager.php#L364-L401
CharlotteDunois/Yasmin
src/HTTP/APIManager.php
APIManager.getRatelimitEndpoint
function getRatelimitEndpoint(\CharlotteDunois\Yasmin\HTTP\APIRequest $request) { $endpoint = $request->getEndpoint(); if($request->isReactionEndpoint()) { \preg_match('/channels\/(\d+)\/messages\/(\d+)\/reactions\/.*/', $endpoint, $matches); return 'channels/'.$matches[1].'/messages/'.$matches[2].'/reactions'; } $firstPart = \substr($endpoint, 0, (\strpos($endpoint, '/') ?: \strlen($endpoint))); $majorRoutes = array('channels', 'guilds', 'webhooks'); if(!\in_array($firstPart, $majorRoutes, true)) { return $firstPart; } \preg_match('/((?:.*?)\/(?:\d+))(?:\/messages\/((?:bulk(?:-|_)delete)|(?:\d+)){0,1})?/', $endpoint, $matches); if(\is_numeric(($matches[2] ?? null)) && $request->getMethod() === 'DELETE') { return 'delete@'.$matches[0]; } elseif(\stripos(($matches[2] ?? ''), 'bulk') !== false) { return $matches[0]; } return ($matches[1] ?? $endpoint); }
php
function getRatelimitEndpoint(\CharlotteDunois\Yasmin\HTTP\APIRequest $request) { $endpoint = $request->getEndpoint(); if($request->isReactionEndpoint()) { \preg_match('/channels\/(\d+)\/messages\/(\d+)\/reactions\/.*/', $endpoint, $matches); return 'channels/'.$matches[1].'/messages/'.$matches[2].'/reactions'; } $firstPart = \substr($endpoint, 0, (\strpos($endpoint, '/') ?: \strlen($endpoint))); $majorRoutes = array('channels', 'guilds', 'webhooks'); if(!\in_array($firstPart, $majorRoutes, true)) { return $firstPart; } \preg_match('/((?:.*?)\/(?:\d+))(?:\/messages\/((?:bulk(?:-|_)delete)|(?:\d+)){0,1})?/', $endpoint, $matches); if(\is_numeric(($matches[2] ?? null)) && $request->getMethod() === 'DELETE') { return 'delete@'.$matches[0]; } elseif(\stripos(($matches[2] ?? ''), 'bulk') !== false) { return $matches[0]; } return ($matches[1] ?? $endpoint); }
[ "function", "getRatelimitEndpoint", "(", "\\", "CharlotteDunois", "\\", "Yasmin", "\\", "HTTP", "\\", "APIRequest", "$", "request", ")", "{", "$", "endpoint", "=", "$", "request", "->", "getEndpoint", "(", ")", ";", "if", "(", "$", "request", "->", "isReac...
Turns an endpoint path to the ratelimit path. @param \CharlotteDunois\Yasmin\HTTP\APIRequest $request @return string
[ "Turns", "an", "endpoint", "path", "to", "the", "ratelimit", "path", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/APIManager.php#L408-L432
CharlotteDunois/Yasmin
src/HTTP/APIManager.php
APIManager.getRatelimitBucket
protected function getRatelimitBucket(string $endpoint) { if(empty($this->ratelimits[$endpoint])) { $bucket = $this->bucketName; $this->ratelimits[$endpoint] = new $bucket($this, $endpoint); } return $this->ratelimits[$endpoint]; }
php
protected function getRatelimitBucket(string $endpoint) { if(empty($this->ratelimits[$endpoint])) { $bucket = $this->bucketName; $this->ratelimits[$endpoint] = new $bucket($this, $endpoint); } return $this->ratelimits[$endpoint]; }
[ "protected", "function", "getRatelimitBucket", "(", "string", "$", "endpoint", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "ratelimits", "[", "$", "endpoint", "]", ")", ")", "{", "$", "bucket", "=", "$", "this", "->", "bucketName", ";", "$", ...
Gets the ratelimit bucket for the specific endpoint. @param string $endpoint @return \CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface
[ "Gets", "the", "ratelimit", "bucket", "for", "the", "specific", "endpoint", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/APIManager.php#L439-L446
CharlotteDunois/Yasmin
src/HTTP/APIManager.php
APIManager.extractRatelimit
function extractRatelimit(\Psr\Http\Message\ResponseInterface $response) { $date = (new \DateTime($response->getHeader('Date')[0]))->getTimestamp(); $limit = ($response->hasHeader('X-RateLimit-Limit') ? ((int) $response->getHeader('X-RateLimit-Limit')[0]) : null); $remaining = ($response->hasHeader('X-RateLimit-Remaining') ? ((int) $response->getHeader('X-RateLimit-Remaining')[0]) : null); $resetTime = ($response->hasHeader('Retry-After') ? ((float) \bcadd(\microtime(true), (((int) $response->getHeader('Retry-After')[0]) / 1000))) : ($response->hasHeader('X-RateLimit-Reset') ? ((float) \bcadd(\microtime(true), (((int) $response->getHeader('X-RateLimit-Reset')[0]) - $date))) : null) ); return \compact('limit', 'remaining', 'resetTime'); }
php
function extractRatelimit(\Psr\Http\Message\ResponseInterface $response) { $date = (new \DateTime($response->getHeader('Date')[0]))->getTimestamp(); $limit = ($response->hasHeader('X-RateLimit-Limit') ? ((int) $response->getHeader('X-RateLimit-Limit')[0]) : null); $remaining = ($response->hasHeader('X-RateLimit-Remaining') ? ((int) $response->getHeader('X-RateLimit-Remaining')[0]) : null); $resetTime = ($response->hasHeader('Retry-After') ? ((float) \bcadd(\microtime(true), (((int) $response->getHeader('Retry-After')[0]) / 1000))) : ($response->hasHeader('X-RateLimit-Reset') ? ((float) \bcadd(\microtime(true), (((int) $response->getHeader('X-RateLimit-Reset')[0]) - $date))) : null) ); return \compact('limit', 'remaining', 'resetTime'); }
[ "function", "extractRatelimit", "(", "\\", "Psr", "\\", "Http", "\\", "Message", "\\", "ResponseInterface", "$", "response", ")", "{", "$", "date", "=", "(", "new", "\\", "DateTime", "(", "$", "response", "->", "getHeader", "(", "'Date'", ")", "[", "0", ...
Extracts ratelimits from a response. @param \Psr\Http\Message\ResponseInterface $response @return mixed[]
[ "Extracts", "ratelimits", "from", "a", "response", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/APIManager.php#L453-L464
CharlotteDunois/Yasmin
src/HTTP/APIManager.php
APIManager.handleRatelimit
function handleRatelimit(\Psr\Http\Message\ResponseInterface $response, ?\CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface $ratelimit = null, bool $isReactionEndpoint = false) { \extract($this->extractRatelimit($response)); if($isReactionEndpoint && !empty($resetTime)) { $resetTime = (float) \bcadd(\microtime(true), 0.25); } $global = false; if($response->hasHeader('X-RateLimit-Global')) { $global = true; $this->limit = $limit ?? $this->limit; $this->remaining = $remaining ?? $this->remaining; $this->resetTime = $resetTime ?? $this->resetTime; if($this->remaining === 0 && $this->resetTime > \microtime(true)) { $this->limited = true; $this->client->emit('debug', 'Global ratelimit encountered, continueing in '.($this->resetTime - \microtime(true)).' seconds'); } else { $this->limited = false; } } elseif($ratelimit !== null) { $set = $ratelimit->handleRatelimit($limit, $remaining, $resetTime); if($set instanceof \React\Promise\ExtendedPromiseInterface) { $this->bucketRatelimitPromises[$ratelimit->getEndpoint()] = $set; } } $this->loop->futureTick(function () use ($ratelimit, $global, $limit, $remaining, $resetTime) { $this->client->emit('ratelimit', array( 'endpoint' => ($ratelimit !== null ? $ratelimit->getEndpoint() : 'global'), 'global' => $global, 'limit' => $limit, 'remaining' => $remaining, 'resetTime' => $resetTime )); }); }
php
function handleRatelimit(\Psr\Http\Message\ResponseInterface $response, ?\CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface $ratelimit = null, bool $isReactionEndpoint = false) { \extract($this->extractRatelimit($response)); if($isReactionEndpoint && !empty($resetTime)) { $resetTime = (float) \bcadd(\microtime(true), 0.25); } $global = false; if($response->hasHeader('X-RateLimit-Global')) { $global = true; $this->limit = $limit ?? $this->limit; $this->remaining = $remaining ?? $this->remaining; $this->resetTime = $resetTime ?? $this->resetTime; if($this->remaining === 0 && $this->resetTime > \microtime(true)) { $this->limited = true; $this->client->emit('debug', 'Global ratelimit encountered, continueing in '.($this->resetTime - \microtime(true)).' seconds'); } else { $this->limited = false; } } elseif($ratelimit !== null) { $set = $ratelimit->handleRatelimit($limit, $remaining, $resetTime); if($set instanceof \React\Promise\ExtendedPromiseInterface) { $this->bucketRatelimitPromises[$ratelimit->getEndpoint()] = $set; } } $this->loop->futureTick(function () use ($ratelimit, $global, $limit, $remaining, $resetTime) { $this->client->emit('ratelimit', array( 'endpoint' => ($ratelimit !== null ? $ratelimit->getEndpoint() : 'global'), 'global' => $global, 'limit' => $limit, 'remaining' => $remaining, 'resetTime' => $resetTime )); }); }
[ "function", "handleRatelimit", "(", "\\", "Psr", "\\", "Http", "\\", "Message", "\\", "ResponseInterface", "$", "response", ",", "?", "\\", "CharlotteDunois", "\\", "Yasmin", "\\", "Interfaces", "\\", "RatelimitBucketInterface", "$", "ratelimit", "=", "null", ",...
Handles ratelimits. @param \Psr\Http\Message\ResponseInterface $response @param \CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface|null $ratelimit @param bool $isReactionEndpoint @return void
[ "Handles", "ratelimits", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/APIManager.php#L473-L510
CharlotteDunois/Yasmin
src/HTTP/RatelimitBucket.php
RatelimitBucket.handleRatelimit
function handleRatelimit(?int $limit, ?int $remaining, ?float $resetTime) { if($limit === null && $remaining === null && $resetTime === null) { $this->remaining++; // there is no ratelimit... return; } $this->limit = $limit ?? $this->limit; $this->remaining = $remaining ?? $this->remaining; $this->resetTime = $resetTime ?? $this->resetTime; if($this->remaining === 0 && $this->resetTime > \microtime(true)) { $this->api->client->emit('debug', 'Endpoint "'.$this->endpoint.'" ratelimit encountered, continueing in '.($this->resetTime - \microtime(true)).' seconds'); } }
php
function handleRatelimit(?int $limit, ?int $remaining, ?float $resetTime) { if($limit === null && $remaining === null && $resetTime === null) { $this->remaining++; // there is no ratelimit... return; } $this->limit = $limit ?? $this->limit; $this->remaining = $remaining ?? $this->remaining; $this->resetTime = $resetTime ?? $this->resetTime; if($this->remaining === 0 && $this->resetTime > \microtime(true)) { $this->api->client->emit('debug', 'Endpoint "'.$this->endpoint.'" ratelimit encountered, continueing in '.($this->resetTime - \microtime(true)).' seconds'); } }
[ "function", "handleRatelimit", "(", "?", "int", "$", "limit", ",", "?", "int", "$", "remaining", ",", "?", "float", "$", "resetTime", ")", "{", "if", "(", "$", "limit", "===", "null", "&&", "$", "remaining", "===", "null", "&&", "$", "resetTime", "==...
Sets the ratelimits from the response. @param int|null $limit @param int|null $remaining @param float|null $resetTime Reset time in seconds with milliseconds. @return \React\Promise\ExtendedPromiseInterface|void
[ "Sets", "the", "ratelimits", "from", "the", "response", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/RatelimitBucket.php#L100-L113
CharlotteDunois/Yasmin
src/HTTP/RatelimitBucket.php
RatelimitBucket.push
function push(\CharlotteDunois\Yasmin\HTTP\APIRequest $request) { $this->queue[] = $request; return $this; }
php
function push(\CharlotteDunois\Yasmin\HTTP\APIRequest $request) { $this->queue[] = $request; return $this; }
[ "function", "push", "(", "\\", "CharlotteDunois", "\\", "Yasmin", "\\", "HTTP", "\\", "APIRequest", "$", "request", ")", "{", "$", "this", "->", "queue", "[", "]", "=", "$", "request", ";", "return", "$", "this", ";", "}" ]
Pushes a new request into the queue. @param \CharlotteDunois\Yasmin\HTTP\APIRequest $request @return $this
[ "Pushes", "a", "new", "request", "into", "the", "queue", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/RatelimitBucket.php#L136-L139
CharlotteDunois/Yasmin
src/HTTP/RatelimitBucket.php
RatelimitBucket.unshift
function unshift(\CharlotteDunois\Yasmin\HTTP\APIRequest $request) { \array_unshift($this->queue, $request); $this->remaining++; return $this; }
php
function unshift(\CharlotteDunois\Yasmin\HTTP\APIRequest $request) { \array_unshift($this->queue, $request); $this->remaining++; return $this; }
[ "function", "unshift", "(", "\\", "CharlotteDunois", "\\", "Yasmin", "\\", "HTTP", "\\", "APIRequest", "$", "request", ")", "{", "\\", "array_unshift", "(", "$", "this", "->", "queue", ",", "$", "request", ")", ";", "$", "this", "->", "remaining", "++", ...
Unshifts a new request into the queue. Modifies remaining ratelimit. @param \CharlotteDunois\Yasmin\HTTP\APIRequest $request @return $this
[ "Unshifts", "a", "new", "request", "into", "the", "queue", ".", "Modifies", "remaining", "ratelimit", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/RatelimitBucket.php#L146-L150
CharlotteDunois/Yasmin
src/HTTP/RatelimitBucket.php
RatelimitBucket.getMeta
function getMeta() { if($this->resetTime && \microtime(true) > $this->resetTime) { $this->resetTime = null; $this->remaining = ($this->limit ? $this->limit : \INF); $limited = false; } else { $limited = ($this->limit !== 0 && $this->remaining === 0); } return array('limited' => $limited, 'resetTime' => $this->resetTime); }
php
function getMeta() { if($this->resetTime && \microtime(true) > $this->resetTime) { $this->resetTime = null; $this->remaining = ($this->limit ? $this->limit : \INF); $limited = false; } else { $limited = ($this->limit !== 0 && $this->remaining === 0); } return array('limited' => $limited, 'resetTime' => $this->resetTime); }
[ "function", "getMeta", "(", ")", "{", "if", "(", "$", "this", "->", "resetTime", "&&", "\\", "microtime", "(", "true", ")", ">", "$", "this", "->", "resetTime", ")", "{", "$", "this", "->", "resetTime", "=", "null", ";", "$", "this", "->", "remaini...
Retrieves ratelimit meta data. The resolved value must be: ``` array( 'limited' => bool, 'resetTime' => int|null ) ``` @return \React\Promise\ExtendedPromiseInterface|array
[ "Retrieves", "ratelimit", "meta", "data", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/RatelimitBucket.php#L165-L176
CharlotteDunois/Yasmin
src/HTTP/RatelimitBucket.php
RatelimitBucket.shift
function shift() { if(\count($this->queue) === 0) { return false; } $item = \array_shift($this->queue); $this->remaining--; return $item; }
php
function shift() { if(\count($this->queue) === 0) { return false; } $item = \array_shift($this->queue); $this->remaining--; return $item; }
[ "function", "shift", "(", ")", "{", "if", "(", "\\", "count", "(", "$", "this", "->", "queue", ")", "===", "0", ")", "{", "return", "false", ";", "}", "$", "item", "=", "\\", "array_shift", "(", "$", "this", "->", "queue", ")", ";", "$", "this"...
Returns the first queue item or false. Modifies remaining ratelimit. @return \CharlotteDunois\Yasmin\HTTP\APIRequest|false
[ "Returns", "the", "first", "queue", "item", "or", "false", ".", "Modifies", "remaining", "ratelimit", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/HTTP/RatelimitBucket.php#L182-L191
CharlotteDunois/Yasmin
src/WebSocket/Handlers/Dispatch.php
Dispatch.getEvent
function getEvent(string $name) { if(isset($this->wsevents[$name])) { return $this->wsevents[$name]; } throw new \Exception('Unable to find WS event'); }
php
function getEvent(string $name) { if(isset($this->wsevents[$name])) { return $this->wsevents[$name]; } throw new \Exception('Unable to find WS event'); }
[ "function", "getEvent", "(", "string", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "wsevents", "[", "$", "name", "]", ")", ")", "{", "return", "$", "this", "->", "wsevents", "[", "$", "name", "]", ";", "}", "throw", "new", ...
Returns a WS event. @return \CharlotteDunois\Yasmin\Interfaces\WSEventInterface
[ "Returns", "a", "WS", "event", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/WebSocket/Handlers/Dispatch.php#L68-L74
CharlotteDunois/Yasmin
src/WebSocket/Handlers/Dispatch.php
Dispatch.register
function register(string $name, string $class) { if(!\in_array('CharlotteDunois\Yasmin\Interfaces\WSEventInterface', \class_implements($class))) { throw new \RuntimeException('Specified event class does not implement interface'); } $this->wsevents[$name] = new $class($this->wshandler->wsmanager->client, $this->wshandler->wsmanager); }
php
function register(string $name, string $class) { if(!\in_array('CharlotteDunois\Yasmin\Interfaces\WSEventInterface', \class_implements($class))) { throw new \RuntimeException('Specified event class does not implement interface'); } $this->wsevents[$name] = new $class($this->wshandler->wsmanager->client, $this->wshandler->wsmanager); }
[ "function", "register", "(", "string", "$", "name", ",", "string", "$", "class", ")", "{", "if", "(", "!", "\\", "in_array", "(", "'CharlotteDunois\\Yasmin\\Interfaces\\WSEventInterface'", ",", "\\", "class_implements", "(", "$", "class", ")", ")", ")", "{", ...
Registers an event. @return void @throws \RuntimeException
[ "Registers", "an", "event", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/WebSocket/Handlers/Dispatch.php#L90-L96
CharlotteDunois/Yasmin
src/Traits/GuildChannelTrait.php
GuildChannelTrait.createInvite
function createInvite(array $options = array()) { $data = array( 'max_uses' => ($options['maxUses'] ?? 0), 'temporary' => ($options['temporary'] ?? false), 'unique' => ($options['unique'] ?? false) ); if(isset($options['maxAge'])) { $data['max_age'] = $options['maxAge']; } return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($data) { $this->client->apimanager()->endpoints->channel->createChannelInvite($this->id, $data)->done(function ($data) use ($resolve) { $invite = new \CharlotteDunois\Yasmin\Models\Invite($this->client, $data); $resolve($invite); }, $reject); })); }
php
function createInvite(array $options = array()) { $data = array( 'max_uses' => ($options['maxUses'] ?? 0), 'temporary' => ($options['temporary'] ?? false), 'unique' => ($options['unique'] ?? false) ); if(isset($options['maxAge'])) { $data['max_age'] = $options['maxAge']; } return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($data) { $this->client->apimanager()->endpoints->channel->createChannelInvite($this->id, $data)->done(function ($data) use ($resolve) { $invite = new \CharlotteDunois\Yasmin\Models\Invite($this->client, $data); $resolve($invite); }, $reject); })); }
[ "function", "createInvite", "(", "array", "$", "options", "=", "array", "(", ")", ")", "{", "$", "data", "=", "array", "(", "'max_uses'", "=>", "(", "$", "options", "[", "'maxUses'", "]", "??", "0", ")", ",", "'temporary'", "=>", "(", "$", "options",...
Creates an invite. Resolves with an instance of Invite. Options are as following (all are optional). ``` array( 'maxAge' => int, 'maxUses' => int, (0 = unlimited) 'temporary' => bool, 'unique' => bool ) ``` @param array $options @return \React\Promise\ExtendedPromiseInterface @see \CharlotteDunois\Yasmin\Models\Invite
[ "Creates", "an", "invite", ".", "Resolves", "with", "an", "instance", "of", "Invite", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Traits/GuildChannelTrait.php#L34-L51
CharlotteDunois/Yasmin
src/Traits/GuildChannelTrait.php
GuildChannelTrait.clone
function clone(string $name = null, bool $withPermissions = true, bool $withTopic = true, string $reason = '') { $data = array( 'name' => (!empty($name) ? ((string) $name) : $this->name), 'type' => \CharlotteDunois\Yasmin\Models\ChannelStorage::getTypeForChannel($this) ); if($withPermissions) { $data['permission_overwrites'] = \array_values($this->permissionOverwrites->all()); } if($withTopic) { $data['topic'] = $this->topic; } if($this->parentID) { $data['parent_id'] = $this->parentID; } if($this instanceof \CharlotteDunois\Yasmin\Interfaces\VoiceChannelInterface) { $data['bitrate'] = $this->bitrate; $data['user_limit'] = $this->userLimit; } else { $data['nsfw'] = $this->nsfw; } return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($data, $reason) { $this->client->apimanager()->endpoints->guild->createGuildChannel($this->guild->id, $data, $reason)->done(function ($data) use ($resolve) { $channel = $this->guild->channels->factory($data, $this->guild); $resolve($channel); }, $reject); })); }
php
function clone(string $name = null, bool $withPermissions = true, bool $withTopic = true, string $reason = '') { $data = array( 'name' => (!empty($name) ? ((string) $name) : $this->name), 'type' => \CharlotteDunois\Yasmin\Models\ChannelStorage::getTypeForChannel($this) ); if($withPermissions) { $data['permission_overwrites'] = \array_values($this->permissionOverwrites->all()); } if($withTopic) { $data['topic'] = $this->topic; } if($this->parentID) { $data['parent_id'] = $this->parentID; } if($this instanceof \CharlotteDunois\Yasmin\Interfaces\VoiceChannelInterface) { $data['bitrate'] = $this->bitrate; $data['user_limit'] = $this->userLimit; } else { $data['nsfw'] = $this->nsfw; } return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($data, $reason) { $this->client->apimanager()->endpoints->guild->createGuildChannel($this->guild->id, $data, $reason)->done(function ($data) use ($resolve) { $channel = $this->guild->channels->factory($data, $this->guild); $resolve($channel); }, $reject); })); }
[ "function", "clone", "(", "string", "$", "name", "=", "null", ",", "bool", "$", "withPermissions", "=", "true", ",", "bool", "$", "withTopic", "=", "true", ",", "string", "$", "reason", "=", "''", ")", "{", "$", "data", "=", "array", "(", "'name'", ...
Clones a guild channel. Resolves with an instance of GuildChannelInterface. @param string $name Optional name for the new channel, otherwise it has the name of this channel. @param bool $withPermissions Whether to clone the channel with this channel's permission overwrites @param bool $withTopic Whether to clone the channel with this channel's topic. @param string $reason @return \React\Promise\ExtendedPromiseInterface @see \CharlotteDunois\Yasmin\Interfaces\GuildChannelInterface
[ "Clones", "a", "guild", "channel", ".", "Resolves", "with", "an", "instance", "of", "GuildChannelInterface", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Traits/GuildChannelTrait.php#L62-L93
CharlotteDunois/Yasmin
src/Traits/GuildChannelTrait.php
GuildChannelTrait.edit
function edit(array $options, string $reason = '') { if(empty($options)) { throw new \InvalidArgumentException('Unable to edit channel with zero information'); } $data = \CharlotteDunois\Yasmin\Utils\DataHelpers::applyOptions($options, array( 'name' => array('type' => 'string'), 'position' => array('type' => 'int'), 'topic' => array('type' => 'string'), 'nsfw' => array('type' => 'bool'), 'bitrate' => array('type' => 'int'), 'userLimit' => array('key' => 'user_limit', 'type' => 'int'), 'slowmode' => array('key' => 'rate_limit_per_user', 'type' => 'int'), 'parent' => array('key' => 'parent_id', 'parse' => function ($val) { return ($val instanceof \CharlotteDunois\Yasmin\Models\CategoryChannel ? $val->id : $val); }), 'permissionOverwrites' => array('key' => 'permission_overwrites', 'parse' => function ($val) { if($val instanceof \CharlotteDunois\Collect\Collection) { $val = $val->all(); } return \array_values($val); }) )); return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($data, $reason) { $this->client->apimanager()->endpoints->channel->modifyChannel($this->id, $data, $reason)->done(function () use ($resolve) { $resolve($this); }, $reject); })); }
php
function edit(array $options, string $reason = '') { if(empty($options)) { throw new \InvalidArgumentException('Unable to edit channel with zero information'); } $data = \CharlotteDunois\Yasmin\Utils\DataHelpers::applyOptions($options, array( 'name' => array('type' => 'string'), 'position' => array('type' => 'int'), 'topic' => array('type' => 'string'), 'nsfw' => array('type' => 'bool'), 'bitrate' => array('type' => 'int'), 'userLimit' => array('key' => 'user_limit', 'type' => 'int'), 'slowmode' => array('key' => 'rate_limit_per_user', 'type' => 'int'), 'parent' => array('key' => 'parent_id', 'parse' => function ($val) { return ($val instanceof \CharlotteDunois\Yasmin\Models\CategoryChannel ? $val->id : $val); }), 'permissionOverwrites' => array('key' => 'permission_overwrites', 'parse' => function ($val) { if($val instanceof \CharlotteDunois\Collect\Collection) { $val = $val->all(); } return \array_values($val); }) )); return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($data, $reason) { $this->client->apimanager()->endpoints->channel->modifyChannel($this->id, $data, $reason)->done(function () use ($resolve) { $resolve($this); }, $reject); })); }
[ "function", "edit", "(", "array", "$", "options", ",", "string", "$", "reason", "=", "''", ")", "{", "if", "(", "empty", "(", "$", "options", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Unable to edit channel with zero information'"...
Edits the channel. Resolves with $this. Options are as following (at least one is required). ``` array( 'name' => string, 'position' => int, 'topic' => string, (text channels only) 'nsfw' => bool, (text channels only) 'bitrate' => int, (voice channels only) 'userLimit' => int, (voice channels only) 'slowmode' => int, (text channels only, 0-21600) 'parent' => \CharlotteDunois\Yasmin\Models\CategoryChannel|string, (string = channel ID) 'permissionOverwrites' => \CharlotteDunois\Collect\Collection|array (an array or Collection of PermissionOverwrite instances or permission overwrite arrays) ) ``` @param array $options @param string $reason @return \React\Promise\ExtendedPromiseInterface @throws \InvalidArgumentException
[ "Edits", "the", "channel", ".", "Resolves", "with", "$this", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Traits/GuildChannelTrait.php#L119-L149
CharlotteDunois/Yasmin
src/Traits/GuildChannelTrait.php
GuildChannelTrait.delete
function delete(string $reason = '') { return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($reason) { $this->client->apimanager()->endpoints->channel->deleteChannel($this->id, $reason)->done(function () use ($resolve) { $resolve(); }, $reject); })); }
php
function delete(string $reason = '') { return (new \React\Promise\Promise(function (callable $resolve, callable $reject) use ($reason) { $this->client->apimanager()->endpoints->channel->deleteChannel($this->id, $reason)->done(function () use ($resolve) { $resolve(); }, $reject); })); }
[ "function", "delete", "(", "string", "$", "reason", "=", "''", ")", "{", "return", "(", "new", "\\", "React", "\\", "Promise", "\\", "Promise", "(", "function", "(", "callable", "$", "resolve", ",", "callable", "$", "reject", ")", "use", "(", "$", "r...
Deletes the channel. @param string $reason @return \React\Promise\ExtendedPromiseInterface
[ "Deletes", "the", "channel", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Traits/GuildChannelTrait.php#L156-L162
CharlotteDunois/Yasmin
src/Traits/GuildChannelTrait.php
GuildChannelTrait.fetchInvites
function fetchInvites() { return (new \React\Promise\Promise(function (callable $resolve, callable $reject) { $this->client->apimanager()->endpoints->channel->getChannelInvites($this->id)->done(function ($data) use ($resolve) { $collection = new \CharlotteDunois\Collect\Collection(); foreach($data as $invite) { $inv = new \CharlotteDunois\Yasmin\Models\Invite($this->client, $invite); $collection->set($inv->code, $inv); } $resolve($collection); }, $reject); })); }
php
function fetchInvites() { return (new \React\Promise\Promise(function (callable $resolve, callable $reject) { $this->client->apimanager()->endpoints->channel->getChannelInvites($this->id)->done(function ($data) use ($resolve) { $collection = new \CharlotteDunois\Collect\Collection(); foreach($data as $invite) { $inv = new \CharlotteDunois\Yasmin\Models\Invite($this->client, $invite); $collection->set($inv->code, $inv); } $resolve($collection); }, $reject); })); }
[ "function", "fetchInvites", "(", ")", "{", "return", "(", "new", "\\", "React", "\\", "Promise", "\\", "Promise", "(", "function", "(", "callable", "$", "resolve", ",", "callable", "$", "reject", ")", "{", "$", "this", "->", "client", "->", "apimanager",...
Fetches all invites of this channel. Resolves with a Collection of Invite instances, mapped by their code. @return \React\Promise\ExtendedPromiseInterface @see \CharlotteDunois\Yasmin\Models\Invite
[ "Fetches", "all", "invites", "of", "this", "channel", ".", "Resolves", "with", "a", "Collection", "of", "Invite", "instances", "mapped", "by", "their", "code", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Traits/GuildChannelTrait.php#L169-L182
CharlotteDunois/Yasmin
src/Traits/GuildChannelTrait.php
GuildChannelTrait.isPermissionsLocked
function isPermissionsLocked() { if($this->parentID === null) { throw new \BadMethodCallException('This channel does not have a parent'); } $parent = $this->parent; if($parent->permissionOverwrites->count() !== $this->permissionOverwrites->count()) { return false; } return !((bool) $this->permissionOverwrites->first(function ($perm) use ($parent) { $permp = $parent->permissionOverwrites->get($perm->id); return (!$permp || $perm->allowed->bitfield !== $permp->allowed->bitfield || $perm->denied->bitfield !== $permp->denied->bitfield); })); }
php
function isPermissionsLocked() { if($this->parentID === null) { throw new \BadMethodCallException('This channel does not have a parent'); } $parent = $this->parent; if($parent->permissionOverwrites->count() !== $this->permissionOverwrites->count()) { return false; } return !((bool) $this->permissionOverwrites->first(function ($perm) use ($parent) { $permp = $parent->permissionOverwrites->get($perm->id); return (!$permp || $perm->allowed->bitfield !== $permp->allowed->bitfield || $perm->denied->bitfield !== $permp->denied->bitfield); })); }
[ "function", "isPermissionsLocked", "(", ")", "{", "if", "(", "$", "this", "->", "parentID", "===", "null", ")", "{", "throw", "new", "\\", "BadMethodCallException", "(", "'This channel does not have a parent'", ")", ";", "}", "$", "parent", "=", "$", "this", ...
Whether the permission overwrites match the parent channel (permissions synced). @return bool @throws \BadMethodCallException
[ "Whether", "the", "permission", "overwrites", "match", "the", "parent", "channel", "(", "permissions", "synced", ")", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Traits/GuildChannelTrait.php#L189-L204
CharlotteDunois/Yasmin
src/Traits/GuildChannelTrait.php
GuildChannelTrait.permissionsFor
function permissionsFor($member) { $member = $this->guild->members->resolve($member); if($member->id === $this->guild->ownerID) { return (new \CharlotteDunois\Yasmin\Models\Permissions(\CharlotteDunois\Yasmin\Models\Permissions::ALL)); } $permissions = $member->permissions; if($permissions->has('ADMINISTRATOR')) { return (new \CharlotteDunois\Yasmin\Models\Permissions(\CharlotteDunois\Yasmin\Models\Permissions::ALL)); } $overwrites = $this->overwritesFor($member); if($overwrites['everyone']) { $permissions->remove(($overwrites['everyone']->deny->bitfield & ~\CharlotteDunois\Yasmin\Models\Permissions::CHANNEL_UNACCESSIBLE_PERMISSIONS)); $permissions->add(($overwrites['everyone']->allow->bitfield & ~\CharlotteDunois\Yasmin\Models\Permissions::CHANNEL_UNACCESSIBLE_PERMISSIONS)); } foreach($overwrites['roles'] as $role) { $permissions->remove(($role->deny->bitfield & ~\CharlotteDunois\Yasmin\Models\Permissions::CHANNEL_UNACCESSIBLE_PERMISSIONS)); $permissions->add(($role->allow->bitfield & ~\CharlotteDunois\Yasmin\Models\Permissions::CHANNEL_UNACCESSIBLE_PERMISSIONS)); } if($overwrites['member']) { $permissions->remove(($overwrites['member']->deny->bitfield & ~\CharlotteDunois\Yasmin\Models\Permissions::CHANNEL_UNACCESSIBLE_PERMISSIONS)); $permissions->add(($overwrites['member']->allow->bitfield & ~\CharlotteDunois\Yasmin\Models\Permissions::CHANNEL_UNACCESSIBLE_PERMISSIONS)); } return $permissions; }
php
function permissionsFor($member) { $member = $this->guild->members->resolve($member); if($member->id === $this->guild->ownerID) { return (new \CharlotteDunois\Yasmin\Models\Permissions(\CharlotteDunois\Yasmin\Models\Permissions::ALL)); } $permissions = $member->permissions; if($permissions->has('ADMINISTRATOR')) { return (new \CharlotteDunois\Yasmin\Models\Permissions(\CharlotteDunois\Yasmin\Models\Permissions::ALL)); } $overwrites = $this->overwritesFor($member); if($overwrites['everyone']) { $permissions->remove(($overwrites['everyone']->deny->bitfield & ~\CharlotteDunois\Yasmin\Models\Permissions::CHANNEL_UNACCESSIBLE_PERMISSIONS)); $permissions->add(($overwrites['everyone']->allow->bitfield & ~\CharlotteDunois\Yasmin\Models\Permissions::CHANNEL_UNACCESSIBLE_PERMISSIONS)); } foreach($overwrites['roles'] as $role) { $permissions->remove(($role->deny->bitfield & ~\CharlotteDunois\Yasmin\Models\Permissions::CHANNEL_UNACCESSIBLE_PERMISSIONS)); $permissions->add(($role->allow->bitfield & ~\CharlotteDunois\Yasmin\Models\Permissions::CHANNEL_UNACCESSIBLE_PERMISSIONS)); } if($overwrites['member']) { $permissions->remove(($overwrites['member']->deny->bitfield & ~\CharlotteDunois\Yasmin\Models\Permissions::CHANNEL_UNACCESSIBLE_PERMISSIONS)); $permissions->add(($overwrites['member']->allow->bitfield & ~\CharlotteDunois\Yasmin\Models\Permissions::CHANNEL_UNACCESSIBLE_PERMISSIONS)); } return $permissions; }
[ "function", "permissionsFor", "(", "$", "member", ")", "{", "$", "member", "=", "$", "this", "->", "guild", "->", "members", "->", "resolve", "(", "$", "member", ")", ";", "if", "(", "$", "member", "->", "id", "===", "$", "this", "->", "guild", "->...
Returns the permissions for the given member. @param \CharlotteDunois\Yasmin\Models\GuildMember|string $member @return \CharlotteDunois\Yasmin\Models\Permissions @throws \InvalidArgumentException @see https://discordapp.com/developers/docs/topics/permissions#permission-overwrites
[ "Returns", "the", "permissions", "for", "the", "given", "member", "." ]
train
https://github.com/CharlotteDunois/Yasmin/blob/7c38faf5784b4bffbe0560931ebf43cc6fa10044/src/Traits/GuildChannelTrait.php#L213-L244