repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
rosasurfer/ministruts | src/util/Validator.php | Validator.isPhoneNumber | public static function isPhoneNumber($value) {
if (!is_string($value)) return false;
// handle empty value
$value = trim($value);
if (!strlen($value)) return false;
// remove spaces
$value = str_replace(' ', '', $value);
// match numbers from BE, ES, BG, CH, A, UK, DE
return (bool) preg_match('/^(00|\+)(32|34|359|41|43|44|49)-?[1-9](-?[0-9]){2,}$/', $value);
// TODO: implement via https://github.com/giggsey/libphonenumber-for-php
} | php | public static function isPhoneNumber($value) {
if (!is_string($value)) return false;
// handle empty value
$value = trim($value);
if (!strlen($value)) return false;
// remove spaces
$value = str_replace(' ', '', $value);
// match numbers from BE, ES, BG, CH, A, UK, DE
return (bool) preg_match('/^(00|\+)(32|34|359|41|43|44|49)-?[1-9](-?[0-9]){2,}$/', $value);
// TODO: implement via https://github.com/giggsey/libphonenumber-for-php
} | [
"public",
"static",
"function",
"isPhoneNumber",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"value",
")",
")",
"return",
"false",
";",
"// handle empty value",
"$",
"value",
"=",
"trim",
"(",
"$",
"value",
")",
";",
"if",
"(",
... | Whether the passed string represents a valid phone number.
@param string $value
@return bool | [
"Whether",
"the",
"passed",
"string",
"represents",
"a",
"valid",
"phone",
"number",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/util/Validator.php#L313-L327 | train |
rosasurfer/ministruts | src/util/Validator.php | Validator.isStreetNumber | public static function isStreetNumber($string) {
static $pattern = '/^[0-9A-Za-z-\/]+$/';
return is_string($string) && strlen($string) && preg_match($pattern, strtolower($string));
} | php | public static function isStreetNumber($string) {
static $pattern = '/^[0-9A-Za-z-\/]+$/';
return is_string($string) && strlen($string) && preg_match($pattern, strtolower($string));
} | [
"public",
"static",
"function",
"isStreetNumber",
"(",
"$",
"string",
")",
"{",
"static",
"$",
"pattern",
"=",
"'/^[0-9A-Za-z-\\/]+$/'",
";",
"return",
"is_string",
"(",
"$",
"string",
")",
"&&",
"strlen",
"(",
"$",
"string",
")",
"&&",
"preg_match",
"(",
... | Ob der uebergebene String eine gueltige Hausnummer ist.
@param string $string - der zu pruefende String
@return bool | [
"Ob",
"der",
"uebergebene",
"String",
"eine",
"gueltige",
"Hausnummer",
"ist",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/util/Validator.php#L402-L405 | train |
rosasurfer/ministruts | src/db/mysql/MySQLConnector.php | MySQLConnector.setUsername | protected function setUsername($name) {
if (!is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name));
if (!strlen($name)) throw new InvalidArgumentException('Invalid parameter $name: "'.$name.'" (empty)');
$this->username = $name;
return $this;
} | php | protected function setUsername($name) {
if (!is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name));
if (!strlen($name)) throw new InvalidArgumentException('Invalid parameter $name: "'.$name.'" (empty)');
$this->username = $name;
return $this;
} | [
"protected",
"function",
"setUsername",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"name",
")",
")",
"throw",
"new",
"IllegalTypeException",
"(",
"'Illegal type of parameter $name: '",
".",
"gettype",
"(",
"$",
"name",
")",
")",
";",
... | Set the username for the connection.
@param string $name
@return $this | [
"Set",
"the",
"username",
"for",
"the",
"connection",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/mysql/MySQLConnector.php#L136-L142 | train |
rosasurfer/ministruts | src/db/mysql/MySQLConnector.php | MySQLConnector.setDatabase | protected function setDatabase($name) {
if (isset($name) && !is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name));
if (!strlen($name))
$name = null;
$this->database = $name;
return $this;
} | php | protected function setDatabase($name) {
if (isset($name) && !is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name));
if (!strlen($name))
$name = null;
$this->database = $name;
return $this;
} | [
"protected",
"function",
"setDatabase",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"name",
")",
"&&",
"!",
"is_string",
"(",
"$",
"name",
")",
")",
"throw",
"new",
"IllegalTypeException",
"(",
"'Illegal type of parameter $name: '",
".",
"getty... | Set the name of the default database schema to use.
@param string $name - schema name
@return $this | [
"Set",
"the",
"name",
"of",
"the",
"default",
"database",
"schema",
"to",
"use",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/mysql/MySQLConnector.php#L168-L175 | train |
rosasurfer/ministruts | src/db/mysql/MySQLConnector.php | MySQLConnector.getConnectionDescription | protected function getConnectionDescription() {
$host = $this->host;
$port = $this->port ? ':'.$this->port : '';
$db = $this->database ? '/'.$this->database : '';
return $host.$port.$db;
} | php | protected function getConnectionDescription() {
$host = $this->host;
$port = $this->port ? ':'.$this->port : '';
$db = $this->database ? '/'.$this->database : '';
return $host.$port.$db;
} | [
"protected",
"function",
"getConnectionDescription",
"(",
")",
"{",
"$",
"host",
"=",
"$",
"this",
"->",
"host",
";",
"$",
"port",
"=",
"$",
"this",
"->",
"port",
"?",
"':'",
".",
"$",
"this",
"->",
"port",
":",
"''",
";",
"$",
"db",
"=",
"$",
"t... | Return a textual description of the main database connection options.
@return string | [
"Return",
"a",
"textual",
"description",
"of",
"the",
"main",
"database",
"connection",
"options",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/mysql/MySQLConnector.php#L197-L202 | train |
rosasurfer/ministruts | src/db/mysql/MySQLConnector.php | MySQLConnector.selectDatabase | protected function selectDatabase() {
if ($this->database !== null) {
try {
mysql_select_db($this->database, $this->hConnection) || trigger_error(mysql_error($this->hConnection), E_USER_ERROR);
}
catch (\Exception $ex) {
$ex = new DatabaseException($ex->getMessage(), mysql_errno($this->hConnection), $ex);
throw $ex->addMessage('Can not select database "'.$this->database.'"');
}
}
return $this;
} | php | protected function selectDatabase() {
if ($this->database !== null) {
try {
mysql_select_db($this->database, $this->hConnection) || trigger_error(mysql_error($this->hConnection), E_USER_ERROR);
}
catch (\Exception $ex) {
$ex = new DatabaseException($ex->getMessage(), mysql_errno($this->hConnection), $ex);
throw $ex->addMessage('Can not select database "'.$this->database.'"');
}
}
return $this;
} | [
"protected",
"function",
"selectDatabase",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"database",
"!==",
"null",
")",
"{",
"try",
"{",
"mysql_select_db",
"(",
"$",
"this",
"->",
"database",
",",
"$",
"this",
"->",
"hConnection",
")",
"||",
"trigger_err... | Pre-select a configured database.
@return $this | [
"Pre",
"-",
"select",
"a",
"configured",
"database",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/mysql/MySQLConnector.php#L268-L279 | train |
rosasurfer/ministruts | src/db/mysql/MySQLConnector.php | MySQLConnector.begin | public function begin() {
if ($this->transactionLevel < 0) throw new RuntimeException('Negative transaction nesting level detected: '.$this->transactionLevel);
if (!$this->transactionLevel)
$this->execute('start transaction');
$this->transactionLevel++;
return $this;
} | php | public function begin() {
if ($this->transactionLevel < 0) throw new RuntimeException('Negative transaction nesting level detected: '.$this->transactionLevel);
if (!$this->transactionLevel)
$this->execute('start transaction');
$this->transactionLevel++;
return $this;
} | [
"public",
"function",
"begin",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"transactionLevel",
"<",
"0",
")",
"throw",
"new",
"RuntimeException",
"(",
"'Negative transaction nesting level detected: '",
".",
"$",
"this",
"->",
"transactionLevel",
")",
";",
"if",... | Start a new transaction. If there is already an active transaction only the transaction nesting level is increased.
@return $this | [
"Start",
"a",
"new",
"transaction",
".",
"If",
"there",
"is",
"already",
"an",
"active",
"transaction",
"only",
"the",
"transaction",
"nesting",
"level",
"is",
"increased",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/db/mysql/MySQLConnector.php#L448-L456 | train |
rosasurfer/ministruts | src/net/TorHelper.php | TorHelper.init | private static function init() {
if (self::$logDebug === null) {
$loglevel = Logger::getLogLevel(__CLASS__);
self::$logDebug = ($loglevel <= L_DEBUG );
self::$logInfo = ($loglevel <= L_INFO );
self::$logNotice = ($loglevel <= L_NOTICE);
}
} | php | private static function init() {
if (self::$logDebug === null) {
$loglevel = Logger::getLogLevel(__CLASS__);
self::$logDebug = ($loglevel <= L_DEBUG );
self::$logInfo = ($loglevel <= L_INFO );
self::$logNotice = ($loglevel <= L_NOTICE);
}
} | [
"private",
"static",
"function",
"init",
"(",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"logDebug",
"===",
"null",
")",
"{",
"$",
"loglevel",
"=",
"Logger",
"::",
"getLogLevel",
"(",
"__CLASS__",
")",
";",
"self",
"::",
"$",
"logDebug",
"=",
"(",
"$",
... | Initialisiert die Klasse. | [
"Initialisiert",
"die",
"Klasse",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/net/TorHelper.php#L59-L66 | train |
rosasurfer/ministruts | src/net/TorHelper.php | TorHelper.isExitNode | public static function isExitNode($ip) {
self::init();
if (!is_string($ip)) throw new IllegalTypeException('Illegal type of parameter $ip: '.gettype($ip));
// TODO: mit Filter-Extension lokale Netze abfangen
if ($ip == '127.0.0.1')
return false;
$nodes = self::getExitNodes();
return isset($nodes[$ip]);
} | php | public static function isExitNode($ip) {
self::init();
if (!is_string($ip)) throw new IllegalTypeException('Illegal type of parameter $ip: '.gettype($ip));
// TODO: mit Filter-Extension lokale Netze abfangen
if ($ip == '127.0.0.1')
return false;
$nodes = self::getExitNodes();
return isset($nodes[$ip]);
} | [
"public",
"static",
"function",
"isExitNode",
"(",
"$",
"ip",
")",
"{",
"self",
"::",
"init",
"(",
")",
";",
"if",
"(",
"!",
"is_string",
"(",
"$",
"ip",
")",
")",
"throw",
"new",
"IllegalTypeException",
"(",
"'Illegal type of parameter $ip: '",
".",
"gett... | Prueft, ob die uebergebene IP-Adresse ein aktueller Tor-Exit-Node ist.
@param string $ip - IP-Adresse
@return bool | [
"Prueft",
"ob",
"die",
"uebergebene",
"IP",
"-",
"Adresse",
"ein",
"aktueller",
"Tor",
"-",
"Exit",
"-",
"Node",
"ist",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/net/TorHelper.php#L76-L86 | train |
rosasurfer/ministruts | src/net/TorHelper.php | TorHelper.getExitNodes | private static function getExitNodes() {
$cache = Cache::me(__CLASS__);
$nodes = $cache->get($key='tor_exit_nodes');
if ($nodes == null) {
// Einlesen der Nodes synchronisieren
synchronized(function() use ($cache, $key, &$nodes) {
$nodes = $cache->get($key);
if ($nodes == null) {
$content = '';
$size = sizeof(self::$torMirrors);
for ($i=0; $i < $size; ++$i) {
$request = new HttpRequest('http://'.self::$torMirrors[$i].'/ip_list_exit.php/Tor_ip_list_EXIT.csv');
try {
// TODO: Warnung ausgeben und Reihenfolge aendern, wenn ein Server nicht antwortet
$response = (new CurlHttpClient())->send($request);
$status = $response->getStatus();
if ($status != 200) {
self::$logNotice && Logger::log('Could not get TOR exit nodes from '.self::$torMirrors[$i].', HTTP status '.$status.' ('.HttpResponse::$sc[$status]."),\n URL: ".$request->getUrl(), L_NOTICE);
continue;
}
}
catch (IOException $ex) {
self::$logNotice && Logger::log('Could not get TOR exit nodes from '.self::$torMirrors[$i], L_NOTICE, ['exception'=>$ex]);
continue;
}
$content = trim($response->getContent());
break;
}
$nodes = strlen($content) ? \array_flip(explode(NL, normalizeEOL($content))) : [];
if (!$nodes) Logger::log('Could not get TOR exit nodes from any server', L_ERROR);
$cache->set($key, $nodes, 30 * MINUTES);
}
});
}
return $nodes;
} | php | private static function getExitNodes() {
$cache = Cache::me(__CLASS__);
$nodes = $cache->get($key='tor_exit_nodes');
if ($nodes == null) {
// Einlesen der Nodes synchronisieren
synchronized(function() use ($cache, $key, &$nodes) {
$nodes = $cache->get($key);
if ($nodes == null) {
$content = '';
$size = sizeof(self::$torMirrors);
for ($i=0; $i < $size; ++$i) {
$request = new HttpRequest('http://'.self::$torMirrors[$i].'/ip_list_exit.php/Tor_ip_list_EXIT.csv');
try {
// TODO: Warnung ausgeben und Reihenfolge aendern, wenn ein Server nicht antwortet
$response = (new CurlHttpClient())->send($request);
$status = $response->getStatus();
if ($status != 200) {
self::$logNotice && Logger::log('Could not get TOR exit nodes from '.self::$torMirrors[$i].', HTTP status '.$status.' ('.HttpResponse::$sc[$status]."),\n URL: ".$request->getUrl(), L_NOTICE);
continue;
}
}
catch (IOException $ex) {
self::$logNotice && Logger::log('Could not get TOR exit nodes from '.self::$torMirrors[$i], L_NOTICE, ['exception'=>$ex]);
continue;
}
$content = trim($response->getContent());
break;
}
$nodes = strlen($content) ? \array_flip(explode(NL, normalizeEOL($content))) : [];
if (!$nodes) Logger::log('Could not get TOR exit nodes from any server', L_ERROR);
$cache->set($key, $nodes, 30 * MINUTES);
}
});
}
return $nodes;
} | [
"private",
"static",
"function",
"getExitNodes",
"(",
")",
"{",
"$",
"cache",
"=",
"Cache",
"::",
"me",
"(",
"__CLASS__",
")",
";",
"$",
"nodes",
"=",
"$",
"cache",
"->",
"get",
"(",
"$",
"key",
"=",
"'tor_exit_nodes'",
")",
";",
"if",
"(",
"$",
"n... | Gibt die aktuellen Exit-Nodes zurueck.
@return array - assoziatives Array mit den IP-Adressen aller Exit-Nodes | [
"Gibt",
"die",
"aktuellen",
"Exit",
"-",
"Nodes",
"zurueck",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/net/TorHelper.php#L94-L138 | train |
timble/kodekit | code/translator/inflector/inflector.php | TranslatorInflector.setPluralRule | public static function setPluralRule(callable $rule, $language)
{
// temporary set a language for brazilian
if ("pt_BR" == $language) {
$language = "xbr";
}
if (strlen($language) > 3) {
$language = substr($language, 0, -strlen(strrchr($language, '_')));
}
if (!is_callable($rule)) {
throw new \LogicException('The given rule can not be called');
}
self::$position_rules[$language] = $rule;
} | php | public static function setPluralRule(callable $rule, $language)
{
// temporary set a language for brazilian
if ("pt_BR" == $language) {
$language = "xbr";
}
if (strlen($language) > 3) {
$language = substr($language, 0, -strlen(strrchr($language, '_')));
}
if (!is_callable($rule)) {
throw new \LogicException('The given rule can not be called');
}
self::$position_rules[$language] = $rule;
} | [
"public",
"static",
"function",
"setPluralRule",
"(",
"callable",
"$",
"rule",
",",
"$",
"language",
")",
"{",
"// temporary set a language for brazilian",
"if",
"(",
"\"pt_BR\"",
"==",
"$",
"language",
")",
"{",
"$",
"language",
"=",
"\"xbr\"",
";",
"}",
"if"... | Overrides the default plural rule for a given language.
@param callable $rule A PHP callable
@param string $language The language
@throws \LogicException
@return void | [
"Overrides",
"the",
"default",
"plural",
"rule",
"for",
"a",
"given",
"language",
"."
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/translator/inflector/inflector.php#L200-L216 | train |
timble/kodekit | code/dispatcher/behavior/routable.php | DispatcherBehaviorRoutable._beforeDispatch | protected function _beforeDispatch(DispatcherContext $context)
{
$view = $context->request->query->get('view', 'cmd');
//Redirect if no view information can be found in the request
if(empty($view))
{
$url = clone($context->request->getUrl());
$url->query['view'] = $this->getController()->getView()->getName();
$this->redirect($url);
return false;
}
return true;
} | php | protected function _beforeDispatch(DispatcherContext $context)
{
$view = $context->request->query->get('view', 'cmd');
//Redirect if no view information can be found in the request
if(empty($view))
{
$url = clone($context->request->getUrl());
$url->query['view'] = $this->getController()->getView()->getName();
$this->redirect($url);
return false;
}
return true;
} | [
"protected",
"function",
"_beforeDispatch",
"(",
"DispatcherContext",
"$",
"context",
")",
"{",
"$",
"view",
"=",
"$",
"context",
"->",
"request",
"->",
"query",
"->",
"get",
"(",
"'view'",
",",
"'cmd'",
")",
";",
"//Redirect if no view information can be found in... | Redirects the page to the default view
@param DispatcherContext $context The active command context
@return bool | [
"Redirects",
"the",
"page",
"to",
"the",
"default",
"view"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/dispatcher/behavior/routable.php#L28-L44 | train |
locomotivemtl/charcoal-core | src/Charcoal/Model/AbstractModel.php | AbstractModel.mergeData | public function mergeData(array $data)
{
$data = $this->setIdFromData($data);
foreach ($data as $propIdent => $val) {
if (!$this->hasProperty($propIdent)) {
$this->logger->warning(sprintf(
'Cannot set property "%s" on object; not defined in metadata.',
$propIdent
));
continue;
}
$property = $this->p($propIdent);
if ($property->l10n() && is_array($val)) {
$currentValue = json_decode(json_encode($this[$propIdent]), true);
if (is_array($currentValue)) {
$this[$propIdent] = array_merge($currentValue, $val);
} else {
$this[$propIdent] = $val;
}
} else {
$this[$propIdent] = $val;
}
}
return $this;
} | php | public function mergeData(array $data)
{
$data = $this->setIdFromData($data);
foreach ($data as $propIdent => $val) {
if (!$this->hasProperty($propIdent)) {
$this->logger->warning(sprintf(
'Cannot set property "%s" on object; not defined in metadata.',
$propIdent
));
continue;
}
$property = $this->p($propIdent);
if ($property->l10n() && is_array($val)) {
$currentValue = json_decode(json_encode($this[$propIdent]), true);
if (is_array($currentValue)) {
$this[$propIdent] = array_merge($currentValue, $val);
} else {
$this[$propIdent] = $val;
}
} else {
$this[$propIdent] = $val;
}
}
return $this;
} | [
"public",
"function",
"mergeData",
"(",
"array",
"$",
"data",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"setIdFromData",
"(",
"$",
"data",
")",
";",
"foreach",
"(",
"$",
"data",
"as",
"$",
"propIdent",
"=>",
"$",
"val",
")",
"{",
"if",
"(",
... | Merge data on the model.
Overrides `\Charcoal\Config\AbstractEntity::setData()`
to take properties into consideration.
Also add a special case, to merge values for l10n properties.
@param array $data The data to merge.
@return self | [
"Merge",
"data",
"on",
"the",
"model",
"."
] | db3a7af547ccf96efe2d9be028b252bc8646f5d5 | https://github.com/locomotivemtl/charcoal-core/blob/db3a7af547ccf96efe2d9be028b252bc8646f5d5/src/Charcoal/Model/AbstractModel.php#L155-L182 | train |
rosasurfer/ministruts | src/log/Logger.php | Logger.init | private static function init() {
static $initialized = false;
if ($initialized) return;
/** @var ConfigInterface $config */
$config = self::di('config');
// (1) Get the application's default loglevel configuration (fall back to the built-in default).
$logLevel = $config->get('log.level', '');
if (is_array($logLevel))
$logLevel = isset($logLevel['']) ? $logLevel[''] : '';
$logLevel = self::logLevelToId($logLevel) ?: self::DEFAULT_LOGLEVEL;
self::$appLogLevel = $logLevel;
// (2) mail handler: enabled if mail receivers are configured
$receivers = [];
foreach (explode(',', $config->get('log.mail.receiver', '')) as $receiver) {
if ($receiver = trim($receiver)) {
if (filter_var($receiver, FILTER_VALIDATE_EMAIL)) { // silently skip invalid addresses
$receivers[] = $receiver;
}
}
}
self::$mailHandler = (bool) $receivers;
self::$mailReceivers = $receivers;
// (3) L_FATAL print handler: enabled on local/white-listed access or if explicitely enabled
self::$printFatalHandler = CLI || Application::isAdminIP() || ini_get_bool('display_errors');
// (4) non L_FATAL print handler: enabled on local access, if explicitely enabled or if the mail handler is disabled
self::$printNonfatalHandler = CLI || in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', $_SERVER['SERVER_ADDR']])
|| ini_get_bool('display_errors')
|| (self::$printFatalHandler && !self::$mailHandler);
// (5) SMS handler: enabled if SMS receivers are configured (operator settings are checked at log time)
self::$smsReceivers = [];
foreach (explode(',', $config->get('log.sms.receiver', '')) as $receiver) {
if ($receiver=trim($receiver)) {
if (strStartsWith($receiver, '+' )) $receiver = substr($receiver, 1);
if (strStartsWith($receiver, '00')) $receiver = substr($receiver, 2);
if (!ctype_digit($receiver)) {
self::log('Invalid SMS receiver configuration: "'.$receiver.'"', L_WARN, ['class'=>__CLASS__, 'file'=>__FILE__, 'line'=>__LINE__]);
continue;
}
self::$smsReceivers[] = $receiver;
}
}
$logLevel = $config->get('log.sms.level', self::$appLogLevel);
if (is_string($logLevel)) // a string if configured
$logLevel = self::logLevelToId($logLevel) ?: self::$appLogLevel;
self::$smsLogLevel = $logLevel;
$options = $config->get('sms', []);
if (!is_array($options)) throw new IllegalTypeException('Invalid type of config value "sms": '.gettype($options).' (not array)');
self::$smsOptions = $options;
self::$smsHandler = self::$smsReceivers && self::$smsOptions;
// (6) PHP error_log handler: enabled if the mail handler is disabled
self::$errorLogHandler = !self::$mailHandler;
$initialized = true;
} | php | private static function init() {
static $initialized = false;
if ($initialized) return;
/** @var ConfigInterface $config */
$config = self::di('config');
// (1) Get the application's default loglevel configuration (fall back to the built-in default).
$logLevel = $config->get('log.level', '');
if (is_array($logLevel))
$logLevel = isset($logLevel['']) ? $logLevel[''] : '';
$logLevel = self::logLevelToId($logLevel) ?: self::DEFAULT_LOGLEVEL;
self::$appLogLevel = $logLevel;
// (2) mail handler: enabled if mail receivers are configured
$receivers = [];
foreach (explode(',', $config->get('log.mail.receiver', '')) as $receiver) {
if ($receiver = trim($receiver)) {
if (filter_var($receiver, FILTER_VALIDATE_EMAIL)) { // silently skip invalid addresses
$receivers[] = $receiver;
}
}
}
self::$mailHandler = (bool) $receivers;
self::$mailReceivers = $receivers;
// (3) L_FATAL print handler: enabled on local/white-listed access or if explicitely enabled
self::$printFatalHandler = CLI || Application::isAdminIP() || ini_get_bool('display_errors');
// (4) non L_FATAL print handler: enabled on local access, if explicitely enabled or if the mail handler is disabled
self::$printNonfatalHandler = CLI || in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', $_SERVER['SERVER_ADDR']])
|| ini_get_bool('display_errors')
|| (self::$printFatalHandler && !self::$mailHandler);
// (5) SMS handler: enabled if SMS receivers are configured (operator settings are checked at log time)
self::$smsReceivers = [];
foreach (explode(',', $config->get('log.sms.receiver', '')) as $receiver) {
if ($receiver=trim($receiver)) {
if (strStartsWith($receiver, '+' )) $receiver = substr($receiver, 1);
if (strStartsWith($receiver, '00')) $receiver = substr($receiver, 2);
if (!ctype_digit($receiver)) {
self::log('Invalid SMS receiver configuration: "'.$receiver.'"', L_WARN, ['class'=>__CLASS__, 'file'=>__FILE__, 'line'=>__LINE__]);
continue;
}
self::$smsReceivers[] = $receiver;
}
}
$logLevel = $config->get('log.sms.level', self::$appLogLevel);
if (is_string($logLevel)) // a string if configured
$logLevel = self::logLevelToId($logLevel) ?: self::$appLogLevel;
self::$smsLogLevel = $logLevel;
$options = $config->get('sms', []);
if (!is_array($options)) throw new IllegalTypeException('Invalid type of config value "sms": '.gettype($options).' (not array)');
self::$smsOptions = $options;
self::$smsHandler = self::$smsReceivers && self::$smsOptions;
// (6) PHP error_log handler: enabled if the mail handler is disabled
self::$errorLogHandler = !self::$mailHandler;
$initialized = true;
} | [
"private",
"static",
"function",
"init",
"(",
")",
"{",
"static",
"$",
"initialized",
"=",
"false",
";",
"if",
"(",
"$",
"initialized",
")",
"return",
";",
"/** @var ConfigInterface $config */",
"$",
"config",
"=",
"self",
"::",
"di",
"(",
"'config'",
")",
... | Initialize the Logger configuration. | [
"Initialize",
"the",
"Logger",
"configuration",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L151-L217 | train |
rosasurfer/ministruts | src/log/Logger.php | Logger.logLevelToId | public static function logLevelToId($value) {
if (!is_string($value)) throw new IllegalTypeException('Illegal type of parameter $value: '.gettype($value));
switch (strtolower($value)) {
case 'debug' : return L_DEBUG;
case 'info' : return L_INFO;
case 'notice': return L_NOTICE;
case 'warn' : return L_WARN;
case 'error' : return L_ERROR;
case 'fatal' : return L_FATAL;
default:
return null;
}
} | php | public static function logLevelToId($value) {
if (!is_string($value)) throw new IllegalTypeException('Illegal type of parameter $value: '.gettype($value));
switch (strtolower($value)) {
case 'debug' : return L_DEBUG;
case 'info' : return L_INFO;
case 'notice': return L_NOTICE;
case 'warn' : return L_WARN;
case 'error' : return L_ERROR;
case 'fatal' : return L_FATAL;
default:
return null;
}
} | [
"public",
"static",
"function",
"logLevelToId",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"value",
")",
")",
"throw",
"new",
"IllegalTypeException",
"(",
"'Illegal type of parameter $value: '",
".",
"gettype",
"(",
"$",
"value",
")",
... | Convert a loglevel description to a loglevel constant.
@param string $value - loglevel description
@return int|null - loglevel constant or NULL, if $value is not a valid loglevel description | [
"Convert",
"a",
"loglevel",
"description",
"to",
"a",
"loglevel",
"constant",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L227-L240 | train |
rosasurfer/ministruts | src/log/Logger.php | Logger.getLogLevel | public static function getLogLevel($class = '') {
if (!is_string($class)) throw new IllegalTypeException('Illegal type of parameter $class: '.gettype($class));
self::init();
// read the configured class specific loglevels
static $logLevels = null;
if ($logLevels === null) {
/** @var ConfigInterface $config */
$config = self::di('config');
$logLevels = $config->get('log.level', []);
if (is_string($logLevels))
$logLevels = ['' => $logLevels]; // only the general application loglevel is configured
foreach ($logLevels as $className => $level) {
if (!is_string($level)) throw new IllegalTypeException('Illegal configuration value for "log.level.'.$className.'": '.gettype($level));
if ($level == '') { // classes with empty values fall back to the application loglevel
unset($logLevels[$className]);
}
else {
$logLevel = self::logLevelToId($level);
if (!$logLevel) throw new InvalidArgumentException('Invalid configuration value for "log.level.'.$className.'" = '.$level);
$logLevels[$className] = $logLevel;
if (strStartsWith($className, '\\')) { // normalize class names: remove leading back slash
unset($logLevels[$className]);
$className = substr($className, 1);
$logLevels[$className] = $logLevel;
}
}
}
$logLevels = \array_change_key_case($logLevels, CASE_LOWER); // normalize class names: lower-case for case-insensitive look-up
}
// look-up the loglevel for the specified class
$class = strtolower($class);
if (isset($logLevels[$class]))
return $logLevels[$class];
// return the general application loglevel if no class specific loglevel is configured
return self::$appLogLevel;
} | php | public static function getLogLevel($class = '') {
if (!is_string($class)) throw new IllegalTypeException('Illegal type of parameter $class: '.gettype($class));
self::init();
// read the configured class specific loglevels
static $logLevels = null;
if ($logLevels === null) {
/** @var ConfigInterface $config */
$config = self::di('config');
$logLevels = $config->get('log.level', []);
if (is_string($logLevels))
$logLevels = ['' => $logLevels]; // only the general application loglevel is configured
foreach ($logLevels as $className => $level) {
if (!is_string($level)) throw new IllegalTypeException('Illegal configuration value for "log.level.'.$className.'": '.gettype($level));
if ($level == '') { // classes with empty values fall back to the application loglevel
unset($logLevels[$className]);
}
else {
$logLevel = self::logLevelToId($level);
if (!$logLevel) throw new InvalidArgumentException('Invalid configuration value for "log.level.'.$className.'" = '.$level);
$logLevels[$className] = $logLevel;
if (strStartsWith($className, '\\')) { // normalize class names: remove leading back slash
unset($logLevels[$className]);
$className = substr($className, 1);
$logLevels[$className] = $logLevel;
}
}
}
$logLevels = \array_change_key_case($logLevels, CASE_LOWER); // normalize class names: lower-case for case-insensitive look-up
}
// look-up the loglevel for the specified class
$class = strtolower($class);
if (isset($logLevels[$class]))
return $logLevels[$class];
// return the general application loglevel if no class specific loglevel is configured
return self::$appLogLevel;
} | [
"public",
"static",
"function",
"getLogLevel",
"(",
"$",
"class",
"=",
"''",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"class",
")",
")",
"throw",
"new",
"IllegalTypeException",
"(",
"'Illegal type of parameter $class: '",
".",
"gettype",
"(",
"$",
"c... | Resolve the loglevel of the specified class.
@param string $class [optional] - class name
@return int - configured loglevel or the application loglevel if no class specific loglevel is configured | [
"Resolve",
"the",
"loglevel",
"of",
"the",
"specified",
"class",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L250-L292 | train |
rosasurfer/ministruts | src/log/Logger.php | Logger.invokeMailHandler | private static function invokeMailHandler($loggable, $level, array &$context) {
if (!key_exists('mailSubject', $context) || !key_exists('mailMessage', $context))
self::composeMailMessage($loggable, $level, $context);
$subject = $context['mailSubject'];
$message = $context['mailMessage'];
/** @var ConfigInterface $config */
$config = self::di('config');
$options = $headers = [];
$sender = null;
if (strlen($name = $config->get('log.mail.profile', ''))) {
$options = $config->get('mail.profile.'.$name, []);
$sender = $config->get('mail.profile.'.$name.'.from', null);
$headers = $config->get('mail.profile.'.$name.'.headers', []);
}
static $mailer; !$mailer && $mailer=Mailer::create($options);
foreach (self::$mailReceivers as $receiver) {
$mailer->sendMail($sender, $receiver, $subject, $message, $headers);
}
} | php | private static function invokeMailHandler($loggable, $level, array &$context) {
if (!key_exists('mailSubject', $context) || !key_exists('mailMessage', $context))
self::composeMailMessage($loggable, $level, $context);
$subject = $context['mailSubject'];
$message = $context['mailMessage'];
/** @var ConfigInterface $config */
$config = self::di('config');
$options = $headers = [];
$sender = null;
if (strlen($name = $config->get('log.mail.profile', ''))) {
$options = $config->get('mail.profile.'.$name, []);
$sender = $config->get('mail.profile.'.$name.'.from', null);
$headers = $config->get('mail.profile.'.$name.'.headers', []);
}
static $mailer; !$mailer && $mailer=Mailer::create($options);
foreach (self::$mailReceivers as $receiver) {
$mailer->sendMail($sender, $receiver, $subject, $message, $headers);
}
} | [
"private",
"static",
"function",
"invokeMailHandler",
"(",
"$",
"loggable",
",",
"$",
"level",
",",
"array",
"&",
"$",
"context",
")",
"{",
"if",
"(",
"!",
"key_exists",
"(",
"'mailSubject'",
",",
"$",
"context",
")",
"||",
"!",
"key_exists",
"(",
"'mail... | Send the message to the configured mail receivers.
@param string|\Exception $loggable - message or exception to log
@param int $level - loglevel of the loggable
@param array $context - reference to the log context with additional data | [
"Send",
"the",
"message",
"to",
"the",
"configured",
"mail",
"receivers",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L404-L426 | train |
rosasurfer/ministruts | src/log/Logger.php | Logger.invokeErrorLogHandler | private static function invokeErrorLogHandler($loggable, $level, array &$context) {
if (!key_exists('cliMessage', $context))
self::composeCliMessage($loggable, $level, $context);
$msg = 'PHP '.$context['cliMessage'];
if (key_exists('cliExtra', $context))
$msg .= $context['cliExtra'];
$msg = str_replace(chr(0), '?', $msg); // replace NUL bytes which mess up the logfile
if (CLI && empty(ini_get('error_log'))) {
// Suppress duplicated output to STDERR, the PrintHandler already wrote to STDOUT.
// TODO: Instead of messing around here the PrintHandler must not print to STDOUT if the ErrorLogHandler
// is active and prints to STDERR.
// TODO: Suppress output to STDERR in interactive terminals only (i.e. not in CRON).
}
else {
error_log(trim($msg), ERROR_LOG_DEFAULT);
}
} | php | private static function invokeErrorLogHandler($loggable, $level, array &$context) {
if (!key_exists('cliMessage', $context))
self::composeCliMessage($loggable, $level, $context);
$msg = 'PHP '.$context['cliMessage'];
if (key_exists('cliExtra', $context))
$msg .= $context['cliExtra'];
$msg = str_replace(chr(0), '?', $msg); // replace NUL bytes which mess up the logfile
if (CLI && empty(ini_get('error_log'))) {
// Suppress duplicated output to STDERR, the PrintHandler already wrote to STDOUT.
// TODO: Instead of messing around here the PrintHandler must not print to STDOUT if the ErrorLogHandler
// is active and prints to STDERR.
// TODO: Suppress output to STDERR in interactive terminals only (i.e. not in CRON).
}
else {
error_log(trim($msg), ERROR_LOG_DEFAULT);
}
} | [
"private",
"static",
"function",
"invokeErrorLogHandler",
"(",
"$",
"loggable",
",",
"$",
"level",
",",
"array",
"&",
"$",
"context",
")",
"{",
"if",
"(",
"!",
"key_exists",
"(",
"'cliMessage'",
",",
"$",
"context",
")",
")",
"self",
"::",
"composeCliMessa... | Pass the message to the PHP default error log mechanism as defined by the PHP configuration value "error_log".
ini_get('error_log')
Name of the file where script errors should be logged. If the special value "syslog" is used, errors are sent to the
system logger instead. On Unix, this means syslog(3) and on Windows it means the event log. If this directive is not
set, errors are sent to the SAPI error logger. For example, it is an error log in Apache or STDERR in CLI mode.
@param string|\Exception $loggable - message or exception to log
@param int $level - loglevel of the loggable
@param array $context - reference to the log context with additional data | [
"Pass",
"the",
"message",
"to",
"the",
"PHP",
"default",
"error",
"log",
"mechanism",
"as",
"defined",
"by",
"the",
"PHP",
"configuration",
"value",
"error_log",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L543-L562 | train |
rosasurfer/ministruts | src/log/Logger.php | Logger.composeMailMessage | private static function composeMailMessage($loggable, $level, array &$context) {
if (!key_exists('cliMessage', $context))
self::composeCliMessage($loggable, $level, $context);
$msg = $context['cliMessage'];
if (key_exists('cliExtra', $context))
$msg .= $context['cliExtra'];
$location = null;
// compose message
if (CLI) {
$msg .= NL.NL.'Shell:'.NL.'------'.NL.print_r(ksort_r($_SERVER), true).NL;
$location = realpath($_SERVER['PHP_SELF']);
}
else {
$request = Request::me();
$location = strLeftTo($request->getUrl(), '?');
$session = null;
if (isset($_SESSION)) {
$session = $_SESSION;
}
else if ($request->hasSessionId()) {
$request->getSession($suppressHeadersAlreadySentError = true);
if (session_id() == $request->getSessionId()) // if both differ the id was regenerated and
$session = $_SESSION; // the session is empty
}
$session = is_null($session) ? null : print_r(ksort_r($session), true);
$ip = $_SERVER['REMOTE_ADDR'];
$host = NetTools::getHostByAddress($ip);
if ($host != $ip)
$ip .= ' ('.$host.')';
$msg .= NL.NL.'Request:'.NL.'--------'.NL.$request.NL.NL
. 'Session: '.($session ? NL.'--------'.NL.$session : '(none)'.NL.'--------'.NL).NL.NL
. 'Server:'.NL.'-------'.NL.print_r(ksort_r($_SERVER), true).NL.NL
. 'IP: '.$ip.NL
. 'Time: '.date('Y-m-d H:i:s').NL;
}
$type = ($loggable instanceof \Exception && key_exists('unhandled', $context)) ? 'Unhandled Exception ':'';
// store subject and message
$context['mailSubject'] = 'PHP ['.self::$logLevels[$level].'] '.$type.(CLI ? 'in ':'at ').$location;
$context['mailMessage'] = $msg;
} | php | private static function composeMailMessage($loggable, $level, array &$context) {
if (!key_exists('cliMessage', $context))
self::composeCliMessage($loggable, $level, $context);
$msg = $context['cliMessage'];
if (key_exists('cliExtra', $context))
$msg .= $context['cliExtra'];
$location = null;
// compose message
if (CLI) {
$msg .= NL.NL.'Shell:'.NL.'------'.NL.print_r(ksort_r($_SERVER), true).NL;
$location = realpath($_SERVER['PHP_SELF']);
}
else {
$request = Request::me();
$location = strLeftTo($request->getUrl(), '?');
$session = null;
if (isset($_SESSION)) {
$session = $_SESSION;
}
else if ($request->hasSessionId()) {
$request->getSession($suppressHeadersAlreadySentError = true);
if (session_id() == $request->getSessionId()) // if both differ the id was regenerated and
$session = $_SESSION; // the session is empty
}
$session = is_null($session) ? null : print_r(ksort_r($session), true);
$ip = $_SERVER['REMOTE_ADDR'];
$host = NetTools::getHostByAddress($ip);
if ($host != $ip)
$ip .= ' ('.$host.')';
$msg .= NL.NL.'Request:'.NL.'--------'.NL.$request.NL.NL
. 'Session: '.($session ? NL.'--------'.NL.$session : '(none)'.NL.'--------'.NL).NL.NL
. 'Server:'.NL.'-------'.NL.print_r(ksort_r($_SERVER), true).NL.NL
. 'IP: '.$ip.NL
. 'Time: '.date('Y-m-d H:i:s').NL;
}
$type = ($loggable instanceof \Exception && key_exists('unhandled', $context)) ? 'Unhandled Exception ':'';
// store subject and message
$context['mailSubject'] = 'PHP ['.self::$logLevels[$level].'] '.$type.(CLI ? 'in ':'at ').$location;
$context['mailMessage'] = $msg;
} | [
"private",
"static",
"function",
"composeMailMessage",
"(",
"$",
"loggable",
",",
"$",
"level",
",",
"array",
"&",
"$",
"context",
")",
"{",
"if",
"(",
"!",
"key_exists",
"(",
"'cliMessage'",
",",
"$",
"context",
")",
")",
"self",
"::",
"composeCliMessage"... | Compose a mail log message and store it in the passed log context under the keys "mailSubject" and "mailMessage".
@param string|\Exception $loggable - message or exception to log
@param int $level - loglevel of the loggable
@param array $context - reference to the log context | [
"Compose",
"a",
"mail",
"log",
"message",
"and",
"store",
"it",
"in",
"the",
"passed",
"log",
"context",
"under",
"the",
"keys",
"mailSubject",
"and",
"mailMessage",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L648-L691 | train |
rosasurfer/ministruts | src/log/Logger.php | Logger.resolveLogLocation | private static function resolveLogLocation(array &$context) {
if (!key_exists('trace', $context))
self::generateStackTrace($context);
$trace = $context['trace'];
foreach ($trace as $i => $frame) { // find the first frame with "file"
if (isset($frame['file'])) { // skip internal PHP functions
$context['file'] = $frame['file'];
$context['line'] = $frame['line'];
break;
}
}
if (!key_exists('file', $context)) {
$context['file'] = '(unknown)';
$context['line'] = '(?)';
}
} | php | private static function resolveLogLocation(array &$context) {
if (!key_exists('trace', $context))
self::generateStackTrace($context);
$trace = $context['trace'];
foreach ($trace as $i => $frame) { // find the first frame with "file"
if (isset($frame['file'])) { // skip internal PHP functions
$context['file'] = $frame['file'];
$context['line'] = $frame['line'];
break;
}
}
if (!key_exists('file', $context)) {
$context['file'] = '(unknown)';
$context['line'] = '(?)';
}
} | [
"private",
"static",
"function",
"resolveLogLocation",
"(",
"array",
"&",
"$",
"context",
")",
"{",
"if",
"(",
"!",
"key_exists",
"(",
"'trace'",
",",
"$",
"context",
")",
")",
"self",
"::",
"generateStackTrace",
"(",
"$",
"context",
")",
";",
"$",
"trac... | Resolve the location the logger was called from and store it in the log context under the keys "file" and "line".
@param array $context - reference to the log context | [
"Resolve",
"the",
"location",
"the",
"logger",
"was",
"called",
"from",
"and",
"store",
"it",
"in",
"the",
"log",
"context",
"under",
"the",
"keys",
"file",
"and",
"line",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L783-L800 | train |
rosasurfer/ministruts | src/log/Logger.php | Logger.resolveLogCaller | private static function resolveLogCaller(array &$context) {
if (!key_exists('trace', $context))
self::generateStackTrace($context);
$trace = $context['trace'];
$context['class'] = isset($trace[0]['class']) ? $trace[0]['class'] : '';
} | php | private static function resolveLogCaller(array &$context) {
if (!key_exists('trace', $context))
self::generateStackTrace($context);
$trace = $context['trace'];
$context['class'] = isset($trace[0]['class']) ? $trace[0]['class'] : '';
} | [
"private",
"static",
"function",
"resolveLogCaller",
"(",
"array",
"&",
"$",
"context",
")",
"{",
"if",
"(",
"!",
"key_exists",
"(",
"'trace'",
",",
"$",
"context",
")",
")",
"self",
"::",
"generateStackTrace",
"(",
"$",
"context",
")",
";",
"$",
"trace"... | Resolve the class the logger was called from and store it in the log context under the key "class".
@param array $context - reference to the log context
TODO: test with Closure and internal PHP functions | [
"Resolve",
"the",
"class",
"the",
"logger",
"was",
"called",
"from",
"and",
"store",
"it",
"in",
"the",
"log",
"context",
"under",
"the",
"key",
"class",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L811-L817 | train |
rosasurfer/ministruts | src/log/Logger.php | Logger.generateStackTrace | private static function generateStackTrace(array &$context) {
if (!key_exists('trace', $context)) {
$trace = DebugHelper::fixTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), __FILE__, __LINE__);
foreach ($trace as $i => $frame) {
if (!isset($frame['class']) || $frame['class']!=__CLASS__) // remove non-logger frames
break;
unset($trace[$i]);
}
$context['trace'] = \array_values($trace);
}
} | php | private static function generateStackTrace(array &$context) {
if (!key_exists('trace', $context)) {
$trace = DebugHelper::fixTrace(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), __FILE__, __LINE__);
foreach ($trace as $i => $frame) {
if (!isset($frame['class']) || $frame['class']!=__CLASS__) // remove non-logger frames
break;
unset($trace[$i]);
}
$context['trace'] = \array_values($trace);
}
} | [
"private",
"static",
"function",
"generateStackTrace",
"(",
"array",
"&",
"$",
"context",
")",
"{",
"if",
"(",
"!",
"key_exists",
"(",
"'trace'",
",",
"$",
"context",
")",
")",
"{",
"$",
"trace",
"=",
"DebugHelper",
"::",
"fixTrace",
"(",
"debug_backtrace"... | Generate an internal stacktrace and store it in the log context under the key "trace".
@param array $context - reference to the log context | [
"Generate",
"an",
"internal",
"stacktrace",
"and",
"store",
"it",
"in",
"the",
"log",
"context",
"under",
"the",
"key",
"trace",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/log/Logger.php#L825-L836 | train |
timble/kodekit | code/user/provider/abstract.php | UserProviderAbstract.getUser | public function getUser($identifier)
{
//Fetch a user from the backend if not loaded yet
if(!$this->isLoaded($identifier)) {
$this->fetch($identifier);
}
//Create an anonymous user was not loaded
if(!$user = $this->findUser($identifier))
{
$user = $this->create(array(
'id' => 0,
'name' => $this->getObject('translator')->translate('Anonymous')
));
}
return $user;
} | php | public function getUser($identifier)
{
//Fetch a user from the backend if not loaded yet
if(!$this->isLoaded($identifier)) {
$this->fetch($identifier);
}
//Create an anonymous user was not loaded
if(!$user = $this->findUser($identifier))
{
$user = $this->create(array(
'id' => 0,
'name' => $this->getObject('translator')->translate('Anonymous')
));
}
return $user;
} | [
"public",
"function",
"getUser",
"(",
"$",
"identifier",
")",
"{",
"//Fetch a user from the backend if not loaded yet",
"if",
"(",
"!",
"$",
"this",
"->",
"isLoaded",
"(",
"$",
"identifier",
")",
")",
"{",
"$",
"this",
"->",
"fetch",
"(",
"$",
"identifier",
... | Load the user for the given username or identifier
If the user could not be loaded an anonymous user will be returned with a user 'id' off 0.
@param string $identifier A unique user identifier, (i.e a username or email address)
@return UserInterface Returns a UserInterface object. | [
"Load",
"the",
"user",
"for",
"the",
"given",
"username",
"or",
"identifier"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/user/provider/abstract.php#L83-L100 | train |
rosasurfer/ministruts | src/console/Command.php | Command.run | public function run() {
$this->input = new Input($this->docoptResult);
$this->di()->set(Input::class, $this->input);
if ($this->validator) $error = $this->validator->__invoke($this->input, $this->output);
else $error = $this->validate($this->input, $this->output);
if ($error)
return $this->status = (int) $error;
if ($this->task) $status = $this->task->__invoke($this->input, $this->output);
else $status = $this->execute($this->input, $this->output);
return $this->status = (int) $status;
} | php | public function run() {
$this->input = new Input($this->docoptResult);
$this->di()->set(Input::class, $this->input);
if ($this->validator) $error = $this->validator->__invoke($this->input, $this->output);
else $error = $this->validate($this->input, $this->output);
if ($error)
return $this->status = (int) $error;
if ($this->task) $status = $this->task->__invoke($this->input, $this->output);
else $status = $this->execute($this->input, $this->output);
return $this->status = (int) $status;
} | [
"public",
"function",
"run",
"(",
")",
"{",
"$",
"this",
"->",
"input",
"=",
"new",
"Input",
"(",
"$",
"this",
"->",
"docoptResult",
")",
";",
"$",
"this",
"->",
"di",
"(",
")",
"->",
"set",
"(",
"Input",
"::",
"class",
",",
"$",
"this",
"->",
... | Trigger execution of the command.
@return int - execution status (0 for success) | [
"Trigger",
"execution",
"of",
"the",
"command",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/console/Command.php#L84-L98 | train |
rosasurfer/ministruts | src/console/Command.php | Command.setAliases | public function setAliases(array $names) {
if ($this->frozen) throw new RuntimeException('Configuration of "'.get_class($this).'" is frozen');
if ($this->name === '') throw new IllegalStateException('A default command (name="") cannot have aliases');
foreach ($names as $i => $alias) {
$this->validateName($alias);
}
$this->aliases = array_diff($names, [$this->name]); // remove an overlapping command name
return $this;
} | php | public function setAliases(array $names) {
if ($this->frozen) throw new RuntimeException('Configuration of "'.get_class($this).'" is frozen');
if ($this->name === '') throw new IllegalStateException('A default command (name="") cannot have aliases');
foreach ($names as $i => $alias) {
$this->validateName($alias);
}
$this->aliases = array_diff($names, [$this->name]); // remove an overlapping command name
return $this;
} | [
"public",
"function",
"setAliases",
"(",
"array",
"$",
"names",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"frozen",
")",
"throw",
"new",
"RuntimeException",
"(",
"'Configuration of \"'",
".",
"get_class",
"(",
"$",
"this",
")",
".",
"'\" is frozen'",
")",
";... | Set the alias names of the command if the command has a non-empty name. A command with an empty name is considered
the default command and cannot have aliases.
@param string[] $names
@return $this | [
"Set",
"the",
"alias",
"names",
"of",
"the",
"command",
"if",
"the",
"command",
"has",
"a",
"non",
"-",
"empty",
"name",
".",
"A",
"command",
"with",
"an",
"empty",
"name",
"is",
"considered",
"the",
"default",
"command",
"and",
"cannot",
"have",
"aliase... | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/console/Command.php#L181-L190 | train |
rosasurfer/ministruts | src/console/Command.php | Command.setDocoptDefinition | public function setDocoptDefinition($doc) {
if ($this->frozen) throw new RuntimeException('Configuration of "'.get_class($this).'" is frozen');
if (!is_string($doc)) throw new IllegalTypeException('Illegal type of parameter $doc: '.gettype($doc));
$parser = new DocoptParser();
$this->docoptResult = $parser->parse($doc);
$this->docoptDefinition = $doc;
return $this;
} | php | public function setDocoptDefinition($doc) {
if ($this->frozen) throw new RuntimeException('Configuration of "'.get_class($this).'" is frozen');
if (!is_string($doc)) throw new IllegalTypeException('Illegal type of parameter $doc: '.gettype($doc));
$parser = new DocoptParser();
$this->docoptResult = $parser->parse($doc);
$this->docoptDefinition = $doc;
return $this;
} | [
"public",
"function",
"setDocoptDefinition",
"(",
"$",
"doc",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"frozen",
")",
"throw",
"new",
"RuntimeException",
"(",
"'Configuration of \"'",
".",
"get_class",
"(",
"$",
"this",
")",
".",
"'\" is frozen'",
")",
";",
... | Set the command's docopt definition.
@param string $doc - syntax definition in docopt format
@return $this
@link http://docopt.org | [
"Set",
"the",
"command",
"s",
"docopt",
"definition",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/console/Command.php#L212-L221 | train |
rosasurfer/ministruts | src/console/Command.php | Command.validateName | private function validateName($name) {
if (!is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name));
if ($name != trim($name)) throw new InvalidArgumentException('Invalid parameter $name: "'.$name.'" (enclosing white space)');
if (strlen($name) && !preg_match('/^[^\s:]+(:[^\s:]+)*$/', $name))
throw new InvalidArgumentException('Invalid parameter $name: "'.$name.'" (not a command name)');
return $this;
} | php | private function validateName($name) {
if (!is_string($name)) throw new IllegalTypeException('Illegal type of parameter $name: '.gettype($name));
if ($name != trim($name)) throw new InvalidArgumentException('Invalid parameter $name: "'.$name.'" (enclosing white space)');
if (strlen($name) && !preg_match('/^[^\s:]+(:[^\s:]+)*$/', $name))
throw new InvalidArgumentException('Invalid parameter $name: "'.$name.'" (not a command name)');
return $this;
} | [
"private",
"function",
"validateName",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"name",
")",
")",
"throw",
"new",
"IllegalTypeException",
"(",
"'Illegal type of parameter $name: '",
".",
"gettype",
"(",
"$",
"name",
")",
")",
";",
... | Validate a command name.
@param string $name
@return $this | [
"Validate",
"a",
"command",
"name",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/console/Command.php#L295-L302 | train |
timble/kodekit | code/user/user.php | User.setProperties | public function setProperties($properties)
{
parent::setProperties($properties);
//Set the user data
$this->getSession()->set('user', ObjectConfig::unbox($properties));
return $this;
} | php | public function setProperties($properties)
{
parent::setProperties($properties);
//Set the user data
$this->getSession()->set('user', ObjectConfig::unbox($properties));
return $this;
} | [
"public",
"function",
"setProperties",
"(",
"$",
"properties",
")",
"{",
"parent",
"::",
"setProperties",
"(",
"$",
"properties",
")",
";",
"//Set the user data",
"$",
"this",
"->",
"getSession",
"(",
")",
"->",
"set",
"(",
"'user'",
",",
"ObjectConfig",
"::... | Set the user properties from an array
@param array $properties An associative array
@return User | [
"Set",
"the",
"user",
"properties",
"from",
"an",
"array"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/user/user.php#L207-L215 | train |
rosasurfer/ministruts | src/debug/ErrorHandler.php | ErrorHandler.setupErrorHandling | public static function setupErrorHandling($mode) {
if ($mode === self::LOG_ERRORS ) self::$errorMode = self::LOG_ERRORS;
elseif ($mode === self::THROW_EXCEPTIONS) self::$errorMode = self::THROW_EXCEPTIONS;
else return null;
return set_error_handler(self::$errorHandler=__CLASS__.'::handleError', error_reporting());
} | php | public static function setupErrorHandling($mode) {
if ($mode === self::LOG_ERRORS ) self::$errorMode = self::LOG_ERRORS;
elseif ($mode === self::THROW_EXCEPTIONS) self::$errorMode = self::THROW_EXCEPTIONS;
else return null;
return set_error_handler(self::$errorHandler=__CLASS__.'::handleError', error_reporting());
} | [
"public",
"static",
"function",
"setupErrorHandling",
"(",
"$",
"mode",
")",
"{",
"if",
"(",
"$",
"mode",
"===",
"self",
"::",
"LOG_ERRORS",
")",
"self",
"::",
"$",
"errorMode",
"=",
"self",
"::",
"LOG_ERRORS",
";",
"elseif",
"(",
"$",
"mode",
"===",
"... | Setup global error handling.
@param int $mode - mode the error handler to setup for
can be either self::LOG_ERRORS or self::THROW_EXCEPTIONS
@return mixed - Returns a string containing the previously defined error handler (if any). If the passed $mode
parameter is invalid or if the built-in error handler was active NULL is returned. If the previous
error handler was a class method an indexed array with the class and the method name is returned. | [
"Setup",
"global",
"error",
"handling",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/debug/ErrorHandler.php#L101-L107 | train |
rosasurfer/ministruts | src/debug/ErrorHandler.php | ErrorHandler.setupExceptionHandling | public static function setupExceptionHandling() {
$previous = set_exception_handler(self::$exceptionHandler=__CLASS__.'::handleException');
/**
* Detect entering of the script's shutdown phase to be capable of handling destructor exceptions during shutdown
* differently and avoid otherwise fatal errors. Should be the very first function on the shutdown function stack.
*
* @see http://php.net/manual/en/language.oop5.decon.php
* @see ErrorHandler::handleDestructorException()
*/
register_shutdown_function(function() {
self::$inShutdown = true;
});
return $previous;
} | php | public static function setupExceptionHandling() {
$previous = set_exception_handler(self::$exceptionHandler=__CLASS__.'::handleException');
/**
* Detect entering of the script's shutdown phase to be capable of handling destructor exceptions during shutdown
* differently and avoid otherwise fatal errors. Should be the very first function on the shutdown function stack.
*
* @see http://php.net/manual/en/language.oop5.decon.php
* @see ErrorHandler::handleDestructorException()
*/
register_shutdown_function(function() {
self::$inShutdown = true;
});
return $previous;
} | [
"public",
"static",
"function",
"setupExceptionHandling",
"(",
")",
"{",
"$",
"previous",
"=",
"set_exception_handler",
"(",
"self",
"::",
"$",
"exceptionHandler",
"=",
"__CLASS__",
".",
"'::handleException'",
")",
";",
"/**\n * Detect entering of the script's shu... | Setup global exception handling.
@return callable|null - Returns the name of the previously defined exception handler, or NULL if no previous handler
was defined or an error occurred. | [
"Setup",
"global",
"exception",
"handling",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/debug/ErrorHandler.php#L116-L130 | train |
rosasurfer/ministruts | src/debug/ErrorHandler.php | ErrorHandler.handleException | public static function handleException(\Exception $exception) {
$context = [];
$second = null;
try {
$context['class' ] = __CLASS__;
$context['file' ] = $exception->getFile(); // If the location is not preset the logger will resolve the
$context['line' ] = $exception->getLine(); // exception handler as the originating location.
$context['unhandled'] = true;
Logger::log($exception, L_FATAL, $context); // log with the highest level
}
// Exceptions thrown from within the exception handler will not be passed back to the handler again. Instead the
// script terminates with an uncatchable fatal error.
catch (\Exception $second) {
$indent = ' '; // the application is crashing, last try to log
// secondary exception
$msg2 = '[FATAL] Unhandled '.trim(DebugHelper::composeBetterMessage($second)).NL;
$file = $second->getFile();
$line = $second->getLine();
$msg2 .= $indent.'in '.$file.' on line '.$line.NL.NL;
$msg2 .= $indent.'Stacktrace:'.NL.$indent.'-----------'.NL;
$msg2 .= DebugHelper::getBetterTraceAsString($second, $indent);
// primary (the causing) exception
if (isset($context['cliMessage'])) {
$msg1 = $context['cliMessage'];
if (isset($context['cliExtra']))
$msg1 .= $context['cliExtra'];
}
else {
$msg1 = $indent.'Unhandled '.trim(DebugHelper::composeBetterMessage($exception)).NL;
$file = $exception->getFile();
$line = $exception->getLine();
$msg1 .= $indent.'in '.$file.' on line '.$line.NL.NL;
$msg1 .= $indent.'Stacktrace:'.NL.$indent.'-----------'.NL;
$msg1 .= DebugHelper::getBetterTraceAsString($exception, $indent);
}
$msg = $msg2.NL;
$msg .= $indent.'caused by'.NL;
$msg .= $msg1;
$msg = str_replace(chr(0), '?', $msg); // replace NUL bytes which mess up the logfile
if (CLI) // full second exception
echo $msg.NL;
error_log(trim($msg), ERROR_LOG_DEFAULT);
}
// web: prevent an empty page
if (!CLI) {
try {
if (Application::isAdminIP() || ini_get_bool('display_errors')) {
if ($second) { // full second exception, full log location
echoPre($second);
echoPre('error log: '.(strlen($errorLog=ini_get('error_log')) ? $errorLog : 'web server'));
}
}
else echoPre('application error (see error log)');
}
catch (\Exception $third) {
echoPre('application error (see error log)');
}
}
} | php | public static function handleException(\Exception $exception) {
$context = [];
$second = null;
try {
$context['class' ] = __CLASS__;
$context['file' ] = $exception->getFile(); // If the location is not preset the logger will resolve the
$context['line' ] = $exception->getLine(); // exception handler as the originating location.
$context['unhandled'] = true;
Logger::log($exception, L_FATAL, $context); // log with the highest level
}
// Exceptions thrown from within the exception handler will not be passed back to the handler again. Instead the
// script terminates with an uncatchable fatal error.
catch (\Exception $second) {
$indent = ' '; // the application is crashing, last try to log
// secondary exception
$msg2 = '[FATAL] Unhandled '.trim(DebugHelper::composeBetterMessage($second)).NL;
$file = $second->getFile();
$line = $second->getLine();
$msg2 .= $indent.'in '.$file.' on line '.$line.NL.NL;
$msg2 .= $indent.'Stacktrace:'.NL.$indent.'-----------'.NL;
$msg2 .= DebugHelper::getBetterTraceAsString($second, $indent);
// primary (the causing) exception
if (isset($context['cliMessage'])) {
$msg1 = $context['cliMessage'];
if (isset($context['cliExtra']))
$msg1 .= $context['cliExtra'];
}
else {
$msg1 = $indent.'Unhandled '.trim(DebugHelper::composeBetterMessage($exception)).NL;
$file = $exception->getFile();
$line = $exception->getLine();
$msg1 .= $indent.'in '.$file.' on line '.$line.NL.NL;
$msg1 .= $indent.'Stacktrace:'.NL.$indent.'-----------'.NL;
$msg1 .= DebugHelper::getBetterTraceAsString($exception, $indent);
}
$msg = $msg2.NL;
$msg .= $indent.'caused by'.NL;
$msg .= $msg1;
$msg = str_replace(chr(0), '?', $msg); // replace NUL bytes which mess up the logfile
if (CLI) // full second exception
echo $msg.NL;
error_log(trim($msg), ERROR_LOG_DEFAULT);
}
// web: prevent an empty page
if (!CLI) {
try {
if (Application::isAdminIP() || ini_get_bool('display_errors')) {
if ($second) { // full second exception, full log location
echoPre($second);
echoPre('error log: '.(strlen($errorLog=ini_get('error_log')) ? $errorLog : 'web server'));
}
}
else echoPre('application error (see error log)');
}
catch (\Exception $third) {
echoPre('application error (see error log)');
}
}
} | [
"public",
"static",
"function",
"handleException",
"(",
"\\",
"Exception",
"$",
"exception",
")",
"{",
"$",
"context",
"=",
"[",
"]",
";",
"$",
"second",
"=",
"null",
";",
"try",
"{",
"$",
"context",
"[",
"'class'",
"]",
"=",
"__CLASS__",
";",
"$",
"... | Global handler for otherwise unhandled exceptions.
The exception is sent to the default logger with loglevel L_FATAL. After the handler returns PHP will terminate
the script.
@param \Exception $exception - the unhandled exception | [
"Global",
"handler",
"for",
"otherwise",
"unhandled",
"exceptions",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/debug/ErrorHandler.php#L231-L297 | train |
rosasurfer/ministruts | src/debug/ErrorHandler.php | ErrorHandler.handleDestructorException | public static function handleDestructorException(\Exception $exception) {
if (self::isInShutdown()) {
self::handleException($exception);
exit(1); // exit and signal the error
// Calling exit() is the only way to prevent the immediately following non-catchable fatal error.
// However, calling exit() in a destructor will also prevent any remaining shutdown routines from executing.
// @see above link
}
return $exception;
} | php | public static function handleDestructorException(\Exception $exception) {
if (self::isInShutdown()) {
self::handleException($exception);
exit(1); // exit and signal the error
// Calling exit() is the only way to prevent the immediately following non-catchable fatal error.
// However, calling exit() in a destructor will also prevent any remaining shutdown routines from executing.
// @see above link
}
return $exception;
} | [
"public",
"static",
"function",
"handleDestructorException",
"(",
"\\",
"Exception",
"$",
"exception",
")",
"{",
"if",
"(",
"self",
"::",
"isInShutdown",
"(",
")",
")",
"{",
"self",
"::",
"handleException",
"(",
"$",
"exception",
")",
";",
"exit",
"(",
"1"... | Manually called handler for exceptions occurring in object destructors.
Attempting to throw an exception from a destructor during script shutdown causes a fatal error. Therefore this method
has to be called manually from object destructors if an exception occurred. If the script is in the shutdown phase
the exception is passed on to the regular exception handler and the script is terminated. If the script is currently
not in the shutdown phase this method ignores the exception. For an example see this package's README.
@param \Exception $exception
@return \Exception - the same exception
@link http://php.net/manual/en/language.oop5.decon.php | [
"Manually",
"called",
"handler",
"for",
"exceptions",
"occurring",
"in",
"object",
"destructors",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/debug/ErrorHandler.php#L314-L324 | train |
rosasurfer/ministruts | src/net/http/CurlHttpResponse.php | CurlHttpResponse.writeContent | public function writeContent($hCurl, $data) {
$this->content .= $data;
$obtainedLength = strlen($data);
$this->currentContentLength += $obtainedLength;
return $obtainedLength;
} | php | public function writeContent($hCurl, $data) {
$this->content .= $data;
$obtainedLength = strlen($data);
$this->currentContentLength += $obtainedLength;
return $obtainedLength;
} | [
"public",
"function",
"writeContent",
"(",
"$",
"hCurl",
",",
"$",
"data",
")",
"{",
"$",
"this",
"->",
"content",
".=",
"$",
"data",
";",
"$",
"obtainedLength",
"=",
"strlen",
"(",
"$",
"data",
")",
";",
"$",
"this",
"->",
"currentContentLength",
"+="... | Callback fuer CurlHttpClient, dem der empfangene Content des HTTP-Requests chunk-weise uebergeben wird.
@param resource $hCurl - das CURL-Handle des aktuellen Requests
@param string $data - die empfangenen Daten
@return int - Anzahl der bei diesem Methodenaufruf erhaltenen Bytes | [
"Callback",
"fuer",
"CurlHttpClient",
"dem",
"der",
"empfangene",
"Content",
"des",
"HTTP",
"-",
"Requests",
"chunk",
"-",
"weise",
"uebergeben",
"wird",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/net/http/CurlHttpResponse.php#L107-L114 | train |
rosasurfer/ministruts | src/console/docopt/DocoptParser.php | DocoptParser.parseArgs | protected static function parseArgs(TokenIterator $tokens, \ArrayIterator $options, $optionsFirst = false) {
$parsed = [];
while ($tokens->current() !== null) {
if ($tokens->current() == '--') {
while ($tokens->current() !== null) {
$parsed[] = new Argument(null, $tokens->move());
}
return $parsed;
}
elseif (strStartsWith($tokens->current(), '--')) {
$parsed = array_merge($parsed, static::parseLong($tokens, $options));
}
elseif (strStartsWith($tokens->current(), '-') && $tokens->current()!='-') {
$parsed = array_merge($parsed, static::parseShort($tokens, $options));
}
elseif ($optionsFirst) {
return array_merge($parsed, array_map(function($value) {
return new Argument(null, $value);
}, $tokens->left()));
}
else {
$parsed[] = new Argument(null, $tokens->move());
}
}
return $parsed;
} | php | protected static function parseArgs(TokenIterator $tokens, \ArrayIterator $options, $optionsFirst = false) {
$parsed = [];
while ($tokens->current() !== null) {
if ($tokens->current() == '--') {
while ($tokens->current() !== null) {
$parsed[] = new Argument(null, $tokens->move());
}
return $parsed;
}
elseif (strStartsWith($tokens->current(), '--')) {
$parsed = array_merge($parsed, static::parseLong($tokens, $options));
}
elseif (strStartsWith($tokens->current(), '-') && $tokens->current()!='-') {
$parsed = array_merge($parsed, static::parseShort($tokens, $options));
}
elseif ($optionsFirst) {
return array_merge($parsed, array_map(function($value) {
return new Argument(null, $value);
}, $tokens->left()));
}
else {
$parsed[] = new Argument(null, $tokens->move());
}
}
return $parsed;
} | [
"protected",
"static",
"function",
"parseArgs",
"(",
"TokenIterator",
"$",
"tokens",
",",
"\\",
"ArrayIterator",
"$",
"options",
",",
"$",
"optionsFirst",
"=",
"false",
")",
"{",
"$",
"parsed",
"=",
"[",
"]",
";",
"while",
"(",
"$",
"tokens",
"->",
"curr... | Parse arguments.
If options_first: argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ;
else: argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ;
@param TokenIterator $tokens
@param \ArrayIterator $options
@param bool $optionsFirst [optional]
@return Pattern[] | [
"Parse",
"arguments",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/console/docopt/DocoptParser.php#L191-L217 | train |
timble/kodekit | code/database/row/abstract.php | DatabaseRowAbstract.clear | public function clear()
{
$this->_data = array();
$this->__modified_properties = array();
$this->setStatus(NULL);
if ($this->isConnected()) {
$this->_data = $this->getTable()->getDefaults();
}
return $this;
} | php | public function clear()
{
$this->_data = array();
$this->__modified_properties = array();
$this->setStatus(NULL);
if ($this->isConnected()) {
$this->_data = $this->getTable()->getDefaults();
}
return $this;
} | [
"public",
"function",
"clear",
"(",
")",
"{",
"$",
"this",
"->",
"_data",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"__modified_properties",
"=",
"array",
"(",
")",
";",
"$",
"this",
"->",
"setStatus",
"(",
"NULL",
")",
";",
"if",
"(",
"$",
... | Clear the row data using the defaults
@return DatabaseRowInterface | [
"Clear",
"the",
"row",
"data",
"using",
"the",
"defaults"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/database/row/abstract.php#L182-L193 | train |
rosasurfer/ministruts | src/ministruts/Tile.php | Tile.setNestedTile | public function setNestedTile($name, Tile $tile = null) {
if ($this->configured) throw new IllegalStateException('Configuration is frozen');
$this->nestedTiles[$name] = $tile;
return $this;
} | php | public function setNestedTile($name, Tile $tile = null) {
if ($this->configured) throw new IllegalStateException('Configuration is frozen');
$this->nestedTiles[$name] = $tile;
return $this;
} | [
"public",
"function",
"setNestedTile",
"(",
"$",
"name",
",",
"Tile",
"$",
"tile",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"configured",
")",
"throw",
"new",
"IllegalStateException",
"(",
"'Configuration is frozen'",
")",
";",
"$",
"this",
"->... | Speichert in der Tile unter dem angegebenen Namen eine Child-Tile.
@param string $name - Name der Tile
@param Tile $tile [optional] - die zu speichernde Tile oder NULL, wenn die Child-Deklaration abstrakt ist
@return $this | [
"Speichert",
"in",
"der",
"Tile",
"unter",
"dem",
"angegebenen",
"Namen",
"eine",
"Child",
"-",
"Tile",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Tile.php#L166-L171 | train |
rosasurfer/ministruts | src/ministruts/Tile.php | Tile.setProperty | public function setProperty($name, $value) {
if ($this->configured) throw new IllegalStateException('Configuration is frozen');
$this->properties[$name] = $value;
return $this;
} | php | public function setProperty($name, $value) {
if ($this->configured) throw new IllegalStateException('Configuration is frozen');
$this->properties[$name] = $value;
return $this;
} | [
"public",
"function",
"setProperty",
"(",
"$",
"name",
",",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"configured",
")",
"throw",
"new",
"IllegalStateException",
"(",
"'Configuration is frozen'",
")",
";",
"$",
"this",
"->",
"properties",
"[",
... | Speichert in der Tile unter dem angegebenen Namen eine zusaetzliche Eigenschaft.
@param string $name - Name der Eigenschaft
@param mixed $value - der zu speichernde Wert
@return $this | [
"Speichert",
"in",
"der",
"Tile",
"unter",
"dem",
"angegebenen",
"Namen",
"eine",
"zusaetzliche",
"Eigenschaft",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Tile.php#L182-L187 | train |
rosasurfer/ministruts | src/ministruts/Tile.php | Tile.getMergedProperties | protected function getMergedProperties() {
$parentProperties = $this->parent ? $this->parent->getMergedProperties() : [];
return \array_merge($parentProperties, $this->properties);
} | php | protected function getMergedProperties() {
$parentProperties = $this->parent ? $this->parent->getMergedProperties() : [];
return \array_merge($parentProperties, $this->properties);
} | [
"protected",
"function",
"getMergedProperties",
"(",
")",
"{",
"$",
"parentProperties",
"=",
"$",
"this",
"->",
"parent",
"?",
"$",
"this",
"->",
"parent",
"->",
"getMergedProperties",
"(",
")",
":",
"[",
"]",
";",
"return",
"\\",
"array_merge",
"(",
"$",
... | Gibt die eigenen und die Properties der umgebenden Tile zurueck. Eigene Properties ueberschreiben gleichnamige
Properties der umgebenden Tile.
@return array - Properties | [
"Gibt",
"die",
"eigenen",
"und",
"die",
"Properties",
"der",
"umgebenden",
"Tile",
"zurueck",
".",
"Eigene",
"Properties",
"ueberschreiben",
"gleichnamige",
"Properties",
"der",
"umgebenden",
"Tile",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Tile.php#L196-L199 | train |
rosasurfer/ministruts | src/ministruts/Tile.php | Tile.freeze | public function freeze() {
if (!$this->configured) {
if (!$this->fileName) throw new StrutsConfigException('<tile name="'.$this->name.'": No file configured.');
foreach ($this->nestedTiles as $tile) {
if ($tile) $tile->freeze();
}
$this->configured = true;
}
return $this;
} | php | public function freeze() {
if (!$this->configured) {
if (!$this->fileName) throw new StrutsConfigException('<tile name="'.$this->name.'": No file configured.');
foreach ($this->nestedTiles as $tile) {
if ($tile) $tile->freeze();
}
$this->configured = true;
}
return $this;
} | [
"public",
"function",
"freeze",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"configured",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"fileName",
")",
"throw",
"new",
"StrutsConfigException",
"(",
"'<tile name=\"'",
".",
"$",
"this",
"->",
"name... | Friert die Konfiguration dieser Komponente ein.
@return $this
@throws StrutsConfigException on configuration errors | [
"Friert",
"die",
"Konfiguration",
"dieser",
"Komponente",
"ein",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Tile.php#L219-L229 | train |
rosasurfer/ministruts | src/ministruts/Tile.php | Tile.render | public function render() {
$request = Request::me();
$namespace = $this->module->getViewNamespace();
$appUri = $request->getApplicationBaseUri();
$nestedTiles = $this->nestedTiles;
foreach ($nestedTiles as $tile) {
$tile->setParent($this);
}
$properties = $this->getMergedProperties();
if (!defined($namespace.'APP')) {
define($namespace.'APP', strLeft($appUri, -1));
}
if (!defined($namespace.'MODULE')) {
$moduleUri = $appUri.$this->module->getPrefix();
define($namespace.'MODULE', strLeft($moduleUri, -1));
}
$properties['request' ] = $request;
$properties['response'] = Response::me();
$properties['session' ] = $request->isSession() ? $request->getSession() : null;
$properties['form' ] = $request->getAttribute(ACTION_FORM_KEY);
$properties['page' ] = Page::me();
if ($this->isPushModelSupport()) {
$pageValues = Page::me()->values();
$properties = \array_merge($properties, $pageValues);
}
$tileHint = false;
if (Application::isAdminIP()) {
$rootDir = $this->di('config')['app.dir.root'];
$file = $this->fileName;
$file = strRightFrom($file, $rootDir.DIRECTORY_SEPARATOR, 1, false, $file);
$file = 'file="'.str_replace('\\', '/', $file).'"';
$tile = $this->name==self::GENERIC_NAME ? '':'tile="'.$this->name.'" ';
$tileHint = $tile.$file;
echo ($this->parent ? NL:'').'<!-- #begin: '.$tileHint.' -->'.NL;
}
includeFile($this->fileName, $nestedTiles + $properties);
if ($tileHint) {
echo NL.'<!-- #end: '.$tileHint.' -->'.NL;
}
return $this;
} | php | public function render() {
$request = Request::me();
$namespace = $this->module->getViewNamespace();
$appUri = $request->getApplicationBaseUri();
$nestedTiles = $this->nestedTiles;
foreach ($nestedTiles as $tile) {
$tile->setParent($this);
}
$properties = $this->getMergedProperties();
if (!defined($namespace.'APP')) {
define($namespace.'APP', strLeft($appUri, -1));
}
if (!defined($namespace.'MODULE')) {
$moduleUri = $appUri.$this->module->getPrefix();
define($namespace.'MODULE', strLeft($moduleUri, -1));
}
$properties['request' ] = $request;
$properties['response'] = Response::me();
$properties['session' ] = $request->isSession() ? $request->getSession() : null;
$properties['form' ] = $request->getAttribute(ACTION_FORM_KEY);
$properties['page' ] = Page::me();
if ($this->isPushModelSupport()) {
$pageValues = Page::me()->values();
$properties = \array_merge($properties, $pageValues);
}
$tileHint = false;
if (Application::isAdminIP()) {
$rootDir = $this->di('config')['app.dir.root'];
$file = $this->fileName;
$file = strRightFrom($file, $rootDir.DIRECTORY_SEPARATOR, 1, false, $file);
$file = 'file="'.str_replace('\\', '/', $file).'"';
$tile = $this->name==self::GENERIC_NAME ? '':'tile="'.$this->name.'" ';
$tileHint = $tile.$file;
echo ($this->parent ? NL:'').'<!-- #begin: '.$tileHint.' -->'.NL;
}
includeFile($this->fileName, $nestedTiles + $properties);
if ($tileHint) {
echo NL.'<!-- #end: '.$tileHint.' -->'.NL;
}
return $this;
} | [
"public",
"function",
"render",
"(",
")",
"{",
"$",
"request",
"=",
"Request",
"::",
"me",
"(",
")",
";",
"$",
"namespace",
"=",
"$",
"this",
"->",
"module",
"->",
"getViewNamespace",
"(",
")",
";",
"$",
"appUri",
"=",
"$",
"request",
"->",
"getAppli... | Render the Tile.
@return $this | [
"Render",
"the",
"Tile",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/src/ministruts/Tile.php#L237-L283 | train |
deArcane/framework | src/User28/Utils/Hash.php | Hash.hash | private function hash(int $length):string {
$char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // strlen($char) = 62
$hash = '';
for( $i=0; $i < $length; $i++ )
$hash .= $char[random_int(0,61)];
return $hash;
} | php | private function hash(int $length):string {
$char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; // strlen($char) = 62
$hash = '';
for( $i=0; $i < $length; $i++ )
$hash .= $char[random_int(0,61)];
return $hash;
} | [
"private",
"function",
"hash",
"(",
"int",
"$",
"length",
")",
":",
"string",
"{",
"$",
"char",
"=",
"'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'",
";",
"// strlen($char) = 62",
"$",
"hash",
"=",
"''",
";",
"for",
"(",
"$",
"i",
"=",
"0",
... | Create random hash. | [
"Create",
"random",
"hash",
"."
] | 468da43678119f8c9e3f67183b5bec727c436404 | https://github.com/deArcane/framework/blob/468da43678119f8c9e3f67183b5bec727c436404/src/User28/Utils/Hash.php#L12-L18 | train |
deArcane/framework | src/User28/Utils/Hash.php | Hash.selector | private function selector():string{
$selector = $this->hash(50);
// Check if selector is unique.
do{
$isUnique = Input::$token->selectOneBySelector($selector);
}while( $isUnique[0] !== null );
return $selector;
} | php | private function selector():string{
$selector = $this->hash(50);
// Check if selector is unique.
do{
$isUnique = Input::$token->selectOneBySelector($selector);
}while( $isUnique[0] !== null );
return $selector;
} | [
"private",
"function",
"selector",
"(",
")",
":",
"string",
"{",
"$",
"selector",
"=",
"$",
"this",
"->",
"hash",
"(",
"50",
")",
";",
"// Check if selector is unique.",
"do",
"{",
"$",
"isUnique",
"=",
"Input",
"::",
"$",
"token",
"->",
"selectOneBySelect... | Create selector. | [
"Create",
"selector",
"."
] | 468da43678119f8c9e3f67183b5bec727c436404 | https://github.com/deArcane/framework/blob/468da43678119f8c9e3f67183b5bec727c436404/src/User28/Utils/Hash.php#L23-L30 | train |
dereuromark/cakephp-feedback | src/Controller/Admin/FeedbackController.php | FeedbackController.index | public function index() {
$savepath = Configure::read('Feedback.configuration.Filesystem.location');
//Check dir
if (!is_dir($savepath)) {
mkdir($savepath, 0770, true);
if (!is_dir($savepath)) {
throw new NotFoundException('Feedback location not found: ' . $savepath);
}
}
//Creat feedback array in a cake-like way
$feedbacks = [];
//Loop through files
foreach (glob($savepath . '*.feedback') as $feedbackfile) {
$feedbackObject = unserialize(file_get_contents($feedbackfile));
$feedbacks[$feedbackObject['time']] = $feedbackObject;
}
//Sort by time
krsort($feedbacks);
$this->set('feedbacks', $feedbacks);
} | php | public function index() {
$savepath = Configure::read('Feedback.configuration.Filesystem.location');
//Check dir
if (!is_dir($savepath)) {
mkdir($savepath, 0770, true);
if (!is_dir($savepath)) {
throw new NotFoundException('Feedback location not found: ' . $savepath);
}
}
//Creat feedback array in a cake-like way
$feedbacks = [];
//Loop through files
foreach (glob($savepath . '*.feedback') as $feedbackfile) {
$feedbackObject = unserialize(file_get_contents($feedbackfile));
$feedbacks[$feedbackObject['time']] = $feedbackObject;
}
//Sort by time
krsort($feedbacks);
$this->set('feedbacks', $feedbacks);
} | [
"public",
"function",
"index",
"(",
")",
"{",
"$",
"savepath",
"=",
"Configure",
"::",
"read",
"(",
"'Feedback.configuration.Filesystem.location'",
")",
";",
"//Check dir",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"savepath",
")",
")",
"{",
"mkdir",
"(",
"$",
"... | Example index function for current save in tmp dir solution
@return \Cake\Http\Response|null | [
"Example",
"index",
"function",
"for",
"current",
"save",
"in",
"tmp",
"dir",
"solution"
] | 0bd774fda38b3cdd05db8c07a06a526d3ba81879 | https://github.com/dereuromark/cakephp-feedback/blob/0bd774fda38b3cdd05db8c07a06a526d3ba81879/src/Controller/Admin/FeedbackController.php#L50-L76 | train |
rosasurfer/ministruts | etc/phpstan/DAO_Find_ReturnType.php | DAO_Find_ReturnType.resolveReturnType | protected function resolveReturnType(Type $type, \Closure $resolver) : Type {
if ($type instanceof UnionType) {
$old = $type->getTypes();
$new = [];
foreach ($old as $subtype)
$new[] = $resolver($subtype);
return ($old===$new) ? $type : new UnionType($new);
}
return $resolver($type);
} | php | protected function resolveReturnType(Type $type, \Closure $resolver) : Type {
if ($type instanceof UnionType) {
$old = $type->getTypes();
$new = [];
foreach ($old as $subtype)
$new[] = $resolver($subtype);
return ($old===$new) ? $type : new UnionType($new);
}
return $resolver($type);
} | [
"protected",
"function",
"resolveReturnType",
"(",
"Type",
"$",
"type",
",",
"\\",
"Closure",
"$",
"resolver",
")",
":",
"Type",
"{",
"if",
"(",
"$",
"type",
"instanceof",
"UnionType",
")",
"{",
"$",
"old",
"=",
"$",
"type",
"->",
"getTypes",
"(",
")",... | Resolve a return type using a resolver function.
@return Type | [
"Resolve",
"a",
"return",
"type",
"using",
"a",
"resolver",
"function",
"."
] | 9d27f93dd53d2d626c75c92cfde9d004bab34d30 | https://github.com/rosasurfer/ministruts/blob/9d27f93dd53d2d626c75c92cfde9d004bab34d30/etc/phpstan/DAO_Find_ReturnType.php#L128-L137 | train |
timble/kodekit | code/controller/response/response.php | ControllerResponse.addMessage | public function addMessage($message, $type = self::FLASH_SUCCESS)
{
if (!is_string($message) && !(is_object($message) && method_exists($message, '__toString')))
{
throw new \UnexpectedValueException(
'The flash message must be a string or object implementing __toString(), "'.gettype($message).'" given.'
);
}
if(!isset($this->_messages[$type])) {
$this->_messages[$type] = array();
}
$this->_messages[$type][] = $message;
return $this;
} | php | public function addMessage($message, $type = self::FLASH_SUCCESS)
{
if (!is_string($message) && !(is_object($message) && method_exists($message, '__toString')))
{
throw new \UnexpectedValueException(
'The flash message must be a string or object implementing __toString(), "'.gettype($message).'" given.'
);
}
if(!isset($this->_messages[$type])) {
$this->_messages[$type] = array();
}
$this->_messages[$type][] = $message;
return $this;
} | [
"public",
"function",
"addMessage",
"(",
"$",
"message",
",",
"$",
"type",
"=",
"self",
"::",
"FLASH_SUCCESS",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"message",
")",
"&&",
"!",
"(",
"is_object",
"(",
"$",
"message",
")",
"&&",
"method_exists"... | Add a response message
Flash messages are self-expiring messages that are meant to live for exactly one request. They can be used
across redirects, or flushed at the end of the request.
@param string $message The flash message
@param string $type Message category type. Default is 'success'.
@throws \UnexpectedValueException
@return ControllerResponse | [
"Add",
"a",
"response",
"message"
] | 4c376f8873f8d10c55e3d290616ff622605cd246 | https://github.com/timble/kodekit/blob/4c376f8873f8d10c55e3d290616ff622605cd246/code/controller/response/response.php#L182-L197 | train |
symbiote/silverstripe-content-services | code/content/ContentService.php | ContentService.getWriterFor | public function getWriterFor(DataObject $object = null, $field = 'FilePointer', $type = null) {
if ($object && $field && $object->hasField($field)) {
$val = $object->$field;
if (strlen($val)) {
$reader = $this->getReader($val);
if ($reader && $reader->isReadable()) {
return $reader->getWriter();
}
}
}
if (!$type) {
// specifically expecting to be handling File objects, but allows other
// objects to play too
if ($object && $object->hasMethod('getEffectiveContentStore')) {
$type = $object->getEffectiveContentStore();
} else {
$type = $this->defaultStore;
}
}
// looks like we're getting a writer with no underlying file (as yet)
return $this->getWriter($type);
} | php | public function getWriterFor(DataObject $object = null, $field = 'FilePointer', $type = null) {
if ($object && $field && $object->hasField($field)) {
$val = $object->$field;
if (strlen($val)) {
$reader = $this->getReader($val);
if ($reader && $reader->isReadable()) {
return $reader->getWriter();
}
}
}
if (!$type) {
// specifically expecting to be handling File objects, but allows other
// objects to play too
if ($object && $object->hasMethod('getEffectiveContentStore')) {
$type = $object->getEffectiveContentStore();
} else {
$type = $this->defaultStore;
}
}
// looks like we're getting a writer with no underlying file (as yet)
return $this->getWriter($type);
} | [
"public",
"function",
"getWriterFor",
"(",
"DataObject",
"$",
"object",
"=",
"null",
",",
"$",
"field",
"=",
"'FilePointer'",
",",
"$",
"type",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"object",
"&&",
"$",
"field",
"&&",
"$",
"object",
"->",
"hasField",
... | Gets a writer for a DataObject
If the field already has a value, a writer is created matching that
identifier. Otherwise, a new writer is created based on either
- The $type passed in
- whether the $object class specifies a prefered storage type via
getEffectiveContentStore
- what the `defaultStore` is set to for the content service
@param DataObject $object
The object to get a writer for
@param String $field
The field being written to
@param String $type
Explicitly state what the content store type will be
@return ContentWriter | [
"Gets",
"a",
"writer",
"for",
"a",
"DataObject"
] | d6dec8da12208d876051aa4329a9b76032172bfa | https://github.com/symbiote/silverstripe-content-services/blob/d6dec8da12208d876051aa4329a9b76032172bfa/code/content/ContentService.php#L68-L91 | train |
symbiote/silverstripe-content-services | code/content/ContentService.php | ContentService.findReaderFor | public function findReaderFor($storeType, $assetName, $remapToId = true) {
$writer = $this->getWriter($storeType);
$contentId = $storeType . self::SEPARATOR . ($remapToId ? $writer->nameToId($assetName) : $assetName);
$reader = $this->getReader($contentId);
return $reader ? ($reader->isReadable() ? $reader : null) : null;
} | php | public function findReaderFor($storeType, $assetName, $remapToId = true) {
$writer = $this->getWriter($storeType);
$contentId = $storeType . self::SEPARATOR . ($remapToId ? $writer->nameToId($assetName) : $assetName);
$reader = $this->getReader($contentId);
return $reader ? ($reader->isReadable() ? $reader : null) : null;
} | [
"public",
"function",
"findReaderFor",
"(",
"$",
"storeType",
",",
"$",
"assetName",
",",
"$",
"remapToId",
"=",
"true",
")",
"{",
"$",
"writer",
"=",
"$",
"this",
"->",
"getWriter",
"(",
"$",
"storeType",
")",
";",
"$",
"contentId",
"=",
"$",
"storeTy... | Gets a content reader for the given store type over the asset given in
assetName. This is used for finding if an asset is stored remotely or
not
Returns NULL if that asset doesn't exist.
@param string $storeType
The named store we're looking into
@param string $assetName
The name of the asset to look up
@param boolean $remapToId
Do we let the reader remap the name to how it represents asset paths? Or are
we looking up an already-mapped path name?
@return ContentReader | [
"Gets",
"a",
"content",
"reader",
"for",
"the",
"given",
"store",
"type",
"over",
"the",
"asset",
"given",
"in",
"assetName",
".",
"This",
"is",
"used",
"for",
"finding",
"if",
"an",
"asset",
"is",
"stored",
"remotely",
"or",
"not"
] | d6dec8da12208d876051aa4329a9b76032172bfa | https://github.com/symbiote/silverstripe-content-services/blob/d6dec8da12208d876051aa4329a9b76032172bfa/code/content/ContentService.php#L161-L166 | train |
Innmind/Immutable | src/Str.php | Str.split | public function split(string $delimiter = null): StreamInterface
{
if (\is_null($delimiter) || $delimiter === '') {
return $this->chunk();
}
$parts = \explode($delimiter, $this->value);
$stream = new Stream(self::class);
foreach ($parts as $part) {
$stream = $stream->add(new self($part, $this->encoding));
}
return $stream;
} | php | public function split(string $delimiter = null): StreamInterface
{
if (\is_null($delimiter) || $delimiter === '') {
return $this->chunk();
}
$parts = \explode($delimiter, $this->value);
$stream = new Stream(self::class);
foreach ($parts as $part) {
$stream = $stream->add(new self($part, $this->encoding));
}
return $stream;
} | [
"public",
"function",
"split",
"(",
"string",
"$",
"delimiter",
"=",
"null",
")",
":",
"StreamInterface",
"{",
"if",
"(",
"\\",
"is_null",
"(",
"$",
"delimiter",
")",
"||",
"$",
"delimiter",
"===",
"''",
")",
"{",
"return",
"$",
"this",
"->",
"chunk",
... | Split the string into a collection of ones
@param string $delimiter
@return StreamInterface<self> | [
"Split",
"the",
"string",
"into",
"a",
"collection",
"of",
"ones"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L74-L88 | train |
Innmind/Immutable | src/Str.php | Str.chunk | public function chunk(int $size = 1): StreamInterface
{
$stream = new Stream(self::class);
$string = $this;
while ($string->length() > 0) {
$stream = $stream->add($string->substring(0, $size));
$string = $string->substring($size);
}
return $stream;
} | php | public function chunk(int $size = 1): StreamInterface
{
$stream = new Stream(self::class);
$string = $this;
while ($string->length() > 0) {
$stream = $stream->add($string->substring(0, $size));
$string = $string->substring($size);
}
return $stream;
} | [
"public",
"function",
"chunk",
"(",
"int",
"$",
"size",
"=",
"1",
")",
":",
"StreamInterface",
"{",
"$",
"stream",
"=",
"new",
"Stream",
"(",
"self",
"::",
"class",
")",
";",
"$",
"string",
"=",
"$",
"this",
";",
"while",
"(",
"$",
"string",
"->",
... | Returns a collection of the string splitted by the given chunk size
@param int $size
@return StreamInterface<self> | [
"Returns",
"a",
"collection",
"of",
"the",
"string",
"splitted",
"by",
"the",
"given",
"chunk",
"size"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L97-L108 | train |
Innmind/Immutable | src/Str.php | Str.position | public function position(string $needle, int $offset = 0): int
{
$position = \mb_strpos($this->value, $needle, $offset, (string) $this->encoding());
if ($position === false) {
throw new SubstringException(\sprintf(
'Substring "%s" not found',
$needle
));
}
return (int) $position;
} | php | public function position(string $needle, int $offset = 0): int
{
$position = \mb_strpos($this->value, $needle, $offset, (string) $this->encoding());
if ($position === false) {
throw new SubstringException(\sprintf(
'Substring "%s" not found',
$needle
));
}
return (int) $position;
} | [
"public",
"function",
"position",
"(",
"string",
"$",
"needle",
",",
"int",
"$",
"offset",
"=",
"0",
")",
":",
"int",
"{",
"$",
"position",
"=",
"\\",
"mb_strpos",
"(",
"$",
"this",
"->",
"value",
",",
"$",
"needle",
",",
"$",
"offset",
",",
"(",
... | Returns the position of the first occurence of the string
@param string $needle
@param int $offset
@throws SubstringException If the string is not found
@return int | [
"Returns",
"the",
"position",
"of",
"the",
"first",
"occurence",
"of",
"the",
"string"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L120-L132 | train |
Innmind/Immutable | src/Str.php | Str.replace | public function replace(string $search, string $replacement): self
{
if (!$this->contains($search)) {
return $this;
}
return $this
->split($search)
->join($replacement);
} | php | public function replace(string $search, string $replacement): self
{
if (!$this->contains($search)) {
return $this;
}
return $this
->split($search)
->join($replacement);
} | [
"public",
"function",
"replace",
"(",
"string",
"$",
"search",
",",
"string",
"$",
"replacement",
")",
":",
"self",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"contains",
"(",
"$",
"search",
")",
")",
"{",
"return",
"$",
"this",
";",
"}",
"return",
"$... | Replace all occurences of the search string with the replacement one
@param string $search
@param string $replacement
@return self | [
"Replace",
"all",
"occurences",
"of",
"the",
"search",
"string",
"with",
"the",
"replacement",
"one"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L142-L151 | train |
Innmind/Immutable | src/Str.php | Str.str | public function str(string $delimiter): self
{
$sub = \mb_strstr($this->value, $delimiter, false, (string) $this->encoding());
if ($sub === false) {
throw new SubstringException(\sprintf(
'Substring "%s" not found',
$delimiter
));
}
return new self($sub, $this->encoding);
} | php | public function str(string $delimiter): self
{
$sub = \mb_strstr($this->value, $delimiter, false, (string) $this->encoding());
if ($sub === false) {
throw new SubstringException(\sprintf(
'Substring "%s" not found',
$delimiter
));
}
return new self($sub, $this->encoding);
} | [
"public",
"function",
"str",
"(",
"string",
"$",
"delimiter",
")",
":",
"self",
"{",
"$",
"sub",
"=",
"\\",
"mb_strstr",
"(",
"$",
"this",
"->",
"value",
",",
"$",
"delimiter",
",",
"false",
",",
"(",
"string",
")",
"$",
"this",
"->",
"encoding",
"... | Returns the string following the given delimiter
@param string $delimiter
@throws SubstringException If the string is not found
@return self | [
"Returns",
"the",
"string",
"following",
"the",
"given",
"delimiter"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L162-L174 | train |
Innmind/Immutable | src/Str.php | Str.rightPad | public function rightPad(int $length, string $character = ' '): self
{
return $this->pad($length, $character, self::PAD_RIGHT);
} | php | public function rightPad(int $length, string $character = ' '): self
{
return $this->pad($length, $character, self::PAD_RIGHT);
} | [
"public",
"function",
"rightPad",
"(",
"int",
"$",
"length",
",",
"string",
"$",
"character",
"=",
"' '",
")",
":",
"self",
"{",
"return",
"$",
"this",
"->",
"pad",
"(",
"$",
"length",
",",
"$",
"character",
",",
"self",
"::",
"PAD_RIGHT",
")",
";",
... | Pad to the right
@param int $length
@param string $character
@return self | [
"Pad",
"to",
"the",
"right"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L232-L235 | train |
Innmind/Immutable | src/Str.php | Str.leftPad | public function leftPad(int $length, string $character = ' '): self
{
return $this->pad($length, $character, self::PAD_LEFT);
} | php | public function leftPad(int $length, string $character = ' '): self
{
return $this->pad($length, $character, self::PAD_LEFT);
} | [
"public",
"function",
"leftPad",
"(",
"int",
"$",
"length",
",",
"string",
"$",
"character",
"=",
"' '",
")",
":",
"self",
"{",
"return",
"$",
"this",
"->",
"pad",
"(",
"$",
"length",
",",
"$",
"character",
",",
"self",
"::",
"PAD_LEFT",
")",
";",
... | Pad to the left
@param int $length
@param string $character
@return self | [
"Pad",
"to",
"the",
"left"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L245-L248 | train |
Innmind/Immutable | src/Str.php | Str.uniPad | public function uniPad(int $length, string $character = ' '): self
{
return $this->pad($length, $character, self::PAD_BOTH);
} | php | public function uniPad(int $length, string $character = ' '): self
{
return $this->pad($length, $character, self::PAD_BOTH);
} | [
"public",
"function",
"uniPad",
"(",
"int",
"$",
"length",
",",
"string",
"$",
"character",
"=",
"' '",
")",
":",
"self",
"{",
"return",
"$",
"this",
"->",
"pad",
"(",
"$",
"length",
",",
"$",
"character",
",",
"self",
"::",
"PAD_BOTH",
")",
";",
"... | Pad both sides
@param int $length
@param string $character
@return self | [
"Pad",
"both",
"sides"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L258-L261 | train |
Innmind/Immutable | src/Str.php | Str.cspn | public function cspn(string $mask, int $start = 0, int $length = null): int
{
if ($length === null) {
$value = \strcspn($this->value, $mask, $start);
} else {
$value = \strcspn(
$this->value,
$mask,
$start,
$length
);
}
return (int) $value;
} | php | public function cspn(string $mask, int $start = 0, int $length = null): int
{
if ($length === null) {
$value = \strcspn($this->value, $mask, $start);
} else {
$value = \strcspn(
$this->value,
$mask,
$start,
$length
);
}
return (int) $value;
} | [
"public",
"function",
"cspn",
"(",
"string",
"$",
"mask",
",",
"int",
"$",
"start",
"=",
"0",
",",
"int",
"$",
"length",
"=",
"null",
")",
":",
"int",
"{",
"if",
"(",
"$",
"length",
"===",
"null",
")",
"{",
"$",
"value",
"=",
"\\",
"strcspn",
"... | Find length of initial segment not matching mask
@param string $mask
@param int $start
@param int $length
@return int | [
"Find",
"length",
"of",
"initial",
"segment",
"not",
"matching",
"mask"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L272-L286 | train |
Innmind/Immutable | src/Str.php | Str.repeat | public function repeat(int $repeat): self
{
return new self(\str_repeat($this->value, $repeat), $this->encoding);
} | php | public function repeat(int $repeat): self
{
return new self(\str_repeat($this->value, $repeat), $this->encoding);
} | [
"public",
"function",
"repeat",
"(",
"int",
"$",
"repeat",
")",
":",
"self",
"{",
"return",
"new",
"self",
"(",
"\\",
"str_repeat",
"(",
"$",
"this",
"->",
"value",
",",
"$",
"repeat",
")",
",",
"$",
"this",
"->",
"encoding",
")",
";",
"}"
] | Repeat the string n times
@param int $repeat
@return self | [
"Repeat",
"the",
"string",
"n",
"times"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L295-L298 | train |
Innmind/Immutable | src/Str.php | Str.shuffle | public function shuffle(): self
{
$parts = $this->chunk()->toPrimitive();
\shuffle($parts);
return new self(\implode('', $parts), $this->encoding);
} | php | public function shuffle(): self
{
$parts = $this->chunk()->toPrimitive();
\shuffle($parts);
return new self(\implode('', $parts), $this->encoding);
} | [
"public",
"function",
"shuffle",
"(",
")",
":",
"self",
"{",
"$",
"parts",
"=",
"$",
"this",
"->",
"chunk",
"(",
")",
"->",
"toPrimitive",
"(",
")",
";",
"\\",
"shuffle",
"(",
"$",
"parts",
")",
";",
"return",
"new",
"self",
"(",
"\\",
"implode",
... | Shuffle the string
@return self | [
"Shuffle",
"the",
"string"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L305-L311 | train |
Innmind/Immutable | src/Str.php | Str.words | public function words(string $charlist = ''): MapInterface
{
$words = \str_word_count($this->value, 2, $charlist);
$map = new Map('int', self::class);
foreach ($words as $position => $word) {
$map = $map->put($position, new self($word, $this->encoding));
}
return $map;
} | php | public function words(string $charlist = ''): MapInterface
{
$words = \str_word_count($this->value, 2, $charlist);
$map = new Map('int', self::class);
foreach ($words as $position => $word) {
$map = $map->put($position, new self($word, $this->encoding));
}
return $map;
} | [
"public",
"function",
"words",
"(",
"string",
"$",
"charlist",
"=",
"''",
")",
":",
"MapInterface",
"{",
"$",
"words",
"=",
"\\",
"str_word_count",
"(",
"$",
"this",
"->",
"value",
",",
"2",
",",
"$",
"charlist",
")",
";",
"$",
"map",
"=",
"new",
"... | Return the collection of words
@param string $charlist
@return MapInterface<int, self> | [
"Return",
"the",
"collection",
"of",
"words"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L356-L366 | train |
Innmind/Immutable | src/Str.php | Str.pregSplit | public function pregSplit(string $regex, int $limit = -1): StreamInterface
{
$strings = \preg_split($regex, $this->value, $limit);
$stream = new Stream(self::class);
foreach ($strings as $string) {
$stream = $stream->add(new self($string, $this->encoding));
}
return $stream;
} | php | public function pregSplit(string $regex, int $limit = -1): StreamInterface
{
$strings = \preg_split($regex, $this->value, $limit);
$stream = new Stream(self::class);
foreach ($strings as $string) {
$stream = $stream->add(new self($string, $this->encoding));
}
return $stream;
} | [
"public",
"function",
"pregSplit",
"(",
"string",
"$",
"regex",
",",
"int",
"$",
"limit",
"=",
"-",
"1",
")",
":",
"StreamInterface",
"{",
"$",
"strings",
"=",
"\\",
"preg_split",
"(",
"$",
"regex",
",",
"$",
"this",
"->",
"value",
",",
"$",
"limit",... | Split the string using a regular expression
@param string $regex
@param int $limit
@return StreamInterface<self> | [
"Split",
"the",
"string",
"using",
"a",
"regular",
"expression"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L376-L386 | train |
Innmind/Immutable | src/Str.php | Str.matches | public function matches(string $regex): bool
{
if (\func_num_args() !== 1) {
throw new LogicException('Offset is no longer supported');
}
return RegExp::of($regex)->matches($this);
} | php | public function matches(string $regex): bool
{
if (\func_num_args() !== 1) {
throw new LogicException('Offset is no longer supported');
}
return RegExp::of($regex)->matches($this);
} | [
"public",
"function",
"matches",
"(",
"string",
"$",
"regex",
")",
":",
"bool",
"{",
"if",
"(",
"\\",
"func_num_args",
"(",
")",
"!==",
"1",
")",
"{",
"throw",
"new",
"LogicException",
"(",
"'Offset is no longer supported'",
")",
";",
"}",
"return",
"RegEx... | Check if the string match the given regular expression
@param string $regex
@throws Exception If the regex failed
@return bool | [
"Check",
"if",
"the",
"string",
"match",
"the",
"given",
"regular",
"expression"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L397-L404 | train |
Innmind/Immutable | src/Str.php | Str.pregReplace | public function pregReplace(
string $regex,
string $replacement,
int $limit = -1
): self {
$value = \preg_replace(
$regex,
$replacement,
$this->value,
$limit
);
if ($value === null) {
throw new RegexException('', \preg_last_error());
}
return new self($value, $this->encoding);
} | php | public function pregReplace(
string $regex,
string $replacement,
int $limit = -1
): self {
$value = \preg_replace(
$regex,
$replacement,
$this->value,
$limit
);
if ($value === null) {
throw new RegexException('', \preg_last_error());
}
return new self($value, $this->encoding);
} | [
"public",
"function",
"pregReplace",
"(",
"string",
"$",
"regex",
",",
"string",
"$",
"replacement",
",",
"int",
"$",
"limit",
"=",
"-",
"1",
")",
":",
"self",
"{",
"$",
"value",
"=",
"\\",
"preg_replace",
"(",
"$",
"regex",
",",
"$",
"replacement",
... | Replace part of the string by using a regular expression
@param string $regex
@param string $replacement
@param int $limit
@throws Exception If the regex failed
@return self | [
"Replace",
"part",
"of",
"the",
"string",
"by",
"using",
"a",
"regular",
"expression"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L456-L473 | train |
Innmind/Immutable | src/Str.php | Str.substring | public function substring(int $start, int $length = null): self
{
if ($this->length() === 0) {
return $this;
}
$sub = \mb_substr($this->value, $start, $length, (string) $this->encoding());
return new self($sub, $this->encoding);
} | php | public function substring(int $start, int $length = null): self
{
if ($this->length() === 0) {
return $this;
}
$sub = \mb_substr($this->value, $start, $length, (string) $this->encoding());
return new self($sub, $this->encoding);
} | [
"public",
"function",
"substring",
"(",
"int",
"$",
"start",
",",
"int",
"$",
"length",
"=",
"null",
")",
":",
"self",
"{",
"if",
"(",
"$",
"this",
"->",
"length",
"(",
")",
"===",
"0",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"sub",
"="... | Return part of the string
@param int $start
@param int $length
@return self | [
"Return",
"part",
"of",
"the",
"string"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L483-L492 | train |
Innmind/Immutable | src/Str.php | Str.camelize | public function camelize(): self
{
return $this
->pregSplit('/_| /')
->map(function(self $part) {
return $part->ucfirst();
})
->join('')
->toEncoding((string) $this->encoding());
} | php | public function camelize(): self
{
return $this
->pregSplit('/_| /')
->map(function(self $part) {
return $part->ucfirst();
})
->join('')
->toEncoding((string) $this->encoding());
} | [
"public",
"function",
"camelize",
"(",
")",
":",
"self",
"{",
"return",
"$",
"this",
"->",
"pregSplit",
"(",
"'/_| /'",
")",
"->",
"map",
"(",
"function",
"(",
"self",
"$",
"part",
")",
"{",
"return",
"$",
"part",
"->",
"ucfirst",
"(",
")",
";",
"}... | Return a CamelCase representation of the string
@return self | [
"Return",
"a",
"CamelCase",
"representation",
"of",
"the",
"string"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L555-L564 | train |
Innmind/Immutable | src/Str.php | Str.append | public function append(string $string): self
{
return new self((string) $this.$string, $this->encoding);
} | php | public function append(string $string): self
{
return new self((string) $this.$string, $this->encoding);
} | [
"public",
"function",
"append",
"(",
"string",
"$",
"string",
")",
":",
"self",
"{",
"return",
"new",
"self",
"(",
"(",
"string",
")",
"$",
"this",
".",
"$",
"string",
",",
"$",
"this",
"->",
"encoding",
")",
";",
"}"
] | Append a string at the end of the current one
@param string $string
@return self | [
"Append",
"a",
"string",
"at",
"the",
"end",
"of",
"the",
"current",
"one"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L573-L576 | train |
Innmind/Immutable | src/Str.php | Str.prepend | public function prepend(string $string): self
{
return new self($string.(string) $this, $this->encoding);
} | php | public function prepend(string $string): self
{
return new self($string.(string) $this, $this->encoding);
} | [
"public",
"function",
"prepend",
"(",
"string",
"$",
"string",
")",
":",
"self",
"{",
"return",
"new",
"self",
"(",
"$",
"string",
".",
"(",
"string",
")",
"$",
"this",
",",
"$",
"this",
"->",
"encoding",
")",
";",
"}"
] | Prepend a string at the beginning of the current one
@param string $string
@return self | [
"Prepend",
"a",
"string",
"at",
"the",
"beginning",
"of",
"the",
"current",
"one"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L585-L588 | train |
Innmind/Immutable | src/Str.php | Str.rightTrim | public function rightTrim(string $mask = null): self
{
return new self(
$mask === null ? \rtrim((string) $this) : \rtrim((string) $this, $mask),
$this->encoding
);
} | php | public function rightTrim(string $mask = null): self
{
return new self(
$mask === null ? \rtrim((string) $this) : \rtrim((string) $this, $mask),
$this->encoding
);
} | [
"public",
"function",
"rightTrim",
"(",
"string",
"$",
"mask",
"=",
"null",
")",
":",
"self",
"{",
"return",
"new",
"self",
"(",
"$",
"mask",
"===",
"null",
"?",
"\\",
"rtrim",
"(",
"(",
"string",
")",
"$",
"this",
")",
":",
"\\",
"rtrim",
"(",
"... | Trim the right side of the string
@param string $mask
@return self | [
"Trim",
"the",
"right",
"side",
"of",
"the",
"string"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L624-L630 | train |
Innmind/Immutable | src/Str.php | Str.leftTrim | public function leftTrim(string $mask = null): self
{
return new self(
$mask === null ? \ltrim((string) $this) : \ltrim((string) $this, $mask),
$this->encoding
);
} | php | public function leftTrim(string $mask = null): self
{
return new self(
$mask === null ? \ltrim((string) $this) : \ltrim((string) $this, $mask),
$this->encoding
);
} | [
"public",
"function",
"leftTrim",
"(",
"string",
"$",
"mask",
"=",
"null",
")",
":",
"self",
"{",
"return",
"new",
"self",
"(",
"$",
"mask",
"===",
"null",
"?",
"\\",
"ltrim",
"(",
"(",
"string",
")",
"$",
"this",
")",
":",
"\\",
"ltrim",
"(",
"(... | Trim the left side of the string
@param string $mask
@return self | [
"Trim",
"the",
"left",
"side",
"of",
"the",
"string"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L639-L645 | train |
Innmind/Immutable | src/Str.php | Str.contains | public function contains(string $value): bool
{
try {
$this->position($value);
return true;
} catch (SubstringException $e) {
return false;
}
} | php | public function contains(string $value): bool
{
try {
$this->position($value);
return true;
} catch (SubstringException $e) {
return false;
}
} | [
"public",
"function",
"contains",
"(",
"string",
"$",
"value",
")",
":",
"bool",
"{",
"try",
"{",
"$",
"this",
"->",
"position",
"(",
"$",
"value",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"SubstringException",
"$",
"e",
")",
"{",
"return"... | Check if the given string is present in the current one
@param string $value
@return bool | [
"Check",
"if",
"the",
"given",
"string",
"is",
"present",
"in",
"the",
"current",
"one"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L654-L663 | train |
Innmind/Immutable | src/Str.php | Str.endsWith | public function endsWith(string $value): bool
{
if ($value === '') {
return true;
}
return (string) $this->takeEnd(self::of($value, $this->encoding)->length()) === $value;
} | php | public function endsWith(string $value): bool
{
if ($value === '') {
return true;
}
return (string) $this->takeEnd(self::of($value, $this->encoding)->length()) === $value;
} | [
"public",
"function",
"endsWith",
"(",
"string",
"$",
"value",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"value",
"===",
"''",
")",
"{",
"return",
"true",
";",
"}",
"return",
"(",
"string",
")",
"$",
"this",
"->",
"takeEnd",
"(",
"self",
"::",
"of",
... | Check if the current string ends with the given string
@param string $value
@return bool | [
"Check",
"if",
"the",
"current",
"string",
"ends",
"with",
"the",
"given",
"string"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L692-L699 | train |
Innmind/Immutable | src/Str.php | Str.pregQuote | public function pregQuote(string $delimiter = ''): self
{
return new self(\preg_quote((string) $this, $delimiter), $this->encoding);
} | php | public function pregQuote(string $delimiter = ''): self
{
return new self(\preg_quote((string) $this, $delimiter), $this->encoding);
} | [
"public",
"function",
"pregQuote",
"(",
"string",
"$",
"delimiter",
"=",
"''",
")",
":",
"self",
"{",
"return",
"new",
"self",
"(",
"\\",
"preg_quote",
"(",
"(",
"string",
")",
"$",
"this",
",",
"$",
"delimiter",
")",
",",
"$",
"this",
"->",
"encodin... | Quote regular expression characters
@param string $delimiter
@return self | [
"Quote",
"regular",
"expression",
"characters"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L708-L711 | train |
Innmind/Immutable | src/Str.php | Str.pad | private function pad(
int $length,
string $character = ' ',
int $direction = self::PAD_RIGHT
): self {
return new self(\str_pad(
$this->value,
$length,
$character,
$direction
), $this->encoding);
} | php | private function pad(
int $length,
string $character = ' ',
int $direction = self::PAD_RIGHT
): self {
return new self(\str_pad(
$this->value,
$length,
$character,
$direction
), $this->encoding);
} | [
"private",
"function",
"pad",
"(",
"int",
"$",
"length",
",",
"string",
"$",
"character",
"=",
"' '",
",",
"int",
"$",
"direction",
"=",
"self",
"::",
"PAD_RIGHT",
")",
":",
"self",
"{",
"return",
"new",
"self",
"(",
"\\",
"str_pad",
"(",
"$",
"this"... | Pad the string
@param int $length
@param string $character
@param int $direction
@return self | [
"Pad",
"the",
"string"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Str.php#L722-L733 | train |
symbiote/silverstripe-content-services | code/content/ContentWriter.php | ContentWriter.getReaderWrapper | protected function getReaderWrapper($content) {
if (!$content) {
$content = $this->source;
}
$reader = null;
if (is_resource($content)) {
$data = null;
while (!feof($content)) {
$data .= fread($content, 8192);
}
fclose($content);
$reader = new RawContentReader($data);
} else if ($content instanceof ContentReader) {
$reader = $content;
} else if (is_string($content)) {
// assumed to be a file
if (file_exists($content) && is_readable($content)) {
// naughty, but it's the exception that proves the rule...
$reader = new FileContentReader($content);
} else {
$reader = new RawContentReader($content);
}
}
return $reader;
} | php | protected function getReaderWrapper($content) {
if (!$content) {
$content = $this->source;
}
$reader = null;
if (is_resource($content)) {
$data = null;
while (!feof($content)) {
$data .= fread($content, 8192);
}
fclose($content);
$reader = new RawContentReader($data);
} else if ($content instanceof ContentReader) {
$reader = $content;
} else if (is_string($content)) {
// assumed to be a file
if (file_exists($content) && is_readable($content)) {
// naughty, but it's the exception that proves the rule...
$reader = new FileContentReader($content);
} else {
$reader = new RawContentReader($content);
}
}
return $reader;
} | [
"protected",
"function",
"getReaderWrapper",
"(",
"$",
"content",
")",
"{",
"if",
"(",
"!",
"$",
"content",
")",
"{",
"$",
"content",
"=",
"$",
"this",
"->",
"source",
";",
"}",
"$",
"reader",
"=",
"null",
";",
"if",
"(",
"is_resource",
"(",
"$",
"... | Get content reader wrapper around a given piece of content
@param mixed $content | [
"Get",
"content",
"reader",
"wrapper",
"around",
"a",
"given",
"piece",
"of",
"content"
] | d6dec8da12208d876051aa4329a9b76032172bfa | https://github.com/symbiote/silverstripe-content-services/blob/d6dec8da12208d876051aa4329a9b76032172bfa/code/content/ContentWriter.php#L59-L86 | train |
Innmind/Immutable | src/Type.php | Type.of | public static function of(string $type): SpecificationInterface
{
if (\function_exists('is_'.$type)) {
return new PrimitiveType($type);
}
if ($type === 'variable') {
return new VariableType;
}
if ($type === 'mixed') {
return new MixedType;
}
return new ClassType($type);
} | php | public static function of(string $type): SpecificationInterface
{
if (\function_exists('is_'.$type)) {
return new PrimitiveType($type);
}
if ($type === 'variable') {
return new VariableType;
}
if ($type === 'mixed') {
return new MixedType;
}
return new ClassType($type);
} | [
"public",
"static",
"function",
"of",
"(",
"string",
"$",
"type",
")",
":",
"SpecificationInterface",
"{",
"if",
"(",
"\\",
"function_exists",
"(",
"'is_'",
".",
"$",
"type",
")",
")",
"{",
"return",
"new",
"PrimitiveType",
"(",
"$",
"type",
")",
";",
... | Build the appropriate specification for the given type
@param string $type
@return SpecificationInterface | [
"Build",
"the",
"appropriate",
"specification",
"for",
"the",
"given",
"type"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Type.php#L22-L37 | train |
Innmind/Immutable | src/Type.php | Type.determine | public static function determine($value): string
{
$type = \gettype($value);
switch ($type) {
case 'object':
return \get_class($value);
case 'integer':
return 'int';
case 'boolean':
return 'bool';
case 'NULL':
return 'null';
case 'double':
return 'float';
default:
return $type;
}
} | php | public static function determine($value): string
{
$type = \gettype($value);
switch ($type) {
case 'object':
return \get_class($value);
case 'integer':
return 'int';
case 'boolean':
return 'bool';
case 'NULL':
return 'null';
case 'double':
return 'float';
default:
return $type;
}
} | [
"public",
"static",
"function",
"determine",
"(",
"$",
"value",
")",
":",
"string",
"{",
"$",
"type",
"=",
"\\",
"gettype",
"(",
"$",
"value",
")",
";",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"'object'",
":",
"return",
"\\",
"get_class",
"(",
... | Return the type of the given value
@param mixed $value
@return string | [
"Return",
"the",
"type",
"of",
"the",
"given",
"value"
] | e41bc01b13c1b11226e5ac6937bccf3c60813ca9 | https://github.com/Innmind/Immutable/blob/e41bc01b13c1b11226e5ac6937bccf3c60813ca9/src/Type.php#L46-L69 | train |
symbiote/silverstripe-content-services | code/content/FileContentReader.php | FileContentReader.read | public function read() {
$id = $this->getId();
$path = $this->getPath($id);
if (!is_readable($path)) {
throw new Exception("Expected path $path is not readable");
}
return file_get_contents($path);
} | php | public function read() {
$id = $this->getId();
$path = $this->getPath($id);
if (!is_readable($path)) {
throw new Exception("Expected path $path is not readable");
}
return file_get_contents($path);
} | [
"public",
"function",
"read",
"(",
")",
"{",
"$",
"id",
"=",
"$",
"this",
"->",
"getId",
"(",
")",
";",
"$",
"path",
"=",
"$",
"this",
"->",
"getPath",
"(",
"$",
"id",
")",
";",
"if",
"(",
"!",
"is_readable",
"(",
"$",
"path",
")",
")",
"{",
... | Read content back to the user
@return string | [
"Read",
"content",
"back",
"to",
"the",
"user"
] | d6dec8da12208d876051aa4329a9b76032172bfa | https://github.com/symbiote/silverstripe-content-services/blob/d6dec8da12208d876051aa4329a9b76032172bfa/code/content/FileContentReader.php#L81-L90 | train |
hipchat/hipchat-php | src/HipChat/HipChat.php | HipChat.room_exists | public function room_exists($room_id) {
try {
$this->get_room($room_id);
}
catch (HipChat_Exception $e) {
if ($e->code === self::STATUS_NOT_FOUND) {
return false;
}
throw $e;
}
return true;
} | php | public function room_exists($room_id) {
try {
$this->get_room($room_id);
}
catch (HipChat_Exception $e) {
if ($e->code === self::STATUS_NOT_FOUND) {
return false;
}
throw $e;
}
return true;
} | [
"public",
"function",
"room_exists",
"(",
"$",
"room_id",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"get_room",
"(",
"$",
"room_id",
")",
";",
"}",
"catch",
"(",
"HipChat_Exception",
"$",
"e",
")",
"{",
"if",
"(",
"$",
"e",
"->",
"code",
"===",
"sel... | Determine if the given room name or room id already exists.
@param mixed $room_id
@return boolean | [
"Determine",
"if",
"the",
"given",
"room",
"name",
"or",
"room",
"id",
"already",
"exists",
"."
] | 5936c0a48d2d514d94bfc1d774b04c42cd3bc39e | https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L94-L105 | train |
hipchat/hipchat-php | src/HipChat/HipChat.php | HipChat.message_room | public function message_room($room_id, $from, $message, $notify = false,
$color = self::COLOR_YELLOW,
$message_format = self::FORMAT_HTML) {
$args = array(
'room_id' => $room_id,
'from' => $from,
'message' => $message,
'notify' => (int)$notify,
'color' => $color,
'message_format' => $message_format
);
$response = $this->make_request('rooms/message', $args, 'POST');
return ($response->status == 'sent');
} | php | public function message_room($room_id, $from, $message, $notify = false,
$color = self::COLOR_YELLOW,
$message_format = self::FORMAT_HTML) {
$args = array(
'room_id' => $room_id,
'from' => $from,
'message' => $message,
'notify' => (int)$notify,
'color' => $color,
'message_format' => $message_format
);
$response = $this->make_request('rooms/message', $args, 'POST');
return ($response->status == 'sent');
} | [
"public",
"function",
"message_room",
"(",
"$",
"room_id",
",",
"$",
"from",
",",
"$",
"message",
",",
"$",
"notify",
"=",
"false",
",",
"$",
"color",
"=",
"self",
"::",
"COLOR_YELLOW",
",",
"$",
"message_format",
"=",
"self",
"::",
"FORMAT_HTML",
")",
... | Send a message to a room
@see http://api.hipchat.com/docs/api/method/rooms/message | [
"Send",
"a",
"message",
"to",
"a",
"room"
] | 5936c0a48d2d514d94bfc1d774b04c42cd3bc39e | https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L122-L135 | train |
hipchat/hipchat-php | src/HipChat/HipChat.php | HipChat.get_rooms_history | public function get_rooms_history($room_id, $date = 'recent') {
$response = $this->make_request('rooms/history', array(
'room_id' => $room_id,
'date' => $date
));
return $response->messages;
} | php | public function get_rooms_history($room_id, $date = 'recent') {
$response = $this->make_request('rooms/history', array(
'room_id' => $room_id,
'date' => $date
));
return $response->messages;
} | [
"public",
"function",
"get_rooms_history",
"(",
"$",
"room_id",
",",
"$",
"date",
"=",
"'recent'",
")",
"{",
"$",
"response",
"=",
"$",
"this",
"->",
"make_request",
"(",
"'rooms/history'",
",",
"array",
"(",
"'room_id'",
"=>",
"$",
"room_id",
",",
"'date'... | Get chat history for a room
@see https://www.hipchat.com/docs/api/method/rooms/history | [
"Get",
"chat",
"history",
"for",
"a",
"room"
] | 5936c0a48d2d514d94bfc1d774b04c42cd3bc39e | https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L142-L148 | train |
hipchat/hipchat-php | src/HipChat/HipChat.php | HipChat.set_room_topic | public function set_room_topic($room_id, $topic, $from = null) {
$args = array(
'room_id' => $room_id,
'topic' => $topic,
);
if ($from) {
$args['from'] = $from;
}
$response = $this->make_request('rooms/topic', $args, 'POST');
return ($response->status == 'ok');
} | php | public function set_room_topic($room_id, $topic, $from = null) {
$args = array(
'room_id' => $room_id,
'topic' => $topic,
);
if ($from) {
$args['from'] = $from;
}
$response = $this->make_request('rooms/topic', $args, 'POST');
return ($response->status == 'ok');
} | [
"public",
"function",
"set_room_topic",
"(",
"$",
"room_id",
",",
"$",
"topic",
",",
"$",
"from",
"=",
"null",
")",
"{",
"$",
"args",
"=",
"array",
"(",
"'room_id'",
"=>",
"$",
"room_id",
",",
"'topic'",
"=>",
"$",
"topic",
",",
")",
";",
"if",
"("... | Set a room's topic
@see http://api.hipchat.com/docs/api/method/rooms/topic | [
"Set",
"a",
"room",
"s",
"topic"
] | 5936c0a48d2d514d94bfc1d774b04c42cd3bc39e | https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L155-L167 | train |
hipchat/hipchat-php | src/HipChat/HipChat.php | HipChat.create_room | public function create_room($name, $owner_user_id = null, $privacy = null, $topic = null, $guest_access = null) {
$args = array(
'name' => $name
);
if ($owner_user_id) {
$args['owner_user_id'] = $owner_user_id;
}
if ($privacy) {
$args['privacy'] = $privacy;
}
if ($topic) {
$args['topic'] = $topic;
}
if ($guest_access) {
$args['guest_access'] = (int)$guest_access;
}
// Return the std object
return $this->make_request('rooms/create', $args, 'POST');
} | php | public function create_room($name, $owner_user_id = null, $privacy = null, $topic = null, $guest_access = null) {
$args = array(
'name' => $name
);
if ($owner_user_id) {
$args['owner_user_id'] = $owner_user_id;
}
if ($privacy) {
$args['privacy'] = $privacy;
}
if ($topic) {
$args['topic'] = $topic;
}
if ($guest_access) {
$args['guest_access'] = (int)$guest_access;
}
// Return the std object
return $this->make_request('rooms/create', $args, 'POST');
} | [
"public",
"function",
"create_room",
"(",
"$",
"name",
",",
"$",
"owner_user_id",
"=",
"null",
",",
"$",
"privacy",
"=",
"null",
",",
"$",
"topic",
"=",
"null",
",",
"$",
"guest_access",
"=",
"null",
")",
"{",
"$",
"args",
"=",
"array",
"(",
"'name'"... | Create a room
@see http://api.hipchat.com/docs/api/method/rooms/create | [
"Create",
"a",
"room"
] | 5936c0a48d2d514d94bfc1d774b04c42cd3bc39e | https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L174-L197 | train |
hipchat/hipchat-php | src/HipChat/HipChat.php | HipChat.delete_room | public function delete_room($room_id){
$args = array(
'room_id' => $room_id
);
$response = $this->make_request('rooms/delete', $args, 'POST');
return ($response->deleted == 'true');
} | php | public function delete_room($room_id){
$args = array(
'room_id' => $room_id
);
$response = $this->make_request('rooms/delete', $args, 'POST');
return ($response->deleted == 'true');
} | [
"public",
"function",
"delete_room",
"(",
"$",
"room_id",
")",
"{",
"$",
"args",
"=",
"array",
"(",
"'room_id'",
"=>",
"$",
"room_id",
")",
";",
"$",
"response",
"=",
"$",
"this",
"->",
"make_request",
"(",
"'rooms/delete'",
",",
"$",
"args",
",",
"'PO... | Delete a room
@see http://api.hipchat.com/docs/api/method/rooms/delete | [
"Delete",
"a",
"room"
] | 5936c0a48d2d514d94bfc1d774b04c42cd3bc39e | https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L204-L212 | train |
hipchat/hipchat-php | src/HipChat/HipChat.php | HipChat.create_user | public function create_user($email, $name, $mention_name = null,
$title = null, $is_group_admin = 0,
$password = null, $timezone = null) {
$args = array(
'email' => $email,
'name' => $name,
);
if ($mention_name) {
$args['mention_name'] = $mention_name;
}
if ($title) {
$args['title'] = $title;
}
if ($is_group_admin) {
$args['is_group_admin'] = (int)$is_group_admin;
}
if ($password) {
$args['password'] = $password;
}
// @see http://api.hipchat.com/docs/api/timezones
if ($timezone) {
$args['timezone'] = $timezone;
}
// Return the std object
return $this->make_request('users/create', $args, 'POST');
} | php | public function create_user($email, $name, $mention_name = null,
$title = null, $is_group_admin = 0,
$password = null, $timezone = null) {
$args = array(
'email' => $email,
'name' => $name,
);
if ($mention_name) {
$args['mention_name'] = $mention_name;
}
if ($title) {
$args['title'] = $title;
}
if ($is_group_admin) {
$args['is_group_admin'] = (int)$is_group_admin;
}
if ($password) {
$args['password'] = $password;
}
// @see http://api.hipchat.com/docs/api/timezones
if ($timezone) {
$args['timezone'] = $timezone;
}
// Return the std object
return $this->make_request('users/create', $args, 'POST');
} | [
"public",
"function",
"create_user",
"(",
"$",
"email",
",",
"$",
"name",
",",
"$",
"mention_name",
"=",
"null",
",",
"$",
"title",
"=",
"null",
",",
"$",
"is_group_admin",
"=",
"0",
",",
"$",
"password",
"=",
"null",
",",
"$",
"timezone",
"=",
"null... | Create a new user in your group.
@see http://api.hipchat.com/docs/api/method/users/create | [
"Create",
"a",
"new",
"user",
"in",
"your",
"group",
"."
] | 5936c0a48d2d514d94bfc1d774b04c42cd3bc39e | https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L245-L276 | train |
hipchat/hipchat-php | src/HipChat/HipChat.php | HipChat.curl_request | public function curl_request($url, $post_data = null) {
if (is_array($post_data)) {
$post_data = array_map(array($this, 'sanitize_curl_parameter'), $post_data);
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->request_timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verify_ssl);
if (isset($this->proxy)) {
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
curl_setopt($ch, CURLOPT_PROXY, $this->proxy);
}
if (is_array($post_data)) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
$response = curl_exec($ch);
// make sure we got a real response
if (strlen($response) == 0) {
$errno = curl_errno($ch);
$error = curl_error($ch);
throw new HipChat_Exception(self::STATUS_BAD_RESPONSE,
"CURL error: $errno - $error", $url);
}
// make sure we got a 200
$code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code != self::STATUS_OK) {
throw new HipChat_Exception($code,
"HTTP status code: $code, response=$response", $url);
}
curl_close($ch);
return $response;
} | php | public function curl_request($url, $post_data = null) {
if (is_array($post_data)) {
$post_data = array_map(array($this, 'sanitize_curl_parameter'), $post_data);
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->request_timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verify_ssl);
if (isset($this->proxy)) {
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
curl_setopt($ch, CURLOPT_PROXY, $this->proxy);
}
if (is_array($post_data)) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
$response = curl_exec($ch);
// make sure we got a real response
if (strlen($response) == 0) {
$errno = curl_errno($ch);
$error = curl_error($ch);
throw new HipChat_Exception(self::STATUS_BAD_RESPONSE,
"CURL error: $errno - $error", $url);
}
// make sure we got a 200
$code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code != self::STATUS_OK) {
throw new HipChat_Exception($code,
"HTTP status code: $code, response=$response", $url);
}
curl_close($ch);
return $response;
} | [
"public",
"function",
"curl_request",
"(",
"$",
"url",
",",
"$",
"post_data",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"post_data",
")",
")",
"{",
"$",
"post_data",
"=",
"array_map",
"(",
"array",
"(",
"$",
"this",
",",
"'sanitize_curl_p... | Performs a curl request
@param $url URL to hit.
@param $post_data Data to send via POST. Leave null for GET request.
@throws HipChat_Exception
@return string | [
"Performs",
"a",
"curl",
"request"
] | 5936c0a48d2d514d94bfc1d774b04c42cd3bc39e | https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L359-L398 | train |
hipchat/hipchat-php | src/HipChat/HipChat.php | HipChat.make_request | public function make_request($api_method, $args = array(),
$http_method = 'GET') {
$args['format'] = 'json';
$args['auth_token'] = $this->auth_token;
$url = "$this->api_target/$this->api_version/$api_method";
$post_data = null;
// add args to url for GET
if ($http_method == 'GET') {
$url .= '?' . http_build_query($args);
} else {
$post_data = $args;
}
$response = $this->curl_request($url, $post_data);
// make sure response is valid json
$response = json_decode($response);
if (!$response) {
throw new HipChat_Exception(self::STATUS_BAD_RESPONSE,
"Invalid JSON received: $response", $url);
}
return $response;
} | php | public function make_request($api_method, $args = array(),
$http_method = 'GET') {
$args['format'] = 'json';
$args['auth_token'] = $this->auth_token;
$url = "$this->api_target/$this->api_version/$api_method";
$post_data = null;
// add args to url for GET
if ($http_method == 'GET') {
$url .= '?' . http_build_query($args);
} else {
$post_data = $args;
}
$response = $this->curl_request($url, $post_data);
// make sure response is valid json
$response = json_decode($response);
if (!$response) {
throw new HipChat_Exception(self::STATUS_BAD_RESPONSE,
"Invalid JSON received: $response", $url);
}
return $response;
} | [
"public",
"function",
"make_request",
"(",
"$",
"api_method",
",",
"$",
"args",
"=",
"array",
"(",
")",
",",
"$",
"http_method",
"=",
"'GET'",
")",
"{",
"$",
"args",
"[",
"'format'",
"]",
"=",
"'json'",
";",
"$",
"args",
"[",
"'auth_token'",
"]",
"="... | Make an API request using curl
@param string $api_method Which API method to hit, like 'rooms/show'.
@param array $args Data to send.
@param string $http_method HTTP method (GET or POST).
@throws HipChat_Exception
@return mixed | [
"Make",
"an",
"API",
"request",
"using",
"curl"
] | 5936c0a48d2d514d94bfc1d774b04c42cd3bc39e | https://github.com/hipchat/hipchat-php/blob/5936c0a48d2d514d94bfc1d774b04c42cd3bc39e/src/HipChat/HipChat.php#L429-L453 | train |
symbiote/silverstripe-content-services | code/content/ReaderWriterBase.php | ReaderWriterBase.getContentId | public function getContentId() {
if (!$this->id) {
throw new Exception("Null content identifier; content must be written before retrieving id");
}
return $this->getSourceIdentifier() . ContentService::SEPARATOR . $this->id;
} | php | public function getContentId() {
if (!$this->id) {
throw new Exception("Null content identifier; content must be written before retrieving id");
}
return $this->getSourceIdentifier() . ContentService::SEPARATOR . $this->id;
} | [
"public",
"function",
"getContentId",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"id",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"Null content identifier; content must be written before retrieving id\"",
")",
";",
"}",
"return",
"$",
"this",
"->",
"ge... | Get content identifier that can be used to retrieve this content at a
later point in timer | [
"Get",
"content",
"identifier",
"that",
"can",
"be",
"used",
"to",
"retrieve",
"this",
"content",
"at",
"a",
"later",
"point",
"in",
"timer"
] | d6dec8da12208d876051aa4329a9b76032172bfa | https://github.com/symbiote/silverstripe-content-services/blob/d6dec8da12208d876051aa4329a9b76032172bfa/code/content/ReaderWriterBase.php#L67-L72 | train |
inpsyde/Wonolog | src/Data/FailedLogin.php | FailedLogin.level | public function level() {
$this->count_attempts( 300 );
switch ( TRUE ) {
case ( $this->attempts > 2 && $this->attempts <= 100 ) :
return Logger::NOTICE;
case ( $this->attempts > 100 && $this->attempts <= 590 ) :
return Logger::WARNING;
case ( $this->attempts > 590 && $this->attempts <= 990 ) :
return Logger::ERROR;
case ( $this->attempts > 990 ) :
return Logger::CRITICAL;
}
return 0;
} | php | public function level() {
$this->count_attempts( 300 );
switch ( TRUE ) {
case ( $this->attempts > 2 && $this->attempts <= 100 ) :
return Logger::NOTICE;
case ( $this->attempts > 100 && $this->attempts <= 590 ) :
return Logger::WARNING;
case ( $this->attempts > 590 && $this->attempts <= 990 ) :
return Logger::ERROR;
case ( $this->attempts > 990 ) :
return Logger::CRITICAL;
}
return 0;
} | [
"public",
"function",
"level",
"(",
")",
"{",
"$",
"this",
"->",
"count_attempts",
"(",
"300",
")",
";",
"switch",
"(",
"TRUE",
")",
"{",
"case",
"(",
"$",
"this",
"->",
"attempts",
">",
"2",
"&&",
"$",
"this",
"->",
"attempts",
"<=",
"100",
")",
... | Determine severity of the error based on the number of login attempts in
last 5 minutes.
@return int | [
"Determine",
"severity",
"of",
"the",
"error",
"based",
"on",
"the",
"number",
"of",
"login",
"attempts",
"in",
"last",
"5",
"minutes",
"."
] | 87ed9a60c6f5cc3a057db857273dc504efc5ad9f | https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Data/FailedLogin.php#L60-L76 | train |
inpsyde/Wonolog | src/Data/FailedLogin.php | FailedLogin.sniff_ip | private function sniff_ip() {
if ( $this->ip_data ) {
return;
}
if ( PHP_SAPI === 'cli' ) {
$this->ip_data = [ '127.0.0.1', 'CLI' ];
return;
}
$ip_server_keys = [ 'REMOTE_ADDR' => '', 'HTTP_CLIENT_IP' => '', 'HTTP_X_FORWARDED_FOR' => '', ];
$ips = array_intersect_key( $_SERVER, $ip_server_keys );
$this->ip_data = $ips ? [ reset( $ips ), key( $ips ) ] : [ '0.0.0.0', 'Hidden IP' ];
} | php | private function sniff_ip() {
if ( $this->ip_data ) {
return;
}
if ( PHP_SAPI === 'cli' ) {
$this->ip_data = [ '127.0.0.1', 'CLI' ];
return;
}
$ip_server_keys = [ 'REMOTE_ADDR' => '', 'HTTP_CLIENT_IP' => '', 'HTTP_X_FORWARDED_FOR' => '', ];
$ips = array_intersect_key( $_SERVER, $ip_server_keys );
$this->ip_data = $ips ? [ reset( $ips ), key( $ips ) ] : [ '0.0.0.0', 'Hidden IP' ];
} | [
"private",
"function",
"sniff_ip",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"ip_data",
")",
"{",
"return",
";",
"}",
"if",
"(",
"PHP_SAPI",
"===",
"'cli'",
")",
"{",
"$",
"this",
"->",
"ip_data",
"=",
"[",
"'127.0.0.1'",
",",
"'CLI'",
"]",
";",... | Try to sniff the current client IP. | [
"Try",
"to",
"sniff",
"the",
"current",
"client",
"IP",
"."
] | 87ed9a60c6f5cc3a057db857273dc504efc5ad9f | https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Data/FailedLogin.php#L126-L141 | train |
inpsyde/Wonolog | src/Data/FailedLogin.php | FailedLogin.count_attempts | private function count_attempts( $ttl = 300 ) {
if ( isset( $this->attempts ) ) {
return;
}
$this->sniff_ip();
$ip = $this->ip_data[ 0 ];
$attempts = get_site_transient( self::TRANSIENT_NAME );
is_array( $attempts ) or $attempts = [];
// Seems the first time a failed attempt for this IP
if ( ! $attempts || ! array_key_exists( $ip, $attempts ) ) {
$attempts[ $ip ] = [ 'count' => 0, 'last_logged' => 0, ];
}
$attempts[ $ip ][ 'count' ] ++;
$this->attempts_data = $attempts;
$count = $attempts[ $ip ][ 'count' ];
$last_logged = $attempts[ $ip ][ 'last_logged' ];
/**
* During a brute force attack, logging all the failed attempts can be so expensive to put the server down.
* So we log:
*
* - 3rd attempt
* - every 20 when total attempts are > 23 && < 100 (23rd, 43rd...)
* - every 100 when total attempts are > 182 && < 1182 (183rd, 283rd...)
* - every 200 when total attempts are > 1182 (1183rd, 1383rd...)
*/
$do_log =
$count === 3
|| ( $count < 100 && ( $count - $last_logged ) === 20 )
|| ( $count < 1000 && ( $count - $last_logged ) === 100 )
|| ( ( $count - $last_logged ) === 200 );
$do_log and $attempts[ $ip ][ 'last_logged' ] = $count;
set_site_transient( self::TRANSIENT_NAME, $attempts, $ttl );
$this->attempts = $do_log ? $count : 0;
} | php | private function count_attempts( $ttl = 300 ) {
if ( isset( $this->attempts ) ) {
return;
}
$this->sniff_ip();
$ip = $this->ip_data[ 0 ];
$attempts = get_site_transient( self::TRANSIENT_NAME );
is_array( $attempts ) or $attempts = [];
// Seems the first time a failed attempt for this IP
if ( ! $attempts || ! array_key_exists( $ip, $attempts ) ) {
$attempts[ $ip ] = [ 'count' => 0, 'last_logged' => 0, ];
}
$attempts[ $ip ][ 'count' ] ++;
$this->attempts_data = $attempts;
$count = $attempts[ $ip ][ 'count' ];
$last_logged = $attempts[ $ip ][ 'last_logged' ];
/**
* During a brute force attack, logging all the failed attempts can be so expensive to put the server down.
* So we log:
*
* - 3rd attempt
* - every 20 when total attempts are > 23 && < 100 (23rd, 43rd...)
* - every 100 when total attempts are > 182 && < 1182 (183rd, 283rd...)
* - every 200 when total attempts are > 1182 (1183rd, 1383rd...)
*/
$do_log =
$count === 3
|| ( $count < 100 && ( $count - $last_logged ) === 20 )
|| ( $count < 1000 && ( $count - $last_logged ) === 100 )
|| ( ( $count - $last_logged ) === 200 );
$do_log and $attempts[ $ip ][ 'last_logged' ] = $count;
set_site_transient( self::TRANSIENT_NAME, $attempts, $ttl );
$this->attempts = $do_log ? $count : 0;
} | [
"private",
"function",
"count_attempts",
"(",
"$",
"ttl",
"=",
"300",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"attempts",
")",
")",
"{",
"return",
";",
"}",
"$",
"this",
"->",
"sniff_ip",
"(",
")",
";",
"$",
"ip",
"=",
"$",
"this",
... | Determine how many failed login attempts comes from the guessed IP.
Use a site transient to count them.
@param int $ttl transient time to live in seconds | [
"Determine",
"how",
"many",
"failed",
"login",
"attempts",
"comes",
"from",
"the",
"guessed",
"IP",
".",
"Use",
"a",
"site",
"transient",
"to",
"count",
"them",
"."
] | 87ed9a60c6f5cc3a057db857273dc504efc5ad9f | https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Data/FailedLogin.php#L149-L191 | train |
inpsyde/Wonolog | src/PhpErrorController.php | PhpErrorController.on_exception | public function on_exception( $e ) {
// Log the PHP exception.
do_action(
\Inpsyde\Wonolog\LOG,
new Log(
$e->getMessage(),
Logger::CRITICAL,
Channels::PHP_ERROR,
[
'exception' => get_class( $e ),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTraceAsString(),
]
)
);
// after logging let's reset handler and throw the exception
restore_exception_handler();
throw $e;
} | php | public function on_exception( $e ) {
// Log the PHP exception.
do_action(
\Inpsyde\Wonolog\LOG,
new Log(
$e->getMessage(),
Logger::CRITICAL,
Channels::PHP_ERROR,
[
'exception' => get_class( $e ),
'file' => $e->getFile(),
'line' => $e->getLine(),
'trace' => $e->getTraceAsString(),
]
)
);
// after logging let's reset handler and throw the exception
restore_exception_handler();
throw $e;
} | [
"public",
"function",
"on_exception",
"(",
"$",
"e",
")",
"{",
"// Log the PHP exception.",
"do_action",
"(",
"\\",
"Inpsyde",
"\\",
"Wonolog",
"\\",
"LOG",
",",
"new",
"Log",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
",",
"Logger",
"::",
"CRITICAL",
... | Uncaught exception handler.
@param \Throwable $e
@throws \Throwable | [
"Uncaught",
"exception",
"handler",
"."
] | 87ed9a60c6f5cc3a057db857273dc504efc5ad9f | https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/PhpErrorController.php#L96-L117 | train |
inpsyde/Wonolog | src/PhpErrorController.php | PhpErrorController.on_fatal | public function on_fatal() {
$last_error = error_get_last();
if ( ! $last_error ) {
return;
}
$error = array_merge( [ 'type' => -1, 'message' => '', 'file' => '', 'line' => 0 ], $last_error );
$fatals = [
E_ERROR,
E_PARSE,
E_CORE_ERROR,
E_CORE_WARNING,
E_COMPILE_ERROR,
E_COMPILE_WARNING,
];
if ( in_array( $error[ 'type' ], $fatals, TRUE ) ) {
$this->on_error( $error[ 'type' ], $error[ 'message' ], $error[ 'file' ], $error[ 'line' ] );
}
} | php | public function on_fatal() {
$last_error = error_get_last();
if ( ! $last_error ) {
return;
}
$error = array_merge( [ 'type' => -1, 'message' => '', 'file' => '', 'line' => 0 ], $last_error );
$fatals = [
E_ERROR,
E_PARSE,
E_CORE_ERROR,
E_CORE_WARNING,
E_COMPILE_ERROR,
E_COMPILE_WARNING,
];
if ( in_array( $error[ 'type' ], $fatals, TRUE ) ) {
$this->on_error( $error[ 'type' ], $error[ 'message' ], $error[ 'file' ], $error[ 'line' ] );
}
} | [
"public",
"function",
"on_fatal",
"(",
")",
"{",
"$",
"last_error",
"=",
"error_get_last",
"(",
")",
";",
"if",
"(",
"!",
"$",
"last_error",
")",
"{",
"return",
";",
"}",
"$",
"error",
"=",
"array_merge",
"(",
"[",
"'type'",
"=>",
"-",
"1",
",",
"'... | Checks for a fatal error, work-around for `set_error_handler` not working with fatal errors. | [
"Checks",
"for",
"a",
"fatal",
"error",
"work",
"-",
"around",
"for",
"set_error_handler",
"not",
"working",
"with",
"fatal",
"errors",
"."
] | 87ed9a60c6f5cc3a057db857273dc504efc5ad9f | https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/PhpErrorController.php#L122-L143 | train |
inpsyde/Wonolog | src/HookListener/QueryErrorsListener.php | QueryErrorsListener.update | public function update( array $args ) {
$wp = $args ? reset( $args ) : NULL;
if ( ! $wp instanceof \WP ) {
return new NullLog();
}
$error = [];
isset( $wp->query_vars[ 'error' ] ) and $error[] = $wp->query_vars[ 'error' ];
is_404() and $error[] = '404 Page not found';
if ( empty( $error ) ) {
return new NullLog();
}
$url = filter_var( add_query_arg( [] ), FILTER_SANITIZE_URL );
$message = "Error on frontend request for url {$url}.";
$context = [
'error' => $error,
'query_vars' => $wp->query_vars,
'matched_rule' => $wp->matched_rule,
];
return new Debug( $message, Channels::HTTP, $context );
} | php | public function update( array $args ) {
$wp = $args ? reset( $args ) : NULL;
if ( ! $wp instanceof \WP ) {
return new NullLog();
}
$error = [];
isset( $wp->query_vars[ 'error' ] ) and $error[] = $wp->query_vars[ 'error' ];
is_404() and $error[] = '404 Page not found';
if ( empty( $error ) ) {
return new NullLog();
}
$url = filter_var( add_query_arg( [] ), FILTER_SANITIZE_URL );
$message = "Error on frontend request for url {$url}.";
$context = [
'error' => $error,
'query_vars' => $wp->query_vars,
'matched_rule' => $wp->matched_rule,
];
return new Debug( $message, Channels::HTTP, $context );
} | [
"public",
"function",
"update",
"(",
"array",
"$",
"args",
")",
"{",
"$",
"wp",
"=",
"$",
"args",
"?",
"reset",
"(",
"$",
"args",
")",
":",
"NULL",
";",
"if",
"(",
"!",
"$",
"wp",
"instanceof",
"\\",
"WP",
")",
"{",
"return",
"new",
"NullLog",
... | Checks frontend request for any errors and log them.
@param $args
@return LogDataInterface
@wp-hook wp | [
"Checks",
"frontend",
"request",
"for",
"any",
"errors",
"and",
"log",
"them",
"."
] | 87ed9a60c6f5cc3a057db857273dc504efc5ad9f | https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/HookListener/QueryErrorsListener.php#L43-L68 | train |
inpsyde/Wonolog | src/HookListener/HookListenersRegistry.php | HookListenersRegistry.initialize | public static function initialize() {
$instance = new static();
/**
* Fires right before hook listeners are registered.
*
* @param HookListenersRegistry $registry
*/
do_action( self::ACTION_REGISTER, $instance );
array_walk(
$instance->listeners,
function ( HookListenerInterface $listener ) use ( $instance ) {
/**
* Filters whether to enable the hook listener.
*
* @param bool $enable
* @param HookListenerInterface $listener
*/
if ( apply_filters( self::FILTER_ENABLED, TRUE, $listener ) ) {
$hooks = (array) $listener->listen_to();
array_walk( $hooks, [ $instance, 'listen_hook' ], $listener );
}
}
);
unset( $instance->listeners );
$instance->listeners = [];
} | php | public static function initialize() {
$instance = new static();
/**
* Fires right before hook listeners are registered.
*
* @param HookListenersRegistry $registry
*/
do_action( self::ACTION_REGISTER, $instance );
array_walk(
$instance->listeners,
function ( HookListenerInterface $listener ) use ( $instance ) {
/**
* Filters whether to enable the hook listener.
*
* @param bool $enable
* @param HookListenerInterface $listener
*/
if ( apply_filters( self::FILTER_ENABLED, TRUE, $listener ) ) {
$hooks = (array) $listener->listen_to();
array_walk( $hooks, [ $instance, 'listen_hook' ], $listener );
}
}
);
unset( $instance->listeners );
$instance->listeners = [];
} | [
"public",
"static",
"function",
"initialize",
"(",
")",
"{",
"$",
"instance",
"=",
"new",
"static",
"(",
")",
";",
"/**\n\t\t * Fires right before hook listeners are registered.\n\t\t *\n\t\t * @param HookListenersRegistry $registry\n\t\t */",
"do_action",
"(",
"self",
"::",
... | Initialize the class, fire an hook to allow listener registration and adds the hook that will make log happen | [
"Initialize",
"the",
"class",
"fire",
"an",
"hook",
"to",
"allow",
"listener",
"registration",
"and",
"adds",
"the",
"hook",
"that",
"will",
"make",
"log",
"happen"
] | 87ed9a60c6f5cc3a057db857273dc504efc5ad9f | https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/HookListener/HookListenersRegistry.php#L35-L65 | train |
inpsyde/Wonolog | src/Data/HookLogFactory.php | HookLogFactory.extract_log_objects_in_args | private function extract_log_objects_in_args( array $args, $hook_level ) {
$logs = [];
foreach ( $args as $arg ) {
if ( $arg instanceof LogDataInterface ) {
$logs[] = $this->maybe_raise_level( $hook_level, $arg );
}
}
return $logs;
} | php | private function extract_log_objects_in_args( array $args, $hook_level ) {
$logs = [];
foreach ( $args as $arg ) {
if ( $arg instanceof LogDataInterface ) {
$logs[] = $this->maybe_raise_level( $hook_level, $arg );
}
}
return $logs;
} | [
"private",
"function",
"extract_log_objects_in_args",
"(",
"array",
"$",
"args",
",",
"$",
"hook_level",
")",
"{",
"$",
"logs",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"args",
"as",
"$",
"arg",
")",
"{",
"if",
"(",
"$",
"arg",
"instanceof",
"LogDataIn... | If one or more LogData objects are passed as argument, extract all of them and return remaining objects.
@param array $args
@param int $hook_level
@return LogDataInterface[] | [
"If",
"one",
"or",
"more",
"LogData",
"objects",
"are",
"passed",
"as",
"argument",
"extract",
"all",
"of",
"them",
"and",
"return",
"remaining",
"objects",
"."
] | 87ed9a60c6f5cc3a057db857273dc504efc5ad9f | https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Data/HookLogFactory.php#L83-L94 | train |
inpsyde/Wonolog | src/HookListener/CronDebugListener.php | CronDebugListener.cron_action_profile | private function cron_action_profile() {
if ( ! defined( 'DOING_CRON' ) || ! DOING_CRON ) {
return;
}
$hook = current_filter();
if ( ! isset( $this->done[ $hook ] ) ) {
$this->done[ $hook ][ 'start' ] = microtime( TRUE );
return;
}
if ( ! isset( $this->done[ $hook ][ 'duration' ] ) ) {
$duration = number_format( microtime( TRUE ) - $this->done[ $hook ][ 'start' ], 2 );
$this->done[ $hook ][ 'duration' ] = $duration . ' s';
// Log the cron action performed.
do_action(
\Inpsyde\Wonolog\LOG,
new Info( "Cron action \"{$hook}\" performed.", Channels::DEBUG, $this->done[ $hook ] )
);
}
} | php | private function cron_action_profile() {
if ( ! defined( 'DOING_CRON' ) || ! DOING_CRON ) {
return;
}
$hook = current_filter();
if ( ! isset( $this->done[ $hook ] ) ) {
$this->done[ $hook ][ 'start' ] = microtime( TRUE );
return;
}
if ( ! isset( $this->done[ $hook ][ 'duration' ] ) ) {
$duration = number_format( microtime( TRUE ) - $this->done[ $hook ][ 'start' ], 2 );
$this->done[ $hook ][ 'duration' ] = $duration . ' s';
// Log the cron action performed.
do_action(
\Inpsyde\Wonolog\LOG,
new Info( "Cron action \"{$hook}\" performed.", Channels::DEBUG, $this->done[ $hook ] )
);
}
} | [
"private",
"function",
"cron_action_profile",
"(",
")",
"{",
"if",
"(",
"!",
"defined",
"(",
"'DOING_CRON'",
")",
"||",
"!",
"DOING_CRON",
")",
"{",
"return",
";",
"}",
"$",
"hook",
"=",
"current_filter",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
... | Run before and after that any cron action ran, logging it and its performance. | [
"Run",
"before",
"and",
"after",
"that",
"any",
"cron",
"action",
"ran",
"logging",
"it",
"and",
"its",
"performance",
"."
] | 87ed9a60c6f5cc3a057db857273dc504efc5ad9f | https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/HookListener/CronDebugListener.php#L139-L164 | train |
inpsyde/Wonolog | src/Controller.php | Controller.setup | public function setup( $priority = 100 ) {
if ( did_action( self::ACTION_SETUP ) ) {
return $this;
}
// We use WONOLOG_DISABLE instead of WONOLOG_ENABLE so that not defined (default) means enabled.
$disable_by_env = filter_var( getenv( 'WONOLOG_DISABLE' ), FILTER_VALIDATE_BOOLEAN );
/**
* Filters whether to completely disable Wonolog.
*
* @param bool $disable
*/
if ( apply_filters( self::FILTER_DISABLE, $disable_by_env ) ) {
return $this;
}
/**
* Fires right before Wonolog is set up.
*/
do_action( self::ACTION_SETUP );
$processor_registry = new ProcessorsRegistry();
$handlers_registry = new HandlersRegistry( $processor_registry );
$subscriber = new LogActionSubscriber( new Channels( $handlers_registry, $processor_registry ) );
$listener = [ $subscriber, 'listen' ];
add_action( LOG, $listener, $priority, PHP_INT_MAX );
foreach ( Logger::getLevels() as $level => $level_code ) {
// $level_code is from 100 (DEBUG) to 600 (EMERGENCY) this makes hook priority based on level priority
add_action( LOG . '.' . strtolower( $level ), $listener, $priority + ( 601 - $level_code ), PHP_INT_MAX );
}
add_action( 'muplugins_loaded', [ HookListenersRegistry::class, 'initialize' ], PHP_INT_MAX );
/**
* Fires right after Wonolog has been set up.
*/
do_action( self::ACTION_LOADED );
return $this;
} | php | public function setup( $priority = 100 ) {
if ( did_action( self::ACTION_SETUP ) ) {
return $this;
}
// We use WONOLOG_DISABLE instead of WONOLOG_ENABLE so that not defined (default) means enabled.
$disable_by_env = filter_var( getenv( 'WONOLOG_DISABLE' ), FILTER_VALIDATE_BOOLEAN );
/**
* Filters whether to completely disable Wonolog.
*
* @param bool $disable
*/
if ( apply_filters( self::FILTER_DISABLE, $disable_by_env ) ) {
return $this;
}
/**
* Fires right before Wonolog is set up.
*/
do_action( self::ACTION_SETUP );
$processor_registry = new ProcessorsRegistry();
$handlers_registry = new HandlersRegistry( $processor_registry );
$subscriber = new LogActionSubscriber( new Channels( $handlers_registry, $processor_registry ) );
$listener = [ $subscriber, 'listen' ];
add_action( LOG, $listener, $priority, PHP_INT_MAX );
foreach ( Logger::getLevels() as $level => $level_code ) {
// $level_code is from 100 (DEBUG) to 600 (EMERGENCY) this makes hook priority based on level priority
add_action( LOG . '.' . strtolower( $level ), $listener, $priority + ( 601 - $level_code ), PHP_INT_MAX );
}
add_action( 'muplugins_loaded', [ HookListenersRegistry::class, 'initialize' ], PHP_INT_MAX );
/**
* Fires right after Wonolog has been set up.
*/
do_action( self::ACTION_LOADED );
return $this;
} | [
"public",
"function",
"setup",
"(",
"$",
"priority",
"=",
"100",
")",
"{",
"if",
"(",
"did_action",
"(",
"self",
"::",
"ACTION_SETUP",
")",
")",
"{",
"return",
"$",
"this",
";",
"}",
"// We use WONOLOG_DISABLE instead of WONOLOG_ENABLE so that not defined (default) ... | Initialize Wonolog.
@param int $priority
@return Controller | [
"Initialize",
"Wonolog",
"."
] | 87ed9a60c6f5cc3a057db857273dc504efc5ad9f | https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Controller.php#L41-L84 | train |
inpsyde/Wonolog | src/Controller.php | Controller.log_php_errors | public function log_php_errors( $error_types = NULL ) {
static $done = FALSE;
if ( $done ) {
return $this;
}
$done = TRUE;
is_int( $error_types ) or $error_types = E_ALL | E_STRICT;
$controller = new PhpErrorController();
register_shutdown_function( [ $controller, 'on_fatal', ] );
set_error_handler( [ $controller, 'on_error' ], $error_types );
set_exception_handler( [ $controller, 'on_exception', ] );
// Ensure that channel Channels::PHP_ERROR error is there
add_filter(
Channels::FILTER_CHANNELS,
function ( array $channels ) {
$channels[] = Channels::PHP_ERROR;
return $channels;
},
PHP_INT_MAX
);
return $this;
} | php | public function log_php_errors( $error_types = NULL ) {
static $done = FALSE;
if ( $done ) {
return $this;
}
$done = TRUE;
is_int( $error_types ) or $error_types = E_ALL | E_STRICT;
$controller = new PhpErrorController();
register_shutdown_function( [ $controller, 'on_fatal', ] );
set_error_handler( [ $controller, 'on_error' ], $error_types );
set_exception_handler( [ $controller, 'on_exception', ] );
// Ensure that channel Channels::PHP_ERROR error is there
add_filter(
Channels::FILTER_CHANNELS,
function ( array $channels ) {
$channels[] = Channels::PHP_ERROR;
return $channels;
},
PHP_INT_MAX
);
return $this;
} | [
"public",
"function",
"log_php_errors",
"(",
"$",
"error_types",
"=",
"NULL",
")",
"{",
"static",
"$",
"done",
"=",
"FALSE",
";",
"if",
"(",
"$",
"done",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"done",
"=",
"TRUE",
";",
"is_int",
"(",
"$",
... | Tell Wonolog to use the PHP errors handler.
@param int|null $error_types bitmask of error types constants, default to E_ALL | E_STRICT
@return Controller | [
"Tell",
"Wonolog",
"to",
"use",
"the",
"PHP",
"errors",
"handler",
"."
] | 87ed9a60c6f5cc3a057db857273dc504efc5ad9f | https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Controller.php#L93-L121 | train |
inpsyde/Wonolog | src/Controller.php | Controller.use_default_handler | public function use_default_handler( HandlerInterface $handler = NULL ) {
static $done = FALSE;
if ( $done ) {
return $this;
}
$done = TRUE;
add_action(
HandlersRegistry::ACTION_REGISTER,
function ( HandlersRegistry $registry ) use ( $handler ) {
$handler = DefaultHandlerFactory::with_default_handler( $handler )
->create_default_handler();
$registry->add_handler( $handler, HandlersRegistry::DEFAULT_NAME );
},
1
);
return $this;
} | php | public function use_default_handler( HandlerInterface $handler = NULL ) {
static $done = FALSE;
if ( $done ) {
return $this;
}
$done = TRUE;
add_action(
HandlersRegistry::ACTION_REGISTER,
function ( HandlersRegistry $registry ) use ( $handler ) {
$handler = DefaultHandlerFactory::with_default_handler( $handler )
->create_default_handler();
$registry->add_handler( $handler, HandlersRegistry::DEFAULT_NAME );
},
1
);
return $this;
} | [
"public",
"function",
"use_default_handler",
"(",
"HandlerInterface",
"$",
"handler",
"=",
"NULL",
")",
"{",
"static",
"$",
"done",
"=",
"FALSE",
";",
"if",
"(",
"$",
"done",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"done",
"=",
"TRUE",
";",
"... | Tell Wonolog to use a default handler that can be passed as argument or build using settings customizable via
hooks.
@param HandlerInterface $handler
@return Controller | [
"Tell",
"Wonolog",
"to",
"use",
"a",
"default",
"handler",
"that",
"can",
"be",
"passed",
"as",
"argument",
"or",
"build",
"using",
"settings",
"customizable",
"via",
"hooks",
"."
] | 87ed9a60c6f5cc3a057db857273dc504efc5ad9f | https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Controller.php#L131-L153 | train |
inpsyde/Wonolog | src/Controller.php | Controller.use_handler | public function use_handler( HandlerInterface $handler, array $channels = [], $handler_id = NULL ) {
add_action(
HandlersRegistry::ACTION_REGISTER,
function ( HandlersRegistry $registry ) use ( $handler_id, $handler ) {
$registry->add_handler( $handler, $handler_id );
},
1
);
( $handler_id === null ) and $handler_id = $handler;
add_action(
Channels::ACTION_LOGGER,
function ( Logger $logger, HandlersRegistry $handlers ) use ( $handler_id, $channels ) {
if ( $channels === [] || in_array( $logger->getName(), $channels, TRUE ) ) {
$logger->pushHandler( $handlers->find( $handler_id ) );
}
},
10,
2
);
return $this;
} | php | public function use_handler( HandlerInterface $handler, array $channels = [], $handler_id = NULL ) {
add_action(
HandlersRegistry::ACTION_REGISTER,
function ( HandlersRegistry $registry ) use ( $handler_id, $handler ) {
$registry->add_handler( $handler, $handler_id );
},
1
);
( $handler_id === null ) and $handler_id = $handler;
add_action(
Channels::ACTION_LOGGER,
function ( Logger $logger, HandlersRegistry $handlers ) use ( $handler_id, $channels ) {
if ( $channels === [] || in_array( $logger->getName(), $channels, TRUE ) ) {
$logger->pushHandler( $handlers->find( $handler_id ) );
}
},
10,
2
);
return $this;
} | [
"public",
"function",
"use_handler",
"(",
"HandlerInterface",
"$",
"handler",
",",
"array",
"$",
"channels",
"=",
"[",
"]",
",",
"$",
"handler_id",
"=",
"NULL",
")",
"{",
"add_action",
"(",
"HandlersRegistry",
"::",
"ACTION_REGISTER",
",",
"function",
"(",
"... | Tell Wonolog to make given handler available to loggers with given id. If one or more channels are passed,
the handler will be attached to related Monolog loggers.
@param HandlerInterface $handler
@param string[] $channels
@param string|NULL $handler_id
@return Controller | [
"Tell",
"Wonolog",
"to",
"make",
"given",
"handler",
"available",
"to",
"loggers",
"with",
"given",
"id",
".",
"If",
"one",
"or",
"more",
"channels",
"are",
"passed",
"the",
"handler",
"will",
"be",
"attached",
"to",
"related",
"Monolog",
"loggers",
"."
] | 87ed9a60c6f5cc3a057db857273dc504efc5ad9f | https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Controller.php#L165-L191 | train |
inpsyde/Wonolog | src/Controller.php | Controller.use_default_processor | public function use_default_processor( callable $processor = null ) {
static $done = FALSE;
if ( $done ) {
return $this;
}
$done = TRUE;
add_action(
ProcessorsRegistry::ACTION_REGISTER,
function ( ProcessorsRegistry $registry ) use ($processor) {
$processor or $processor = new WpContextProcessor();
$registry->add_processor( $processor, ProcessorsRegistry::DEFAULT_NAME );
}
);
return $this;
} | php | public function use_default_processor( callable $processor = null ) {
static $done = FALSE;
if ( $done ) {
return $this;
}
$done = TRUE;
add_action(
ProcessorsRegistry::ACTION_REGISTER,
function ( ProcessorsRegistry $registry ) use ($processor) {
$processor or $processor = new WpContextProcessor();
$registry->add_processor( $processor, ProcessorsRegistry::DEFAULT_NAME );
}
);
return $this;
} | [
"public",
"function",
"use_default_processor",
"(",
"callable",
"$",
"processor",
"=",
"null",
")",
"{",
"static",
"$",
"done",
"=",
"FALSE",
";",
"if",
"(",
"$",
"done",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"done",
"=",
"TRUE",
";",
"add_... | Tell Wonolog to use default log processor.
@param callable $processor
@return Controller | [
"Tell",
"Wonolog",
"to",
"use",
"default",
"log",
"processor",
"."
] | 87ed9a60c6f5cc3a057db857273dc504efc5ad9f | https://github.com/inpsyde/Wonolog/blob/87ed9a60c6f5cc3a057db857273dc504efc5ad9f/src/Controller.php#L200-L219 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.