repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
swoft-cloud/swoft-framework
src/Log/Logger.php
Logger.profileEnd
public function profileEnd($name) { if (! $this->enable || \is_string($name) === false || empty($name)) { return; } $cid = Coroutine::tid(); if (! isset($this->profiles[$cid][$name])) { $this->profiles[$cid][$name] = [ 'cost' => 0, 'total' => 0, ]; } $this->profiles[$cid][$name]['cost'] += microtime(true) - $this->profileStacks[$cid][$name]['start']; $this->profiles[$cid][$name]['total'] += 1; }
php
public function profileEnd($name) { if (! $this->enable || \is_string($name) === false || empty($name)) { return; } $cid = Coroutine::tid(); if (! isset($this->profiles[$cid][$name])) { $this->profiles[$cid][$name] = [ 'cost' => 0, 'total' => 0, ]; } $this->profiles[$cid][$name]['cost'] += microtime(true) - $this->profileStacks[$cid][$name]['start']; $this->profiles[$cid][$name]['total'] += 1; }
[ "public", "function", "profileEnd", "(", "$", "name", ")", "{", "if", "(", "!", "$", "this", "->", "enable", "||", "\\", "is_string", "(", "$", "name", ")", "===", "false", "||", "empty", "(", "$", "name", ")", ")", "{", "return", ";", "}", "$", ...
标记开始 @param string $name 标记名称
[ "标记开始" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Log/Logger.php#L215-L231
swoft-cloud/swoft-framework
src/Log/Logger.php
Logger.getProfilesInfos
public function getProfilesInfos() { $profileAry = []; $cid = Coroutine::tid(); $profiles = $this->profiles[$cid] ?? []; foreach ($profiles as $key => $profile) { if (!isset($profile['cost'], $profile['total'])) { continue; } $cost = sprintf('%.2f', $profile['cost'] * 1000); $profileAry[] = "$key=" . $cost . '(ms)/' . $profile['total']; } return implode(',', $profileAry); }
php
public function getProfilesInfos() { $profileAry = []; $cid = Coroutine::tid(); $profiles = $this->profiles[$cid] ?? []; foreach ($profiles as $key => $profile) { if (!isset($profile['cost'], $profile['total'])) { continue; } $cost = sprintf('%.2f', $profile['cost'] * 1000); $profileAry[] = "$key=" . $cost . '(ms)/' . $profile['total']; } return implode(',', $profileAry); }
[ "public", "function", "getProfilesInfos", "(", ")", "{", "$", "profileAry", "=", "[", "]", ";", "$", "cid", "=", "Coroutine", "::", "tid", "(", ")", ";", "$", "profiles", "=", "$", "this", "->", "profiles", "[", "$", "cid", "]", "??", "[", "]", "...
组装profiles
[ "组装profiles" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Log/Logger.php#L236-L250
swoft-cloud/swoft-framework
src/Log/Logger.php
Logger.counting
public function counting($name, $hit, $total = null) { if (! \is_string($name) || empty($name)) { return; } $cid = Coroutine::tid(); if (! isset($this->countings[$cid][$name])) { $this->countings[$cid][$name] = ['hit' => 0, 'total' => 0]; } $this->countings[$cid][$name]['hit'] += (int)$hit; if ($total !== null) { $this->countings[$cid][$name]['total'] += (int)$total; } }
php
public function counting($name, $hit, $total = null) { if (! \is_string($name) || empty($name)) { return; } $cid = Coroutine::tid(); if (! isset($this->countings[$cid][$name])) { $this->countings[$cid][$name] = ['hit' => 0, 'total' => 0]; } $this->countings[$cid][$name]['hit'] += (int)$hit; if ($total !== null) { $this->countings[$cid][$name]['total'] += (int)$total; } }
[ "public", "function", "counting", "(", "$", "name", ",", "$", "hit", ",", "$", "total", "=", "null", ")", "{", "if", "(", "!", "\\", "is_string", "(", "$", "name", ")", "||", "empty", "(", "$", "name", ")", ")", "{", "return", ";", "}", "$", ...
缓存命中率计算 @param string $name 计算KEY @param int $hit 命中数 @param int $total 总数
[ "缓存命中率计算" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Log/Logger.php#L259-L273
swoft-cloud/swoft-framework
src/Log/Logger.php
Logger.getCountingInfo
public function getCountingInfo() { $cid = Coroutine::tid(); if (! isset($this->countings[$cid]) || empty($this->countings[$cid])) { return ''; } $countAry = []; $countings = $this->countings[$cid]; foreach ($countings ?? [] as $name => $counter) { if (isset($counter['hit'], $counter['total']) && $counter['total'] !== 0) { $countAry[] = "$name=" . $counter['hit'] . '/' . $counter['total']; } elseif (isset($counter['hit'])) { $countAry[] = "$name=" . $counter['hit']; } } return implode(',', $countAry); }
php
public function getCountingInfo() { $cid = Coroutine::tid(); if (! isset($this->countings[$cid]) || empty($this->countings[$cid])) { return ''; } $countAry = []; $countings = $this->countings[$cid]; foreach ($countings ?? [] as $name => $counter) { if (isset($counter['hit'], $counter['total']) && $counter['total'] !== 0) { $countAry[] = "$name=" . $counter['hit'] . '/' . $counter['total']; } elseif (isset($counter['hit'])) { $countAry[] = "$name=" . $counter['hit']; } } return implode(',', $countAry); }
[ "public", "function", "getCountingInfo", "(", ")", "{", "$", "cid", "=", "Coroutine", "::", "tid", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "countings", "[", "$", "cid", "]", ")", "||", "empty", "(", "$", "this", "->", "cou...
组装字符串
[ "组装字符串" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Log/Logger.php#L278-L295
swoft-cloud/swoft-framework
src/Log/Logger.php
Logger.getTrace
public function getTrace($message): string { $traces = debug_backtrace(); $count = \count($traces); $ex = ''; if ($count >= 7) { $info = $traces[6]; if (isset($info['file'], $info['line'])) { $filename = basename($info['file']); $lineNum = $info['line']; $ex = "$filename:$lineNum"; } } if ($count >= 8) { $info = $traces[7]; if (isset($info['class'], $info['type'], $info['function'])) { $ex .= ',' . $info['class'] . $info['type'] . $info['function']; } elseif (isset($info['function'])) { $ex .= ',' . $info['function']; } } if (!empty($ex)) { $message = "trace[$ex] " . $message; } return $message; }
php
public function getTrace($message): string { $traces = debug_backtrace(); $count = \count($traces); $ex = ''; if ($count >= 7) { $info = $traces[6]; if (isset($info['file'], $info['line'])) { $filename = basename($info['file']); $lineNum = $info['line']; $ex = "$filename:$lineNum"; } } if ($count >= 8) { $info = $traces[7]; if (isset($info['class'], $info['type'], $info['function'])) { $ex .= ',' . $info['class'] . $info['type'] . $info['function']; } elseif (isset($info['function'])) { $ex .= ',' . $info['function']; } } if (!empty($ex)) { $message = "trace[$ex] " . $message; } return $message; }
[ "public", "function", "getTrace", "(", "$", "message", ")", ":", "string", "{", "$", "traces", "=", "debug_backtrace", "(", ")", ";", "$", "count", "=", "\\", "count", "(", "$", "traces", ")", ";", "$", "ex", "=", "''", ";", "if", "(", "$", "coun...
计算调用trace @param $message @return string
[ "计算调用trace" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Log/Logger.php#L317-L345
swoft-cloud/swoft-framework
src/Log/Logger.php
Logger.flushLog
public function flushLog() { if (empty($this->messages)) { return; } reset($this->handlers); while ($handler = current($this->handlers)) { $handler->handleBatch($this->messages); next($this->handlers); } // 清空数组 $this->messages = []; }
php
public function flushLog() { if (empty($this->messages)) { return; } reset($this->handlers); while ($handler = current($this->handlers)) { $handler->handleBatch($this->messages); next($this->handlers); } // 清空数组 $this->messages = []; }
[ "public", "function", "flushLog", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "messages", ")", ")", "{", "return", ";", "}", "reset", "(", "$", "this", "->", "handlers", ")", ";", "while", "(", "$", "handler", "=", "current", "(", ...
刷新日志到handlers
[ "刷新日志到handlers" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Log/Logger.php#L350-L365
swoft-cloud/swoft-framework
src/Log/Logger.php
Logger.appendNoticeLog
public function appendNoticeLog($flush = false) { if (! $this->enable) { return; } $cid = Coroutine::tid(); $ts = $this->getLoggerTime(); // php耗时单位ms毫秒 $timeUsed = sprintf('%.2f', (microtime(true) - $this->getRequestTime()) * 1000); // php运行内存大小单位M $memUsed = sprintf('%.0f', memory_get_peak_usage() / (1024 * 1024)); $profileInfo = $this->getProfilesInfos(); $countingInfo = $this->getCountingInfo(); $pushlogs = $this->pushlogs[$cid] ?? []; $messageAry = array( "[$timeUsed(ms)]", "[$memUsed(MB)]", "[{$this->getUri()}]", '[' . implode(' ', $pushlogs) . ']', 'profile[' . $profileInfo . ']', 'counting[' . $countingInfo . ']' ); $message = implode(' ', $messageAry); unset($this->profiles[$cid], $this->countings[$cid], $this->pushlogs[$cid], $this->profileStacks[$cid]); $levelName = self::$levels[self::NOTICE]; $message = $this->formateRecord($message, [], self::NOTICE, $levelName, $ts, []); $this->messages[] = $message; // 一个请求完成刷新一次或达到刷新的次数 $isReached = \count($this->messages) >= $this->flushInterval; if ($this->flushRequest || $isReached || $flush) { $this->flushLog(); } }
php
public function appendNoticeLog($flush = false) { if (! $this->enable) { return; } $cid = Coroutine::tid(); $ts = $this->getLoggerTime(); // php耗时单位ms毫秒 $timeUsed = sprintf('%.2f', (microtime(true) - $this->getRequestTime()) * 1000); // php运行内存大小单位M $memUsed = sprintf('%.0f', memory_get_peak_usage() / (1024 * 1024)); $profileInfo = $this->getProfilesInfos(); $countingInfo = $this->getCountingInfo(); $pushlogs = $this->pushlogs[$cid] ?? []; $messageAry = array( "[$timeUsed(ms)]", "[$memUsed(MB)]", "[{$this->getUri()}]", '[' . implode(' ', $pushlogs) . ']', 'profile[' . $profileInfo . ']', 'counting[' . $countingInfo . ']' ); $message = implode(' ', $messageAry); unset($this->profiles[$cid], $this->countings[$cid], $this->pushlogs[$cid], $this->profileStacks[$cid]); $levelName = self::$levels[self::NOTICE]; $message = $this->formateRecord($message, [], self::NOTICE, $levelName, $ts, []); $this->messages[] = $message; // 一个请求完成刷新一次或达到刷新的次数 $isReached = \count($this->messages) >= $this->flushInterval; if ($this->flushRequest || $isReached || $flush) { $this->flushLog(); } }
[ "public", "function", "appendNoticeLog", "(", "$", "flush", "=", "false", ")", "{", "if", "(", "!", "$", "this", "->", "enable", ")", "{", "return", ";", "}", "$", "cid", "=", "Coroutine", "::", "tid", "(", ")", ";", "$", "ts", "=", "$", "this", ...
请求完成追加一条notice日志 @param bool $flush 是否刷新日志
[ "请求完成追加一条notice日志" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Log/Logger.php#L372-L414
swoft-cloud/swoft-framework
src/Log/Logger.php
Logger.getLoggerTime
private function getLoggerTime() { if (! static::$timezone) { static::$timezone = new \DateTimeZone(date_default_timezone_get() ? : 'UTC'); } // php7.1+ always has microseconds enabled, so we do not need this hack if ($this->microsecondTimestamps && PHP_VERSION_ID < 70100) { $ts = \DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true)), static::$timezone); } else { $ts = new \DateTime(null, static::$timezone); } $ts->setTimezone(static::$timezone); return $ts; }
php
private function getLoggerTime() { if (! static::$timezone) { static::$timezone = new \DateTimeZone(date_default_timezone_get() ? : 'UTC'); } // php7.1+ always has microseconds enabled, so we do not need this hack if ($this->microsecondTimestamps && PHP_VERSION_ID < 70100) { $ts = \DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true)), static::$timezone); } else { $ts = new \DateTime(null, static::$timezone); } $ts->setTimezone(static::$timezone); return $ts; }
[ "private", "function", "getLoggerTime", "(", ")", "{", "if", "(", "!", "static", "::", "$", "timezone", ")", "{", "static", "::", "$", "timezone", "=", "new", "\\", "DateTimeZone", "(", "date_default_timezone_get", "(", ")", "?", ":", "'UTC'", ")", ";", ...
获取去日志时间 @return \DateTime
[ "获取去日志时间" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Log/Logger.php#L421-L436
swoft-cloud/swoft-framework
src/Log/Logger.php
Logger.initialize
public function initialize() { $this->profiles = []; $this->countings = []; $this->pushlogs = []; $this->profileStacks = []; $this->messages = []; }
php
public function initialize() { $this->profiles = []; $this->countings = []; $this->pushlogs = []; $this->profileStacks = []; $this->messages = []; }
[ "public", "function", "initialize", "(", ")", "{", "$", "this", "->", "profiles", "=", "[", "]", ";", "$", "this", "->", "countings", "=", "[", "]", ";", "$", "this", "->", "pushlogs", "=", "[", "]", ";", "$", "this", "->", "profileStacks", "=", ...
日志初始化
[ "日志初始化" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Log/Logger.php#L441-L449
swoft-cloud/swoft-framework
src/Validator/EnumValidator.php
EnumValidator.validate
public function validate(...$params) { list($name, $value, $validValues, $throws, $template) = $params; return ValidatorHelper::validateEnum($name, $value, $validValues, $throws, $template); }
php
public function validate(...$params) { list($name, $value, $validValues, $throws, $template) = $params; return ValidatorHelper::validateEnum($name, $value, $validValues, $throws, $template); }
[ "public", "function", "validate", "(", "...", "$", "params", ")", "{", "list", "(", "$", "name", ",", "$", "value", ",", "$", "validValues", ",", "$", "throws", ",", "$", "template", ")", "=", "$", "params", ";", "return", "ValidatorHelper", "::", "v...
@param array ...$params @return mixed @throws \Swoft\Exception\ValidatorException
[ "@param", "array", "...", "$params" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Validator/EnumValidator.php#L20-L25
swoft-cloud/swoft-framework
src/Proxy/Handler/AopHandler.php
AopHandler.invoke
public function invoke($method, $parameters) { /* @var Aop $aop */ $aop = \bean(Aop::class); return $aop->execute($this->target, $method, $parameters); }
php
public function invoke($method, $parameters) { /* @var Aop $aop */ $aop = \bean(Aop::class); return $aop->execute($this->target, $method, $parameters); }
[ "public", "function", "invoke", "(", "$", "method", ",", "$", "parameters", ")", "{", "/* @var Aop $aop */", "$", "aop", "=", "\\", "bean", "(", "Aop", "::", "class", ")", ";", "return", "$", "aop", "->", "execute", "(", "$", "this", "->", "target", ...
ProceedingJoinPoint @param $method @param $parameters @return mixed @throws \ReflectionException @throws \Throwable
[ "ProceedingJoinPoint" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Proxy/Handler/AopHandler.php#L38-L44
swoft-cloud/swoft-framework
src/Helper/DocumentHelper.php
DocumentHelper.tagList
public static function tagList(string $comment) { $comment = "@Description \n" . strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/'))), "\r", ''); $parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY); $tags = []; foreach ($parts as $part) { $isMatch = preg_match('/^(\w+)(.*)/ms', trim($part), $matches); if ($isMatch == false) { continue; } $name = $matches[1]; if (!isset($tags[$name])) { $tags[$name] = trim($matches[2]); continue; } if (is_array($tags[$name])) { $tags[$name][] = trim($matches[2]); continue; } $tags[$name] = [$tags[$name], trim($matches[2])]; } return $tags; }
php
public static function tagList(string $comment) { $comment = "@Description \n" . strtr(trim(preg_replace('/^\s*\**( |\t)?/m', '', trim($comment, '/'))), "\r", ''); $parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY); $tags = []; foreach ($parts as $part) { $isMatch = preg_match('/^(\w+)(.*)/ms', trim($part), $matches); if ($isMatch == false) { continue; } $name = $matches[1]; if (!isset($tags[$name])) { $tags[$name] = trim($matches[2]); continue; } if (is_array($tags[$name])) { $tags[$name][] = trim($matches[2]); continue; } $tags[$name] = [$tags[$name], trim($matches[2])]; } return $tags; }
[ "public", "static", "function", "tagList", "(", "string", "$", "comment", ")", "{", "$", "comment", "=", "\"@Description \\n\"", ".", "strtr", "(", "trim", "(", "preg_replace", "(", "'/^\\s*\\**( |\\t)?/m'", ",", "''", ",", "trim", "(", "$", "comment", ",", ...
解析注解文档 @param string $comment 注解文档 @return array
[ "解析注解文档" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Helper/DocumentHelper.php#L23-L47
swoft-cloud/swoft-framework
src/Helper/StringHelper.php
StringHelper.ascii
public static function ascii($value) { foreach (static::charsArray() as $key => $val) { $value = str_replace($val, $key, $value); } return preg_replace('/[^\x20-\x7E]/u', '', $value); }
php
public static function ascii($value) { foreach (static::charsArray() as $key => $val) { $value = str_replace($val, $key, $value); } return preg_replace('/[^\x20-\x7E]/u', '', $value); }
[ "public", "static", "function", "ascii", "(", "$", "value", ")", "{", "foreach", "(", "static", "::", "charsArray", "(", ")", "as", "$", "key", "=>", "$", "val", ")", "{", "$", "value", "=", "str_replace", "(", "$", "val", ",", "$", "key", ",", "...
Transliterate a UTF-8 value to ASCII. @param string $value @return string
[ "Transliterate", "a", "UTF", "-", "8", "value", "to", "ASCII", "." ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Helper/StringHelper.php#L44-L51
swoft-cloud/swoft-framework
src/Helper/StringHelper.php
StringHelper.randomString
public static function randomString($type = 'alnum', $length = 8) { $utf8 = false; switch ($type) { case 'alnum': $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'alpha': $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'lowalnum': $pool = '0123456789abcdefghijklmnopqrstuvwxyz'; break; case 'hexdec': $pool = '0123456789abcdef'; break; case 'numeric': $pool = '0123456789'; break; case 'nozero': $pool = '123456789'; break; case 'distinct': $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ'; break; default: $pool = (string)$type; $utf8 = ! self::isAscii($pool); break; } // Split the pool into an array of characters $pool = ($utf8 === true) ? self::strSplit($pool, 1) : str_split($pool, 1); // Largest pool key $max = count($pool) - 1; $str = ''; for ($i = 0; $i < $length; $i++) { // Select a random character from the pool and add it to the string $str .= $pool[mt_rand(0, $max)]; } // Make sure alnum strings contain at least one letter and one digit if ($type === 'alnum' and $length > 1) { if (ctype_alpha($str)) { // Add a random digit $str[mt_rand(0, $length - 1)] = chr(mt_rand(48, 57)); } elseif (ctype_digit($str)) { // Add a random letter $str[mt_rand(0, $length - 1)] = chr(mt_rand(65, 90)); } } return $str; }
php
public static function randomString($type = 'alnum', $length = 8) { $utf8 = false; switch ($type) { case 'alnum': $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'alpha': $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; break; case 'lowalnum': $pool = '0123456789abcdefghijklmnopqrstuvwxyz'; break; case 'hexdec': $pool = '0123456789abcdef'; break; case 'numeric': $pool = '0123456789'; break; case 'nozero': $pool = '123456789'; break; case 'distinct': $pool = '2345679ACDEFHJKLMNPRSTUVWXYZ'; break; default: $pool = (string)$type; $utf8 = ! self::isAscii($pool); break; } // Split the pool into an array of characters $pool = ($utf8 === true) ? self::strSplit($pool, 1) : str_split($pool, 1); // Largest pool key $max = count($pool) - 1; $str = ''; for ($i = 0; $i < $length; $i++) { // Select a random character from the pool and add it to the string $str .= $pool[mt_rand(0, $max)]; } // Make sure alnum strings contain at least one letter and one digit if ($type === 'alnum' and $length > 1) { if (ctype_alpha($str)) { // Add a random digit $str[mt_rand(0, $length - 1)] = chr(mt_rand(48, 57)); } elseif (ctype_digit($str)) { // Add a random letter $str[mt_rand(0, $length - 1)] = chr(mt_rand(65, 90)); } } return $str; }
[ "public", "static", "function", "randomString", "(", "$", "type", "=", "'alnum'", ",", "$", "length", "=", "8", ")", "{", "$", "utf8", "=", "false", ";", "switch", "(", "$", "type", ")", "{", "case", "'alnum'", ":", "$", "pool", "=", "'0123456789abcd...
Generates a random string of a given type and length. Possible values for the first argument ($type) are: - alnum - alpha-numeric characters (including capitals) - alpha - alphabetical characters (including capitals) - hexdec - hexadecimal characters, 0-9 plus a-f - numeric - digit characters, 0-9 - nozero - digit characters, 1-9 - distinct - clearly distinct alpha-numeric characters. For values that do not match any of the above, the characters passed in will be used. ##### Example echo Str::random('alpha', 20); // Output: DdyQFCddSKeTkfjCewPa echo Str::random('distinct', 20); // Output: XCDDVXV7FUSYAVXFFKSL @param string $type A type of pool, or a string of characters to use as the pool @param integer $length Length of string to return @return string
[ "Generates", "a", "random", "string", "of", "a", "given", "type", "and", "length", ".", "Possible", "values", "for", "the", "first", "argument", "(", "$type", ")", "are", ":", "-", "alnum", "-", "alpha", "-", "numeric", "characters", "(", "including", "c...
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Helper/StringHelper.php#L1033-L1089
swoft-cloud/swoft-framework
src/Bean/Parser/PoolParser.php
PoolParser.parser
public function parser( string $className, $objectAnnotation = null, string $propertyName = "", string $methodName = "", $propertyValue = null ) { PoolCollector::collect($className, $objectAnnotation, $propertyName, $methodName, $propertyValue); return [$className, Scope::SINGLETON, ""]; }
php
public function parser( string $className, $objectAnnotation = null, string $propertyName = "", string $methodName = "", $propertyValue = null ) { PoolCollector::collect($className, $objectAnnotation, $propertyName, $methodName, $propertyValue); return [$className, Scope::SINGLETON, ""]; }
[ "public", "function", "parser", "(", "string", "$", "className", ",", "$", "objectAnnotation", "=", "null", ",", "string", "$", "propertyName", "=", "\"\"", ",", "string", "$", "methodName", "=", "\"\"", ",", "$", "propertyValue", "=", "null", ")", "{", ...
@param string $className @param Pool $objectAnnotation @param string $propertyName @param string $methodName @param null $propertyValue @return mixed
[ "@param", "string", "$className", "@param", "Pool", "$objectAnnotation", "@param", "string", "$propertyName", "@param", "string", "$methodName", "@param", "null", "$propertyValue" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Parser/PoolParser.php#L29-L39
swoft-cloud/swoft-framework
src/Bean/Parser/CachePutParser.php
CachePutParser.parser
public function parser(string $className, $objectAnnotation = null, string $propertyName = "", string $methodName = "", $propertyValue = null) { Collector::$methodAnnotations[$className][$methodName][] = get_class($objectAnnotation); return null; }
php
public function parser(string $className, $objectAnnotation = null, string $propertyName = "", string $methodName = "", $propertyValue = null) { Collector::$methodAnnotations[$className][$methodName][] = get_class($objectAnnotation); return null; }
[ "public", "function", "parser", "(", "string", "$", "className", ",", "$", "objectAnnotation", "=", "null", ",", "string", "$", "propertyName", "=", "\"\"", ",", "string", "$", "methodName", "=", "\"\"", ",", "$", "propertyValue", "=", "null", ")", "{", ...
RequestMapping注解解析 @param string $className @param CachePut $objectAnnotation @param string $propertyName @param string $methodName @param null $propertyValue @return mixed
[ "RequestMapping注解解析" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Parser/CachePutParser.php#L29-L33
swoft-cloud/swoft-framework
src/Helper/PhpHelper.php
PhpHelper.call
public static function call($cb, array $args = []) { $ret = null; if (\is_object($cb) || (\is_string($cb) && \function_exists($cb))) { $ret = $cb(...$args); } elseif (\is_array($cb)) { list($obj, $mhd) = $cb; $ret = \is_object($obj) ? $obj->$mhd(...$args) : $obj::$mhd(...$args); } else { if (SWOOLE_VERSION >= '4.0') { $ret = call_user_func_array($cb, $args); } else { $ret = \Swoole\Coroutine::call_user_func_array($cb, $args); } } return $ret; }
php
public static function call($cb, array $args = []) { $ret = null; if (\is_object($cb) || (\is_string($cb) && \function_exists($cb))) { $ret = $cb(...$args); } elseif (\is_array($cb)) { list($obj, $mhd) = $cb; $ret = \is_object($obj) ? $obj->$mhd(...$args) : $obj::$mhd(...$args); } else { if (SWOOLE_VERSION >= '4.0') { $ret = call_user_func_array($cb, $args); } else { $ret = \Swoole\Coroutine::call_user_func_array($cb, $args); } } return $ret; }
[ "public", "static", "function", "call", "(", "$", "cb", ",", "array", "$", "args", "=", "[", "]", ")", "{", "$", "ret", "=", "null", ";", "if", "(", "\\", "is_object", "(", "$", "cb", ")", "||", "(", "\\", "is_string", "(", "$", "cb", ")", "&...
调用 @param mixed $cb callback函数,多种格式 @param array $args 参数 @return mixed
[ "调用" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Helper/PhpHelper.php#L40-L57
swoft-cloud/swoft-framework
src/Bean/Container.php
Container.get
public function get(string $name) { // 已经创建 if (isset($this->singletonEntries[$name])) { return $this->singletonEntries[$name]; } // 未定义 if (!isset($this->definitions[$name])) { throw new \InvalidArgumentException(sprintf('Bean %s not exist', $name)); } /* @var ObjectDefinition $objectDefinition */ $objectDefinition = $this->definitions[$name]; return $this->set($name, $objectDefinition); }
php
public function get(string $name) { // 已经创建 if (isset($this->singletonEntries[$name])) { return $this->singletonEntries[$name]; } // 未定义 if (!isset($this->definitions[$name])) { throw new \InvalidArgumentException(sprintf('Bean %s not exist', $name)); } /* @var ObjectDefinition $objectDefinition */ $objectDefinition = $this->definitions[$name]; return $this->set($name, $objectDefinition); }
[ "public", "function", "get", "(", "string", "$", "name", ")", "{", "// 已经创建", "if", "(", "isset", "(", "$", "this", "->", "singletonEntries", "[", "$", "name", "]", ")", ")", "{", "return", "$", "this", "->", "singletonEntries", "[", "$", "name", "]"...
获取一个bean @param string $name 名称 @return mixed @throws \ReflectionException @throws \InvalidArgumentException
[ "获取一个bean" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Container.php#L68-L84
swoft-cloud/swoft-framework
src/Bean/Container.php
Container.addDefinitions
public function addDefinitions(array $definitions) { $resource = new DefinitionResource($definitions); $this->definitions = array_merge($resource->getDefinitions(), $this->definitions); }
php
public function addDefinitions(array $definitions) { $resource = new DefinitionResource($definitions); $this->definitions = array_merge($resource->getDefinitions(), $this->definitions); }
[ "public", "function", "addDefinitions", "(", "array", "$", "definitions", ")", "{", "$", "resource", "=", "new", "DefinitionResource", "(", "$", "definitions", ")", ";", "$", "this", "->", "definitions", "=", "array_merge", "(", "$", "resource", "->", "getDe...
定义配置bean @param array $definitions
[ "定义配置bean" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Container.php#L103-L107
swoft-cloud/swoft-framework
src/Bean/Container.php
Container.autoloadServerAnnotation
public function autoloadServerAnnotation() { $bootScan = $this->getScanNamespaceFromProperties('bootScan'); $resource = new ServerAnnotationResource($this->properties); $resource->addScanNamespace($bootScan); $definitions = $resource->getDefinitions(); $this->definitions = array_merge($definitions, $this->definitions); }
php
public function autoloadServerAnnotation() { $bootScan = $this->getScanNamespaceFromProperties('bootScan'); $resource = new ServerAnnotationResource($this->properties); $resource->addScanNamespace($bootScan); $definitions = $resource->getDefinitions(); $this->definitions = array_merge($definitions, $this->definitions); }
[ "public", "function", "autoloadServerAnnotation", "(", ")", "{", "$", "bootScan", "=", "$", "this", "->", "getScanNamespaceFromProperties", "(", "'bootScan'", ")", ";", "$", "resource", "=", "new", "ServerAnnotationResource", "(", "$", "this", "->", "properties", ...
Register the annotation of server
[ "Register", "the", "annotation", "of", "server" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Container.php#L112-L120
swoft-cloud/swoft-framework
src/Bean/Container.php
Container.autoloadWorkerAnnotation
public function autoloadWorkerAnnotation() { $beanScan = $this->getBeanScanNamespace(); $resource = new WorkerAnnotationResource($this->properties); $resource->addScanNamespace($beanScan); $definitions = $resource->getDefinitions(); $this->definitions = \array_merge($definitions, $this->definitions); }
php
public function autoloadWorkerAnnotation() { $beanScan = $this->getBeanScanNamespace(); $resource = new WorkerAnnotationResource($this->properties); $resource->addScanNamespace($beanScan); $definitions = $resource->getDefinitions(); $this->definitions = \array_merge($definitions, $this->definitions); }
[ "public", "function", "autoloadWorkerAnnotation", "(", ")", "{", "$", "beanScan", "=", "$", "this", "->", "getBeanScanNamespace", "(", ")", ";", "$", "resource", "=", "new", "WorkerAnnotationResource", "(", "$", "this", "->", "properties", ")", ";", "$", "re...
Register the annotation of worker
[ "Register", "the", "annotation", "of", "worker" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Container.php#L125-L133
swoft-cloud/swoft-framework
src/Bean/Container.php
Container.set
private function set(string $name, ObjectDefinition $objectDefinition) { // bean创建信息 $scope = $objectDefinition->getScope(); $className = $objectDefinition->getClassName(); $propertyInjects = $objectDefinition->getPropertyInjections(); $constructorInject = $objectDefinition->getConstructorInjection(); if ($refBeanName = $objectDefinition->getRef()) { return $this->get($refBeanName); } // 构造函数 $constructorParameters = []; if ($constructorInject !== null) { $constructorParameters = $this->injectConstructor($constructorInject); } $reflectionClass = new \ReflectionClass($className); $properties = $reflectionClass->getProperties(); // new实例 $isExeMethod = $reflectionClass->hasMethod($this->initMethod); $object = $this->newBeanInstance($reflectionClass, $constructorParameters); // 属性注入 $this->injectProperties($object, $properties, $propertyInjects); // 执行初始化方法 if ($isExeMethod) { $object->{$this->initMethod}(); } if (!$object instanceof AopInterface) { $object = $this->proxyBean($name, $className, $object); } // 单例处理 if ($scope === Scope::SINGLETON) { $this->singletonEntries[$name] = $object; } return $object; }
php
private function set(string $name, ObjectDefinition $objectDefinition) { // bean创建信息 $scope = $objectDefinition->getScope(); $className = $objectDefinition->getClassName(); $propertyInjects = $objectDefinition->getPropertyInjections(); $constructorInject = $objectDefinition->getConstructorInjection(); if ($refBeanName = $objectDefinition->getRef()) { return $this->get($refBeanName); } // 构造函数 $constructorParameters = []; if ($constructorInject !== null) { $constructorParameters = $this->injectConstructor($constructorInject); } $reflectionClass = new \ReflectionClass($className); $properties = $reflectionClass->getProperties(); // new实例 $isExeMethod = $reflectionClass->hasMethod($this->initMethod); $object = $this->newBeanInstance($reflectionClass, $constructorParameters); // 属性注入 $this->injectProperties($object, $properties, $propertyInjects); // 执行初始化方法 if ($isExeMethod) { $object->{$this->initMethod}(); } if (!$object instanceof AopInterface) { $object = $this->proxyBean($name, $className, $object); } // 单例处理 if ($scope === Scope::SINGLETON) { $this->singletonEntries[$name] = $object; } return $object; }
[ "private", "function", "set", "(", "string", "$", "name", ",", "ObjectDefinition", "$", "objectDefinition", ")", "{", "// bean创建信息", "$", "scope", "=", "$", "objectDefinition", "->", "getScope", "(", ")", ";", "$", "className", "=", "$", "objectDefinition", ...
创建bean @param string $name 名称 @param ObjectDefinition $objectDefinition bean定义 @return object @throws \ReflectionException @throws \InvalidArgumentException
[ "创建bean" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Container.php#L196-L239
swoft-cloud/swoft-framework
src/Bean/Container.php
Container.proxyBean
private function proxyBean(string $name, string $className, $object) { if (!AspectCollector::hasClassname($className)) { return $object; } /* @var Aop $aop */ $aop = App::getBean(Aop::class); $rc = new \ReflectionClass($className); $rms = $rc->getMethods(); foreach ($rms as $rm) { $method = $rm->getName(); $annotations = Collector::$methodAnnotations[$className][$method] ?? []; $annotations = array_unique($annotations); $aop->match($name, $className, $method, $annotations); } $handler = new AopHandler($object); return Proxy::newProxyInstance(\get_class($object), $handler); }
php
private function proxyBean(string $name, string $className, $object) { if (!AspectCollector::hasClassname($className)) { return $object; } /* @var Aop $aop */ $aop = App::getBean(Aop::class); $rc = new \ReflectionClass($className); $rms = $rc->getMethods(); foreach ($rms as $rm) { $method = $rm->getName(); $annotations = Collector::$methodAnnotations[$className][$method] ?? []; $annotations = array_unique($annotations); $aop->match($name, $className, $method, $annotations); } $handler = new AopHandler($object); return Proxy::newProxyInstance(\get_class($object), $handler); }
[ "private", "function", "proxyBean", "(", "string", "$", "name", ",", "string", "$", "className", ",", "$", "object", ")", "{", "if", "(", "!", "AspectCollector", "::", "hasClassname", "(", "$", "className", ")", ")", "{", "return", "$", "object", ";", ...
proxy bean @param string $name @param string $className @param object $object @return object @throws \ReflectionException
[ "proxy", "bean" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Container.php#L251-L272
swoft-cloud/swoft-framework
src/Bean/Container.php
Container.injectConstructor
private function injectConstructor(MethodInjection $constructorInject): array { $constructorParameters = []; /* @var ArgsInjection $parameter */ foreach ($constructorInject->getParameters() as $parameter) { $argValue = $parameter->getValue(); if (\is_array($argValue)) { $constructorParameters[] = $this->injectArrayArgs($argValue); continue; } if ($parameter->isRef()) { $constructorParameters[] = $this->get($parameter->getValue()); continue; } $constructorParameters[] = $parameter->getValue(); } return $constructorParameters; }
php
private function injectConstructor(MethodInjection $constructorInject): array { $constructorParameters = []; /* @var ArgsInjection $parameter */ foreach ($constructorInject->getParameters() as $parameter) { $argValue = $parameter->getValue(); if (\is_array($argValue)) { $constructorParameters[] = $this->injectArrayArgs($argValue); continue; } if ($parameter->isRef()) { $constructorParameters[] = $this->get($parameter->getValue()); continue; } $constructorParameters[] = $parameter->getValue(); } return $constructorParameters; }
[ "private", "function", "injectConstructor", "(", "MethodInjection", "$", "constructorInject", ")", ":", "array", "{", "$", "constructorParameters", "=", "[", "]", ";", "/* @var ArgsInjection $parameter */", "foreach", "(", "$", "constructorInject", "->", "getParameters"...
获取构造函数参数 @param MethodInjection $constructorInject @return array @throws \InvalidArgumentException @throws \ReflectionException
[ "获取构造函数参数" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Container.php#L283-L302
swoft-cloud/swoft-framework
src/Bean/Container.php
Container.newBeanInstance
private function newBeanInstance(\ReflectionClass $reflectionClass, array $constructorParameters) { if ($reflectionClass->hasMethod('__construct')) { return $reflectionClass->newInstanceArgs($constructorParameters); } return $reflectionClass->newInstance(); }
php
private function newBeanInstance(\ReflectionClass $reflectionClass, array $constructorParameters) { if ($reflectionClass->hasMethod('__construct')) { return $reflectionClass->newInstanceArgs($constructorParameters); } return $reflectionClass->newInstance(); }
[ "private", "function", "newBeanInstance", "(", "\\", "ReflectionClass", "$", "reflectionClass", ",", "array", "$", "constructorParameters", ")", "{", "if", "(", "$", "reflectionClass", "->", "hasMethod", "(", "'__construct'", ")", ")", "{", "return", "$", "refle...
初始化Bean实例 @param \ReflectionClass $reflectionClass @param array $constructorParameters @return object
[ "初始化Bean实例" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Container.php#L312-L319
swoft-cloud/swoft-framework
src/Bean/Container.php
Container.injectProperties
private function injectProperties($object, array $properties, $propertyInjects) { foreach ($properties as $property) { if ($property->isStatic()) { continue; } $propertyName = $property->getName(); if (!isset($propertyInjects[$propertyName])) { continue; } // 设置可用 if (!$property->isPublic()) { $property->setAccessible(true); } /* @var PropertyInjection $propertyInject */ $propertyInject = $propertyInjects[$propertyName]; $injectProperty = $propertyInject->getValue(); // 属性是数组 if (\is_array($injectProperty)) { $injectProperty = $this->injectArrayArgs($injectProperty); } // 属性是bean引用 if ($propertyInject->isRef()) { $injectProperty = $this->get($injectProperty); } if ($injectProperty !== null) { $property->setValue($object, $injectProperty); } } }
php
private function injectProperties($object, array $properties, $propertyInjects) { foreach ($properties as $property) { if ($property->isStatic()) { continue; } $propertyName = $property->getName(); if (!isset($propertyInjects[$propertyName])) { continue; } // 设置可用 if (!$property->isPublic()) { $property->setAccessible(true); } /* @var PropertyInjection $propertyInject */ $propertyInject = $propertyInjects[$propertyName]; $injectProperty = $propertyInject->getValue(); // 属性是数组 if (\is_array($injectProperty)) { $injectProperty = $this->injectArrayArgs($injectProperty); } // 属性是bean引用 if ($propertyInject->isRef()) { $injectProperty = $this->get($injectProperty); } if ($injectProperty !== null) { $property->setValue($object, $injectProperty); } } }
[ "private", "function", "injectProperties", "(", "$", "object", ",", "array", "$", "properties", ",", "$", "propertyInjects", ")", "{", "foreach", "(", "$", "properties", "as", "$", "property", ")", "{", "if", "(", "$", "property", "->", "isStatic", "(", ...
注入属性 @param mixed $object @param \ReflectionProperty[] $properties $properties @param mixed $propertyInjects @throws \InvalidArgumentException @throws \ReflectionException
[ "注入属性" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Container.php#L331-L366
swoft-cloud/swoft-framework
src/Bean/Container.php
Container.injectArrayArgs
private function injectArrayArgs(array $injectProperty): array { $injectAry = []; foreach ($injectProperty as $key => $property) { // 递归循环注入 if (\is_array($property)) { $injectAry[$key] = $this->injectArrayArgs($property); continue; } // 参数注入 if ($property instanceof ArgsInjection) { $propertyValue = $property->getValue(); if ($property->isRef()) { $injectAry[$key] = $this->get($propertyValue); continue; } $injectAry[$key] = $propertyValue; } else { $injectAry[$key] = $property; } } if (empty($injectAry)) { $injectAry = $injectProperty; } return $injectAry; }
php
private function injectArrayArgs(array $injectProperty): array { $injectAry = []; foreach ($injectProperty as $key => $property) { // 递归循环注入 if (\is_array($property)) { $injectAry[$key] = $this->injectArrayArgs($property); continue; } // 参数注入 if ($property instanceof ArgsInjection) { $propertyValue = $property->getValue(); if ($property->isRef()) { $injectAry[$key] = $this->get($propertyValue); continue; } $injectAry[$key] = $propertyValue; } else { $injectAry[$key] = $property; } } if (empty($injectAry)) { $injectAry = $injectProperty; } return $injectAry; }
[ "private", "function", "injectArrayArgs", "(", "array", "$", "injectProperty", ")", ":", "array", "{", "$", "injectAry", "=", "[", "]", ";", "foreach", "(", "$", "injectProperty", "as", "$", "key", "=>", "$", "property", ")", "{", "// 递归循环注入", "if", "(",...
数组属性值注入 @param array $injectProperty @return array @throws \InvalidArgumentException @throws \ReflectionException
[ "数组属性值注入" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Container.php#L377-L405
swoft-cloud/swoft-framework
src/Bean/Container.php
Container.getScanNamespaceFromProperties
private function getScanNamespaceFromProperties(string $name) { $properties = $this->properties; if (!isset($properties[$name]) || !\is_array($properties[$name])) { return []; } return $properties[$name]; }
php
private function getScanNamespaceFromProperties(string $name) { $properties = $this->properties; if (!isset($properties[$name]) || !\is_array($properties[$name])) { return []; } return $properties[$name]; }
[ "private", "function", "getScanNamespaceFromProperties", "(", "string", "$", "name", ")", "{", "$", "properties", "=", "$", "this", "->", "properties", ";", "if", "(", "!", "isset", "(", "$", "properties", "[", "$", "name", "]", ")", "||", "!", "\\", "...
@param string $name @return array
[ "@param", "string", "$name" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Container.php#L412-L421
swoft-cloud/swoft-framework
src/Bean/Parser/BootstrapParser.php
BootstrapParser.parser
public function parser(string $className, $objectAnnotation = null, string $propertyName = "", string $methodName = "", $propertyValue = null) { $beanName = $className; $scope = Scope::SINGLETON; BootstrapCollector::collect($className, $objectAnnotation, $propertyName, $methodName, $propertyValue); return [$beanName, $scope, ""]; }
php
public function parser(string $className, $objectAnnotation = null, string $propertyName = "", string $methodName = "", $propertyValue = null) { $beanName = $className; $scope = Scope::SINGLETON; BootstrapCollector::collect($className, $objectAnnotation, $propertyName, $methodName, $propertyValue); return [$beanName, $scope, ""]; }
[ "public", "function", "parser", "(", "string", "$", "className", ",", "$", "objectAnnotation", "=", "null", ",", "string", "$", "propertyName", "=", "\"\"", ",", "string", "$", "methodName", "=", "\"\"", ",", "$", "propertyValue", "=", "null", ")", "{", ...
@param string $className @param Bootstrap $objectAnnotation @param string $propertyName @param string $methodName @param mixed $propertyValue @return array
[ "@param", "string", "$className", "@param", "Bootstrap", "$objectAnnotation", "@param", "string", "$propertyName", "@param", "string", "$methodName", "@param", "mixed", "$propertyValue" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Parser/BootstrapParser.php#L29-L37
swoft-cloud/swoft-framework
src/Aop/ProceedingJoinPoint.php
ProceedingJoinPoint.proceed
public function proceed($params = []) { // before if (isset($this->advice['before']) && !empty($this->advice['before'])) { list($aspectClass, $aspectMethod) = $this->advice['before']; $aspect = App::getBean($aspectClass); $aspect->$aspectMethod(); } if (empty($this->advices)) { // execute $methodParams = !empty($params) ? $params : $this->args; $result = $this->target->{$this->method}(...$methodParams); } else { /* @var \Swoft\Aop\Aop $aop */ $aop = App::getBean(Aop::class); $result = $aop->doAdvice($this->target, $this->method, $this->args, $this->advices); } return $result; }
php
public function proceed($params = []) { // before if (isset($this->advice['before']) && !empty($this->advice['before'])) { list($aspectClass, $aspectMethod) = $this->advice['before']; $aspect = App::getBean($aspectClass); $aspect->$aspectMethod(); } if (empty($this->advices)) { // execute $methodParams = !empty($params) ? $params : $this->args; $result = $this->target->{$this->method}(...$methodParams); } else { /* @var \Swoft\Aop\Aop $aop */ $aop = App::getBean(Aop::class); $result = $aop->doAdvice($this->target, $this->method, $this->args, $this->advices); } return $result; }
[ "public", "function", "proceed", "(", "$", "params", "=", "[", "]", ")", "{", "// before", "if", "(", "isset", "(", "$", "this", "->", "advice", "[", "'before'", "]", ")", "&&", "!", "empty", "(", "$", "this", "->", "advice", "[", "'before'", "]", ...
proceed @param array $params If the params is not empty, the params is used to call the method of target @return mixed
[ "proceed" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Aop/ProceedingJoinPoint.php#L52-L72
swoft-cloud/swoft-framework
src/Bean/Resource/CustomComponentsRegister.php
CustomComponentsRegister.registerServerNamespace
public function registerServerNamespace() { foreach ($this->customComponents as $ns => $componentDir) { if (is_int($ns)) { $ns = $componentDir; $componentDir = ComposerHelper::getDirByNamespace($ns); $ns = rtrim($ns, "\\"); $componentDir = rtrim($componentDir, "/"); } $this->componentNamespaces[] = $ns; $componentDir = alias($componentDir); foreach ($this->serverScan as $dir) { $scanDir = $componentDir . DS . $dir; if (!is_dir($scanDir)) { continue; } $scanNs = $ns . "\\" . $dir; $this->scanNamespaces[$scanNs] = $scanDir; } } }
php
public function registerServerNamespace() { foreach ($this->customComponents as $ns => $componentDir) { if (is_int($ns)) { $ns = $componentDir; $componentDir = ComposerHelper::getDirByNamespace($ns); $ns = rtrim($ns, "\\"); $componentDir = rtrim($componentDir, "/"); } $this->componentNamespaces[] = $ns; $componentDir = alias($componentDir); foreach ($this->serverScan as $dir) { $scanDir = $componentDir . DS . $dir; if (!is_dir($scanDir)) { continue; } $scanNs = $ns . "\\" . $dir; $this->scanNamespaces[$scanNs] = $scanDir; } } }
[ "public", "function", "registerServerNamespace", "(", ")", "{", "foreach", "(", "$", "this", "->", "customComponents", "as", "$", "ns", "=>", "$", "componentDir", ")", "{", "if", "(", "is_int", "(", "$", "ns", ")", ")", "{", "$", "ns", "=", "$", "com...
Register the server namespace @author limx
[ "Register", "the", "server", "namespace" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Resource/CustomComponentsRegister.php#L12-L35
swoft-cloud/swoft-framework
src/Bean/Resource/CustomComponentsRegister.php
CustomComponentsRegister.registerWorkerNamespace
public function registerWorkerNamespace() { foreach ($this->customComponents as $ns => $componentDir) { if (is_int($ns)) { $ns = $componentDir; $componentDir = ComposerHelper::getDirByNamespace($ns); $ns = rtrim($ns, "\\"); $componentDir = rtrim($componentDir, "/"); } $this->componentNamespaces[] = $ns; $componentDir = alias($componentDir); if (!is_dir($componentDir)) { continue; } $scanDirs = scandir($componentDir, null); foreach ($scanDirs as $dir) { if ($dir == '.' || $dir == '..') { continue; } if (\in_array($dir, $this->serverScan, true)) { continue; } $scanDir = $componentDir . DS . $dir; if (!is_dir($scanDir)) { $this->scanFiles[$ns][] = $scanDir; continue; } $scanNs = $ns . '\\' . $dir; $this->scanNamespaces[$scanNs] = $scanDir; } } }
php
public function registerWorkerNamespace() { foreach ($this->customComponents as $ns => $componentDir) { if (is_int($ns)) { $ns = $componentDir; $componentDir = ComposerHelper::getDirByNamespace($ns); $ns = rtrim($ns, "\\"); $componentDir = rtrim($componentDir, "/"); } $this->componentNamespaces[] = $ns; $componentDir = alias($componentDir); if (!is_dir($componentDir)) { continue; } $scanDirs = scandir($componentDir, null); foreach ($scanDirs as $dir) { if ($dir == '.' || $dir == '..') { continue; } if (\in_array($dir, $this->serverScan, true)) { continue; } $scanDir = $componentDir . DS . $dir; if (!is_dir($scanDir)) { $this->scanFiles[$ns][] = $scanDir; continue; } $scanNs = $ns . '\\' . $dir; $this->scanNamespaces[$scanNs] = $scanDir; } } }
[ "public", "function", "registerWorkerNamespace", "(", ")", "{", "foreach", "(", "$", "this", "->", "customComponents", "as", "$", "ns", "=>", "$", "componentDir", ")", "{", "if", "(", "is_int", "(", "$", "ns", ")", ")", "{", "$", "ns", "=", "$", "com...
Register the worker namespace @author limx
[ "Register", "the", "worker", "namespace" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Resource/CustomComponentsRegister.php#L41-L79
swoft-cloud/swoft-framework
src/Helper/JsonHelper.php
JsonHelper.encode
public static function encode($value, $options = 0, $depth = 512): string { if ($value instanceof Arrayable) { $value = $value->toArray(); } $json = \json_encode($value, $options, $depth); if (JSON_ERROR_NONE !== json_last_error()) { throw new \InvalidArgumentException('json_encode error: ' . json_last_error_msg()); } return $json; }
php
public static function encode($value, $options = 0, $depth = 512): string { if ($value instanceof Arrayable) { $value = $value->toArray(); } $json = \json_encode($value, $options, $depth); if (JSON_ERROR_NONE !== json_last_error()) { throw new \InvalidArgumentException('json_encode error: ' . json_last_error_msg()); } return $json; }
[ "public", "static", "function", "encode", "(", "$", "value", ",", "$", "options", "=", "0", ",", "$", "depth", "=", "512", ")", ":", "string", "{", "if", "(", "$", "value", "instanceof", "Arrayable", ")", "{", "$", "value", "=", "$", "value", "->",...
Wrapper for JSON encoding that throws when an error occurs. @param mixed $value The value being encoded @param int $options JSON encode option bitmask @param int $depth Set the maximum depth. Must be greater than zero. @return string @throws \InvalidArgumentException if the JSON cannot be encoded. @link http://www.php.net/manual/en/function.json-encode.php
[ "Wrapper", "for", "JSON", "encoding", "that", "throws", "when", "an", "error", "occurs", "." ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Helper/JsonHelper.php#L51-L62
swoft-cloud/swoft-framework
src/Helper/ComponentHelper.php
ComponentHelper.getComponentNamespace
public static function getComponentNamespace(string $component, string $path):string { $composerFile = $path . DS . 'composer.json'; $namespaceMapping = self::parseAutoloadFromComposerFile($composerFile); $ns = $namespaceMapping['src/'] ?? self::getDefaultNamespace($component); return $ns; }
php
public static function getComponentNamespace(string $component, string $path):string { $composerFile = $path . DS . 'composer.json'; $namespaceMapping = self::parseAutoloadFromComposerFile($composerFile); $ns = $namespaceMapping['src/'] ?? self::getDefaultNamespace($component); return $ns; }
[ "public", "static", "function", "getComponentNamespace", "(", "string", "$", "component", ",", "string", "$", "path", ")", ":", "string", "{", "$", "composerFile", "=", "$", "path", ".", "DS", ".", "'composer.json'", ";", "$", "namespaceMapping", "=", "self"...
@param string $component @param string $path @return string
[ "@param", "string", "$component", "@param", "string", "$path" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Helper/ComponentHelper.php#L16-L22
swoft-cloud/swoft-framework
src/Helper/ComponentHelper.php
ComponentHelper.getComponentNs
public static function getComponentNs(string $component): string { if ($component === 'framework') { return ''; } $namespace = ''; $nsAry = explode('-', $component); foreach ($nsAry as $ns) { $namespace .= "\\" . ucfirst($ns); } return $namespace; }
php
public static function getComponentNs(string $component): string { if ($component === 'framework') { return ''; } $namespace = ''; $nsAry = explode('-', $component); foreach ($nsAry as $ns) { $namespace .= "\\" . ucfirst($ns); } return $namespace; }
[ "public", "static", "function", "getComponentNs", "(", "string", "$", "component", ")", ":", "string", "{", "if", "(", "$", "component", "===", "'framework'", ")", "{", "return", "''", ";", "}", "$", "namespace", "=", "''", ";", "$", "nsAry", "=", "exp...
Get the default namespace of component @param string $component @return string
[ "Get", "the", "default", "namespace", "of", "component" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Helper/ComponentHelper.php#L29-L42
swoft-cloud/swoft-framework
src/Bean/Collector/BootstrapCollector.php
BootstrapCollector.collect
public static function collect(string $className, $objectAnnotation = null, string $propertyName = '', string $methodName = '', $propertyValue = null) { if ($objectAnnotation instanceof Bootstrap) { $name = $objectAnnotation->getName(); $order = $objectAnnotation->getOrder(); self::$bootstraps[$className]['name'] = $name; self::$bootstraps[$className]['order'] = $order; } }
php
public static function collect(string $className, $objectAnnotation = null, string $propertyName = '', string $methodName = '', $propertyValue = null) { if ($objectAnnotation instanceof Bootstrap) { $name = $objectAnnotation->getName(); $order = $objectAnnotation->getOrder(); self::$bootstraps[$className]['name'] = $name; self::$bootstraps[$className]['order'] = $order; } }
[ "public", "static", "function", "collect", "(", "string", "$", "className", ",", "$", "objectAnnotation", "=", "null", ",", "string", "$", "propertyName", "=", "''", ",", "string", "$", "methodName", "=", "''", ",", "$", "propertyValue", "=", "null", ")", ...
collect @param string $className @param Bootstrap $objectAnnotation @param string $propertyName @param string $methodName @param null $propertyValue @return void
[ "collect" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Collector/BootstrapCollector.php#L34-L44
swoft-cloud/swoft-framework
src/Bean/Wrapper/AspectWrapper.php
AspectWrapper.isParseMethodAnnotations
public function isParseMethodAnnotations(array $annotations): bool { $after = isset($annotations[After::class]) || isset($annotations[AfterThrowing::class]) || isset($annotations[AfterReturning::class]); return isset($annotations[Before::class]) || isset($annotations[Around::class]) || $after; }
php
public function isParseMethodAnnotations(array $annotations): bool { $after = isset($annotations[After::class]) || isset($annotations[AfterThrowing::class]) || isset($annotations[AfterReturning::class]); return isset($annotations[Before::class]) || isset($annotations[Around::class]) || $after; }
[ "public", "function", "isParseMethodAnnotations", "(", "array", "$", "annotations", ")", ":", "bool", "{", "$", "after", "=", "isset", "(", "$", "annotations", "[", "After", "::", "class", "]", ")", "||", "isset", "(", "$", "annotations", "[", "AfterThrowi...
是否解析方法注解 @param array $annotations @return bool
[ "是否解析方法注解" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Wrapper/AspectWrapper.php#L89-L94
swoft-cloud/swoft-framework
src/Validator/IntegerValidator.php
IntegerValidator.validate
public function validate(...$params) { list($name, $value, $min, $max, $throws, $template) = $params; return ValidatorHelper::validateInteger($name, $value, $min, $max, $throws, $template); }
php
public function validate(...$params) { list($name, $value, $min, $max, $throws, $template) = $params; return ValidatorHelper::validateInteger($name, $value, $min, $max, $throws, $template); }
[ "public", "function", "validate", "(", "...", "$", "params", ")", "{", "list", "(", "$", "name", ",", "$", "value", ",", "$", "min", ",", "$", "max", ",", "$", "throws", ",", "$", "template", ")", "=", "$", "params", ";", "return", "ValidatorHelper...
@param array ...$params @return mixed @throws \Swoft\Exception\ValidatorException
[ "@param", "array", "...", "$params" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Validator/IntegerValidator.php#L20-L25
swoft-cloud/swoft-framework
src/Bean/Collector/AspectCollector.php
AspectCollector.collectPointExecution
private static function collectPointExecution(PointExecution $objectAnnotation, string $className) { if (!isset(self::$aspects[$className])) { return null; } $include = $objectAnnotation->getInclude(); $exclude = $objectAnnotation->getExclude(); self::$aspects[$className]['point']['execution'] = [ 'include' => $include, 'exclude' => $exclude, ]; }
php
private static function collectPointExecution(PointExecution $objectAnnotation, string $className) { if (!isset(self::$aspects[$className])) { return null; } $include = $objectAnnotation->getInclude(); $exclude = $objectAnnotation->getExclude(); self::$aspects[$className]['point']['execution'] = [ 'include' => $include, 'exclude' => $exclude, ]; }
[ "private", "static", "function", "collectPointExecution", "(", "PointExecution", "$", "objectAnnotation", ",", "string", "$", "className", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "aspects", "[", "$", "className", "]", ")", ")", "{", "ret...
@param PointExecution $objectAnnotation @param string $className @return void
[ "@param", "PointExecution", "$objectAnnotation", "@param", "string", "$className" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Collector/AspectCollector.php#L68-L81
swoft-cloud/swoft-framework
src/Bean/Collector/AspectCollector.php
AspectCollector.collectPointBean
private static function collectPointBean(PointBean $objectAnnotation, string $className) { if (!isset(self::$aspects[$className])) { return null; } $include = $objectAnnotation->getInclude(); $exclude = $objectAnnotation->getExclude(); self::$aspects[$className]['point']['bean'] = [ 'include' => $include, 'exclude' => $exclude, ]; }
php
private static function collectPointBean(PointBean $objectAnnotation, string $className) { if (!isset(self::$aspects[$className])) { return null; } $include = $objectAnnotation->getInclude(); $exclude = $objectAnnotation->getExclude(); self::$aspects[$className]['point']['bean'] = [ 'include' => $include, 'exclude' => $exclude, ]; }
[ "private", "static", "function", "collectPointBean", "(", "PointBean", "$", "objectAnnotation", ",", "string", "$", "className", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "aspects", "[", "$", "className", "]", ")", ")", "{", "return", "n...
@param PointBean $objectAnnotation @param string $className @return void
[ "@param", "PointBean", "$objectAnnotation", "@param", "string", "$className" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Collector/AspectCollector.php#L89-L102
swoft-cloud/swoft-framework
src/Bean/Collector/AspectCollector.php
AspectCollector.collectPointAnnotation
private static function collectPointAnnotation(PointAnnotation $objectAnnotation, string $className) { if (!isset(self::$aspects[$className])) { return null; } $include = $objectAnnotation->getInclude(); $exclude = $objectAnnotation->getExclude(); self::$aspects[$className]['point']['annotation'] = [ 'include' => $include, 'exclude' => $exclude, ]; }
php
private static function collectPointAnnotation(PointAnnotation $objectAnnotation, string $className) { if (!isset(self::$aspects[$className])) { return null; } $include = $objectAnnotation->getInclude(); $exclude = $objectAnnotation->getExclude(); self::$aspects[$className]['point']['annotation'] = [ 'include' => $include, 'exclude' => $exclude, ]; }
[ "private", "static", "function", "collectPointAnnotation", "(", "PointAnnotation", "$", "objectAnnotation", ",", "string", "$", "className", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "aspects", "[", "$", "className", "]", ")", ")", "{", "r...
@param PointAnnotation $objectAnnotation @param string $className @return void
[ "@param", "PointAnnotation", "$objectAnnotation", "@param", "string", "$className" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Collector/AspectCollector.php#L110-L123
swoft-cloud/swoft-framework
src/Bean/Collector/AspectCollector.php
AspectCollector.collectAfter
private static function collectAfter(string $className, string $methodName) { if (!isset(self::$aspects[$className])) { return null; } self::$aspects[$className]['advice']['after'] = [$className, $methodName]; }
php
private static function collectAfter(string $className, string $methodName) { if (!isset(self::$aspects[$className])) { return null; } self::$aspects[$className]['advice']['after'] = [$className, $methodName]; }
[ "private", "static", "function", "collectAfter", "(", "string", "$", "className", ",", "string", "$", "methodName", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "aspects", "[", "$", "className", "]", ")", ")", "{", "return", "null", ";", ...
@param string $className @param string $methodName @return void
[ "@param", "string", "$className", "@param", "string", "$methodName" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Collector/AspectCollector.php#L142-L149
swoft-cloud/swoft-framework
src/Bean/Collector/AspectCollector.php
AspectCollector.collectBefore
private static function collectBefore(string $className, string $methodName) { if (!isset(self::$aspects[$className])) { return null; } self::$aspects[$className]['advice']['before'] = [$className, $methodName]; }
php
private static function collectBefore(string $className, string $methodName) { if (!isset(self::$aspects[$className])) { return null; } self::$aspects[$className]['advice']['before'] = [$className, $methodName]; }
[ "private", "static", "function", "collectBefore", "(", "string", "$", "className", ",", "string", "$", "methodName", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "aspects", "[", "$", "className", "]", ")", ")", "{", "return", "null", ";",...
@param string $className @param string $methodName @return void
[ "@param", "string", "$className", "@param", "string", "$methodName" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Collector/AspectCollector.php#L157-L164
swoft-cloud/swoft-framework
src/Bean/Collector/AspectCollector.php
AspectCollector.collectAround
private static function collectAround(string $className, string $methodName) { if (!isset(self::$aspects[$className])) { return null; } self::$aspects[$className]['advice']['around'] = [$className, $methodName]; }
php
private static function collectAround(string $className, string $methodName) { if (!isset(self::$aspects[$className])) { return null; } self::$aspects[$className]['advice']['around'] = [$className, $methodName]; }
[ "private", "static", "function", "collectAround", "(", "string", "$", "className", ",", "string", "$", "methodName", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "aspects", "[", "$", "className", "]", ")", ")", "{", "return", "null", ";",...
@param string $className @param string $methodName @return void
[ "@param", "string", "$className", "@param", "string", "$methodName" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Collector/AspectCollector.php#L172-L179
swoft-cloud/swoft-framework
src/Bean/Collector/AspectCollector.php
AspectCollector.collectAfterThrowing
private static function collectAfterThrowing(string $className, string $methodName) { if (!isset(self::$aspects[$className])) { return null; } self::$aspects[$className]['advice']['afterThrowing'] = [$className, $methodName]; }
php
private static function collectAfterThrowing(string $className, string $methodName) { if (!isset(self::$aspects[$className])) { return null; } self::$aspects[$className]['advice']['afterThrowing'] = [$className, $methodName]; }
[ "private", "static", "function", "collectAfterThrowing", "(", "string", "$", "className", ",", "string", "$", "methodName", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "aspects", "[", "$", "className", "]", ")", ")", "{", "return", "null",...
@param string $className @param string $methodName @return void
[ "@param", "string", "$className", "@param", "string", "$methodName" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Collector/AspectCollector.php#L187-L194
swoft-cloud/swoft-framework
src/Bean/Collector/AspectCollector.php
AspectCollector.collectAfterReturning
private static function collectAfterReturning(string $className, string $methodName) { if (!isset(self::$aspects[$className])) { return null; } self::$aspects[$className]['advice']['afterReturning'] = [$className, $methodName]; }
php
private static function collectAfterReturning(string $className, string $methodName) { if (!isset(self::$aspects[$className])) { return null; } self::$aspects[$className]['advice']['afterReturning'] = [$className, $methodName]; }
[ "private", "static", "function", "collectAfterReturning", "(", "string", "$", "className", ",", "string", "$", "methodName", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "aspects", "[", "$", "className", "]", ")", ")", "{", "return", "null"...
@param string $className @param string $methodName @return void
[ "@param", "string", "$className", "@param", "string", "$methodName" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Collector/AspectCollector.php#L202-L208
swoft-cloud/swoft-framework
src/Core/ApplicationContext.php
ApplicationContext.createBean
public static function createBean($beanName, $type, $params = []) { if (!empty($params) && \is_array($type)) { array_unshift($type, $params); } return BeanFactory::createBean($beanName, $type); }
php
public static function createBean($beanName, $type, $params = []) { if (!empty($params) && \is_array($type)) { array_unshift($type, $params); } return BeanFactory::createBean($beanName, $type); }
[ "public", "static", "function", "createBean", "(", "$", "beanName", ",", "$", "type", ",", "$", "params", "=", "[", "]", ")", "{", "if", "(", "!", "empty", "(", "$", "params", ")", "&&", "\\", "is_array", "(", "$", "type", ")", ")", "{", "array_u...
运行过程中创建一个Bean Below are some examples: // 类名称创建 ApplicationContext::createBean('name', '\Swoft\Web\UrlManage'); // 配置信息创建,切支持properties.php配置引用和bean引用 ApplicationContext::createBean( [ 'class' => '\Swoft\Web\UrlManage', 'field' => 'value1', 'field2' => 'value'2 ] ); @param string $beanName the name of bean @param array|string $type class definition @param array $params constructor parameters @return mixed
[ "运行过程中创建一个Bean" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Core/ApplicationContext.php#L68-L75
swoft-cloud/swoft-framework
src/Core/ApplicationContext.php
ApplicationContext.registerListeners
public static function registerListeners(array $listeners) { foreach ($listeners as $eventName => $eventListeners) { foreach ($eventListeners as $listenerClassName) { $listener = self::getBean($listenerClassName); self::addListener($eventName, $listener); } } }
php
public static function registerListeners(array $listeners) { foreach ($listeners as $eventName => $eventListeners) { foreach ($eventListeners as $listenerClassName) { $listener = self::getBean($listenerClassName); self::addListener($eventName, $listener); } } }
[ "public", "static", "function", "registerListeners", "(", "array", "$", "listeners", ")", "{", "foreach", "(", "$", "listeners", "as", "$", "eventName", "=>", "$", "eventListeners", ")", "{", "foreach", "(", "$", "eventListeners", "as", "$", "listenerClassName...
初始化注册监听器 @param array[] $listeners 监听器集合
[ "初始化注册监听器" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Core/ApplicationContext.php#L126-L134
swoft-cloud/swoft-framework
src/Core/ApplicationContext.php
ApplicationContext.addListener
public static function addListener(string $name, $listener, $priority = 0) { BeanFactory::getBean('eventManager')->attach($name, $listener, $priority); }
php
public static function addListener(string $name, $listener, $priority = 0) { BeanFactory::getBean('eventManager')->attach($name, $listener, $priority); }
[ "public", "static", "function", "addListener", "(", "string", "$", "name", ",", "$", "listener", ",", "$", "priority", "=", "0", ")", "{", "BeanFactory", "::", "getBean", "(", "'eventManager'", ")", "->", "attach", "(", "$", "name", ",", "$", "listener",...
注册一个监听器 @param string $name 监听的事件名称 @param callable $listener 监听器 @param int $priority 优先级
[ "注册一个监听器" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Core/ApplicationContext.php#L142-L145
swoft-cloud/swoft-framework
src/Core/RequestHandler.php
RequestHandler.handle
public function handle(ServerRequestInterface $request): ResponseInterface { if (!empty($this->default) && empty($this->middlewares[$this->offset])) { $handler = App::getBean($this->default); } else { $handler = $this->middlewares[$this->offset]; \is_string($handler) && $handler = App::getBean($handler); } if (!$handler instanceof MiddlewareInterface) { throw new \InvalidArgumentException('Invalid Handler. It must be an instance of MiddlewareInterface'); } return $handler->process($request, $this->next()); }
php
public function handle(ServerRequestInterface $request): ResponseInterface { if (!empty($this->default) && empty($this->middlewares[$this->offset])) { $handler = App::getBean($this->default); } else { $handler = $this->middlewares[$this->offset]; \is_string($handler) && $handler = App::getBean($handler); } if (!$handler instanceof MiddlewareInterface) { throw new \InvalidArgumentException('Invalid Handler. It must be an instance of MiddlewareInterface'); } return $handler->process($request, $this->next()); }
[ "public", "function", "handle", "(", "ServerRequestInterface", "$", "request", ")", ":", "ResponseInterface", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "default", ")", "&&", "empty", "(", "$", "this", "->", "middlewares", "[", "$", "this", "-...
Process the request using the current middleware. @param ServerRequestInterface $request @return ResponseInterface @throws \InvalidArgumentException
[ "Process", "the", "request", "using", "the", "current", "middleware", "." ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Core/RequestHandler.php#L51-L65
swoft-cloud/swoft-framework
src/Core/RequestHandler.php
RequestHandler.insertMiddlewares
public function insertMiddlewares(array $middlewares, $offset = null) { null === $offset && $offset = $this->offset; $chunkArray = array_chunk($this->middlewares, $offset); $after = []; $before = $chunkArray[0]; if (isset($chunkArray[1])) { $after = $chunkArray[1]; } $middlewares = array_merge((array)$before, $middlewares, (array)$after); $this->middlewares = $middlewares; return $this; }
php
public function insertMiddlewares(array $middlewares, $offset = null) { null === $offset && $offset = $this->offset; $chunkArray = array_chunk($this->middlewares, $offset); $after = []; $before = $chunkArray[0]; if (isset($chunkArray[1])) { $after = $chunkArray[1]; } $middlewares = array_merge((array)$before, $middlewares, (array)$after); $this->middlewares = $middlewares; return $this; }
[ "public", "function", "insertMiddlewares", "(", "array", "$", "middlewares", ",", "$", "offset", "=", "null", ")", "{", "null", "===", "$", "offset", "&&", "$", "offset", "=", "$", "this", "->", "offset", ";", "$", "chunkArray", "=", "array_chunk", "(", ...
Insert middlewares to the next position @param array $middlewares @param null $offset @return $this
[ "Insert", "middlewares", "to", "the", "next", "position" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Core/RequestHandler.php#L86-L98
swoft-cloud/swoft-framework
src/Pool/ConnectionPool.php
ConnectionPool.init
public function init() { if (empty($this->poolConfig)) { throw new PoolException('You must to set poolConfig by @Inject!'); } if (App::isWorkerStatus()) { $this->channel = new Channel($this->poolConfig->getMaxActive()); } else { $this->queue = new \SplQueue(); } }
php
public function init() { if (empty($this->poolConfig)) { throw new PoolException('You must to set poolConfig by @Inject!'); } if (App::isWorkerStatus()) { $this->channel = new Channel($this->poolConfig->getMaxActive()); } else { $this->queue = new \SplQueue(); } }
[ "public", "function", "init", "(", ")", "{", "if", "(", "empty", "(", "$", "this", "->", "poolConfig", ")", ")", "{", "throw", "new", "PoolException", "(", "'You must to set poolConfig by @Inject!'", ")", ";", "}", "if", "(", "App", "::", "isWorkerStatus", ...
Initialization
[ "Initialization" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Pool/ConnectionPool.php#L44-L55
swoft-cloud/swoft-framework
src/Pool/ConnectionPool.php
ConnectionPool.getConnection
public function getConnection():ConnectionInterface { if (App::isCoContext()) { $connection = $this->getConnectionByChannel(); } else { $connection = $this->getConnectionByQueue(); } if ($connection->check() == false) { $connection->reconnect(); } $this->addContextConnection($connection); return $connection; }
php
public function getConnection():ConnectionInterface { if (App::isCoContext()) { $connection = $this->getConnectionByChannel(); } else { $connection = $this->getConnectionByQueue(); } if ($connection->check() == false) { $connection->reconnect(); } $this->addContextConnection($connection); return $connection; }
[ "public", "function", "getConnection", "(", ")", ":", "ConnectionInterface", "{", "if", "(", "App", "::", "isCoContext", "(", ")", ")", "{", "$", "connection", "=", "$", "this", "->", "getConnectionByChannel", "(", ")", ";", "}", "else", "{", "$", "conne...
Get connection @throws ConnectionException; @return ConnectionInterface
[ "Get", "connection" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Pool/ConnectionPool.php#L63-L77
swoft-cloud/swoft-framework
src/Pool/ConnectionPool.php
ConnectionPool.release
public function release(ConnectionInterface $connection) { $connectionId = $connection->getConnectionId(); if($this->hasContextConnection($connectionId)) { $connection->updateLastTime(); $connection->setRecv(true); $connection->setAutoRelease(true); if (App::isCoContext()) { $this->releaseToChannel($connection); } else { $this->releaseToQueue($connection); } $this->removeContextConnection($connectionId); } }
php
public function release(ConnectionInterface $connection) { $connectionId = $connection->getConnectionId(); if($this->hasContextConnection($connectionId)) { $connection->updateLastTime(); $connection->setRecv(true); $connection->setAutoRelease(true); if (App::isCoContext()) { $this->releaseToChannel($connection); } else { $this->releaseToQueue($connection); } $this->removeContextConnection($connectionId); } }
[ "public", "function", "release", "(", "ConnectionInterface", "$", "connection", ")", "{", "$", "connectionId", "=", "$", "connection", "->", "getConnectionId", "(", ")", ";", "if", "(", "$", "this", "->", "hasContextConnection", "(", "$", "connectionId", ")", ...
Release connection @param ConnectionInterface $connection
[ "Release", "connection" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Pool/ConnectionPool.php#L84-L100
swoft-cloud/swoft-framework
src/Pool/ConnectionPool.php
ConnectionPool.getConnectionAddress
public function getConnectionAddress():string { $serviceList = $this->getServiceList(); if (App::hasBean('balancerSelector')) { $balancerType = $this->poolConfig->getBalancer(); $balancer = balancer()->select($balancerType); return $balancer->select($serviceList); } return current($serviceList); }
php
public function getConnectionAddress():string { $serviceList = $this->getServiceList(); if (App::hasBean('balancerSelector')) { $balancerType = $this->poolConfig->getBalancer(); $balancer = balancer()->select($balancerType); return $balancer->select($serviceList); } return current($serviceList); }
[ "public", "function", "getConnectionAddress", "(", ")", ":", "string", "{", "$", "serviceList", "=", "$", "this", "->", "getServiceList", "(", ")", ";", "if", "(", "App", "::", "hasBean", "(", "'balancerSelector'", ")", ")", "{", "$", "balancerType", "=", ...
Get one address @return string "127.0.0.1:88"
[ "Get", "one", "address" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Pool/ConnectionPool.php#L107-L116
swoft-cloud/swoft-framework
src/Pool/ConnectionPool.php
ConnectionPool.getServiceList
protected function getServiceList() { $name = $this->poolConfig->getName(); if ($this->poolConfig->isUseProvider() && App::hasBean('providerSelector')) { $type = $this->poolConfig->getProvider(); return provider()->select($type)->getServiceList($name); } $uri = $this->poolConfig->getUri(); if (empty($uri)) { $error = sprintf('Service does not configure uri name=%s', $name); App::error($error); throw new \InvalidArgumentException($error); } return $uri; }
php
protected function getServiceList() { $name = $this->poolConfig->getName(); if ($this->poolConfig->isUseProvider() && App::hasBean('providerSelector')) { $type = $this->poolConfig->getProvider(); return provider()->select($type)->getServiceList($name); } $uri = $this->poolConfig->getUri(); if (empty($uri)) { $error = sprintf('Service does not configure uri name=%s', $name); App::error($error); throw new \InvalidArgumentException($error); } return $uri; }
[ "protected", "function", "getServiceList", "(", ")", "{", "$", "name", "=", "$", "this", "->", "poolConfig", "->", "getName", "(", ")", ";", "if", "(", "$", "this", "->", "poolConfig", "->", "isUseProvider", "(", ")", "&&", "App", "::", "hasBean", "(",...
Get service list @return array <pre> [ "127.0.0.1:88", "127.0.0.1:88" ] </pre>
[ "Get", "service", "list" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Pool/ConnectionPool.php#L129-L146
swoft-cloud/swoft-framework
src/Pool/ConnectionPool.php
ConnectionPool.releaseToQueue
private function releaseToQueue(ConnectionInterface $connection) { if ($this->queue->count() < $this->poolConfig->getMaxActive()) { $this->queue->push($connection); } }
php
private function releaseToQueue(ConnectionInterface $connection) { if ($this->queue->count() < $this->poolConfig->getMaxActive()) { $this->queue->push($connection); } }
[ "private", "function", "releaseToQueue", "(", "ConnectionInterface", "$", "connection", ")", "{", "if", "(", "$", "this", "->", "queue", "->", "count", "(", ")", "<", "$", "this", "->", "poolConfig", "->", "getMaxActive", "(", ")", ")", "{", "$", "this",...
Release to queue @param $connection
[ "Release", "to", "queue" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Pool/ConnectionPool.php#L169-L174
swoft-cloud/swoft-framework
src/Pool/ConnectionPool.php
ConnectionPool.releaseToChannel
private function releaseToChannel(ConnectionInterface $connection) { $stats = $this->channel->stats(); $maxActive = $this->poolConfig->getMaxActive(); if ($stats['queue_num'] < $maxActive) { $this->channel->push($connection); } }
php
private function releaseToChannel(ConnectionInterface $connection) { $stats = $this->channel->stats(); $maxActive = $this->poolConfig->getMaxActive(); if ($stats['queue_num'] < $maxActive) { $this->channel->push($connection); } }
[ "private", "function", "releaseToChannel", "(", "ConnectionInterface", "$", "connection", ")", "{", "$", "stats", "=", "$", "this", "->", "channel", "->", "stats", "(", ")", ";", "$", "maxActive", "=", "$", "this", "->", "poolConfig", "->", "getMaxActive", ...
Release to channel @param $connection
[ "Release", "to", "channel" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Pool/ConnectionPool.php#L181-L188
swoft-cloud/swoft-framework
src/Pool/ConnectionPool.php
ConnectionPool.getConnectionByQueue
private function getConnectionByQueue(): ConnectionInterface { if($this->queue == null){ $this->queue = new \SplQueue(); } if (!$this->queue->isEmpty()) { return $this->getEffectiveConnection($this->queue->count(), false); } if ($this->currentCount >= $this->poolConfig->getMaxActive()) { throw new ConnectionException('Connection pool queue is full'); } $connect = $this->createConnection(); $this->currentCount++; return $connect; }
php
private function getConnectionByQueue(): ConnectionInterface { if($this->queue == null){ $this->queue = new \SplQueue(); } if (!$this->queue->isEmpty()) { return $this->getEffectiveConnection($this->queue->count(), false); } if ($this->currentCount >= $this->poolConfig->getMaxActive()) { throw new ConnectionException('Connection pool queue is full'); } $connect = $this->createConnection(); $this->currentCount++; return $connect; }
[ "private", "function", "getConnectionByQueue", "(", ")", ":", "ConnectionInterface", "{", "if", "(", "$", "this", "->", "queue", "==", "null", ")", "{", "$", "this", "->", "queue", "=", "new", "\\", "SplQueue", "(", ")", ";", "}", "if", "(", "!", "$"...
Get connection by queue @return ConnectionInterface @throws ConnectionException
[ "Get", "connection", "by", "queue" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Pool/ConnectionPool.php#L196-L213
swoft-cloud/swoft-framework
src/Pool/ConnectionPool.php
ConnectionPool.getConnectionByChannel
private function getConnectionByChannel(): ConnectionInterface { if($this->channel === null){ $this->channel = new Channel($this->poolConfig->getMaxActive()); } $stats = $this->channel->stats(); if ($stats['queue_num'] > 0) { return $this->getEffectiveConnection($stats['queue_num']); } $maxActive = $this->poolConfig->getMaxActive(); if ($this->currentCount < $maxActive) { $connection = $this->createConnection(); $this->currentCount++; return $connection; } $maxWait = $this->poolConfig->getMaxWait(); if ($maxWait != 0 && $stats['consumer_num'] >= $maxWait) { throw new ConnectionException(sprintf('Connection pool waiting queue is full, maxActive=%d,maxWait=%d,currentCount=%d', $maxActive, $maxWait, $this->currentCount)); } $maxWaitTime = $this->poolConfig->getMaxWaitTime(); if ($maxWaitTime == 0) { return $this->channel->pop(); } // When swoole version is larger than 4.0.3, Channel->select is removed. if (version_compare(swoole_version(), '4.0.3', '>=')) { $result = $this->channel->pop($maxWaitTime); if ($result === false) { throw new ConnectionException('Connection pool waiting queue timeout, timeout=' . $maxWaitTime); } return $result; } $writes = []; $reads = [$this->channel]; $result = $this->channel->select($reads, $writes, $maxWaitTime); if ($result === false || empty($reads)) { throw new ConnectionException('Connection pool waiting queue timeout, timeout='.$maxWaitTime); } $readChannel = $reads[0]; return $readChannel->pop(); }
php
private function getConnectionByChannel(): ConnectionInterface { if($this->channel === null){ $this->channel = new Channel($this->poolConfig->getMaxActive()); } $stats = $this->channel->stats(); if ($stats['queue_num'] > 0) { return $this->getEffectiveConnection($stats['queue_num']); } $maxActive = $this->poolConfig->getMaxActive(); if ($this->currentCount < $maxActive) { $connection = $this->createConnection(); $this->currentCount++; return $connection; } $maxWait = $this->poolConfig->getMaxWait(); if ($maxWait != 0 && $stats['consumer_num'] >= $maxWait) { throw new ConnectionException(sprintf('Connection pool waiting queue is full, maxActive=%d,maxWait=%d,currentCount=%d', $maxActive, $maxWait, $this->currentCount)); } $maxWaitTime = $this->poolConfig->getMaxWaitTime(); if ($maxWaitTime == 0) { return $this->channel->pop(); } // When swoole version is larger than 4.0.3, Channel->select is removed. if (version_compare(swoole_version(), '4.0.3', '>=')) { $result = $this->channel->pop($maxWaitTime); if ($result === false) { throw new ConnectionException('Connection pool waiting queue timeout, timeout=' . $maxWaitTime); } return $result; } $writes = []; $reads = [$this->channel]; $result = $this->channel->select($reads, $writes, $maxWaitTime); if ($result === false || empty($reads)) { throw new ConnectionException('Connection pool waiting queue timeout, timeout='.$maxWaitTime); } $readChannel = $reads[0]; return $readChannel->pop(); }
[ "private", "function", "getConnectionByChannel", "(", ")", ":", "ConnectionInterface", "{", "if", "(", "$", "this", "->", "channel", "===", "null", ")", "{", "$", "this", "->", "channel", "=", "new", "Channel", "(", "$", "this", "->", "poolConfig", "->", ...
* Get connection by channel @return ConnectionInterface @throws ConnectionException
[ "*", "Get", "connection", "by", "channel" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Pool/ConnectionPool.php#L221-L270
swoft-cloud/swoft-framework
src/Pool/ConnectionPool.php
ConnectionPool.getEffectiveConnection
private function getEffectiveConnection(int $queueNum, bool $isChannel = true): ConnectionInterface { $minActive = $this->poolConfig->getMinActive(); if ($queueNum <= $minActive) { return $this->getOriginalConnection($isChannel); } $time = time(); $moreActive = $queueNum - $minActive; $maxIdleTime = $this->poolConfig->getMaxIdleTime(); for ($i = 0; $i < $moreActive; $i++) { /* @var ConnectionInterface $connection */ $connection = $this->getOriginalConnection($isChannel);; $lastTime = $connection->getLastTime(); if ($time - $lastTime < $maxIdleTime) { return $connection; } $this->currentCount--; } return $this->getOriginalConnection($isChannel); }
php
private function getEffectiveConnection(int $queueNum, bool $isChannel = true): ConnectionInterface { $minActive = $this->poolConfig->getMinActive(); if ($queueNum <= $minActive) { return $this->getOriginalConnection($isChannel); } $time = time(); $moreActive = $queueNum - $minActive; $maxIdleTime = $this->poolConfig->getMaxIdleTime(); for ($i = 0; $i < $moreActive; $i++) { /* @var ConnectionInterface $connection */ $connection = $this->getOriginalConnection($isChannel);; $lastTime = $connection->getLastTime(); if ($time - $lastTime < $maxIdleTime) { return $connection; } $this->currentCount--; } return $this->getOriginalConnection($isChannel); }
[ "private", "function", "getEffectiveConnection", "(", "int", "$", "queueNum", ",", "bool", "$", "isChannel", "=", "true", ")", ":", "ConnectionInterface", "{", "$", "minActive", "=", "$", "this", "->", "poolConfig", "->", "getMinActive", "(", ")", ";", "if",...
Get effective connection @param int $queueNum @param bool $isChannel @return ConnectionInterface
[ "Get", "effective", "connection" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Pool/ConnectionPool.php#L280-L301
swoft-cloud/swoft-framework
src/Pool/ConnectionPool.php
ConnectionPool.getOriginalConnection
private function getOriginalConnection(bool $isChannel = true): ConnectionInterface { if ($isChannel) { return $this->channel->pop(); } return $this->queue->shift(); }
php
private function getOriginalConnection(bool $isChannel = true): ConnectionInterface { if ($isChannel) { return $this->channel->pop(); } return $this->queue->shift(); }
[ "private", "function", "getOriginalConnection", "(", "bool", "$", "isChannel", "=", "true", ")", ":", "ConnectionInterface", "{", "if", "(", "$", "isChannel", ")", "{", "return", "$", "this", "->", "channel", "->", "pop", "(", ")", ";", "}", "return", "$...
Get original connection @param bool $isChannel @return ConnectionInterface
[ "Get", "original", "connection" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Pool/ConnectionPool.php#L310-L317
swoft-cloud/swoft-framework
src/Bean/Resource/AbstractResource.php
AbstractResource.getTransferProperty
public function getTransferProperty($property) { if (!is_string($property)) { return [$property, 0]; } // 正则匹配 $injectProperty = $property; $isRef = preg_match('/^\$\{(.*)\}$/', $property, $match); // 解析 if (!empty($match)) { $isRef = strpos($match[1], 'config') === 0 ? 0 : $isRef; $injectProperty = $this->getInjectProperty($match[1]); } return [$injectProperty, $isRef]; }
php
public function getTransferProperty($property) { if (!is_string($property)) { return [$property, 0]; } // 正则匹配 $injectProperty = $property; $isRef = preg_match('/^\$\{(.*)\}$/', $property, $match); // 解析 if (!empty($match)) { $isRef = strpos($match[1], 'config') === 0 ? 0 : $isRef; $injectProperty = $this->getInjectProperty($match[1]); } return [$injectProperty, $isRef]; }
[ "public", "function", "getTransferProperty", "(", "$", "property", ")", "{", "if", "(", "!", "is_string", "(", "$", "property", ")", ")", "{", "return", "[", "$", "property", ",", "0", "]", ";", "}", "// 正则匹配", "$", "injectProperty", "=", "$", "propert...
非数组格式属性值转换 @param $property @return array
[ "非数组格式属性值转换" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Resource/AbstractResource.php#L24-L41
swoft-cloud/swoft-framework
src/Bean/Resource/AbstractResource.php
AbstractResource.getInjectProperty
public function getInjectProperty(string $property) { // '${beanName}'格式解析 $propertyKeys = explode(".", $property); if (count($propertyKeys) == 1) { return $property; } if ($propertyKeys[0] != 'config') { throw new \InvalidArgumentException("properties配置引用格式不正确,key=" . $propertyKeys[0]); } // '${config.xx.yy}' 格式解析,直接key $propertyKey = str_replace("config.", "", $property); if (isset($this->properties[$propertyKey])) { return $this->properties[$propertyKey]; } // '${config.xx.yy}' 格式解析, 层级解析 unset($propertyKeys[0]); $layerProperty = empty($propertyKeys)? null: $this->properties; foreach ($propertyKeys as $subPropertyKey) { if (isset($layerProperty[$subPropertyKey])) { $layerProperty = $layerProperty[$subPropertyKey]; continue; } $layerProperty = null; break; } return $layerProperty; }
php
public function getInjectProperty(string $property) { // '${beanName}'格式解析 $propertyKeys = explode(".", $property); if (count($propertyKeys) == 1) { return $property; } if ($propertyKeys[0] != 'config') { throw new \InvalidArgumentException("properties配置引用格式不正确,key=" . $propertyKeys[0]); } // '${config.xx.yy}' 格式解析,直接key $propertyKey = str_replace("config.", "", $property); if (isset($this->properties[$propertyKey])) { return $this->properties[$propertyKey]; } // '${config.xx.yy}' 格式解析, 层级解析 unset($propertyKeys[0]); $layerProperty = empty($propertyKeys)? null: $this->properties; foreach ($propertyKeys as $subPropertyKey) { if (isset($layerProperty[$subPropertyKey])) { $layerProperty = $layerProperty[$subPropertyKey]; continue; } $layerProperty = null; break; } return $layerProperty; }
[ "public", "function", "getInjectProperty", "(", "string", "$", "property", ")", "{", "// '${beanName}'格式解析", "$", "propertyKeys", "=", "explode", "(", "\".\"", ",", "$", "property", ")", ";", "if", "(", "count", "(", "$", "propertyKeys", ")", "==", "1", ")...
属性值引用解析 @param string $property @return mixed|string
[ "属性值引用解析" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Resource/AbstractResource.php#L50-L82
swoft-cloud/swoft-framework
src/Bean/Parser/BeanParser.php
BeanParser.parser
public function parser(string $className, $objectAnnotation = null, string $propertyName = "", string $methodName = "", $propertyValue = null) { $name = $objectAnnotation->getName(); $scope = $objectAnnotation->getScope(); $ref = $objectAnnotation->getRef(); $beanName = empty($name) ? $className : $name; return [$beanName, $scope, $ref]; }
php
public function parser(string $className, $objectAnnotation = null, string $propertyName = "", string $methodName = "", $propertyValue = null) { $name = $objectAnnotation->getName(); $scope = $objectAnnotation->getScope(); $ref = $objectAnnotation->getRef(); $beanName = empty($name) ? $className : $name; return [$beanName, $scope, $ref]; }
[ "public", "function", "parser", "(", "string", "$", "className", ",", "$", "objectAnnotation", "=", "null", ",", "string", "$", "propertyName", "=", "\"\"", ",", "string", "$", "methodName", "=", "\"\"", ",", "$", "propertyValue", "=", "null", ")", "{", ...
Bean注解解析 @param string $className @param Bean $objectAnnotation @param string $propertyName @param string $methodName @param null $propertyValue @return array
[ "Bean注解解析" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Parser/BeanParser.php#L28-L36
swoft-cloud/swoft-framework
src/Bean/Collector/ValidatorCollector.php
ValidatorCollector.collect
public static function collect( string $className, $objectAnnotation = null, string $propertyName = '', string $methodName = '', $propertyValue = null ) { if ($objectAnnotation instanceof Strings) { self::collectString($objectAnnotation, $className, $methodName); } elseif ($objectAnnotation instanceof Floats) { self::collectFloats($objectAnnotation, $className, $methodName); } elseif ($objectAnnotation instanceof Number) { self::collectNumber($objectAnnotation, $className, $methodName); } elseif ($objectAnnotation instanceof Integer) { self::collectInteger($objectAnnotation, $className, $methodName); } elseif ($objectAnnotation instanceof Enum) { self::collectEnum($objectAnnotation, $className, $methodName); } }
php
public static function collect( string $className, $objectAnnotation = null, string $propertyName = '', string $methodName = '', $propertyValue = null ) { if ($objectAnnotation instanceof Strings) { self::collectString($objectAnnotation, $className, $methodName); } elseif ($objectAnnotation instanceof Floats) { self::collectFloats($objectAnnotation, $className, $methodName); } elseif ($objectAnnotation instanceof Number) { self::collectNumber($objectAnnotation, $className, $methodName); } elseif ($objectAnnotation instanceof Integer) { self::collectInteger($objectAnnotation, $className, $methodName); } elseif ($objectAnnotation instanceof Enum) { self::collectEnum($objectAnnotation, $className, $methodName); } }
[ "public", "static", "function", "collect", "(", "string", "$", "className", ",", "$", "objectAnnotation", "=", "null", ",", "string", "$", "propertyName", "=", "''", ",", "string", "$", "methodName", "=", "''", ",", "$", "propertyValue", "=", "null", ")", ...
@param string $className @param object $objectAnnotation @param string $propertyName @param string $methodName @param null $propertyValue @return mixed|void
[ "@param", "string", "$className", "@param", "object", "$objectAnnotation", "@param", "string", "$propertyName", "@param", "string", "$methodName", "@param", "null", "$propertyValue" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Collector/ValidatorCollector.php#L38-L56
swoft-cloud/swoft-framework
src/Bean/Parser/InjectParser.php
InjectParser.parser
public function parser(string $className, $objectAnnotation = null, string $propertyName = "", string $methodName = "", $propertyValue = null) { $injectValue = $objectAnnotation->getName(); if (!empty($injectValue)) { return [$injectValue, true]; } // phpdoc解析 $phpReader = new PhpDocReader(); $property = new \ReflectionProperty($className, $propertyName); $propertyClass = $phpReader->getPropertyClass($property); $isRef = true; $injectProperty = $propertyClass; return [$injectProperty, $isRef]; }
php
public function parser(string $className, $objectAnnotation = null, string $propertyName = "", string $methodName = "", $propertyValue = null) { $injectValue = $objectAnnotation->getName(); if (!empty($injectValue)) { return [$injectValue, true]; } // phpdoc解析 $phpReader = new PhpDocReader(); $property = new \ReflectionProperty($className, $propertyName); $propertyClass = $phpReader->getPropertyClass($property); $isRef = true; $injectProperty = $propertyClass; return [$injectProperty, $isRef]; }
[ "public", "function", "parser", "(", "string", "$", "className", ",", "$", "objectAnnotation", "=", "null", ",", "string", "$", "propertyName", "=", "\"\"", ",", "string", "$", "methodName", "=", "\"\"", ",", "$", "propertyValue", "=", "null", ")", "{", ...
Inject注解解析 @param string $className @param object $objectAnnotation @param string $propertyName @param string $methodName @param null $propertyValue @return array
[ "Inject注解解析" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Parser/InjectParser.php#L29-L44
swoft-cloud/swoft-framework
src/Aop/Aop.php
Aop.execute
public function execute($target, string $method, array $params) { $class = \get_class($target); // If doesn't have any advices, then execute the origin method if (!isset($this->map[$class][$method]) || empty($this->map[$class][$method])) { return $target->$method(...$params); } // Apply advices's functionality $advices = $this->map[$class][$method]; return $this->doAdvice($target, $method, $params, $advices); }
php
public function execute($target, string $method, array $params) { $class = \get_class($target); // If doesn't have any advices, then execute the origin method if (!isset($this->map[$class][$method]) || empty($this->map[$class][$method])) { return $target->$method(...$params); } // Apply advices's functionality $advices = $this->map[$class][$method]; return $this->doAdvice($target, $method, $params, $advices); }
[ "public", "function", "execute", "(", "$", "target", ",", "string", "$", "method", ",", "array", "$", "params", ")", "{", "$", "class", "=", "\\", "get_class", "(", "$", "target", ")", ";", "// If doesn't have any advices, then execute the origin method", "if", ...
Execute origin method by aop @param object $target Origin object @param string $method The execution method @param array $params The parameters of execution method @return mixed @throws \ReflectionException @throws Throwable
[ "Execute", "origin", "method", "by", "aop" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Aop/Aop.php#L51-L63
swoft-cloud/swoft-framework
src/Aop/Aop.php
Aop.doPoint
private function doPoint( array $pointAdvice, $target, string $method, array $args, array $advice, array $advices, $return = null, Throwable $catch = null ) { list($aspectClass, $aspectMethod) = $pointAdvice; $reflectionClass = new \ReflectionClass($aspectClass); $reflectionMethod = $reflectionClass->getMethod($aspectMethod); $reflectionParameters = $reflectionMethod->getParameters(); // Bind the param of method $aspectArgs = []; foreach ($reflectionParameters as $reflectionParameter) { $parameterType = $reflectionParameter->getType(); if ($parameterType === null) { $aspectArgs[] = null; continue; } // JoinPoint object $type = $parameterType->__toString(); if ($type === JoinPoint::class) { $aspectArgs[] = new JoinPoint($target, $method, $args, $return, $catch); continue; } // ProceedingJoinPoint object if ($type === ProceedingJoinPoint::class) { $aspectArgs[] = new ProceedingJoinPoint($target, $method, $args, $advice, $advices); continue; } // Throwable object if ($catch && $catch instanceof $type) { $aspectArgs[] = $catch; continue; } $aspectArgs[] = null; } $aspect = \bean($aspectClass); return $aspect->$aspectMethod(...$aspectArgs); }
php
private function doPoint( array $pointAdvice, $target, string $method, array $args, array $advice, array $advices, $return = null, Throwable $catch = null ) { list($aspectClass, $aspectMethod) = $pointAdvice; $reflectionClass = new \ReflectionClass($aspectClass); $reflectionMethod = $reflectionClass->getMethod($aspectMethod); $reflectionParameters = $reflectionMethod->getParameters(); // Bind the param of method $aspectArgs = []; foreach ($reflectionParameters as $reflectionParameter) { $parameterType = $reflectionParameter->getType(); if ($parameterType === null) { $aspectArgs[] = null; continue; } // JoinPoint object $type = $parameterType->__toString(); if ($type === JoinPoint::class) { $aspectArgs[] = new JoinPoint($target, $method, $args, $return, $catch); continue; } // ProceedingJoinPoint object if ($type === ProceedingJoinPoint::class) { $aspectArgs[] = new ProceedingJoinPoint($target, $method, $args, $advice, $advices); continue; } // Throwable object if ($catch && $catch instanceof $type) { $aspectArgs[] = $catch; continue; } $aspectArgs[] = null; } $aspect = \bean($aspectClass); return $aspect->$aspectMethod(...$aspectArgs); }
[ "private", "function", "doPoint", "(", "array", "$", "pointAdvice", ",", "$", "target", ",", "string", "$", "method", ",", "array", "$", "args", ",", "array", "$", "advice", ",", "array", "$", "advices", ",", "$", "return", "=", "null", ",", "Throwable...
Do pointcut @param array $pointAdvice the pointcut advice @param object $target Origin object @param string $method The execution method @param array $args The parameters of execution method @param array $advice the advice of pointcut @param array $advices The advices of this object method @param mixed $return @param Throwable $catch The Throwable object caught @return mixed @throws \ReflectionException
[ "Do", "pointcut" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Aop/Aop.php#L130-L179
swoft-cloud/swoft-framework
src/Aop/Aop.php
Aop.match
public function match(string $beanName, string $class, string $method, array $annotations) { foreach ($this->aspects as $aspectClass => $aspect) { if (!isset($aspect['point'], $aspect['advice'])) { continue; } // Include $pointBeanInclude = $aspect['point']['bean']['include'] ?? []; $pointAnnotationInclude = $aspect['point']['annotation']['include'] ?? []; $pointExecutionInclude = $aspect['point']['execution']['include'] ?? []; // Exclude $pointBeanExclude = $aspect['point']['bean']['exclude'] ?? []; $pointAnnotationExclude = $aspect['point']['annotation']['exclude'] ?? []; $pointExecutionExclude = $aspect['point']['execution']['exclude'] ?? []; $includeMath = $this->matchBeanAndAnnotation([$beanName], $pointBeanInclude) || $this->matchBeanAndAnnotation($annotations, $pointAnnotationInclude) || $this->matchExecution($class, $method, $pointExecutionInclude); $excludeMath = $this->matchBeanAndAnnotation([$beanName], $pointBeanExclude) || $this->matchBeanAndAnnotation($annotations, $pointAnnotationExclude) || $this->matchExecution($class, $method, $pointExecutionExclude); if ($includeMath && ! $excludeMath) { $this->map[$class][$method][] = $aspect['advice']; } } }
php
public function match(string $beanName, string $class, string $method, array $annotations) { foreach ($this->aspects as $aspectClass => $aspect) { if (!isset($aspect['point'], $aspect['advice'])) { continue; } // Include $pointBeanInclude = $aspect['point']['bean']['include'] ?? []; $pointAnnotationInclude = $aspect['point']['annotation']['include'] ?? []; $pointExecutionInclude = $aspect['point']['execution']['include'] ?? []; // Exclude $pointBeanExclude = $aspect['point']['bean']['exclude'] ?? []; $pointAnnotationExclude = $aspect['point']['annotation']['exclude'] ?? []; $pointExecutionExclude = $aspect['point']['execution']['exclude'] ?? []; $includeMath = $this->matchBeanAndAnnotation([$beanName], $pointBeanInclude) || $this->matchBeanAndAnnotation($annotations, $pointAnnotationInclude) || $this->matchExecution($class, $method, $pointExecutionInclude); $excludeMath = $this->matchBeanAndAnnotation([$beanName], $pointBeanExclude) || $this->matchBeanAndAnnotation($annotations, $pointAnnotationExclude) || $this->matchExecution($class, $method, $pointExecutionExclude); if ($includeMath && ! $excludeMath) { $this->map[$class][$method][] = $aspect['advice']; } } }
[ "public", "function", "match", "(", "string", "$", "beanName", ",", "string", "$", "class", ",", "string", "$", "method", ",", "array", "$", "annotations", ")", "{", "foreach", "(", "$", "this", "->", "aspects", "as", "$", "aspectClass", "=>", "$", "as...
Match aop @param string $beanName Bean name @param string $class Class name @param string $method Method name @param array $annotations The annotations of method
[ "Match", "aop" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Aop/Aop.php#L189-L214
swoft-cloud/swoft-framework
src/Aop/Aop.php
Aop.register
public function register(array $aspects) { $temp = \array_column($aspects, 'order'); \array_multisort($temp, SORT_ASC, $aspects); $this->aspects = $aspects; }
php
public function register(array $aspects) { $temp = \array_column($aspects, 'order'); \array_multisort($temp, SORT_ASC, $aspects); $this->aspects = $aspects; }
[ "public", "function", "register", "(", "array", "$", "aspects", ")", "{", "$", "temp", "=", "\\", "array_column", "(", "$", "aspects", ",", "'order'", ")", ";", "\\", "array_multisort", "(", "$", "temp", ",", "SORT_ASC", ",", "$", "aspects", ")", ";", ...
Register aspects @param array $aspects
[ "Register", "aspects" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Aop/Aop.php#L221-L226
swoft-cloud/swoft-framework
src/Aop/Aop.php
Aop.matchBeanAndAnnotation
private function matchBeanAndAnnotation(array $pointAry, array $classAry): bool { $intersectAry = \array_intersect($pointAry, $classAry); if (empty($intersectAry)) { return false; } return true; }
php
private function matchBeanAndAnnotation(array $pointAry, array $classAry): bool { $intersectAry = \array_intersect($pointAry, $classAry); if (empty($intersectAry)) { return false; } return true; }
[ "private", "function", "matchBeanAndAnnotation", "(", "array", "$", "pointAry", ",", "array", "$", "classAry", ")", ":", "bool", "{", "$", "intersectAry", "=", "\\", "array_intersect", "(", "$", "pointAry", ",", "$", "classAry", ")", ";", "if", "(", "empty...
Match bean and annotation @param array $pointAry @param array $classAry @return bool
[ "Match", "bean", "and", "annotation" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Aop/Aop.php#L235-L243
swoft-cloud/swoft-framework
src/Aop/Aop.php
Aop.matchExecution
private function matchExecution(string $class, string $method, array $executions): bool { foreach ($executions as $execution) { $executionAry = \explode('::', $execution); if (\count($executionAry) < 2) { continue; } // Class list($executionClass, $executionMethod) = $executionAry; if ($executionClass !== $class) { continue; } // Method $reg = '/^(?:' . $executionMethod . ')$/'; if (\preg_match($reg, $method)) { return true; } } return false; }
php
private function matchExecution(string $class, string $method, array $executions): bool { foreach ($executions as $execution) { $executionAry = \explode('::', $execution); if (\count($executionAry) < 2) { continue; } // Class list($executionClass, $executionMethod) = $executionAry; if ($executionClass !== $class) { continue; } // Method $reg = '/^(?:' . $executionMethod . ')$/'; if (\preg_match($reg, $method)) { return true; } } return false; }
[ "private", "function", "matchExecution", "(", "string", "$", "class", ",", "string", "$", "method", ",", "array", "$", "executions", ")", ":", "bool", "{", "foreach", "(", "$", "executions", "as", "$", "execution", ")", "{", "$", "executionAry", "=", "\\...
Match execution @param string $class @param string $method @param array $executions @return bool
[ "Match", "execution" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Aop/Aop.php#L253-L275
swoft-cloud/swoft-framework
src/Event/Event.php
Event.addParam
public function addParam($name, $value): self { if (!isset($this->params[$name])) { $this->setParam($name, $value); } return $this; }
php
public function addParam($name, $value): self { if (!isset($this->params[$name])) { $this->setParam($name, $value); } return $this; }
[ "public", "function", "addParam", "(", "$", "name", ",", "$", "value", ")", ":", "self", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "params", "[", "$", "name", "]", ")", ")", "{", "$", "this", "->", "setParam", "(", "$", "name", ",",...
add a argument @param $name @param $value @return $this @throws \InvalidArgumentException
[ "add", "a", "argument" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Event/Event.php#L125-L132
swoft-cloud/swoft-framework
src/Event/Event.php
Event.setParam
public function setParam($name, $value): self { if (null === $name) { throw new \InvalidArgumentException('The argument name cannot be null.'); } $this->params[$name] = $value; return $this; }
php
public function setParam($name, $value): self { if (null === $name) { throw new \InvalidArgumentException('The argument name cannot be null.'); } $this->params[$name] = $value; return $this; }
[ "public", "function", "setParam", "(", "$", "name", ",", "$", "value", ")", ":", "self", "{", "if", "(", "null", "===", "$", "name", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The argument name cannot be null.'", ")", ";", "}", "$",...
set a argument @param $name @param $value @throws \InvalidArgumentException If the argument name is null. @return $this
[ "set", "a", "argument" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Event/Event.php#L141-L150
swoft-cloud/swoft-framework
src/Event/Event.php
Event.unserialize
public function unserialize($serialized) { list( $this->name, $this->params, $this->stopPropagation ) = \unserialize($serialized, ['allowed_classes' => false]); }
php
public function unserialize($serialized) { list( $this->name, $this->params, $this->stopPropagation ) = \unserialize($serialized, ['allowed_classes' => false]); }
[ "public", "function", "unserialize", "(", "$", "serialized", ")", "{", "list", "(", "$", "this", "->", "name", ",", "$", "this", "->", "params", ",", "$", "this", "->", "stopPropagation", ")", "=", "\\", "unserialize", "(", "$", "serialized", ",", "[",...
Unserialize the event. @param string $serialized The serialized event. @return void
[ "Unserialize", "the", "event", "." ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Event/Event.php#L232-L239
swoft-cloud/swoft-framework
src/Core/AbstractCoResult.php
AbstractCoResult.recv
public function recv($defer = false) { if ($this->connection instanceof ConnectionInterface) { $result = $this->connection->receive(); $this->connection->release(); return $result; } $result = $this->connection->recv(); if ($defer) { $this->connection->setDefer(false); } return $result; }
php
public function recv($defer = false) { if ($this->connection instanceof ConnectionInterface) { $result = $this->connection->receive(); $this->connection->release(); return $result; } $result = $this->connection->recv(); if ($defer) { $this->connection->setDefer(false); } return $result; }
[ "public", "function", "recv", "(", "$", "defer", "=", "false", ")", "{", "if", "(", "$", "this", "->", "connection", "instanceof", "ConnectionInterface", ")", "{", "$", "result", "=", "$", "this", "->", "connection", "->", "receive", "(", ")", ";", "$"...
Receive by defer @param bool $defer @return mixed
[ "Receive", "by", "defer" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Core/AbstractCoResult.php#L41-L56
swoft-cloud/swoft-framework
src/Core/AbstractResult.php
AbstractResult.recv
protected function recv(bool $defer = false, bool $release = true) { if ($this->connection instanceof ConnectionInterface) { try { $result = $this->connection->receive(); } catch (\Throwable $throwable) { throw $throwable; } finally { $this->release($release); } return $result; } try { $result = $this->connection->recv(); } catch (\Throwable $throwable) { throw $throwable; } finally { if ($defer) { $this->connection->setDefer(false); } } return $result; }
php
protected function recv(bool $defer = false, bool $release = true) { if ($this->connection instanceof ConnectionInterface) { try { $result = $this->connection->receive(); } catch (\Throwable $throwable) { throw $throwable; } finally { $this->release($release); } return $result; } try { $result = $this->connection->recv(); } catch (\Throwable $throwable) { throw $throwable; } finally { if ($defer) { $this->connection->setDefer(false); } } return $result; }
[ "protected", "function", "recv", "(", "bool", "$", "defer", "=", "false", ",", "bool", "$", "release", "=", "true", ")", "{", "if", "(", "$", "this", "->", "connection", "instanceof", "ConnectionInterface", ")", "{", "try", "{", "$", "result", "=", "$"...
Receive by defer @param bool $defer @param bool $release @return mixed
[ "Receive", "by", "defer" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Core/AbstractResult.php#L49-L74
swoft-cloud/swoft-framework
src/App.php
App.setProperties
public static function setProperties($properties = null) { if ($properties === null) { $properties = self::getProperties(); } self::$properties = $properties; }
php
public static function setProperties($properties = null) { if ($properties === null) { $properties = self::getProperties(); } self::$properties = $properties; }
[ "public", "static", "function", "setProperties", "(", "$", "properties", "=", "null", ")", "{", "if", "(", "$", "properties", "===", "null", ")", "{", "$", "properties", "=", "self", "::", "getProperties", "(", ")", ";", "}", "self", "::", "$", "proper...
初始化配置对象 @param Config $properties 容器中config对象
[ "初始化配置对象" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/App.php#L150-L157
swoft-cloud/swoft-framework
src/App.php
App.getPool
public static function getPool(string $name): PoolInterface { $collector = PoolCollector::getCollector(); if (!isset($collector[$name])) { throw new InvalidArgumentException("the pool of $name is not exist!"); } $poolBeanName = $collector[$name]; return self::getBean($poolBeanName); }
php
public static function getPool(string $name): PoolInterface { $collector = PoolCollector::getCollector(); if (!isset($collector[$name])) { throw new InvalidArgumentException("the pool of $name is not exist!"); } $poolBeanName = $collector[$name]; return self::getBean($poolBeanName); }
[ "public", "static", "function", "getPool", "(", "string", "$", "name", ")", ":", "PoolInterface", "{", "$", "collector", "=", "PoolCollector", "::", "getCollector", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "collector", "[", "$", "name", "]", "...
get pool by name @param string $name @return PoolInterface @throws \Swoft\Exception\InvalidArgumentException
[ "get", "pool", "by", "name" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/App.php#L193-L203
swoft-cloud/swoft-framework
src/App.php
App.hasPool
public static function hasPool(string $name): bool { $collector = PoolCollector::getCollector(); return isset($collector[$name]); }
php
public static function hasPool(string $name): bool { $collector = PoolCollector::getCollector(); return isset($collector[$name]); }
[ "public", "static", "function", "hasPool", "(", "string", "$", "name", ")", ":", "bool", "{", "$", "collector", "=", "PoolCollector", "::", "getCollector", "(", ")", ";", "return", "isset", "(", "$", "collector", "[", "$", "name", "]", ")", ";", "}" ]
@param string $name @return bool
[ "@param", "string", "$name" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/App.php#L210-L215
swoft-cloud/swoft-framework
src/App.php
App.trigger
public static function trigger($event, $target = null, ...$params) { /** @var \Swoft\Event\EventManager $em */ $em = ApplicationContext::getBean('eventManager'); return $em->trigger($event, $target, $params); }
php
public static function trigger($event, $target = null, ...$params) { /** @var \Swoft\Event\EventManager $em */ $em = ApplicationContext::getBean('eventManager'); return $em->trigger($event, $target, $params); }
[ "public", "static", "function", "trigger", "(", "$", "event", ",", "$", "target", "=", "null", ",", "...", "$", "params", ")", "{", "/** @var \\Swoft\\Event\\EventManager $em */", "$", "em", "=", "ApplicationContext", "::", "getBean", "(", "'eventManager'", ")",...
触发事件 @param string|\Swoft\Event\EventInterface $event 发布的事件名称|对象 @param mixed $target @param array $params 附加数据信息 @return mixed @throws \InvalidArgumentException
[ "触发事件" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/App.php#L237-L243
swoft-cloud/swoft-framework
src/App.php
App.setAliases
public static function setAliases(array $aliases) { foreach ($aliases as $name => $path) { self::setAlias($name, $path); } }
php
public static function setAliases(array $aliases) { foreach ($aliases as $name => $path) { self::setAlias($name, $path); } }
[ "public", "static", "function", "setAliases", "(", "array", "$", "aliases", ")", "{", "foreach", "(", "$", "aliases", "as", "$", "name", "=>", "$", "path", ")", "{", "self", "::", "setAlias", "(", "$", "name", ",", "$", "path", ")", ";", "}", "}" ]
注册多个别名 @param array $aliases 别名数组 <pre> [ '@root' => BASE_PATH ...... ] </pre> @throws \InvalidArgumentException
[ "注册多个别名" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/App.php#L258-L263
swoft-cloud/swoft-framework
src/App.php
App.setAlias
public static function setAlias(string $alias, string $path = null) { if ($alias[0] !== '@') { $alias = '@' . $alias; } // Delete alias if (!$path) { unset(self::$aliases[$alias]); return; } // $path 不是别名,直接设置 if ($path[0] !== '@') { self::$aliases[$alias] = $path; return; } // $path是一个别名 if (isset(self::$aliases[$path])) { self::$aliases[$alias] = self::$aliases[$path]; return; } list($root) = explode('/', $path); if (!isset(self::$aliases[$root])) { throw new \InvalidArgumentException('The set root alias does not exist,alias=' . $root); } $rootPath = self::$aliases[$root]; $aliasPath = str_replace($root, '', $path); self::$aliases[$alias] = $rootPath . $aliasPath; }
php
public static function setAlias(string $alias, string $path = null) { if ($alias[0] !== '@') { $alias = '@' . $alias; } // Delete alias if (!$path) { unset(self::$aliases[$alias]); return; } // $path 不是别名,直接设置 if ($path[0] !== '@') { self::$aliases[$alias] = $path; return; } // $path是一个别名 if (isset(self::$aliases[$path])) { self::$aliases[$alias] = self::$aliases[$path]; return; } list($root) = explode('/', $path); if (!isset(self::$aliases[$root])) { throw new \InvalidArgumentException('The set root alias does not exist,alias=' . $root); } $rootPath = self::$aliases[$root]; $aliasPath = str_replace($root, '', $path); self::$aliases[$alias] = $rootPath . $aliasPath; }
[ "public", "static", "function", "setAlias", "(", "string", "$", "alias", ",", "string", "$", "path", "=", "null", ")", "{", "if", "(", "$", "alias", "[", "0", "]", "!==", "'@'", ")", "{", "$", "alias", "=", "'@'", ".", "$", "alias", ";", "}", "...
Set alias @param string $alias alias @param string $path path @throws \InvalidArgumentException
[ "Set", "alias" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/App.php#L273-L309
swoft-cloud/swoft-framework
src/App.php
App.getAlias
public static function getAlias(string $alias): string { // empty OR not an alias if (!$alias || $alias[0] !== '@') { return $alias; } if (isset(self::$aliases[$alias])) { return self::$aliases[$alias]; } list($root) = \explode('/', $alias, 2); if (!isset(self::$aliases[$root])) { throw new \InvalidArgumentException('The set root alias does not exist,alias=' . $root); } $rootPath = self::$aliases[$root]; $aliasPath = \str_replace($root, '', $alias); return $rootPath . $aliasPath; }
php
public static function getAlias(string $alias): string { // empty OR not an alias if (!$alias || $alias[0] !== '@') { return $alias; } if (isset(self::$aliases[$alias])) { return self::$aliases[$alias]; } list($root) = \explode('/', $alias, 2); if (!isset(self::$aliases[$root])) { throw new \InvalidArgumentException('The set root alias does not exist,alias=' . $root); } $rootPath = self::$aliases[$root]; $aliasPath = \str_replace($root, '', $alias); return $rootPath . $aliasPath; }
[ "public", "static", "function", "getAlias", "(", "string", "$", "alias", ")", ":", "string", "{", "// empty OR not an alias", "if", "(", "!", "$", "alias", "||", "$", "alias", "[", "0", "]", "!==", "'@'", ")", "{", "return", "$", "alias", ";", "}", "...
Get alias @param string $alias @return string @throws \InvalidArgumentException
[ "Get", "alias" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/App.php#L319-L339
swoft-cloud/swoft-framework
src/App.php
App.hasAlias
public static function hasAlias(string $alias): bool { // empty OR not an alias if (!$alias || $alias[0] !== '@') { return false; } return isset(self::$aliases[$alias]); }
php
public static function hasAlias(string $alias): bool { // empty OR not an alias if (!$alias || $alias[0] !== '@') { return false; } return isset(self::$aliases[$alias]); }
[ "public", "static", "function", "hasAlias", "(", "string", "$", "alias", ")", ":", "bool", "{", "// empty OR not an alias", "if", "(", "!", "$", "alias", "||", "$", "alias", "[", "0", "]", "!==", "'@'", ")", "{", "return", "false", ";", "}", "return", ...
Is alias exist ? @param string $alias @return bool @throws \InvalidArgumentException
[ "Is", "alias", "exist", "?" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/App.php#L349-L357
swoft-cloud/swoft-framework
src/App.php
App.getWorkerId
public static function getWorkerId(): int { if (self::$server === null) { return 0; } $server = self::$server->getServer(); if ($server && \property_exists($server, 'worker_id') && $server->worker_id > 0) { return $server->worker_id; } return 0; }
php
public static function getWorkerId(): int { if (self::$server === null) { return 0; } $server = self::$server->getServer(); if ($server && \property_exists($server, 'worker_id') && $server->worker_id > 0) { return $server->worker_id; } return 0; }
[ "public", "static", "function", "getWorkerId", "(", ")", ":", "int", "{", "if", "(", "self", "::", "$", "server", "===", "null", ")", "{", "return", "0", ";", "}", "$", "server", "=", "self", "::", "$", "server", "->", "getServer", "(", ")", ";", ...
Get workerId
[ "Get", "workerId" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/App.php#L466-L479
swoft-cloud/swoft-framework
src/App.php
App.counting
public static function counting(string $name, int $hit, $total = null) { self::getLogger()->counting($name, $hit, $total); }
php
public static function counting(string $name, int $hit, $total = null) { self::getLogger()->counting($name, $hit, $total); }
[ "public", "static", "function", "counting", "(", "string", "$", "name", ",", "int", "$", "hit", ",", "$", "total", "=", "null", ")", "{", "self", "::", "getLogger", "(", ")", "->", "counting", "(", "$", "name", ",", "$", "hit", ",", "$", "total", ...
命中率计算 @param string $name 名称 @param int $hit 命中 @param int $total 总共
[ "命中率计算" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/App.php#L498-L501
swoft-cloud/swoft-framework
src/Bean/Resource/AnnotationResource.php
AnnotationResource.getDefinitions
public function getDefinitions() { // 获取扫描的PHP文件 $classNames = $this->registerLoaderAndScanBean(); $fileClassNames = $this->scanFilePhpClass(); $classNames = array_merge($classNames, $fileClassNames); foreach ($classNames as $className) { $this->parseBeanAnnotations($className); } $this->parseAnnotationsData(); return $this->definitions; }
php
public function getDefinitions() { // 获取扫描的PHP文件 $classNames = $this->registerLoaderAndScanBean(); $fileClassNames = $this->scanFilePhpClass(); $classNames = array_merge($classNames, $fileClassNames); foreach ($classNames as $className) { $this->parseBeanAnnotations($className); } $this->parseAnnotationsData(); return $this->definitions; }
[ "public", "function", "getDefinitions", "(", ")", "{", "// 获取扫描的PHP文件", "$", "classNames", "=", "$", "this", "->", "registerLoaderAndScanBean", "(", ")", ";", "$", "fileClassNames", "=", "$", "this", "->", "scanFilePhpClass", "(", ")", ";", "$", "classNames", ...
获取已解析的配置beans @return array <pre> [ 'beanName' => ObjectDefinition, ... ] </pre>
[ "获取已解析的配置beans" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Resource/AnnotationResource.php#L113-L127
swoft-cloud/swoft-framework
src/Bean/Resource/AnnotationResource.php
AnnotationResource.parseBeanAnnotations
public function parseBeanAnnotations(string $className) { if (!class_exists($className) && !interface_exists($className)) { return null; } // 注解解析器 $reader = new AnnotationReader(); $reader = $this->addIgnoredNames($reader); $reflectionClass = new \ReflectionClass($className); $classAnnotations = $reader->getClassAnnotations($reflectionClass); // 没有类注解不解析其它注解 if (empty($classAnnotations)) { return; } foreach ($classAnnotations as $classAnnotation) { $this->annotations[$className]['class'][get_class($classAnnotation)] = $classAnnotation; } // 解析属性 $properties = $reflectionClass->getProperties(); foreach ($properties as $property) { if ($property->isStatic()) { continue; } $propertyName = $property->getName(); $propertyAnnotations = $reader->getPropertyAnnotations($property); foreach ($propertyAnnotations as $propertyAnnotation) { $this->annotations[$className]['property'][$propertyName][get_class($propertyAnnotation)] = $propertyAnnotation; } } // 解析方法 $publicMethods = $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC); foreach ($publicMethods as $method) { if ($method->isStatic()) { continue; } $methodName = $method->getName(); // 解析方法注解 $methodAnnotations = $reader->getMethodAnnotations($method); foreach ($methodAnnotations as $methodAnnotation) { $this->annotations[$className]['method'][$methodName][get_class($methodAnnotation)][] = $methodAnnotation; } } }
php
public function parseBeanAnnotations(string $className) { if (!class_exists($className) && !interface_exists($className)) { return null; } // 注解解析器 $reader = new AnnotationReader(); $reader = $this->addIgnoredNames($reader); $reflectionClass = new \ReflectionClass($className); $classAnnotations = $reader->getClassAnnotations($reflectionClass); // 没有类注解不解析其它注解 if (empty($classAnnotations)) { return; } foreach ($classAnnotations as $classAnnotation) { $this->annotations[$className]['class'][get_class($classAnnotation)] = $classAnnotation; } // 解析属性 $properties = $reflectionClass->getProperties(); foreach ($properties as $property) { if ($property->isStatic()) { continue; } $propertyName = $property->getName(); $propertyAnnotations = $reader->getPropertyAnnotations($property); foreach ($propertyAnnotations as $propertyAnnotation) { $this->annotations[$className]['property'][$propertyName][get_class($propertyAnnotation)] = $propertyAnnotation; } } // 解析方法 $publicMethods = $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC); foreach ($publicMethods as $method) { if ($method->isStatic()) { continue; } $methodName = $method->getName(); // 解析方法注解 $methodAnnotations = $reader->getMethodAnnotations($method); foreach ($methodAnnotations as $methodAnnotation) { $this->annotations[$className]['method'][$methodName][get_class($methodAnnotation)][] = $methodAnnotation; } } }
[ "public", "function", "parseBeanAnnotations", "(", "string", "$", "className", ")", "{", "if", "(", "!", "class_exists", "(", "$", "className", ")", "&&", "!", "interface_exists", "(", "$", "className", ")", ")", "{", "return", "null", ";", "}", "// 注解解析器"...
解析bean注解 @param string $className @return null
[ "解析bean注解" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Resource/AnnotationResource.php#L136-L186
swoft-cloud/swoft-framework
src/Bean/Resource/AnnotationResource.php
AnnotationResource.parseAnnotationsData
public function parseAnnotationsData() { foreach ($this->annotations as $className => $annotation) { $classAnnotations = $annotation['class']; $this->parseClassAnnotations($className, $annotation, $classAnnotations); } }
php
public function parseAnnotationsData() { foreach ($this->annotations as $className => $annotation) { $classAnnotations = $annotation['class']; $this->parseClassAnnotations($className, $annotation, $classAnnotations); } }
[ "public", "function", "parseAnnotationsData", "(", ")", "{", "foreach", "(", "$", "this", "->", "annotations", "as", "$", "className", "=>", "$", "annotation", ")", "{", "$", "classAnnotations", "=", "$", "annotation", "[", "'class'", "]", ";", "$", "this"...
解析注解数据
[ "解析注解数据" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Resource/AnnotationResource.php#L191-L197
swoft-cloud/swoft-framework
src/Bean/Resource/AnnotationResource.php
AnnotationResource.scanPhpFile
protected function scanPhpFile(string $dir, string $namespace) { if (!is_dir($dir)) { return []; } $iterator = new \RecursiveDirectoryIterator($dir); $files = new \RecursiveIteratorIterator($iterator); $phpFiles = []; foreach ($files as $file) { $fileType = pathinfo($file, PATHINFO_EXTENSION); if ($fileType != 'php') { continue; } $replaces = ['', '\\', '', '']; $searches = [$dir, '/', '.php', '.PHP']; $file = str_replace($searches, $replaces, $file); $phpFiles[] = $namespace . $file; } return $phpFiles; }
php
protected function scanPhpFile(string $dir, string $namespace) { if (!is_dir($dir)) { return []; } $iterator = new \RecursiveDirectoryIterator($dir); $files = new \RecursiveIteratorIterator($iterator); $phpFiles = []; foreach ($files as $file) { $fileType = pathinfo($file, PATHINFO_EXTENSION); if ($fileType != 'php') { continue; } $replaces = ['', '\\', '', '']; $searches = [$dir, '/', '.php', '.PHP']; $file = str_replace($searches, $replaces, $file); $phpFiles[] = $namespace . $file; } return $phpFiles; }
[ "protected", "function", "scanPhpFile", "(", "string", "$", "dir", ",", "string", "$", "namespace", ")", "{", "if", "(", "!", "is_dir", "(", "$", "dir", ")", ")", "{", "return", "[", "]", ";", "}", "$", "iterator", "=", "new", "\\", "RecursiveDirecto...
扫描目录下PHP文件 @param string $dir @param string $namespace @return array
[ "扫描目录下PHP文件" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Resource/AnnotationResource.php#L235-L259
swoft-cloud/swoft-framework
src/Bean/Resource/AnnotationResource.php
AnnotationResource.scanFilePhpClass
protected function scanFilePhpClass() { $phpClass = []; foreach ($this->scanFiles as $ns => $files) { foreach ($files as $file) { $pathInfo = pathinfo($file); if (!isset($pathInfo['filename'])) { continue; } $phpClass[] = $ns . "\\" . $pathInfo['filename']; } } return $phpClass; }
php
protected function scanFilePhpClass() { $phpClass = []; foreach ($this->scanFiles as $ns => $files) { foreach ($files as $file) { $pathInfo = pathinfo($file); if (!isset($pathInfo['filename'])) { continue; } $phpClass[] = $ns . "\\" . $pathInfo['filename']; } } return $phpClass; }
[ "protected", "function", "scanFilePhpClass", "(", ")", "{", "$", "phpClass", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "scanFiles", "as", "$", "ns", "=>", "$", "files", ")", "{", "foreach", "(", "$", "files", "as", "$", "file", ")", "{...
scan files
[ "scan", "files" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Resource/AnnotationResource.php#L264-L278
swoft-cloud/swoft-framework
src/Bean/Resource/AnnotationResource.php
AnnotationResource.registerLoaderAndScanBean
protected function registerLoaderAndScanBean() { $phpClass = []; foreach ($this->scanNamespaces as $namespace => $dir) { AnnotationRegistry::registerLoader(function ($class) { if (class_exists($class) || interface_exists($class)) { return true; } return false; }); $scanClass = $this->scanPhpFile($dir, $namespace); $phpClass = array_merge($phpClass, $scanClass); } return array_unique($phpClass); }
php
protected function registerLoaderAndScanBean() { $phpClass = []; foreach ($this->scanNamespaces as $namespace => $dir) { AnnotationRegistry::registerLoader(function ($class) { if (class_exists($class) || interface_exists($class)) { return true; } return false; }); $scanClass = $this->scanPhpFile($dir, $namespace); $phpClass = array_merge($phpClass, $scanClass); } return array_unique($phpClass); }
[ "protected", "function", "registerLoaderAndScanBean", "(", ")", "{", "$", "phpClass", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "scanNamespaces", "as", "$", "namespace", "=>", "$", "dir", ")", "{", "AnnotationRegistry", "::", "registerLoader", "...
注册加载器和扫描PHP文件 @return array
[ "注册加载器和扫描PHP文件" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Resource/AnnotationResource.php#L285-L301
swoft-cloud/swoft-framework
src/Bean/Resource/AnnotationResource.php
AnnotationResource.addIgnoredNames
protected function addIgnoredNames(AnnotationReader $reader) { foreach ($this->ignoredNames as $name) { $reader->addGlobalIgnoredName($name); } return $reader; }
php
protected function addIgnoredNames(AnnotationReader $reader) { foreach ($this->ignoredNames as $name) { $reader->addGlobalIgnoredName($name); } return $reader; }
[ "protected", "function", "addIgnoredNames", "(", "AnnotationReader", "$", "reader", ")", "{", "foreach", "(", "$", "this", "->", "ignoredNames", "as", "$", "name", ")", "{", "$", "reader", "->", "addGlobalIgnoredName", "(", "$", "name", ")", ";", "}", "ret...
add ignored names @param AnnotationReader $reader @return AnnotationReader
[ "add", "ignored", "names" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Resource/AnnotationResource.php#L310-L317
swoft-cloud/swoft-framework
src/Bean/Resource/AnnotationResource.php
AnnotationResource.parseClassAnnotations
private function parseClassAnnotations(string $className, array $annotation, array $classAnnotations) { foreach ($classAnnotations as $classAnnotation) { $annotationClassName = get_class($classAnnotation); $classNameTmp = str_replace('\\', '/', $annotationClassName); $classFileName = basename($classNameTmp); $beanNamespaceTmp = dirname($classNameTmp, 2); $beanNamespace = str_replace('/', '\\', $beanNamespaceTmp); $annotationWrapperClassName = "{$beanNamespace}\\Wrapper\\{$classFileName}Wrapper"; if (!class_exists($annotationWrapperClassName)) { continue; } /* @var WrapperInterface $wrapper */ $wrapper = new $annotationWrapperClassName($this); // wrapper extend foreach ($this->componentNamespaces as $componentNamespace) { $annotationWrapperExtendClassName = "{$componentNamespace}\\Bean\\Wrapper\\Extend\\{$classFileName}Extend"; if (!class_exists($annotationWrapperExtendClassName)) { continue; } $extend = new $annotationWrapperExtendClassName(); $wrapper->addExtends($extend); } $objectDefinitionAry = $wrapper->doWrapper($className, $annotation); if ($objectDefinitionAry != null) { list($beanName, $objectDefinition) = $objectDefinitionAry; $this->definitions[$beanName] = $objectDefinition; } } }
php
private function parseClassAnnotations(string $className, array $annotation, array $classAnnotations) { foreach ($classAnnotations as $classAnnotation) { $annotationClassName = get_class($classAnnotation); $classNameTmp = str_replace('\\', '/', $annotationClassName); $classFileName = basename($classNameTmp); $beanNamespaceTmp = dirname($classNameTmp, 2); $beanNamespace = str_replace('/', '\\', $beanNamespaceTmp); $annotationWrapperClassName = "{$beanNamespace}\\Wrapper\\{$classFileName}Wrapper"; if (!class_exists($annotationWrapperClassName)) { continue; } /* @var WrapperInterface $wrapper */ $wrapper = new $annotationWrapperClassName($this); // wrapper extend foreach ($this->componentNamespaces as $componentNamespace) { $annotationWrapperExtendClassName = "{$componentNamespace}\\Bean\\Wrapper\\Extend\\{$classFileName}Extend"; if (!class_exists($annotationWrapperExtendClassName)) { continue; } $extend = new $annotationWrapperExtendClassName(); $wrapper->addExtends($extend); } $objectDefinitionAry = $wrapper->doWrapper($className, $annotation); if ($objectDefinitionAry != null) { list($beanName, $objectDefinition) = $objectDefinitionAry; $this->definitions[$beanName] = $objectDefinition; } } }
[ "private", "function", "parseClassAnnotations", "(", "string", "$", "className", ",", "array", "$", "annotation", ",", "array", "$", "classAnnotations", ")", "{", "foreach", "(", "$", "classAnnotations", "as", "$", "classAnnotation", ")", "{", "$", "annotationCl...
类注解封装 @param string $className @param array $annotation @param array $classAnnotations
[ "类注解封装" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bean/Resource/AnnotationResource.php#L326-L360
swoft-cloud/swoft-framework
src/Bootstrap/Listeners/BeforeStartListener.php
BeforeStartListener.checkTask
private function checkTask() { $settings = App::getAppProperties()->get('server'); $settings = $settings['setting']; $collector = SwooleListenerCollector::getCollector(); $isConfigTask = isset($settings['task_worker_num']) && $settings['task_worker_num'] > 0; $isInstallTask = isset($collector[SwooleEvent::TYPE_SERVER][SwooleEvent::ON_TASK]) && isset($collector[SwooleEvent::TYPE_SERVER][SwooleEvent::ON_FINISH]); if ($isConfigTask && !$isInstallTask) { throw new InvalidArgumentException("Please 'composer require swoft/task' or set task_worker_num=0 !"); } if (!$isConfigTask && $isInstallTask) { throw new InvalidArgumentException('Please set task_worker_num > 0 !'); } }
php
private function checkTask() { $settings = App::getAppProperties()->get('server'); $settings = $settings['setting']; $collector = SwooleListenerCollector::getCollector(); $isConfigTask = isset($settings['task_worker_num']) && $settings['task_worker_num'] > 0; $isInstallTask = isset($collector[SwooleEvent::TYPE_SERVER][SwooleEvent::ON_TASK]) && isset($collector[SwooleEvent::TYPE_SERVER][SwooleEvent::ON_FINISH]); if ($isConfigTask && !$isInstallTask) { throw new InvalidArgumentException("Please 'composer require swoft/task' or set task_worker_num=0 !"); } if (!$isConfigTask && $isInstallTask) { throw new InvalidArgumentException('Please set task_worker_num > 0 !'); } }
[ "private", "function", "checkTask", "(", ")", "{", "$", "settings", "=", "App", "::", "getAppProperties", "(", ")", "->", "get", "(", "'server'", ")", ";", "$", "settings", "=", "$", "settings", "[", "'setting'", "]", ";", "$", "collector", "=", "Swool...
check task @throws \Swoft\Exception\InvalidArgumentException
[ "check", "task" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Bootstrap/Listeners/BeforeStartListener.php#L38-L54
swoft-cloud/swoft-framework
src/Event/EventManager.php
EventManager.attach
public function attach($event, $callback, $priority = 0): bool { return $this->addListener($callback, [$event => $priority]); }
php
public function attach($event, $callback, $priority = 0): bool { return $this->addListener($callback, [$event => $priority]); }
[ "public", "function", "attach", "(", "$", "event", ",", "$", "callback", ",", "$", "priority", "=", "0", ")", ":", "bool", "{", "return", "$", "this", "->", "addListener", "(", "$", "callback", ",", "[", "$", "event", "=>", "$", "priority", "]", ")...
Attaches a listener to an event @param string $event the event to attach too @param callable|EventHandlerInterface|mixed $callback A callable listener @param int $priority the priority at which the $callback executed @return bool true on success false on failure
[ "Attaches", "a", "listener", "to", "an", "event" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Event/EventManager.php#L84-L87
swoft-cloud/swoft-framework
src/Event/EventManager.php
EventManager.addListener
public function addListener($listener, $definition = null): bool { // ensure $listener is a object. if (!\is_object($listener)) { if (\is_string($listener) && \class_exists($listener)) { $listener = new $listener; // like 'function' OR '[object, method]' } else { $listener = new LazyListener($listener); } } $defaultPriority = ListenerPriority::NORMAL; if (is_numeric($definition)) { $defaultPriority = (int)$definition; $definition = null; } elseif (\is_string($definition)) { // 仅是个 事件名称 $definition = [$definition => $defaultPriority]; } elseif ($definition instanceof EventInterface) { // 仅是个 事件对象,取出名称 $definition = [$definition->getName() => $defaultPriority]; } if ($listener instanceof EventSubscriberInterface) { foreach ($listener::getSubscribedEvents() as $name => $conf) { if (!isset($this->listeners[$name])) { $this->listeners[$name] = new ListenerQueue; } $queue = $this->listeners[$name]; if (\is_string($conf)) { $queue->add(new LazyListener([$listener, $conf]), $defaultPriority); // ['onPost', ListenerPriority::LOW] } elseif (\is_string($conf[0])) { $queue->add(new LazyListener([$listener, $conf[0]]), $conf[1] ?? $defaultPriority); } } return true; } // 将 监听器 关联到 各个事件 if ($definition) { foreach ($definition as $name => $priority) { if (\is_int($name)) { if (!$priority || !\is_string($priority)) { continue; } $name = $priority; $priority = $defaultPriority; } if (!$name = trim($name, '. ')) { continue; } if (!isset($this->listeners[$name])) { $this->listeners[$name] = new ListenerQueue; } $this->listeners[$name]->add($listener, $priority); } return true; } return false; }
php
public function addListener($listener, $definition = null): bool { // ensure $listener is a object. if (!\is_object($listener)) { if (\is_string($listener) && \class_exists($listener)) { $listener = new $listener; // like 'function' OR '[object, method]' } else { $listener = new LazyListener($listener); } } $defaultPriority = ListenerPriority::NORMAL; if (is_numeric($definition)) { $defaultPriority = (int)$definition; $definition = null; } elseif (\is_string($definition)) { // 仅是个 事件名称 $definition = [$definition => $defaultPriority]; } elseif ($definition instanceof EventInterface) { // 仅是个 事件对象,取出名称 $definition = [$definition->getName() => $defaultPriority]; } if ($listener instanceof EventSubscriberInterface) { foreach ($listener::getSubscribedEvents() as $name => $conf) { if (!isset($this->listeners[$name])) { $this->listeners[$name] = new ListenerQueue; } $queue = $this->listeners[$name]; if (\is_string($conf)) { $queue->add(new LazyListener([$listener, $conf]), $defaultPriority); // ['onPost', ListenerPriority::LOW] } elseif (\is_string($conf[0])) { $queue->add(new LazyListener([$listener, $conf[0]]), $conf[1] ?? $defaultPriority); } } return true; } // 将 监听器 关联到 各个事件 if ($definition) { foreach ($definition as $name => $priority) { if (\is_int($name)) { if (!$priority || !\is_string($priority)) { continue; } $name = $priority; $priority = $defaultPriority; } if (!$name = trim($name, '. ')) { continue; } if (!isset($this->listeners[$name])) { $this->listeners[$name] = new ListenerQueue; } $this->listeners[$name]->add($listener, $priority); } return true; } return false; }
[ "public", "function", "addListener", "(", "$", "listener", ",", "$", "definition", "=", "null", ")", ":", "bool", "{", "// ensure $listener is a object.", "if", "(", "!", "\\", "is_object", "(", "$", "listener", ")", ")", "{", "if", "(", "\\", "is_string",...
添加监听器 并关联到 某一个(多个)事件 @param \Closure|callback|mixed $listener 监听器 @param array|string|int $definition 事件名,优先级设置 Allowed: $definition = [ 'event name' => priority(int), 'event name1' => priority(int), ] OR $definition = [ 'event name','event name1', ] OR $definition = 'event name' OR // The priority of the listener 监听器的优先级 $definition = 1 @return bool
[ "添加监听器", "并关联到", "某一个", "(", "多个", ")", "事件" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Event/EventManager.php#L128-L198
swoft-cloud/swoft-framework
src/Event/EventManager.php
EventManager.trigger
public function trigger($event, $target = null, array $args = []): EventInterface { if (!$event instanceof EventInterface) { $event = (string)$event; if (isset($this->events[$event])) { $event = $this->events[$event]; } else { $event = $this->wrapperEvent($event); } } /** @var EventInterface $event */ if (!$name = $event->getName()) { throw new \InvalidArgumentException('The triggered event name cannot be empty!'); } $event->setParams($args); $event->setTarget($target); // Initial value of stop propagation flag should be false $event->stopPropagation(false); // have matched listener if (isset($this->listeners[$name])) { $this->triggerListeners($this->listeners[$name], $event); if ($event->isPropagationStopped()) { return $event; } } // have matched listener in parent if ($this->parent && ($listenerQueue = $this->parent->getListenerQueue($event))) { $this->triggerListeners($listenerQueue, $event); unset($listenerQueue); } // like 'app.start' 'app.db.query' if ($pos = \strrpos($name, '.')) { $prefix = substr($name, 0, $pos); $method = substr($name, $pos + 1); // have a group listener. eg 'app' if (isset($this->listeners[$prefix])) { $this->triggerListeners($this->listeners[$prefix], $event, $method); } if ($event->isPropagationStopped()) { return $event; } // have a wildcards listener. eg 'app.*' $wildcardEvent = $prefix . '.*'; if (isset($this->listeners[$wildcardEvent])) { $this->triggerListeners($this->listeners[$wildcardEvent], $event, $method); } if ($event->isPropagationStopped()) { return $event; } } // have global wildcards '*' listener. if (isset($this->listeners['*'])) { $this->triggerListeners($this->listeners['*'], $event); } return $event; }
php
public function trigger($event, $target = null, array $args = []): EventInterface { if (!$event instanceof EventInterface) { $event = (string)$event; if (isset($this->events[$event])) { $event = $this->events[$event]; } else { $event = $this->wrapperEvent($event); } } /** @var EventInterface $event */ if (!$name = $event->getName()) { throw new \InvalidArgumentException('The triggered event name cannot be empty!'); } $event->setParams($args); $event->setTarget($target); // Initial value of stop propagation flag should be false $event->stopPropagation(false); // have matched listener if (isset($this->listeners[$name])) { $this->triggerListeners($this->listeners[$name], $event); if ($event->isPropagationStopped()) { return $event; } } // have matched listener in parent if ($this->parent && ($listenerQueue = $this->parent->getListenerQueue($event))) { $this->triggerListeners($listenerQueue, $event); unset($listenerQueue); } // like 'app.start' 'app.db.query' if ($pos = \strrpos($name, '.')) { $prefix = substr($name, 0, $pos); $method = substr($name, $pos + 1); // have a group listener. eg 'app' if (isset($this->listeners[$prefix])) { $this->triggerListeners($this->listeners[$prefix], $event, $method); } if ($event->isPropagationStopped()) { return $event; } // have a wildcards listener. eg 'app.*' $wildcardEvent = $prefix . '.*'; if (isset($this->listeners[$wildcardEvent])) { $this->triggerListeners($this->listeners[$wildcardEvent], $event, $method); } if ($event->isPropagationStopped()) { return $event; } } // have global wildcards '*' listener. if (isset($this->listeners['*'])) { $this->triggerListeners($this->listeners['*'], $event); } return $event; }
[ "public", "function", "trigger", "(", "$", "event", ",", "$", "target", "=", "null", ",", "array", "$", "args", "=", "[", "]", ")", ":", "EventInterface", "{", "if", "(", "!", "$", "event", "instanceof", "EventInterface", ")", "{", "$", "event", "=",...
Trigger an event Can accept an EventInterface or will create one if not passed @param string|EventInterface $event 'app.start' 'app.stop' @param mixed|string $target It is object or string. @param array|mixed $args @return EventInterface @throws \InvalidArgumentException
[ "Trigger", "an", "event", "Can", "accept", "an", "EventInterface", "or", "will", "create", "one", "if", "not", "passed" ]
train
https://github.com/swoft-cloud/swoft-framework/blob/454e2f378373cbc93b07449dc305326deaab2ec2/src/Event/EventManager.php#L235-L305