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
sequencelengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
sequencelengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Template.php
Template.parseTagLib
public function parseTagLib($tagLib,&$content,$hide=false) { $begin = $this->config['taglib_begin']; $end = $this->config['taglib_end']; if(strpos($tagLib,'\\')){ // 支持指定标签库的命名空间 $className = $tagLib; $tagLib = substr($tagLib,strrpos($tagLib,'\\')+1); }else{ $className = 'Think\\Template\TagLib\\'.ucwords($tagLib); } $tLib = \Think\Think::instance($className); $that = $this; foreach ($tLib->getTags() as $name=>$val){ $tags = array($name); if(isset($val['alias'])) {// 别名设置 $tags = explode(',',$val['alias']); $tags[] = $name; } $level = isset($val['level'])?$val['level']:1; $closeTag = isset($val['close'])?$val['close']:true; foreach ($tags as $tag){ $parseTag = !$hide? $tagLib.':'.$tag: $tag;// 实际要解析的标签名称 if(!method_exists($tLib,'_'.$tag)) { // 别名可以无需定义解析方法 $tag = $name; } $n1 = empty($val['attr'])?'(\s*?)':'\s([^'.$end.']*)'; $this->tempVar = array($tagLib, $tag); if (!$closeTag){ $patterns = '/'.$begin.$parseTag.$n1.'\/(\s*?)'.$end.'/is'; $content = preg_replace_callback($patterns, function($matches) use($tLib,$tag,$that){ return $that->parseXmlTag($tLib,$tag,$matches[1],$matches[2]); },$content); }else{ $patterns = '/'.$begin.$parseTag.$n1.$end.'(.*?)'.$begin.'\/'.$parseTag.'(\s*?)'.$end.'/is'; for($i=0;$i<$level;$i++) { $content=preg_replace_callback($patterns,function($matches) use($tLib,$tag,$that){ return $that->parseXmlTag($tLib,$tag,$matches[1],$matches[2]); },$content); } } } } }
php
public function parseTagLib($tagLib,&$content,$hide=false) { $begin = $this->config['taglib_begin']; $end = $this->config['taglib_end']; if(strpos($tagLib,'\\')){ // 支持指定标签库的命名空间 $className = $tagLib; $tagLib = substr($tagLib,strrpos($tagLib,'\\')+1); }else{ $className = 'Think\\Template\TagLib\\'.ucwords($tagLib); } $tLib = \Think\Think::instance($className); $that = $this; foreach ($tLib->getTags() as $name=>$val){ $tags = array($name); if(isset($val['alias'])) {// 别名设置 $tags = explode(',',$val['alias']); $tags[] = $name; } $level = isset($val['level'])?$val['level']:1; $closeTag = isset($val['close'])?$val['close']:true; foreach ($tags as $tag){ $parseTag = !$hide? $tagLib.':'.$tag: $tag;// 实际要解析的标签名称 if(!method_exists($tLib,'_'.$tag)) { // 别名可以无需定义解析方法 $tag = $name; } $n1 = empty($val['attr'])?'(\s*?)':'\s([^'.$end.']*)'; $this->tempVar = array($tagLib, $tag); if (!$closeTag){ $patterns = '/'.$begin.$parseTag.$n1.'\/(\s*?)'.$end.'/is'; $content = preg_replace_callback($patterns, function($matches) use($tLib,$tag,$that){ return $that->parseXmlTag($tLib,$tag,$matches[1],$matches[2]); },$content); }else{ $patterns = '/'.$begin.$parseTag.$n1.$end.'(.*?)'.$begin.'\/'.$parseTag.'(\s*?)'.$end.'/is'; for($i=0;$i<$level;$i++) { $content=preg_replace_callback($patterns,function($matches) use($tLib,$tag,$that){ return $that->parseXmlTag($tLib,$tag,$matches[1],$matches[2]); },$content); } } } } }
[ "public", "function", "parseTagLib", "(", "$", "tagLib", ",", "&", "$", "content", ",", "$", "hide", "=", "false", ")", "{", "$", "begin", "=", "$", "this", "->", "config", "[", "'taglib_begin'", "]", ";", "$", "end", "=", "$", "this", "->", "config", "[", "'taglib_end'", "]", ";", "if", "(", "strpos", "(", "$", "tagLib", ",", "'\\\\'", ")", ")", "{", "// 支持指定标签库的命名空间", "$", "className", "=", "$", "tagLib", ";", "$", "tagLib", "=", "substr", "(", "$", "tagLib", ",", "strrpos", "(", "$", "tagLib", ",", "'\\\\'", ")", "+", "1", ")", ";", "}", "else", "{", "$", "className", "=", "'Think\\\\Template\\TagLib\\\\'", ".", "ucwords", "(", "$", "tagLib", ")", ";", "}", "$", "tLib", "=", "\\", "Think", "\\", "Think", "::", "instance", "(", "$", "className", ")", ";", "$", "that", "=", "$", "this", ";", "foreach", "(", "$", "tLib", "->", "getTags", "(", ")", "as", "$", "name", "=>", "$", "val", ")", "{", "$", "tags", "=", "array", "(", "$", "name", ")", ";", "if", "(", "isset", "(", "$", "val", "[", "'alias'", "]", ")", ")", "{", "// 别名设置", "$", "tags", "=", "explode", "(", "','", ",", "$", "val", "[", "'alias'", "]", ")", ";", "$", "tags", "[", "]", "=", "$", "name", ";", "}", "$", "level", "=", "isset", "(", "$", "val", "[", "'level'", "]", ")", "?", "$", "val", "[", "'level'", "]", ":", "1", ";", "$", "closeTag", "=", "isset", "(", "$", "val", "[", "'close'", "]", ")", "?", "$", "val", "[", "'close'", "]", ":", "true", ";", "foreach", "(", "$", "tags", "as", "$", "tag", ")", "{", "$", "parseTag", "=", "!", "$", "hide", "?", "$", "tagLib", ".", "':'", ".", "$", "tag", ":", "$", "tag", ";", "// 实际要解析的标签名称", "if", "(", "!", "method_exists", "(", "$", "tLib", ",", "'_'", ".", "$", "tag", ")", ")", "{", "// 别名可以无需定义解析方法", "$", "tag", "=", "$", "name", ";", "}", "$", "n1", "=", "empty", "(", "$", "val", "[", "'attr'", "]", ")", "?", "'(\\s*?)'", ":", "'\\s([^'", ".", "$", "end", ".", "']*)'", ";", "$", "this", "->", "tempVar", "=", "array", "(", "$", "tagLib", ",", "$", "tag", ")", ";", "if", "(", "!", "$", "closeTag", ")", "{", "$", "patterns", "=", "'/'", ".", "$", "begin", ".", "$", "parseTag", ".", "$", "n1", ".", "'\\/(\\s*?)'", ".", "$", "end", ".", "'/is'", ";", "$", "content", "=", "preg_replace_callback", "(", "$", "patterns", ",", "function", "(", "$", "matches", ")", "use", "(", "$", "tLib", ",", "$", "tag", ",", "$", "that", ")", "{", "return", "$", "that", "->", "parseXmlTag", "(", "$", "tLib", ",", "$", "tag", ",", "$", "matches", "[", "1", "]", ",", "$", "matches", "[", "2", "]", ")", ";", "}", ",", "$", "content", ")", ";", "}", "else", "{", "$", "patterns", "=", "'/'", ".", "$", "begin", ".", "$", "parseTag", ".", "$", "n1", ".", "$", "end", ".", "'(.*?)'", ".", "$", "begin", ".", "'\\/'", ".", "$", "parseTag", ".", "'(\\s*?)'", ".", "$", "end", ".", "'/is'", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "level", ";", "$", "i", "++", ")", "{", "$", "content", "=", "preg_replace_callback", "(", "$", "patterns", ",", "function", "(", "$", "matches", ")", "use", "(", "$", "tLib", ",", "$", "tag", ",", "$", "that", ")", "{", "return", "$", "that", "->", "parseXmlTag", "(", "$", "tLib", ",", "$", "tag", ",", "$", "matches", "[", "1", "]", ",", "$", "matches", "[", "2", "]", ")", ";", "}", ",", "$", "content", ")", ";", "}", "}", "}", "}", "}" ]
TagLib库解析 @access public @param string $tagLib 要解析的标签库 @param string $content 要解析的模板内容 @param boolean $hide 是否隐藏标签库前缀 @return string
[ "TagLib库解析" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Template.php#L388-L432
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Template.php
Template.parseXmlTag
public function parseXmlTag($tagLib,$tag,$attr,$content) { if(ini_get('magic_quotes_sybase')) $attr = str_replace('\"','\'',$attr); $parse = '_'.$tag; $content = trim($content); $tags = $tagLib->parseXmlAttr($attr,$tag); return $tagLib->$parse($tags,$content); }
php
public function parseXmlTag($tagLib,$tag,$attr,$content) { if(ini_get('magic_quotes_sybase')) $attr = str_replace('\"','\'',$attr); $parse = '_'.$tag; $content = trim($content); $tags = $tagLib->parseXmlAttr($attr,$tag); return $tagLib->$parse($tags,$content); }
[ "public", "function", "parseXmlTag", "(", "$", "tagLib", ",", "$", "tag", ",", "$", "attr", ",", "$", "content", ")", "{", "if", "(", "ini_get", "(", "'magic_quotes_sybase'", ")", ")", "$", "attr", "=", "str_replace", "(", "'\\\"'", ",", "'\\''", ",", "$", "attr", ")", ";", "$", "parse", "=", "'_'", ".", "$", "tag", ";", "$", "content", "=", "trim", "(", "$", "content", ")", ";", "$", "tags", "=", "$", "tagLib", "->", "parseXmlAttr", "(", "$", "attr", ",", "$", "tag", ")", ";", "return", "$", "tagLib", "->", "$", "parse", "(", "$", "tags", ",", "$", "content", ")", ";", "}" ]
解析标签库的标签 需要调用对应的标签库文件解析类 @access public @param object $tagLib 标签库对象实例 @param string $tag 标签名 @param string $attr 标签属性 @param string $content 标签内容 @return string|false
[ "解析标签库的标签", "需要调用对应的标签库文件解析类" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Template.php#L444-L451
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Template.php
Template.parseTag
public function parseTag($tagStr){ if(is_array($tagStr)) $tagStr = $tagStr[2]; //if (MAGIC_QUOTES_GPC) { $tagStr = stripslashes($tagStr); //} $flag = substr($tagStr,0,1); $flag2 = substr($tagStr,1,1); $name = substr($tagStr,1); if('$' == $flag && '.' != $flag2 && '(' != $flag2){ //解析模板变量 格式 {$varName} return $this->parseVar($name); }elseif('-' == $flag || '+'== $flag){ // 输出计算 return '<?php echo '.$flag.$name.';?>'; }elseif(':' == $flag){ // 输出某个函数的结果 return '<?php echo '.$name.';?>'; }elseif('~' == $flag){ // 执行某个函数 return '<?php '.$name.';?>'; }elseif(substr($tagStr,0,2)=='//' || (substr($tagStr,0,2)=='/*' && substr(rtrim($tagStr),-2)=='*/')){ //注释标签 return ''; } // 未识别的标签直接返回 return C('TMPL_L_DELIM') . $tagStr .C('TMPL_R_DELIM'); }
php
public function parseTag($tagStr){ if(is_array($tagStr)) $tagStr = $tagStr[2]; //if (MAGIC_QUOTES_GPC) { $tagStr = stripslashes($tagStr); //} $flag = substr($tagStr,0,1); $flag2 = substr($tagStr,1,1); $name = substr($tagStr,1); if('$' == $flag && '.' != $flag2 && '(' != $flag2){ //解析模板变量 格式 {$varName} return $this->parseVar($name); }elseif('-' == $flag || '+'== $flag){ // 输出计算 return '<?php echo '.$flag.$name.';?>'; }elseif(':' == $flag){ // 输出某个函数的结果 return '<?php echo '.$name.';?>'; }elseif('~' == $flag){ // 执行某个函数 return '<?php '.$name.';?>'; }elseif(substr($tagStr,0,2)=='//' || (substr($tagStr,0,2)=='/*' && substr(rtrim($tagStr),-2)=='*/')){ //注释标签 return ''; } // 未识别的标签直接返回 return C('TMPL_L_DELIM') . $tagStr .C('TMPL_R_DELIM'); }
[ "public", "function", "parseTag", "(", "$", "tagStr", ")", "{", "if", "(", "is_array", "(", "$", "tagStr", ")", ")", "$", "tagStr", "=", "$", "tagStr", "[", "2", "]", ";", "//if (MAGIC_QUOTES_GPC) {", "$", "tagStr", "=", "stripslashes", "(", "$", "tagStr", ")", ";", "//}", "$", "flag", "=", "substr", "(", "$", "tagStr", ",", "0", ",", "1", ")", ";", "$", "flag2", "=", "substr", "(", "$", "tagStr", ",", "1", ",", "1", ")", ";", "$", "name", "=", "substr", "(", "$", "tagStr", ",", "1", ")", ";", "if", "(", "'$'", "==", "$", "flag", "&&", "'.'", "!=", "$", "flag2", "&&", "'('", "!=", "$", "flag2", ")", "{", "//解析模板变量 格式 {$varName}", "return", "$", "this", "->", "parseVar", "(", "$", "name", ")", ";", "}", "elseif", "(", "'-'", "==", "$", "flag", "||", "'+'", "==", "$", "flag", ")", "{", "// 输出计算", "return", "'<?php echo '", ".", "$", "flag", ".", "$", "name", ".", "';?>'", ";", "}", "elseif", "(", "':'", "==", "$", "flag", ")", "{", "// 输出某个函数的结果", "return", "'<?php echo '", ".", "$", "name", ".", "';?>'", ";", "}", "elseif", "(", "'~'", "==", "$", "flag", ")", "{", "// 执行某个函数", "return", "'<?php '", ".", "$", "name", ".", "';?>'", ";", "}", "elseif", "(", "substr", "(", "$", "tagStr", ",", "0", ",", "2", ")", "==", "'//'", "||", "(", "substr", "(", "$", "tagStr", ",", "0", ",", "2", ")", "==", "'/*'", "&&", "substr", "(", "rtrim", "(", "$", "tagStr", ")", ",", "-", "2", ")", "==", "'*/'", ")", ")", "{", "//注释标签", "return", "''", ";", "}", "// 未识别的标签直接返回", "return", "C", "(", "'TMPL_L_DELIM'", ")", ".", "$", "tagStr", ".", "C", "(", "'TMPL_R_DELIM'", ")", ";", "}" ]
模板标签解析 格式: {TagName:args [|content] } @access public @param string $tagStr 标签内容 @return string
[ "模板标签解析", "格式:", "{", "TagName", ":", "args", "[", "|content", "]", "}" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Template.php#L460-L482
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Template.php
Template.parseVar
public function parseVar($varStr){ $varStr = trim($varStr); static $_varParseList = array(); //如果已经解析过该变量字串,则直接返回变量值 if(isset($_varParseList[$varStr])) return $_varParseList[$varStr]; $parseStr = ''; $varExists = true; if(!empty($varStr)){ $varArray = explode('|',$varStr); //取得变量名称 $var = array_shift($varArray); if('Think.' == substr($var,0,6)){ // 所有以Think.打头的以特殊变量对待 无需模板赋值就可以输出 $name = $this->parseThinkVar($var); }elseif( false !== strpos($var,'.')) { //支持 {$var.property} $vars = explode('.',$var); $var = array_shift($vars); switch(strtolower(C('TMPL_VAR_IDENTIFY'))) { case 'array': // 识别为数组 $name = '$'.$var; foreach ($vars as $key=>$val) $name .= '["'.$val.'"]'; break; case 'obj': // 识别为对象 $name = '$'.$var; foreach ($vars as $key=>$val) $name .= '->'.$val; break; default: // 自动判断数组或对象 只支持二维 $name = 'is_array($'.$var.')?$'.$var.'["'.$vars[0].'"]:$'.$var.'->'.$vars[0]; } }elseif(false !== strpos($var,'[')) { //支持 {$var['key']} 方式输出数组 $name = "$".$var; preg_match('/(.+?)\[(.+?)\]/is',$var,$match); $var = $match[1]; }elseif(false !==strpos($var,':') && false ===strpos($var,'(') && false ===strpos($var,'::') && false ===strpos($var,'?')){ //支持 {$var:property} 方式输出对象的属性 $vars = explode(':',$var); $var = str_replace(':','->',$var); $name = "$".$var; $var = $vars[0]; }else { $name = "$$var"; } //对变量使用函数 if(count($varArray)>0) $name = $this->parseVarFunction($name,$varArray); $parseStr = '<?php echo ('.$name.'); ?>'; } $_varParseList[$varStr] = $parseStr; return $parseStr; }
php
public function parseVar($varStr){ $varStr = trim($varStr); static $_varParseList = array(); //如果已经解析过该变量字串,则直接返回变量值 if(isset($_varParseList[$varStr])) return $_varParseList[$varStr]; $parseStr = ''; $varExists = true; if(!empty($varStr)){ $varArray = explode('|',$varStr); //取得变量名称 $var = array_shift($varArray); if('Think.' == substr($var,0,6)){ // 所有以Think.打头的以特殊变量对待 无需模板赋值就可以输出 $name = $this->parseThinkVar($var); }elseif( false !== strpos($var,'.')) { //支持 {$var.property} $vars = explode('.',$var); $var = array_shift($vars); switch(strtolower(C('TMPL_VAR_IDENTIFY'))) { case 'array': // 识别为数组 $name = '$'.$var; foreach ($vars as $key=>$val) $name .= '["'.$val.'"]'; break; case 'obj': // 识别为对象 $name = '$'.$var; foreach ($vars as $key=>$val) $name .= '->'.$val; break; default: // 自动判断数组或对象 只支持二维 $name = 'is_array($'.$var.')?$'.$var.'["'.$vars[0].'"]:$'.$var.'->'.$vars[0]; } }elseif(false !== strpos($var,'[')) { //支持 {$var['key']} 方式输出数组 $name = "$".$var; preg_match('/(.+?)\[(.+?)\]/is',$var,$match); $var = $match[1]; }elseif(false !==strpos($var,':') && false ===strpos($var,'(') && false ===strpos($var,'::') && false ===strpos($var,'?')){ //支持 {$var:property} 方式输出对象的属性 $vars = explode(':',$var); $var = str_replace(':','->',$var); $name = "$".$var; $var = $vars[0]; }else { $name = "$$var"; } //对变量使用函数 if(count($varArray)>0) $name = $this->parseVarFunction($name,$varArray); $parseStr = '<?php echo ('.$name.'); ?>'; } $_varParseList[$varStr] = $parseStr; return $parseStr; }
[ "public", "function", "parseVar", "(", "$", "varStr", ")", "{", "$", "varStr", "=", "trim", "(", "$", "varStr", ")", ";", "static", "$", "_varParseList", "=", "array", "(", ")", ";", "//如果已经解析过该变量字串,则直接返回变量值", "if", "(", "isset", "(", "$", "_varParseList", "[", "$", "varStr", "]", ")", ")", "return", "$", "_varParseList", "[", "$", "varStr", "]", ";", "$", "parseStr", "=", "''", ";", "$", "varExists", "=", "true", ";", "if", "(", "!", "empty", "(", "$", "varStr", ")", ")", "{", "$", "varArray", "=", "explode", "(", "'|'", ",", "$", "varStr", ")", ";", "//取得变量名称", "$", "var", "=", "array_shift", "(", "$", "varArray", ")", ";", "if", "(", "'Think.'", "==", "substr", "(", "$", "var", ",", "0", ",", "6", ")", ")", "{", "// 所有以Think.打头的以特殊变量对待 无需模板赋值就可以输出", "$", "name", "=", "$", "this", "->", "parseThinkVar", "(", "$", "var", ")", ";", "}", "elseif", "(", "false", "!==", "strpos", "(", "$", "var", ",", "'.'", ")", ")", "{", "//支持 {$var.property}", "$", "vars", "=", "explode", "(", "'.'", ",", "$", "var", ")", ";", "$", "var", "=", "array_shift", "(", "$", "vars", ")", ";", "switch", "(", "strtolower", "(", "C", "(", "'TMPL_VAR_IDENTIFY'", ")", ")", ")", "{", "case", "'array'", ":", "// 识别为数组", "$", "name", "=", "'$'", ".", "$", "var", ";", "foreach", "(", "$", "vars", "as", "$", "key", "=>", "$", "val", ")", "$", "name", ".=", "'[\"'", ".", "$", "val", ".", "'\"]'", ";", "break", ";", "case", "'obj'", ":", "// 识别为对象", "$", "name", "=", "'$'", ".", "$", "var", ";", "foreach", "(", "$", "vars", "as", "$", "key", "=>", "$", "val", ")", "$", "name", ".=", "'->'", ".", "$", "val", ";", "break", ";", "default", ":", "// 自动判断数组或对象 只支持二维", "$", "name", "=", "'is_array($'", ".", "$", "var", ".", "')?$'", ".", "$", "var", ".", "'[\"'", ".", "$", "vars", "[", "0", "]", ".", "'\"]:$'", ".", "$", "var", ".", "'->'", ".", "$", "vars", "[", "0", "]", ";", "}", "}", "elseif", "(", "false", "!==", "strpos", "(", "$", "var", ",", "'['", ")", ")", "{", "//支持 {$var['key']} 方式输出数组", "$", "name", "=", "\"$\"", ".", "$", "var", ";", "preg_match", "(", "'/(.+?)\\[(.+?)\\]/is'", ",", "$", "var", ",", "$", "match", ")", ";", "$", "var", "=", "$", "match", "[", "1", "]", ";", "}", "elseif", "(", "false", "!==", "strpos", "(", "$", "var", ",", "':'", ")", "&&", "false", "===", "strpos", "(", "$", "var", ",", "'('", ")", "&&", "false", "===", "strpos", "(", "$", "var", ",", "'::'", ")", "&&", "false", "===", "strpos", "(", "$", "var", ",", "'?'", ")", ")", "{", "//支持 {$var:property} 方式输出对象的属性", "$", "vars", "=", "explode", "(", "':'", ",", "$", "var", ")", ";", "$", "var", "=", "str_replace", "(", "':'", ",", "'->'", ",", "$", "var", ")", ";", "$", "name", "=", "\"$\"", ".", "$", "var", ";", "$", "var", "=", "$", "vars", "[", "0", "]", ";", "}", "else", "{", "$", "name", "=", "\"$$var\"", ";", "}", "//对变量使用函数", "if", "(", "count", "(", "$", "varArray", ")", ">", "0", ")", "$", "name", "=", "$", "this", "->", "parseVarFunction", "(", "$", "name", ",", "$", "varArray", ")", ";", "$", "parseStr", "=", "'<?php echo ('", ".", "$", "name", ".", "'); ?>'", ";", "}", "$", "_varParseList", "[", "$", "varStr", "]", "=", "$", "parseStr", ";", "return", "$", "parseStr", ";", "}" ]
模板变量解析,支持使用函数 格式: {$varname|function1|function2=arg1,arg2} @access public @param string $varStr 变量数据 @return string
[ "模板变量解析", "支持使用函数", "格式:", "{", "$varname|function1|function2", "=", "arg1", "arg2", "}" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Template.php#L491-L544
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Template.php
Template.parseVarFunction
public function parseVarFunction($name,$varArray){ //对变量使用函数 $length = count($varArray); //取得模板禁止使用函数列表 $template_deny_funs = explode(',',C('TMPL_DENY_FUNC_LIST')); for($i=0;$i<$length ;$i++ ){ $args = explode('=',$varArray[$i],2); //模板函数过滤 $fun = trim($args[0]); switch($fun) { case 'default': // 特殊模板函数 $name = '(isset('.$name.') && ('.$name.' !== ""))?('.$name.'):'.$args[1]; break; default: // 通用模板函数 if(!in_array($fun,$template_deny_funs)){ if(isset($args[1])){ if(strstr($args[1],'###')){ $args[1] = str_replace('###',$name,$args[1]); $name = "$fun($args[1])"; }else{ $name = "$fun($name,$args[1])"; } }else if(!empty($args[0])){ $name = "$fun($name)"; } } } } return $name; }
php
public function parseVarFunction($name,$varArray){ //对变量使用函数 $length = count($varArray); //取得模板禁止使用函数列表 $template_deny_funs = explode(',',C('TMPL_DENY_FUNC_LIST')); for($i=0;$i<$length ;$i++ ){ $args = explode('=',$varArray[$i],2); //模板函数过滤 $fun = trim($args[0]); switch($fun) { case 'default': // 特殊模板函数 $name = '(isset('.$name.') && ('.$name.' !== ""))?('.$name.'):'.$args[1]; break; default: // 通用模板函数 if(!in_array($fun,$template_deny_funs)){ if(isset($args[1])){ if(strstr($args[1],'###')){ $args[1] = str_replace('###',$name,$args[1]); $name = "$fun($args[1])"; }else{ $name = "$fun($name,$args[1])"; } }else if(!empty($args[0])){ $name = "$fun($name)"; } } } } return $name; }
[ "public", "function", "parseVarFunction", "(", "$", "name", ",", "$", "varArray", ")", "{", "//对变量使用函数", "$", "length", "=", "count", "(", "$", "varArray", ")", ";", "//取得模板禁止使用函数列表", "$", "template_deny_funs", "=", "explode", "(", "','", ",", "C", "(", "'TMPL_DENY_FUNC_LIST'", ")", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "length", ";", "$", "i", "++", ")", "{", "$", "args", "=", "explode", "(", "'='", ",", "$", "varArray", "[", "$", "i", "]", ",", "2", ")", ";", "//模板函数过滤", "$", "fun", "=", "trim", "(", "$", "args", "[", "0", "]", ")", ";", "switch", "(", "$", "fun", ")", "{", "case", "'default'", ":", "// 特殊模板函数", "$", "name", "=", "'(isset('", ".", "$", "name", ".", "') && ('", ".", "$", "name", ".", "' !== \"\"))?('", ".", "$", "name", ".", "'):'", ".", "$", "args", "[", "1", "]", ";", "break", ";", "default", ":", "// 通用模板函数", "if", "(", "!", "in_array", "(", "$", "fun", ",", "$", "template_deny_funs", ")", ")", "{", "if", "(", "isset", "(", "$", "args", "[", "1", "]", ")", ")", "{", "if", "(", "strstr", "(", "$", "args", "[", "1", "]", ",", "'###'", ")", ")", "{", "$", "args", "[", "1", "]", "=", "str_replace", "(", "'###'", ",", "$", "name", ",", "$", "args", "[", "1", "]", ")", ";", "$", "name", "=", "\"$fun($args[1])\"", ";", "}", "else", "{", "$", "name", "=", "\"$fun($name,$args[1])\"", ";", "}", "}", "else", "if", "(", "!", "empty", "(", "$", "args", "[", "0", "]", ")", ")", "{", "$", "name", "=", "\"$fun($name)\"", ";", "}", "}", "}", "}", "return", "$", "name", ";", "}" ]
对模板变量使用函数 格式 {$varname|function1|function2=arg1,arg2} @access public @param string $name 变量名 @param array $varArray 函数列表 @return string
[ "对模板变量使用函数", "格式", "{", "$varname|function1|function2", "=", "arg1", "arg2", "}" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Template.php#L554-L583
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Template.php
Template.parseThinkVar
public function parseThinkVar($varStr){ $vars = explode('.',$varStr); $vars[1] = strtoupper(trim($vars[1])); $parseStr = ''; if(count($vars)>=3){ $vars[2] = trim($vars[2]); switch($vars[1]){ case 'SERVER': $parseStr = '$_SERVER[\''.strtoupper($vars[2]).'\']';break; case 'GET': $parseStr = '$_GET[\''.$vars[2].'\']';break; case 'POST': $parseStr = '$_POST[\''.$vars[2].'\']';break; case 'COOKIE': if(isset($vars[3])) { $parseStr = '$_COOKIE[\''.$vars[2].'\'][\''.$vars[3].'\']'; }else{ $parseStr = 'cookie(\''.$vars[2].'\')'; } break; case 'SESSION': if(isset($vars[3])) { $parseStr = '$_SESSION[\''.$vars[2].'\'][\''.$vars[3].'\']'; }else{ $parseStr = 'session(\''.$vars[2].'\')'; } break; case 'ENV': $parseStr = '$_ENV[\''.strtoupper($vars[2]).'\']';break; case 'REQUEST': $parseStr = '$_REQUEST[\''.$vars[2].'\']';break; case 'CONST': $parseStr = strtoupper($vars[2]);break; case 'LANG': $parseStr = 'L("'.$vars[2].'")';break; case 'CONFIG': if(isset($vars[3])) { $vars[2] .= '.'.$vars[3]; } $parseStr = 'C("'.$vars[2].'")';break; default:break; } }else if(count($vars)==2){ switch($vars[1]){ case 'NOW': $parseStr = "date('Y-m-d g:i a',time())"; break; case 'VERSION': $parseStr = 'THINK_VERSION'; break; case 'TEMPLATE': $parseStr = "'".$this->templateFile."'";//'C("TEMPLATE_NAME")'; break; case 'LDELIM': $parseStr = 'C("TMPL_L_DELIM")'; break; case 'RDELIM': $parseStr = 'C("TMPL_R_DELIM")'; break; default: if(defined($vars[1])) $parseStr = $vars[1]; } } return $parseStr; }
php
public function parseThinkVar($varStr){ $vars = explode('.',$varStr); $vars[1] = strtoupper(trim($vars[1])); $parseStr = ''; if(count($vars)>=3){ $vars[2] = trim($vars[2]); switch($vars[1]){ case 'SERVER': $parseStr = '$_SERVER[\''.strtoupper($vars[2]).'\']';break; case 'GET': $parseStr = '$_GET[\''.$vars[2].'\']';break; case 'POST': $parseStr = '$_POST[\''.$vars[2].'\']';break; case 'COOKIE': if(isset($vars[3])) { $parseStr = '$_COOKIE[\''.$vars[2].'\'][\''.$vars[3].'\']'; }else{ $parseStr = 'cookie(\''.$vars[2].'\')'; } break; case 'SESSION': if(isset($vars[3])) { $parseStr = '$_SESSION[\''.$vars[2].'\'][\''.$vars[3].'\']'; }else{ $parseStr = 'session(\''.$vars[2].'\')'; } break; case 'ENV': $parseStr = '$_ENV[\''.strtoupper($vars[2]).'\']';break; case 'REQUEST': $parseStr = '$_REQUEST[\''.$vars[2].'\']';break; case 'CONST': $parseStr = strtoupper($vars[2]);break; case 'LANG': $parseStr = 'L("'.$vars[2].'")';break; case 'CONFIG': if(isset($vars[3])) { $vars[2] .= '.'.$vars[3]; } $parseStr = 'C("'.$vars[2].'")';break; default:break; } }else if(count($vars)==2){ switch($vars[1]){ case 'NOW': $parseStr = "date('Y-m-d g:i a',time())"; break; case 'VERSION': $parseStr = 'THINK_VERSION'; break; case 'TEMPLATE': $parseStr = "'".$this->templateFile."'";//'C("TEMPLATE_NAME")'; break; case 'LDELIM': $parseStr = 'C("TMPL_L_DELIM")'; break; case 'RDELIM': $parseStr = 'C("TMPL_R_DELIM")'; break; default: if(defined($vars[1])) $parseStr = $vars[1]; } } return $parseStr; }
[ "public", "function", "parseThinkVar", "(", "$", "varStr", ")", "{", "$", "vars", "=", "explode", "(", "'.'", ",", "$", "varStr", ")", ";", "$", "vars", "[", "1", "]", "=", "strtoupper", "(", "trim", "(", "$", "vars", "[", "1", "]", ")", ")", ";", "$", "parseStr", "=", "''", ";", "if", "(", "count", "(", "$", "vars", ")", ">=", "3", ")", "{", "$", "vars", "[", "2", "]", "=", "trim", "(", "$", "vars", "[", "2", "]", ")", ";", "switch", "(", "$", "vars", "[", "1", "]", ")", "{", "case", "'SERVER'", ":", "$", "parseStr", "=", "'$_SERVER[\\''", ".", "strtoupper", "(", "$", "vars", "[", "2", "]", ")", ".", "'\\']'", ";", "break", ";", "case", "'GET'", ":", "$", "parseStr", "=", "'$_GET[\\''", ".", "$", "vars", "[", "2", "]", ".", "'\\']'", ";", "break", ";", "case", "'POST'", ":", "$", "parseStr", "=", "'$_POST[\\''", ".", "$", "vars", "[", "2", "]", ".", "'\\']'", ";", "break", ";", "case", "'COOKIE'", ":", "if", "(", "isset", "(", "$", "vars", "[", "3", "]", ")", ")", "{", "$", "parseStr", "=", "'$_COOKIE[\\''", ".", "$", "vars", "[", "2", "]", ".", "'\\'][\\''", ".", "$", "vars", "[", "3", "]", ".", "'\\']'", ";", "}", "else", "{", "$", "parseStr", "=", "'cookie(\\''", ".", "$", "vars", "[", "2", "]", ".", "'\\')'", ";", "}", "break", ";", "case", "'SESSION'", ":", "if", "(", "isset", "(", "$", "vars", "[", "3", "]", ")", ")", "{", "$", "parseStr", "=", "'$_SESSION[\\''", ".", "$", "vars", "[", "2", "]", ".", "'\\'][\\''", ".", "$", "vars", "[", "3", "]", ".", "'\\']'", ";", "}", "else", "{", "$", "parseStr", "=", "'session(\\''", ".", "$", "vars", "[", "2", "]", ".", "'\\')'", ";", "}", "break", ";", "case", "'ENV'", ":", "$", "parseStr", "=", "'$_ENV[\\''", ".", "strtoupper", "(", "$", "vars", "[", "2", "]", ")", ".", "'\\']'", ";", "break", ";", "case", "'REQUEST'", ":", "$", "parseStr", "=", "'$_REQUEST[\\''", ".", "$", "vars", "[", "2", "]", ".", "'\\']'", ";", "break", ";", "case", "'CONST'", ":", "$", "parseStr", "=", "strtoupper", "(", "$", "vars", "[", "2", "]", ")", ";", "break", ";", "case", "'LANG'", ":", "$", "parseStr", "=", "'L(\"'", ".", "$", "vars", "[", "2", "]", ".", "'\")'", ";", "break", ";", "case", "'CONFIG'", ":", "if", "(", "isset", "(", "$", "vars", "[", "3", "]", ")", ")", "{", "$", "vars", "[", "2", "]", ".=", "'.'", ".", "$", "vars", "[", "3", "]", ";", "}", "$", "parseStr", "=", "'C(\"'", ".", "$", "vars", "[", "2", "]", ".", "'\")'", ";", "break", ";", "default", ":", "break", ";", "}", "}", "else", "if", "(", "count", "(", "$", "vars", ")", "==", "2", ")", "{", "switch", "(", "$", "vars", "[", "1", "]", ")", "{", "case", "'NOW'", ":", "$", "parseStr", "=", "\"date('Y-m-d g:i a',time())\"", ";", "break", ";", "case", "'VERSION'", ":", "$", "parseStr", "=", "'THINK_VERSION'", ";", "break", ";", "case", "'TEMPLATE'", ":", "$", "parseStr", "=", "\"'\"", ".", "$", "this", "->", "templateFile", ".", "\"'\"", ";", "//'C(\"TEMPLATE_NAME\")';", "break", ";", "case", "'LDELIM'", ":", "$", "parseStr", "=", "'C(\"TMPL_L_DELIM\")'", ";", "break", ";", "case", "'RDELIM'", ":", "$", "parseStr", "=", "'C(\"TMPL_R_DELIM\")'", ";", "break", ";", "default", ":", "if", "(", "defined", "(", "$", "vars", "[", "1", "]", ")", ")", "$", "parseStr", "=", "$", "vars", "[", "1", "]", ";", "}", "}", "return", "$", "parseStr", ";", "}" ]
特殊模板变量解析 格式 以 $Think. 打头的变量属于特殊模板变量 @access public @param string $varStr 变量字符串 @return string
[ "特殊模板变量解析", "格式", "以", "$Think", ".", "打头的变量属于特殊模板变量" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Template.php#L592-L657
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Template.php
Template.parseTemplateName
private function parseTemplateName($templateName){ if(substr($templateName,0,1)=='$') //支持加载变量文件名 $templateName = $this->get(substr($templateName,1)); $array = explode(',',$templateName); $parseStr = ''; foreach ($array as $templateName){ if(empty($templateName)) continue; if(false === strpos($templateName,$this->config['template_suffix'])) { // 解析规则为 模块@主题/控制器/操作 $templateName = T($templateName); } // 获取模板文件内容 $parseStr .= file_get_contents($templateName); } return $parseStr; }
php
private function parseTemplateName($templateName){ if(substr($templateName,0,1)=='$') //支持加载变量文件名 $templateName = $this->get(substr($templateName,1)); $array = explode(',',$templateName); $parseStr = ''; foreach ($array as $templateName){ if(empty($templateName)) continue; if(false === strpos($templateName,$this->config['template_suffix'])) { // 解析规则为 模块@主题/控制器/操作 $templateName = T($templateName); } // 获取模板文件内容 $parseStr .= file_get_contents($templateName); } return $parseStr; }
[ "private", "function", "parseTemplateName", "(", "$", "templateName", ")", "{", "if", "(", "substr", "(", "$", "templateName", ",", "0", ",", "1", ")", "==", "'$'", ")", "//支持加载变量文件名", "$", "templateName", "=", "$", "this", "->", "get", "(", "substr", "(", "$", "templateName", ",", "1", ")", ")", ";", "$", "array", "=", "explode", "(", "','", ",", "$", "templateName", ")", ";", "$", "parseStr", "=", "''", ";", "foreach", "(", "$", "array", "as", "$", "templateName", ")", "{", "if", "(", "empty", "(", "$", "templateName", ")", ")", "continue", ";", "if", "(", "false", "===", "strpos", "(", "$", "templateName", ",", "$", "this", "->", "config", "[", "'template_suffix'", "]", ")", ")", "{", "// 解析规则为 模块@主题/控制器/操作", "$", "templateName", "=", "T", "(", "$", "templateName", ")", ";", "}", "// 获取模板文件内容", "$", "parseStr", ".=", "file_get_contents", "(", "$", "templateName", ")", ";", "}", "return", "$", "parseStr", ";", "}" ]
分析加载的模板文件并读取内容 支持多个模板文件读取 @access private @param string $tmplPublicName 模板文件名 @return string
[ "分析加载的模板文件并读取内容", "支持多个模板文件读取" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Template.php#L683-L699
webfactorybulgaria/laravel-shop-gateway-paypal
src/GatewayPayPalExpress.php
GatewayPayPalExpress.toPayPalItems
private function toPayPalItems($order) { $items = []; foreach ($order->items as $shopItem) { if ($shopItem->price > 0) { $item = new Item(); $item->setName(substr($shopItem->displayName, 0, 127)) ->setDescription($shopItem->sku) ->setCurrency($shopItem->currency) ->setQuantity($shopItem->quantity) ->setTax($shopItem->tax) ->setPrice($shopItem->price); $items[] = $item; } } if ($discount = $order->totalDiscount) { $item = new Item(); $item->setName('Discount') ->setDescription('discount') ->setCurrency($shopItem->currency) ->setQuantity(1) ->setTax(0) ->setPrice(-$discount); $items[] = $item; } return $items; }
php
private function toPayPalItems($order) { $items = []; foreach ($order->items as $shopItem) { if ($shopItem->price > 0) { $item = new Item(); $item->setName(substr($shopItem->displayName, 0, 127)) ->setDescription($shopItem->sku) ->setCurrency($shopItem->currency) ->setQuantity($shopItem->quantity) ->setTax($shopItem->tax) ->setPrice($shopItem->price); $items[] = $item; } } if ($discount = $order->totalDiscount) { $item = new Item(); $item->setName('Discount') ->setDescription('discount') ->setCurrency($shopItem->currency) ->setQuantity(1) ->setTax(0) ->setPrice(-$discount); $items[] = $item; } return $items; }
[ "private", "function", "toPayPalItems", "(", "$", "order", ")", "{", "$", "items", "=", "[", "]", ";", "foreach", "(", "$", "order", "->", "items", "as", "$", "shopItem", ")", "{", "if", "(", "$", "shopItem", "->", "price", ">", "0", ")", "{", "$", "item", "=", "new", "Item", "(", ")", ";", "$", "item", "->", "setName", "(", "substr", "(", "$", "shopItem", "->", "displayName", ",", "0", ",", "127", ")", ")", "->", "setDescription", "(", "$", "shopItem", "->", "sku", ")", "->", "setCurrency", "(", "$", "shopItem", "->", "currency", ")", "->", "setQuantity", "(", "$", "shopItem", "->", "quantity", ")", "->", "setTax", "(", "$", "shopItem", "->", "tax", ")", "->", "setPrice", "(", "$", "shopItem", "->", "price", ")", ";", "$", "items", "[", "]", "=", "$", "item", ";", "}", "}", "if", "(", "$", "discount", "=", "$", "order", "->", "totalDiscount", ")", "{", "$", "item", "=", "new", "Item", "(", ")", ";", "$", "item", "->", "setName", "(", "'Discount'", ")", "->", "setDescription", "(", "'discount'", ")", "->", "setCurrency", "(", "$", "shopItem", "->", "currency", ")", "->", "setQuantity", "(", "1", ")", "->", "setTax", "(", "0", ")", "->", "setPrice", "(", "-", "$", "discount", ")", ";", "$", "items", "[", "]", "=", "$", "item", ";", "}", "return", "$", "items", ";", "}" ]
Converts the items in the order into paypal items for purchase. @param object $order Order. @return array
[ "Converts", "the", "items", "in", "the", "order", "into", "paypal", "items", "for", "purchase", "." ]
train
https://github.com/webfactorybulgaria/laravel-shop-gateway-paypal/blob/7df3d8ad05f78848d80ff47e1665d76c218220a2/src/GatewayPayPalExpress.php#L253-L287
kaiohken1982/NeobazaarDocumentModule
src/Document/Model/Location/Sitemap.php
Sitemap.init
public function init(Geonames $document) { $this->title = $document->getAsciiname(); $this->address = $this->getAddress($document); return $this; }
php
public function init(Geonames $document) { $this->title = $document->getAsciiname(); $this->address = $this->getAddress($document); return $this; }
[ "public", "function", "init", "(", "Geonames", "$", "document", ")", "{", "$", "this", "->", "title", "=", "$", "document", "->", "getAsciiname", "(", ")", ";", "$", "this", "->", "address", "=", "$", "this", "->", "getAddress", "(", "$", "document", ")", ";", "return", "$", "this", ";", "}" ]
Fill the model with data @return \Document\Model\Location\Sitemap
[ "Fill", "the", "model", "with", "data" ]
train
https://github.com/kaiohken1982/NeobazaarDocumentModule/blob/edb0223878fe02e791d2a0266c5a7c0f2029e3fe/src/Document/Model/Location/Sitemap.php#L68-L74
SagittariusX/Beluga.Translation
src/Beluga/Translation/Locale.php
Locale.TryParseUrlPath
public static function TryParseUrlPath( &$refLocale, string $urlPath = null ) : bool { // Get URL path from $_SERVER[ 'SCRIPT_URL' ] if ( empty( $urlPath ) ) { if ( \filter_has_var( \INPUT_SERVER, 'REQUEST_URI' ) ) { $urlPath = \filter_input( \INPUT_SERVER, 'REQUEST_URI' ); } else { if ( ! \filter_has_var( \INPUT_SERVER, 'SCRIPT_URL' ) ) { return false; } $urlPath = \filter_input( \INPUT_SERVER, 'SCRIPT_URL' ); } } // IF the value does not match the required data format stop this method here if ( ! \preg_match( '~^/([a-zA-Z]{2})([_-]([a-zA-Z]{2}))?/~', $urlPath, $matches ) ) { return false; } // Getting the LID + CID $lid = \strtolower( $matches[ 1 ] ); $cid = empty( $matches[ 2 ] ) ? null : \strtoupper( $matches[ 3 ] ); // Everything is OK. Init the new instance and return TRUE $refLocale = new Locale( $lid, $cid ); return true; }
php
public static function TryParseUrlPath( &$refLocale, string $urlPath = null ) : bool { // Get URL path from $_SERVER[ 'SCRIPT_URL' ] if ( empty( $urlPath ) ) { if ( \filter_has_var( \INPUT_SERVER, 'REQUEST_URI' ) ) { $urlPath = \filter_input( \INPUT_SERVER, 'REQUEST_URI' ); } else { if ( ! \filter_has_var( \INPUT_SERVER, 'SCRIPT_URL' ) ) { return false; } $urlPath = \filter_input( \INPUT_SERVER, 'SCRIPT_URL' ); } } // IF the value does not match the required data format stop this method here if ( ! \preg_match( '~^/([a-zA-Z]{2})([_-]([a-zA-Z]{2}))?/~', $urlPath, $matches ) ) { return false; } // Getting the LID + CID $lid = \strtolower( $matches[ 1 ] ); $cid = empty( $matches[ 2 ] ) ? null : \strtoupper( $matches[ 3 ] ); // Everything is OK. Init the new instance and return TRUE $refLocale = new Locale( $lid, $cid ); return true; }
[ "public", "static", "function", "TryParseUrlPath", "(", "&", "$", "refLocale", ",", "string", "$", "urlPath", "=", "null", ")", ":", "bool", "{", "// Get URL path from $_SERVER[ 'SCRIPT_URL' ]", "if", "(", "empty", "(", "$", "urlPath", ")", ")", "{", "if", "(", "\\", "filter_has_var", "(", "\\", "INPUT_SERVER", ",", "'REQUEST_URI'", ")", ")", "{", "$", "urlPath", "=", "\\", "filter_input", "(", "\\", "INPUT_SERVER", ",", "'REQUEST_URI'", ")", ";", "}", "else", "{", "if", "(", "!", "\\", "filter_has_var", "(", "\\", "INPUT_SERVER", ",", "'SCRIPT_URL'", ")", ")", "{", "return", "false", ";", "}", "$", "urlPath", "=", "\\", "filter_input", "(", "\\", "INPUT_SERVER", ",", "'SCRIPT_URL'", ")", ";", "}", "}", "// IF the value does not match the required data format stop this method here", "if", "(", "!", "\\", "preg_match", "(", "'~^/([a-zA-Z]{2})([_-]([a-zA-Z]{2}))?/~'", ",", "$", "urlPath", ",", "$", "matches", ")", ")", "{", "return", "false", ";", "}", "// Getting the LID + CID", "$", "lid", "=", "\\", "strtolower", "(", "$", "matches", "[", "1", "]", ")", ";", "$", "cid", "=", "empty", "(", "$", "matches", "[", "2", "]", ")", "?", "null", ":", "\\", "strtoupper", "(", "$", "matches", "[", "3", "]", ")", ";", "// Everything is OK. Init the new instance and return TRUE", "$", "refLocale", "=", "new", "Locale", "(", "$", "lid", ",", "$", "cid", ")", ";", "return", "true", ";", "}" ]
Tries to create a new Locale instance from an specific URL path part. If no URL path part is defined it uses $_SERVER[ 'REQUEST_URI' ] or $_SERVER[ 'SCRIPT_URL' ] otherwise. @param \Beluga\Translation\Locale $refLocale Returns the Locale instance if the method return TRUE. @param string|null $urlPath @return bool
[ "Tries", "to", "create", "a", "new", "Locale", "instance", "from", "an", "specific", "URL", "path", "part", ".", "If", "no", "URL", "path", "part", "is", "defined", "it", "uses", "$_SERVER", "[", "REQUEST_URI", "]", "or", "$_SERVER", "[", "SCRIPT_URL", "]", "otherwise", "." ]
train
https://github.com/SagittariusX/Beluga.Translation/blob/8f66c4fef6fa4494413972ca56bd8e13f5a7e444/src/Beluga/Translation/Locale.php#L339-L379
SagittariusX/Beluga.Translation
src/Beluga/Translation/Locale.php
Locale.TryParseArray
public static function TryParseArray( &$refLocale, array $requestData, array $acceptedKeys = [ 'locale', 'language', 'lang', 'loc', 'lc', 'lng' ] ) : bool { if ( \count( $requestData ) < 1 ) { return false; } $requestData = \array_change_key_case( $requestData , \CASE_LOWER ); $acceptedKeys = \array_change_key_case( $acceptedKeys, \CASE_LOWER ); $language = null; foreach ( $acceptedKeys as $key ) { if ( ! isset( $requestData[ $key ] ) ) { continue; } $language = \trim( $requestData[ 'language' ] ); break; } if ( empty( $language ) ) { return false; } if ( ! \preg_match( '~^([a-zA-Z]{2})([_-]([a-zA-Z]{2}))?~', $language, $matches ) ) { return false; } // Getting the LID + CID $lid = \strtolower( $matches[ 1 ] ); $cid = empty( $matches[ 2 ] ) ? null : \strtoupper( $matches[ 3 ] ); // Everything is OK. Init the new instance and return TRUE $refLocale = new Locale( $lid, $cid ); return true; }
php
public static function TryParseArray( &$refLocale, array $requestData, array $acceptedKeys = [ 'locale', 'language', 'lang', 'loc', 'lc', 'lng' ] ) : bool { if ( \count( $requestData ) < 1 ) { return false; } $requestData = \array_change_key_case( $requestData , \CASE_LOWER ); $acceptedKeys = \array_change_key_case( $acceptedKeys, \CASE_LOWER ); $language = null; foreach ( $acceptedKeys as $key ) { if ( ! isset( $requestData[ $key ] ) ) { continue; } $language = \trim( $requestData[ 'language' ] ); break; } if ( empty( $language ) ) { return false; } if ( ! \preg_match( '~^([a-zA-Z]{2})([_-]([a-zA-Z]{2}))?~', $language, $matches ) ) { return false; } // Getting the LID + CID $lid = \strtolower( $matches[ 1 ] ); $cid = empty( $matches[ 2 ] ) ? null : \strtoupper( $matches[ 3 ] ); // Everything is OK. Init the new instance and return TRUE $refLocale = new Locale( $lid, $cid ); return true; }
[ "public", "static", "function", "TryParseArray", "(", "&", "$", "refLocale", ",", "array", "$", "requestData", ",", "array", "$", "acceptedKeys", "=", "[", "'locale'", ",", "'language'", ",", "'lang'", ",", "'loc'", ",", "'lc'", ",", "'lng'", "]", ")", ":", "bool", "{", "if", "(", "\\", "count", "(", "$", "requestData", ")", "<", "1", ")", "{", "return", "false", ";", "}", "$", "requestData", "=", "\\", "array_change_key_case", "(", "$", "requestData", ",", "\\", "CASE_LOWER", ")", ";", "$", "acceptedKeys", "=", "\\", "array_change_key_case", "(", "$", "acceptedKeys", ",", "\\", "CASE_LOWER", ")", ";", "$", "language", "=", "null", ";", "foreach", "(", "$", "acceptedKeys", "as", "$", "key", ")", "{", "if", "(", "!", "isset", "(", "$", "requestData", "[", "$", "key", "]", ")", ")", "{", "continue", ";", "}", "$", "language", "=", "\\", "trim", "(", "$", "requestData", "[", "'language'", "]", ")", ";", "break", ";", "}", "if", "(", "empty", "(", "$", "language", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "\\", "preg_match", "(", "'~^([a-zA-Z]{2})([_-]([a-zA-Z]{2}))?~'", ",", "$", "language", ",", "$", "matches", ")", ")", "{", "return", "false", ";", "}", "// Getting the LID + CID", "$", "lid", "=", "\\", "strtolower", "(", "$", "matches", "[", "1", "]", ")", ";", "$", "cid", "=", "empty", "(", "$", "matches", "[", "2", "]", ")", "?", "null", ":", "\\", "strtoupper", "(", "$", "matches", "[", "3", "]", ")", ";", "// Everything is OK. Init the new instance and return TRUE", "$", "refLocale", "=", "new", "Locale", "(", "$", "lid", ",", "$", "cid", ")", ";", "return", "true", ";", "}" ]
Tries to create a new Locale instance from defined array. It accepts one of the following array keys to declare an @param \Beluga\Translation\Locale $refLocale Returns the Locale instance if the method return TRUE. @param array $requestData The array with the data that should be used for getting local info from. @return bool
[ "Tries", "to", "create", "a", "new", "Locale", "instance", "from", "defined", "array", ".", "It", "accepts", "one", "of", "the", "following", "array", "keys", "to", "declare", "an" ]
train
https://github.com/SagittariusX/Beluga.Translation/blob/8f66c4fef6fa4494413972ca56bd8e13f5a7e444/src/Beluga/Translation/Locale.php#L389-L431
SagittariusX/Beluga.Translation
src/Beluga/Translation/Locale.php
Locale.TryParseSystem
public static function TryParseSystem( &$refLocale ) : bool { // Getting the current system used locale of LC_ALL $lcString = \setlocale( \LC_ALL, '0' ); // Ignore values with lower than 2 characters. It also ignores the 'C' locale if ( empty( $lcString ) || 2 > \strlen( $lcString ) ) { return false; } // Pre initialize the local LID, CID and Charset variables $lid = ''; $cid = ''; $charset = ''; // Handle windows different from other OS if ( \DIRECTORY_SEPARATOR === '\\' ) { $tmp = \explode( ';', $lcString ); // Loop the exploded elements foreach ( $tmp as $element ) { // Explode at the first equal sign '=' $tmp2 = \explode( '=', $element, 2 ); // If the explode before results in only one element (no '=' inside $element found) if ( 2 > \count( $tmp2 ) ) { // Convert to LCID. If it fails ignore this $element if ( false === ( $lcid = LocaleHelper::ConvertWinToLCID( $element ) ) ) { continue; } // Get the elements of the current LCID LocaleHelper::ExpandLCID( $lcid, $lid, $cid, $charset ); // Create a new instance and return TRUE $refLocale = new Locale( $lid, $cid, $charset ); return true; } // Ignore 'LC_TYPE' locale types if ( 'LC_CTYPE' === \strtoupper( $tmp2[ 0 ] ) ) { continue; } // Convert the value (after the =) to a LCID. If it fails ignore this $element if ( false === ( $lcid = LocaleHelper::ConvertWinToLCID( $tmp2[ 1 ] ) ) ) { continue; } // Get the elements of the current LCID LocaleHelper::ExpandLCID( $lcid, $lid, $cid, $charset ); $refLocale = new Locale( $lid, $cid, $charset ); return true; } // Return false if no usable locale is found by this way return false; } // No windows systems if ( ! \preg_match( '~^[a-z]{2}([_-][a-z]{2})?(@[a-z_-]+)?(\.[a-z0-9_-]{1,14})?$~i', $lcString ) ) { // A unknown locale string format return false; } LocaleHelper::ExpandLCID( $lcString, $lid, $cid, $charset ); $refLocale = new Locale( $lid, $cid, $charset ); return true; }
php
public static function TryParseSystem( &$refLocale ) : bool { // Getting the current system used locale of LC_ALL $lcString = \setlocale( \LC_ALL, '0' ); // Ignore values with lower than 2 characters. It also ignores the 'C' locale if ( empty( $lcString ) || 2 > \strlen( $lcString ) ) { return false; } // Pre initialize the local LID, CID and Charset variables $lid = ''; $cid = ''; $charset = ''; // Handle windows different from other OS if ( \DIRECTORY_SEPARATOR === '\\' ) { $tmp = \explode( ';', $lcString ); // Loop the exploded elements foreach ( $tmp as $element ) { // Explode at the first equal sign '=' $tmp2 = \explode( '=', $element, 2 ); // If the explode before results in only one element (no '=' inside $element found) if ( 2 > \count( $tmp2 ) ) { // Convert to LCID. If it fails ignore this $element if ( false === ( $lcid = LocaleHelper::ConvertWinToLCID( $element ) ) ) { continue; } // Get the elements of the current LCID LocaleHelper::ExpandLCID( $lcid, $lid, $cid, $charset ); // Create a new instance and return TRUE $refLocale = new Locale( $lid, $cid, $charset ); return true; } // Ignore 'LC_TYPE' locale types if ( 'LC_CTYPE' === \strtoupper( $tmp2[ 0 ] ) ) { continue; } // Convert the value (after the =) to a LCID. If it fails ignore this $element if ( false === ( $lcid = LocaleHelper::ConvertWinToLCID( $tmp2[ 1 ] ) ) ) { continue; } // Get the elements of the current LCID LocaleHelper::ExpandLCID( $lcid, $lid, $cid, $charset ); $refLocale = new Locale( $lid, $cid, $charset ); return true; } // Return false if no usable locale is found by this way return false; } // No windows systems if ( ! \preg_match( '~^[a-z]{2}([_-][a-z]{2})?(@[a-z_-]+)?(\.[a-z0-9_-]{1,14})?$~i', $lcString ) ) { // A unknown locale string format return false; } LocaleHelper::ExpandLCID( $lcString, $lid, $cid, $charset ); $refLocale = new Locale( $lid, $cid, $charset ); return true; }
[ "public", "static", "function", "TryParseSystem", "(", "&", "$", "refLocale", ")", ":", "bool", "{", "// Getting the current system used locale of LC_ALL", "$", "lcString", "=", "\\", "setlocale", "(", "\\", "LC_ALL", ",", "'0'", ")", ";", "// Ignore values with lower than 2 characters. It also ignores the 'C' locale", "if", "(", "empty", "(", "$", "lcString", ")", "||", "2", ">", "\\", "strlen", "(", "$", "lcString", ")", ")", "{", "return", "false", ";", "}", "// Pre initialize the local LID, CID and Charset variables", "$", "lid", "=", "''", ";", "$", "cid", "=", "''", ";", "$", "charset", "=", "''", ";", "// Handle windows different from other OS", "if", "(", "\\", "DIRECTORY_SEPARATOR", "===", "'\\\\'", ")", "{", "$", "tmp", "=", "\\", "explode", "(", "';'", ",", "$", "lcString", ")", ";", "// Loop the exploded elements", "foreach", "(", "$", "tmp", "as", "$", "element", ")", "{", "// Explode at the first equal sign '='", "$", "tmp2", "=", "\\", "explode", "(", "'='", ",", "$", "element", ",", "2", ")", ";", "// If the explode before results in only one element (no '=' inside $element found)", "if", "(", "2", ">", "\\", "count", "(", "$", "tmp2", ")", ")", "{", "// Convert to LCID. If it fails ignore this $element", "if", "(", "false", "===", "(", "$", "lcid", "=", "LocaleHelper", "::", "ConvertWinToLCID", "(", "$", "element", ")", ")", ")", "{", "continue", ";", "}", "// Get the elements of the current LCID", "LocaleHelper", "::", "ExpandLCID", "(", "$", "lcid", ",", "$", "lid", ",", "$", "cid", ",", "$", "charset", ")", ";", "// Create a new instance and return TRUE", "$", "refLocale", "=", "new", "Locale", "(", "$", "lid", ",", "$", "cid", ",", "$", "charset", ")", ";", "return", "true", ";", "}", "// Ignore 'LC_TYPE' locale types", "if", "(", "'LC_CTYPE'", "===", "\\", "strtoupper", "(", "$", "tmp2", "[", "0", "]", ")", ")", "{", "continue", ";", "}", "// Convert the value (after the =) to a LCID. If it fails ignore this $element", "if", "(", "false", "===", "(", "$", "lcid", "=", "LocaleHelper", "::", "ConvertWinToLCID", "(", "$", "tmp2", "[", "1", "]", ")", ")", ")", "{", "continue", ";", "}", "// Get the elements of the current LCID", "LocaleHelper", "::", "ExpandLCID", "(", "$", "lcid", ",", "$", "lid", ",", "$", "cid", ",", "$", "charset", ")", ";", "$", "refLocale", "=", "new", "Locale", "(", "$", "lid", ",", "$", "cid", ",", "$", "charset", ")", ";", "return", "true", ";", "}", "// Return false if no usable locale is found by this way", "return", "false", ";", "}", "// No windows systems", "if", "(", "!", "\\", "preg_match", "(", "'~^[a-z]{2}([_-][a-z]{2})?(@[a-z_-]+)?(\\.[a-z0-9_-]{1,14})?$~i'", ",", "$", "lcString", ")", ")", "{", "// A unknown locale string format", "return", "false", ";", "}", "LocaleHelper", "::", "ExpandLCID", "(", "$", "lcString", ",", "$", "lid", ",", "$", "cid", ",", "$", "charset", ")", ";", "$", "refLocale", "=", "new", "Locale", "(", "$", "lid", ",", "$", "cid", ",", "$", "charset", ")", ";", "return", "true", ";", "}" ]
Tries to create a new Locale instance from underlying system/OS locale settings. @param \Beluga\Translation\Locale $refLocale Returns the Locale instance if the method return TRUE. @return bool
[ "Tries", "to", "create", "a", "new", "Locale", "instance", "from", "underlying", "system", "/", "OS", "locale", "settings", "." ]
train
https://github.com/SagittariusX/Beluga.Translation/blob/8f66c4fef6fa4494413972ca56bd8e13f5a7e444/src/Beluga/Translation/Locale.php#L439-L524
SagittariusX/Beluga.Translation
src/Beluga/Translation/Locale.php
Locale.TryParseBrowserInfo
public static function TryParseBrowserInfo( &$refLocale ) : bool { // If init by browser info is disabled, or the required $_SERVER['HTTP_ACCEPT_LANGUAGE'] is not defined if ( ! \filter_has_var( \INPUT_SERVER, 'HTTP_ACCEPT_LANGUAGE' ) ) { return false; } // Format like: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3 $tmp = \explode( ',', \filter_input( \INPUT_SERVER , 'HTTP_ACCEPT_LANGUAGE' ) ); // Iterate over each exploded element for ( $i = 0; $i < count( $tmp ); $i++ ) { // Explode each element at first semicolon ';' to max. 2 sub elements $tmp2 = \explode( ';', $tmp[ $i ], 2 ); // Explode the first sub element (must be a LCID) at '-' into LID and CID $tmp3 = \explode( '-', $tmp2[ 0 ], 2 ); // If last explode result not with 2 sub elements explode at '_' into LID and CID if ( \count( $tmp3 ) < 2 ) { $tmp3 = \explode( '_', $tmp2[ 0 ], 2 ); } // If last explode result not with 2 sub elements use only the LID if ( \count( $tmp3 ) < 2 ) { $tmp3 = [ $tmp2[ 0 ] ]; } $la = \trim( $tmp3[ 0 ] ); // If the LID do not use 2 characters ignore this element and restart with the next if ( \strlen( $la ) != 2 ) { continue; } // Init a empty CID $co = null; // Init a empty charset $cs = null; // If there are more than 1 sub elements extracted from current element if ( isset( $tmp3[ 1 ] ) ) { // Explode the second sub element at first point '.'. It separates the CID from the optional character set. $tmp2 = \explode( '.', $tmp3[ 1 ], 2 ); // Assign the CID $co = \trim( $tmp2[ 0 ] ); // A charset is defined, assign it if ( isset( $tmp2[ 1 ] ) ) { $cs = \trim( $tmp2[ 1 ] ); } // clear the CID if its not defined by 2 characters if ( \strlen( $co ) != 2 ) { $co = null; } // Otherwise convert the CID to lower case else { $co = \strtoupper ( $co ); } } // Init the new Locale instance and return it. $refLocale = new Locale( $la, $co, $cs ); return true; } // return FALSE if no usable local here was found. return false; }
php
public static function TryParseBrowserInfo( &$refLocale ) : bool { // If init by browser info is disabled, or the required $_SERVER['HTTP_ACCEPT_LANGUAGE'] is not defined if ( ! \filter_has_var( \INPUT_SERVER, 'HTTP_ACCEPT_LANGUAGE' ) ) { return false; } // Format like: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3 $tmp = \explode( ',', \filter_input( \INPUT_SERVER , 'HTTP_ACCEPT_LANGUAGE' ) ); // Iterate over each exploded element for ( $i = 0; $i < count( $tmp ); $i++ ) { // Explode each element at first semicolon ';' to max. 2 sub elements $tmp2 = \explode( ';', $tmp[ $i ], 2 ); // Explode the first sub element (must be a LCID) at '-' into LID and CID $tmp3 = \explode( '-', $tmp2[ 0 ], 2 ); // If last explode result not with 2 sub elements explode at '_' into LID and CID if ( \count( $tmp3 ) < 2 ) { $tmp3 = \explode( '_', $tmp2[ 0 ], 2 ); } // If last explode result not with 2 sub elements use only the LID if ( \count( $tmp3 ) < 2 ) { $tmp3 = [ $tmp2[ 0 ] ]; } $la = \trim( $tmp3[ 0 ] ); // If the LID do not use 2 characters ignore this element and restart with the next if ( \strlen( $la ) != 2 ) { continue; } // Init a empty CID $co = null; // Init a empty charset $cs = null; // If there are more than 1 sub elements extracted from current element if ( isset( $tmp3[ 1 ] ) ) { // Explode the second sub element at first point '.'. It separates the CID from the optional character set. $tmp2 = \explode( '.', $tmp3[ 1 ], 2 ); // Assign the CID $co = \trim( $tmp2[ 0 ] ); // A charset is defined, assign it if ( isset( $tmp2[ 1 ] ) ) { $cs = \trim( $tmp2[ 1 ] ); } // clear the CID if its not defined by 2 characters if ( \strlen( $co ) != 2 ) { $co = null; } // Otherwise convert the CID to lower case else { $co = \strtoupper ( $co ); } } // Init the new Locale instance and return it. $refLocale = new Locale( $la, $co, $cs ); return true; } // return FALSE if no usable local here was found. return false; }
[ "public", "static", "function", "TryParseBrowserInfo", "(", "&", "$", "refLocale", ")", ":", "bool", "{", "// If init by browser info is disabled, or the required $_SERVER['HTTP_ACCEPT_LANGUAGE'] is not defined", "if", "(", "!", "\\", "filter_has_var", "(", "\\", "INPUT_SERVER", ",", "'HTTP_ACCEPT_LANGUAGE'", ")", ")", "{", "return", "false", ";", "}", "// Format like: de-de,de;q=0.8,en-us;q=0.5,en;q=0.3", "$", "tmp", "=", "\\", "explode", "(", "','", ",", "\\", "filter_input", "(", "\\", "INPUT_SERVER", ",", "'HTTP_ACCEPT_LANGUAGE'", ")", ")", ";", "// Iterate over each exploded element", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "tmp", ")", ";", "$", "i", "++", ")", "{", "// Explode each element at first semicolon ';' to max. 2 sub elements", "$", "tmp2", "=", "\\", "explode", "(", "';'", ",", "$", "tmp", "[", "$", "i", "]", ",", "2", ")", ";", "// Explode the first sub element (must be a LCID) at '-' into LID and CID", "$", "tmp3", "=", "\\", "explode", "(", "'-'", ",", "$", "tmp2", "[", "0", "]", ",", "2", ")", ";", "// If last explode result not with 2 sub elements explode at '_' into LID and CID", "if", "(", "\\", "count", "(", "$", "tmp3", ")", "<", "2", ")", "{", "$", "tmp3", "=", "\\", "explode", "(", "'_'", ",", "$", "tmp2", "[", "0", "]", ",", "2", ")", ";", "}", "// If last explode result not with 2 sub elements use only the LID", "if", "(", "\\", "count", "(", "$", "tmp3", ")", "<", "2", ")", "{", "$", "tmp3", "=", "[", "$", "tmp2", "[", "0", "]", "]", ";", "}", "$", "la", "=", "\\", "trim", "(", "$", "tmp3", "[", "0", "]", ")", ";", "// If the LID do not use 2 characters ignore this element and restart with the next", "if", "(", "\\", "strlen", "(", "$", "la", ")", "!=", "2", ")", "{", "continue", ";", "}", "// Init a empty CID", "$", "co", "=", "null", ";", "// Init a empty charset", "$", "cs", "=", "null", ";", "// If there are more than 1 sub elements extracted from current element", "if", "(", "isset", "(", "$", "tmp3", "[", "1", "]", ")", ")", "{", "// Explode the second sub element at first point '.'. It separates the CID from the optional character set.", "$", "tmp2", "=", "\\", "explode", "(", "'.'", ",", "$", "tmp3", "[", "1", "]", ",", "2", ")", ";", "// Assign the CID", "$", "co", "=", "\\", "trim", "(", "$", "tmp2", "[", "0", "]", ")", ";", "// A charset is defined, assign it", "if", "(", "isset", "(", "$", "tmp2", "[", "1", "]", ")", ")", "{", "$", "cs", "=", "\\", "trim", "(", "$", "tmp2", "[", "1", "]", ")", ";", "}", "// clear the CID if its not defined by 2 characters", "if", "(", "\\", "strlen", "(", "$", "co", ")", "!=", "2", ")", "{", "$", "co", "=", "null", ";", "}", "// Otherwise convert the CID to lower case", "else", "{", "$", "co", "=", "\\", "strtoupper", "(", "$", "co", ")", ";", "}", "}", "// Init the new Locale instance and return it.", "$", "refLocale", "=", "new", "Locale", "(", "$", "la", ",", "$", "co", ",", "$", "cs", ")", ";", "return", "true", ";", "}", "// return FALSE if no usable local here was found.", "return", "false", ";", "}" ]
Tries to create a new Locale instance from browser defined Accept-Language header. @param \Beluga\Translation\Locale $refLocale Returns the Locale instance if the method return TRUE. @return bool
[ "Tries", "to", "create", "a", "new", "Locale", "instance", "from", "browser", "defined", "Accept", "-", "Language", "header", "." ]
train
https://github.com/SagittariusX/Beluga.Translation/blob/8f66c4fef6fa4494413972ca56bd8e13f5a7e444/src/Beluga/Translation/Locale.php#L532-L614
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Crypt.php
Crypt.encrypt
public static function encrypt($data,$key,$expire=0){ if(empty(self::$handler)){ self::init(); } $class = self::$handler; return $class::encrypt($data,$key,$expire); }
php
public static function encrypt($data,$key,$expire=0){ if(empty(self::$handler)){ self::init(); } $class = self::$handler; return $class::encrypt($data,$key,$expire); }
[ "public", "static", "function", "encrypt", "(", "$", "data", ",", "$", "key", ",", "$", "expire", "=", "0", ")", "{", "if", "(", "empty", "(", "self", "::", "$", "handler", ")", ")", "{", "self", "::", "init", "(", ")", ";", "}", "$", "class", "=", "self", "::", "$", "handler", ";", "return", "$", "class", "::", "encrypt", "(", "$", "data", ",", "$", "key", ",", "$", "expire", ")", ";", "}" ]
加密字符串 @param string $str 字符串 @param string $key 加密key @param integer $expire 有效期(秒) 0 为永久有效 @return string
[ "加密字符串" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Crypt.php#L32-L38
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Crypt.php
Crypt.decrypt
public static function decrypt($data,$key){ if(empty(self::$handler)){ self::init(); } $class = self::$handler; return $class::decrypt($data,$key); }
php
public static function decrypt($data,$key){ if(empty(self::$handler)){ self::init(); } $class = self::$handler; return $class::decrypt($data,$key); }
[ "public", "static", "function", "decrypt", "(", "$", "data", ",", "$", "key", ")", "{", "if", "(", "empty", "(", "self", "::", "$", "handler", ")", ")", "{", "self", "::", "init", "(", ")", ";", "}", "$", "class", "=", "self", "::", "$", "handler", ";", "return", "$", "class", "::", "decrypt", "(", "$", "data", ",", "$", "key", ")", ";", "}" ]
解密字符串 @param string $str 字符串 @param string $key 加密key @return string
[ "解密字符串" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Crypt.php#L46-L52
miaoxing/user
src/Mailer/ResetPassword.php
ResetPassword.prepare
public function prepare() { // @codingStandardsIgnoreStart $this->Subject = '重置密码'; $this->addAddress($this->user['email']); $nonce = $this->generateNonceStr(); $timestamp = time(); $userId = $this->user['id']; $password = $this->user['password']; $sign = md5($userId . $password . $timestamp . $nonce); $resetUrl = $this->url->full('password/reset-return?', [ 'nonce' => $nonce, 'timestamp' => $timestamp, 'userId' => $userId, 'sign' => $sign, ]); $this->Body = $this->view->render('@user/mailers/resetPassword.php', get_defined_vars()); // @codingStandardsIgnoreEnd }
php
public function prepare() { // @codingStandardsIgnoreStart $this->Subject = '重置密码'; $this->addAddress($this->user['email']); $nonce = $this->generateNonceStr(); $timestamp = time(); $userId = $this->user['id']; $password = $this->user['password']; $sign = md5($userId . $password . $timestamp . $nonce); $resetUrl = $this->url->full('password/reset-return?', [ 'nonce' => $nonce, 'timestamp' => $timestamp, 'userId' => $userId, 'sign' => $sign, ]); $this->Body = $this->view->render('@user/mailers/resetPassword.php', get_defined_vars()); // @codingStandardsIgnoreEnd }
[ "public", "function", "prepare", "(", ")", "{", "// @codingStandardsIgnoreStart", "$", "this", "->", "Subject", "=", "'重置密码';", "", "$", "this", "->", "addAddress", "(", "$", "this", "->", "user", "[", "'email'", "]", ")", ";", "$", "nonce", "=", "$", "this", "->", "generateNonceStr", "(", ")", ";", "$", "timestamp", "=", "time", "(", ")", ";", "$", "userId", "=", "$", "this", "->", "user", "[", "'id'", "]", ";", "$", "password", "=", "$", "this", "->", "user", "[", "'password'", "]", ";", "$", "sign", "=", "md5", "(", "$", "userId", ".", "$", "password", ".", "$", "timestamp", ".", "$", "nonce", ")", ";", "$", "resetUrl", "=", "$", "this", "->", "url", "->", "full", "(", "'password/reset-return?'", ",", "[", "'nonce'", "=>", "$", "nonce", ",", "'timestamp'", "=>", "$", "timestamp", ",", "'userId'", "=>", "$", "userId", ",", "'sign'", "=>", "$", "sign", ",", "]", ")", ";", "$", "this", "->", "Body", "=", "$", "this", "->", "view", "->", "render", "(", "'@user/mailers/resetPassword.php'", ",", "get_defined_vars", "(", ")", ")", ";", "// @codingStandardsIgnoreEnd", "}" ]
{@inheritdoc}
[ "{" ]
train
https://github.com/miaoxing/user/blob/d94e52f64a0151ba7202c857b373394ad09e06ce/src/Mailer/ResetPassword.php#L13-L34
nicolasdewez/webhome-common
Logout/RedirectionHandler.php
RedirectionHandler.onLogoutSuccess
public function onLogoutSuccess(Request $request) { try { return new RedirectResponse(sprintf( '%s?redirect=%s', $this->container->getParameter('webhome_auth_url'), urlencode($this->container->get('router')->generate( $this->getHomepageRouteName(), [], UrlGeneratorInterface::ABSOLUTE_URL )) )); } catch (ResourceNotFoundException $exception) { // no homepage? simple redirection return new RedirectResponse($this->container->getParameter('webhome_auth.logout_url')); } }
php
public function onLogoutSuccess(Request $request) { try { return new RedirectResponse(sprintf( '%s?redirect=%s', $this->container->getParameter('webhome_auth_url'), urlencode($this->container->get('router')->generate( $this->getHomepageRouteName(), [], UrlGeneratorInterface::ABSOLUTE_URL )) )); } catch (ResourceNotFoundException $exception) { // no homepage? simple redirection return new RedirectResponse($this->container->getParameter('webhome_auth.logout_url')); } }
[ "public", "function", "onLogoutSuccess", "(", "Request", "$", "request", ")", "{", "try", "{", "return", "new", "RedirectResponse", "(", "sprintf", "(", "'%s?redirect=%s'", ",", "$", "this", "->", "container", "->", "getParameter", "(", "'webhome_auth_url'", ")", ",", "urlencode", "(", "$", "this", "->", "container", "->", "get", "(", "'router'", ")", "->", "generate", "(", "$", "this", "->", "getHomepageRouteName", "(", ")", ",", "[", "]", ",", "UrlGeneratorInterface", "::", "ABSOLUTE_URL", ")", ")", ")", ")", ";", "}", "catch", "(", "ResourceNotFoundException", "$", "exception", ")", "{", "// no homepage? simple redirection", "return", "new", "RedirectResponse", "(", "$", "this", "->", "container", "->", "getParameter", "(", "'webhome_auth.logout_url'", ")", ")", ";", "}", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/nicolasdewez/webhome-common/blob/a9f6f83fa929ebd0510818c388cfb1ed44b87205/Logout/RedirectionHandler.php#L22-L38
itkg/core
src/Itkg/Core/Cache/Adapter/Chain/UseFirstWorkingStrategy.php
UseFirstWorkingStrategy.get
public function get(array $adapters, CacheableInterface $item) { foreach ($adapters as $adapter) { try { return $adapter->get($item); } catch (\Exception $e) { continue; } } throw new UnhandledCacheException('No cache system is available'); }
php
public function get(array $adapters, CacheableInterface $item) { foreach ($adapters as $adapter) { try { return $adapter->get($item); } catch (\Exception $e) { continue; } } throw new UnhandledCacheException('No cache system is available'); }
[ "public", "function", "get", "(", "array", "$", "adapters", ",", "CacheableInterface", "$", "item", ")", "{", "foreach", "(", "$", "adapters", "as", "$", "adapter", ")", "{", "try", "{", "return", "$", "adapter", "->", "get", "(", "$", "item", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "continue", ";", "}", "}", "throw", "new", "UnhandledCacheException", "(", "'No cache system is available'", ")", ";", "}" ]
Get cache from first up adapter @param array $adapters @param CacheableInterface $item @throws UnhandledCacheException @return mixed
[ "Get", "cache", "from", "first", "up", "adapter" ]
train
https://github.com/itkg/core/blob/e5e4efb05feb4d23b0df41f2b21fd095103e593b/src/Itkg/Core/Cache/Adapter/Chain/UseFirstWorkingStrategy.php#L38-L49
itkg/core
src/Itkg/Core/Cache/Adapter/Chain/UseFirstWorkingStrategy.php
UseFirstWorkingStrategy.remove
public function remove(array $adapters, CacheableInterface $item) { foreach ($adapters as $adapter) { $adapter->remove($item); } }
php
public function remove(array $adapters, CacheableInterface $item) { foreach ($adapters as $adapter) { $adapter->remove($item); } }
[ "public", "function", "remove", "(", "array", "$", "adapters", ",", "CacheableInterface", "$", "item", ")", "{", "foreach", "(", "$", "adapters", "as", "$", "adapter", ")", "{", "$", "adapter", "->", "remove", "(", "$", "item", ")", ";", "}", "}" ]
Remove cache from all adapters @param array $adapters @param CacheableInterface $item @return void
[ "Remove", "cache", "from", "all", "adapters" ]
train
https://github.com/itkg/core/blob/e5e4efb05feb4d23b0df41f2b21fd095103e593b/src/Itkg/Core/Cache/Adapter/Chain/UseFirstWorkingStrategy.php#L80-L85
congraphcms/core
Repositories/RelationLoader.php
RelationLoader.load
public function load($data, $relations = []) { $this->clearQueue(); $relations = $this->parseRelations($relations); $this->queueUnresolvedObjects($data, $relations); $this->loadQueue(); }
php
public function load($data, $relations = []) { $this->clearQueue(); $relations = $this->parseRelations($relations); $this->queueUnresolvedObjects($data, $relations); $this->loadQueue(); }
[ "public", "function", "load", "(", "$", "data", ",", "$", "relations", "=", "[", "]", ")", "{", "$", "this", "->", "clearQueue", "(", ")", ";", "$", "relations", "=", "$", "this", "->", "parseRelations", "(", "$", "relations", ")", ";", "$", "this", "->", "queueUnresolvedObjects", "(", "$", "data", ",", "$", "relations", ")", ";", "$", "this", "->", "loadQueue", "(", ")", ";", "}" ]
Preload relationships @param array $relations @return void
[ "Preload", "relationships" ]
train
https://github.com/congraphcms/core/blob/d017d3951b446fb2ac93b8fcee120549bb125b17/Repositories/RelationLoader.php#L45-L54
congraphcms/core
Repositories/RelationLoader.php
RelationLoader.parseRelations
public function parseRelations($relations) { if(is_numeric($relations)) { return intval($relations); } $relations = ( is_array($relations) ) ? $relations : explode(',', strval($relations)); return $relations; }
php
public function parseRelations($relations) { if(is_numeric($relations)) { return intval($relations); } $relations = ( is_array($relations) ) ? $relations : explode(',', strval($relations)); return $relations; }
[ "public", "function", "parseRelations", "(", "$", "relations", ")", "{", "if", "(", "is_numeric", "(", "$", "relations", ")", ")", "{", "return", "intval", "(", "$", "relations", ")", ";", "}", "$", "relations", "=", "(", "is_array", "(", "$", "relations", ")", ")", "?", "$", "relations", ":", "explode", "(", "','", ",", "strval", "(", "$", "relations", ")", ")", ";", "return", "$", "relations", ";", "}" ]
Add relation properties @param array | string | number $relations @return void
[ "Add", "relation", "properties" ]
train
https://github.com/congraphcms/core/blob/d017d3951b446fb2ac93b8fcee120549bb125b17/Repositories/RelationLoader.php#L73-L82
congraphcms/core
Repositories/RelationLoader.php
RelationLoader.queueUnresolvedObjects
public function queueUnresolvedObjects($data, $relations) { if( is_object($data) ) { if( $data instanceof Model ) { $data = $data->getData(); } if( !$this->resolved($data) ) { $this->addToQueue($data, $relations); return; } $data = get_object_vars($data); } if( is_array($data) ) { foreach ($data as $key => $value) { if(is_int($key)) { $this->queueUnresolvedObjects($value, $relations); } if($this->hasRelation($key, $relations)) { $nestedRelations = $this->getNestedRelations($key, $relations); $this->queueUnresolvedObjects($value, $nestedRelations); } } } }
php
public function queueUnresolvedObjects($data, $relations) { if( is_object($data) ) { if( $data instanceof Model ) { $data = $data->getData(); } if( !$this->resolved($data) ) { $this->addToQueue($data, $relations); return; } $data = get_object_vars($data); } if( is_array($data) ) { foreach ($data as $key => $value) { if(is_int($key)) { $this->queueUnresolvedObjects($value, $relations); } if($this->hasRelation($key, $relations)) { $nestedRelations = $this->getNestedRelations($key, $relations); $this->queueUnresolvedObjects($value, $nestedRelations); } } } }
[ "public", "function", "queueUnresolvedObjects", "(", "$", "data", ",", "$", "relations", ")", "{", "if", "(", "is_object", "(", "$", "data", ")", ")", "{", "if", "(", "$", "data", "instanceof", "Model", ")", "{", "$", "data", "=", "$", "data", "->", "getData", "(", ")", ";", "}", "if", "(", "!", "$", "this", "->", "resolved", "(", "$", "data", ")", ")", "{", "$", "this", "->", "addToQueue", "(", "$", "data", ",", "$", "relations", ")", ";", "return", ";", "}", "$", "data", "=", "get_object_vars", "(", "$", "data", ")", ";", "}", "if", "(", "is_array", "(", "$", "data", ")", ")", "{", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "if", "(", "is_int", "(", "$", "key", ")", ")", "{", "$", "this", "->", "queueUnresolvedObjects", "(", "$", "value", ",", "$", "relations", ")", ";", "}", "if", "(", "$", "this", "->", "hasRelation", "(", "$", "key", ",", "$", "relations", ")", ")", "{", "$", "nestedRelations", "=", "$", "this", "->", "getNestedRelations", "(", "$", "key", ",", "$", "relations", ")", ";", "$", "this", "->", "queueUnresolvedObjects", "(", "$", "value", ",", "$", "nestedRelations", ")", ";", "}", "}", "}", "}" ]
Add unresovled objects to load queue @param mixed $data data to be parsed @param array | integer $relations relations to be loaded @return void
[ "Add", "unresovled", "objects", "to", "load", "queue" ]
train
https://github.com/congraphcms/core/blob/d017d3951b446fb2ac93b8fcee120549bb125b17/Repositories/RelationLoader.php#L92-L127
congraphcms/core
Repositories/RelationLoader.php
RelationLoader.resolved
protected function resolved($obj) { if( ! is_object($obj) ) { return true; } $data = get_object_vars($obj); if( count($data) == 2 && array_key_exists('id', $data) && array_key_exists('type', $data) ) { return false; } return true; }
php
protected function resolved($obj) { if( ! is_object($obj) ) { return true; } $data = get_object_vars($obj); if( count($data) == 2 && array_key_exists('id', $data) && array_key_exists('type', $data) ) { return false; } return true; }
[ "protected", "function", "resolved", "(", "$", "obj", ")", "{", "if", "(", "!", "is_object", "(", "$", "obj", ")", ")", "{", "return", "true", ";", "}", "$", "data", "=", "get_object_vars", "(", "$", "obj", ")", ";", "if", "(", "count", "(", "$", "data", ")", "==", "2", "&&", "array_key_exists", "(", "'id'", ",", "$", "data", ")", "&&", "array_key_exists", "(", "'type'", ",", "$", "data", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check if object is resolved @param stdClass $obj object to check @return boolean
[ "Check", "if", "object", "is", "resolved" ]
train
https://github.com/congraphcms/core/blob/d017d3951b446fb2ac93b8fcee120549bb125b17/Repositories/RelationLoader.php#L136-L153
congraphcms/core
Repositories/RelationLoader.php
RelationLoader.addToQueue
protected function addToQueue($object, $relations) { if( ! array_key_exists($object->type, self::$loadQueue) ) { self::$loadQueue[$object->type] = []; } $relationsKey = base64_encode(json_encode($relations)); if( ! array_key_exists($relationsKey, self::$loadQueue[$object->type]) ) { self::$loadQueue[$object->type][$relationsKey] = [ 'type' => $object->type, 'ids' => [], 'relations' => $relations ]; } self::$loadQueue[$object->type][$relationsKey]['ids'][] = $object->id; }
php
protected function addToQueue($object, $relations) { if( ! array_key_exists($object->type, self::$loadQueue) ) { self::$loadQueue[$object->type] = []; } $relationsKey = base64_encode(json_encode($relations)); if( ! array_key_exists($relationsKey, self::$loadQueue[$object->type]) ) { self::$loadQueue[$object->type][$relationsKey] = [ 'type' => $object->type, 'ids' => [], 'relations' => $relations ]; } self::$loadQueue[$object->type][$relationsKey]['ids'][] = $object->id; }
[ "protected", "function", "addToQueue", "(", "$", "object", ",", "$", "relations", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "object", "->", "type", ",", "self", "::", "$", "loadQueue", ")", ")", "{", "self", "::", "$", "loadQueue", "[", "$", "object", "->", "type", "]", "=", "[", "]", ";", "}", "$", "relationsKey", "=", "base64_encode", "(", "json_encode", "(", "$", "relations", ")", ")", ";", "if", "(", "!", "array_key_exists", "(", "$", "relationsKey", ",", "self", "::", "$", "loadQueue", "[", "$", "object", "->", "type", "]", ")", ")", "{", "self", "::", "$", "loadQueue", "[", "$", "object", "->", "type", "]", "[", "$", "relationsKey", "]", "=", "[", "'type'", "=>", "$", "object", "->", "type", ",", "'ids'", "=>", "[", "]", ",", "'relations'", "=>", "$", "relations", "]", ";", "}", "self", "::", "$", "loadQueue", "[", "$", "object", "->", "type", "]", "[", "$", "relationsKey", "]", "[", "'ids'", "]", "[", "]", "=", "$", "object", "->", "id", ";", "}" ]
Add object to loadQueue if it's specified in relations @param stdClass $object object to add @param array | int $relations relations to check @return void
[ "Add", "object", "to", "loadQueue", "if", "it", "s", "specified", "in", "relations" ]
train
https://github.com/congraphcms/core/blob/d017d3951b446fb2ac93b8fcee120549bb125b17/Repositories/RelationLoader.php#L163-L176
eureka-framework/component-application
src/Application/ApplicationStatic.php
ApplicationStatic.run
public function run() { $this->loadMiddleware(); //~ Default response $response = new HttpMessage\Response(); //$response->getBody()->write('-- static --'); //~ Get response $stack = new HttpMiddleware\Stack($response, $this->middleware); $response = $stack->process(HttpMessage\ServerRequest::createFromGlobal()); //~ Send response (new HttpMessage\ResponseSender($response))->send(); }
php
public function run() { $this->loadMiddleware(); //~ Default response $response = new HttpMessage\Response(); //$response->getBody()->write('-- static --'); //~ Get response $stack = new HttpMiddleware\Stack($response, $this->middleware); $response = $stack->process(HttpMessage\ServerRequest::createFromGlobal()); //~ Send response (new HttpMessage\ResponseSender($response))->send(); }
[ "public", "function", "run", "(", ")", "{", "$", "this", "->", "loadMiddleware", "(", ")", ";", "//~ Default response", "$", "response", "=", "new", "HttpMessage", "\\", "Response", "(", ")", ";", "//$response->getBody()->write('-- static --');", "//~ Get response", "$", "stack", "=", "new", "HttpMiddleware", "\\", "Stack", "(", "$", "response", ",", "$", "this", "->", "middleware", ")", ";", "$", "response", "=", "$", "stack", "->", "process", "(", "HttpMessage", "\\", "ServerRequest", "::", "createFromGlobal", "(", ")", ")", ";", "//~ Send response", "(", "new", "HttpMessage", "\\", "ResponseSender", "(", "$", "response", ")", ")", "->", "send", "(", ")", ";", "}" ]
Run application based on the route. @return ResponseInterface @throws \Exception
[ "Run", "application", "based", "on", "the", "route", "." ]
train
https://github.com/eureka-framework/component-application/blob/5bf70f20967ef15515abe764b465641277a51537/src/Application/ApplicationStatic.php#L41-L55
eureka-framework/component-application
src/Application/ApplicationStatic.php
ApplicationStatic.loadMiddleware
private function loadMiddleware() { $config = Container::getInstance()->get('config'); $this->middleware[] = new Middleware\ExceptionMiddleware\ExceptionMiddleware($config); //~ Request $request = HttpMessage\ServerRequest::createFromGlobal(); $query = $request->getQueryParams(); $this->type = $query['type']; switch ($this->type) { case 'css': $this->middleware[] = new Middleware\StaticMiddleware\CssMiddleware($config); break; case 'js': $this->middleware[] = new Middleware\StaticMiddleware\JsMiddleware($config); break; case 'image': $this->middleware[] = new Middleware\StaticMiddleware\ImageMiddleware($config); break; case 'font': $this->middleware[] = new Middleware\StaticMiddleware\FontMiddleware($config); break; } }
php
private function loadMiddleware() { $config = Container::getInstance()->get('config'); $this->middleware[] = new Middleware\ExceptionMiddleware\ExceptionMiddleware($config); //~ Request $request = HttpMessage\ServerRequest::createFromGlobal(); $query = $request->getQueryParams(); $this->type = $query['type']; switch ($this->type) { case 'css': $this->middleware[] = new Middleware\StaticMiddleware\CssMiddleware($config); break; case 'js': $this->middleware[] = new Middleware\StaticMiddleware\JsMiddleware($config); break; case 'image': $this->middleware[] = new Middleware\StaticMiddleware\ImageMiddleware($config); break; case 'font': $this->middleware[] = new Middleware\StaticMiddleware\FontMiddleware($config); break; } }
[ "private", "function", "loadMiddleware", "(", ")", "{", "$", "config", "=", "Container", "::", "getInstance", "(", ")", "->", "get", "(", "'config'", ")", ";", "$", "this", "->", "middleware", "[", "]", "=", "new", "Middleware", "\\", "ExceptionMiddleware", "\\", "ExceptionMiddleware", "(", "$", "config", ")", ";", "//~ Request", "$", "request", "=", "HttpMessage", "\\", "ServerRequest", "::", "createFromGlobal", "(", ")", ";", "$", "query", "=", "$", "request", "->", "getQueryParams", "(", ")", ";", "$", "this", "->", "type", "=", "$", "query", "[", "'type'", "]", ";", "switch", "(", "$", "this", "->", "type", ")", "{", "case", "'css'", ":", "$", "this", "->", "middleware", "[", "]", "=", "new", "Middleware", "\\", "StaticMiddleware", "\\", "CssMiddleware", "(", "$", "config", ")", ";", "break", ";", "case", "'js'", ":", "$", "this", "->", "middleware", "[", "]", "=", "new", "Middleware", "\\", "StaticMiddleware", "\\", "JsMiddleware", "(", "$", "config", ")", ";", "break", ";", "case", "'image'", ":", "$", "this", "->", "middleware", "[", "]", "=", "new", "Middleware", "\\", "StaticMiddleware", "\\", "ImageMiddleware", "(", "$", "config", ")", ";", "break", ";", "case", "'font'", ":", "$", "this", "->", "middleware", "[", "]", "=", "new", "Middleware", "\\", "StaticMiddleware", "\\", "FontMiddleware", "(", "$", "config", ")", ";", "break", ";", "}", "}" ]
Load middlewares @return void
[ "Load", "middlewares" ]
train
https://github.com/eureka-framework/component-application/blob/5bf70f20967ef15515abe764b465641277a51537/src/Application/ApplicationStatic.php#L62-L89
imsamurai/CakePHP-AdvancedShell
Console/Command/Task/AdvancedTask.php
AdvancedTask.runCommand
public function runCommand($command, $argv) { if (!empty($this->args[0]) && $this->hasMethod($this->args[0])) { $this->action = $this->args[0]; } else { $this->action = null; } $this->statisticsStart('AdvancedShell'); Configure::write('debug', (int)Hash::get($this->params, 'debug')); if ($this->isScheduled()) { if ($this->params['scheduled-no-split']) { $this->setScheduleSplitter(new ScheduleNoSplit()); } $this->schedule(); $out = null; } elseif ($this->action) { $out = $this->{$this->action}(); } else { $out = parent::runCommand($command, $argv); } $this->statisticsEnd('AdvancedShell'); $this->sqlDump(false, false); $this->hr(); return $out; }
php
public function runCommand($command, $argv) { if (!empty($this->args[0]) && $this->hasMethod($this->args[0])) { $this->action = $this->args[0]; } else { $this->action = null; } $this->statisticsStart('AdvancedShell'); Configure::write('debug', (int)Hash::get($this->params, 'debug')); if ($this->isScheduled()) { if ($this->params['scheduled-no-split']) { $this->setScheduleSplitter(new ScheduleNoSplit()); } $this->schedule(); $out = null; } elseif ($this->action) { $out = $this->{$this->action}(); } else { $out = parent::runCommand($command, $argv); } $this->statisticsEnd('AdvancedShell'); $this->sqlDump(false, false); $this->hr(); return $out; }
[ "public", "function", "runCommand", "(", "$", "command", ",", "$", "argv", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "args", "[", "0", "]", ")", "&&", "$", "this", "->", "hasMethod", "(", "$", "this", "->", "args", "[", "0", "]", ")", ")", "{", "$", "this", "->", "action", "=", "$", "this", "->", "args", "[", "0", "]", ";", "}", "else", "{", "$", "this", "->", "action", "=", "null", ";", "}", "$", "this", "->", "statisticsStart", "(", "'AdvancedShell'", ")", ";", "Configure", "::", "write", "(", "'debug'", ",", "(", "int", ")", "Hash", "::", "get", "(", "$", "this", "->", "params", ",", "'debug'", ")", ")", ";", "if", "(", "$", "this", "->", "isScheduled", "(", ")", ")", "{", "if", "(", "$", "this", "->", "params", "[", "'scheduled-no-split'", "]", ")", "{", "$", "this", "->", "setScheduleSplitter", "(", "new", "ScheduleNoSplit", "(", ")", ")", ";", "}", "$", "this", "->", "schedule", "(", ")", ";", "$", "out", "=", "null", ";", "}", "elseif", "(", "$", "this", "->", "action", ")", "{", "$", "out", "=", "$", "this", "->", "{", "$", "this", "->", "action", "}", "(", ")", ";", "}", "else", "{", "$", "out", "=", "parent", "::", "runCommand", "(", "$", "command", ",", "$", "argv", ")", ";", "}", "$", "this", "->", "statisticsEnd", "(", "'AdvancedShell'", ")", ";", "$", "this", "->", "sqlDump", "(", "false", ",", "false", ")", ";", "$", "this", "->", "hr", "(", ")", ";", "return", "$", "out", ";", "}" ]
{@inheritdoc} @param string $command @param array $argv @return bool
[ "{", "@inheritdoc", "}" ]
train
https://github.com/imsamurai/CakePHP-AdvancedShell/blob/087d483742e2a76bee45e35b8d94957b0d20f857/Console/Command/Task/AdvancedTask.php#L58-L81
imsamurai/CakePHP-AdvancedShell
Console/Command/Task/AdvancedTask.php
AdvancedTask.schedule
public function schedule() { if (!empty($this->params['scheduled-wait-prev'])) { $this->_scheduleNextTaskDependsOnPrevious = ($this->params['scheduled-wait-prev'] === 'yes'); } list($command, $path, $arguments, $options) = $this->_scheduleVars(); $lastTaskId = null; foreach ($this->getScheduleSplitter()->split($arguments) as $_arguments) { $_options = $options; if ($this->_scheduleNextTaskDependsOnPrevious && !is_null($lastTaskId)) { $_options['dependsOn'][] = $lastTaskId; } $task = $this->_schedule($command, $path, $_arguments, $_options); $lastTaskId = $task['id']; } }
php
public function schedule() { if (!empty($this->params['scheduled-wait-prev'])) { $this->_scheduleNextTaskDependsOnPrevious = ($this->params['scheduled-wait-prev'] === 'yes'); } list($command, $path, $arguments, $options) = $this->_scheduleVars(); $lastTaskId = null; foreach ($this->getScheduleSplitter()->split($arguments) as $_arguments) { $_options = $options; if ($this->_scheduleNextTaskDependsOnPrevious && !is_null($lastTaskId)) { $_options['dependsOn'][] = $lastTaskId; } $task = $this->_schedule($command, $path, $_arguments, $_options); $lastTaskId = $task['id']; } }
[ "public", "function", "schedule", "(", ")", "{", "if", "(", "!", "empty", "(", "$", "this", "->", "params", "[", "'scheduled-wait-prev'", "]", ")", ")", "{", "$", "this", "->", "_scheduleNextTaskDependsOnPrevious", "=", "(", "$", "this", "->", "params", "[", "'scheduled-wait-prev'", "]", "===", "'yes'", ")", ";", "}", "list", "(", "$", "command", ",", "$", "path", ",", "$", "arguments", ",", "$", "options", ")", "=", "$", "this", "->", "_scheduleVars", "(", ")", ";", "$", "lastTaskId", "=", "null", ";", "foreach", "(", "$", "this", "->", "getScheduleSplitter", "(", ")", "->", "split", "(", "$", "arguments", ")", "as", "$", "_arguments", ")", "{", "$", "_options", "=", "$", "options", ";", "if", "(", "$", "this", "->", "_scheduleNextTaskDependsOnPrevious", "&&", "!", "is_null", "(", "$", "lastTaskId", ")", ")", "{", "$", "_options", "[", "'dependsOn'", "]", "[", "]", "=", "$", "lastTaskId", ";", "}", "$", "task", "=", "$", "this", "->", "_schedule", "(", "$", "command", ",", "$", "path", ",", "$", "_arguments", ",", "$", "_options", ")", ";", "$", "lastTaskId", "=", "$", "task", "[", "'id'", "]", ";", "}", "}" ]
Adds script to sceduler (for ex by date range)
[ "Adds", "script", "to", "sceduler", "(", "for", "ex", "by", "date", "range", ")" ]
train
https://github.com/imsamurai/CakePHP-AdvancedShell/blob/087d483742e2a76bee45e35b8d94957b0d20f857/Console/Command/Task/AdvancedTask.php#L114-L128
imsamurai/CakePHP-AdvancedShell
Console/Command/Task/AdvancedTask.php
AdvancedTask.getOptionParser
public function getOptionParser() { $parser = parent::getOptionParser(); $parser->addOption('range', array( 'help' => 'Either a date range (separator "-") in format ' . Configure::read('Task.dateFormat') )) ->addOption('interval', array( 'help' => 'Interval in date time format (for ex: 15 minutes, 1 hour, 2 days). Defaults 1 day' )) ->addOption('debug', array( 'help' => 'Sets debug level', 'short' => 'd', 'default' => Configure::read('debug') )); if (CakePlugin::loaded('Task')) { $parser->addOption('scheduled', array( 'help' => 'If set then script will be run by task daemon', 'boolean' => true )) ->addOption('scheduled-no-split', array( 'help' => 'If set then script will not be splitten by arguments', 'boolean' => true )) ->addOption('scheduled-process-timeout', array( 'help' => 'Sets task process timeout', 'default' => Configure::read('Task.timeout') )) ->addOption('scheduled-depends-on', array( 'help' => 'Tasks ids that must be done before current task can start. Format: coma separated', )) ->addOption('scheduled-wait-prev', array( 'help' => 'If `yes` each task will wait for previous task, else each task will run independenly. See `$_scheduleNextTaskDependsOnPrevious` for script defaults that used when this parameter was omitted.', )); } else { $parser->epilog($parser->epilog() . "\n" . 'For using `scheduled` install and enable Task plugin https://github.com/imsamurai/cakephp-task-plugin'); } return $parser; }
php
public function getOptionParser() { $parser = parent::getOptionParser(); $parser->addOption('range', array( 'help' => 'Either a date range (separator "-") in format ' . Configure::read('Task.dateFormat') )) ->addOption('interval', array( 'help' => 'Interval in date time format (for ex: 15 minutes, 1 hour, 2 days). Defaults 1 day' )) ->addOption('debug', array( 'help' => 'Sets debug level', 'short' => 'd', 'default' => Configure::read('debug') )); if (CakePlugin::loaded('Task')) { $parser->addOption('scheduled', array( 'help' => 'If set then script will be run by task daemon', 'boolean' => true )) ->addOption('scheduled-no-split', array( 'help' => 'If set then script will not be splitten by arguments', 'boolean' => true )) ->addOption('scheduled-process-timeout', array( 'help' => 'Sets task process timeout', 'default' => Configure::read('Task.timeout') )) ->addOption('scheduled-depends-on', array( 'help' => 'Tasks ids that must be done before current task can start. Format: coma separated', )) ->addOption('scheduled-wait-prev', array( 'help' => 'If `yes` each task will wait for previous task, else each task will run independenly. See `$_scheduleNextTaskDependsOnPrevious` for script defaults that used when this parameter was omitted.', )); } else { $parser->epilog($parser->epilog() . "\n" . 'For using `scheduled` install and enable Task plugin https://github.com/imsamurai/cakephp-task-plugin'); } return $parser; }
[ "public", "function", "getOptionParser", "(", ")", "{", "$", "parser", "=", "parent", "::", "getOptionParser", "(", ")", ";", "$", "parser", "->", "addOption", "(", "'range'", ",", "array", "(", "'help'", "=>", "'Either a date range (separator \"-\") in format '", ".", "Configure", "::", "read", "(", "'Task.dateFormat'", ")", ")", ")", "->", "addOption", "(", "'interval'", ",", "array", "(", "'help'", "=>", "'Interval in date time format (for ex: 15 minutes, 1 hour, 2 days). Defaults 1 day'", ")", ")", "->", "addOption", "(", "'debug'", ",", "array", "(", "'help'", "=>", "'Sets debug level'", ",", "'short'", "=>", "'d'", ",", "'default'", "=>", "Configure", "::", "read", "(", "'debug'", ")", ")", ")", ";", "if", "(", "CakePlugin", "::", "loaded", "(", "'Task'", ")", ")", "{", "$", "parser", "->", "addOption", "(", "'scheduled'", ",", "array", "(", "'help'", "=>", "'If set then script will be run by task daemon'", ",", "'boolean'", "=>", "true", ")", ")", "->", "addOption", "(", "'scheduled-no-split'", ",", "array", "(", "'help'", "=>", "'If set then script will not be splitten by arguments'", ",", "'boolean'", "=>", "true", ")", ")", "->", "addOption", "(", "'scheduled-process-timeout'", ",", "array", "(", "'help'", "=>", "'Sets task process timeout'", ",", "'default'", "=>", "Configure", "::", "read", "(", "'Task.timeout'", ")", ")", ")", "->", "addOption", "(", "'scheduled-depends-on'", ",", "array", "(", "'help'", "=>", "'Tasks ids that must be done before current task can start. Format: coma separated'", ",", ")", ")", "->", "addOption", "(", "'scheduled-wait-prev'", ",", "array", "(", "'help'", "=>", "'If `yes` each task will wait for previous task, else each task will run independenly. \n\t\t\t\t\t\tSee `$_scheduleNextTaskDependsOnPrevious` for script defaults that used when this parameter \n\t\t\t\t\t\twas omitted.'", ",", ")", ")", ";", "}", "else", "{", "$", "parser", "->", "epilog", "(", "$", "parser", "->", "epilog", "(", ")", ".", "\"\\n\"", ".", "'For using `scheduled` install and enable Task plugin https://github.com/imsamurai/cakephp-task-plugin'", ")", ";", "}", "return", "$", "parser", ";", "}" ]
{@inheritdoc} @return ConsoleOptionParser
[ "{", "@inheritdoc", "}" ]
train
https://github.com/imsamurai/CakePHP-AdvancedShell/blob/087d483742e2a76bee45e35b8d94957b0d20f857/Console/Command/Task/AdvancedTask.php#L135-L173
imsamurai/CakePHP-AdvancedShell
Console/Command/Task/AdvancedTask.php
AdvancedTask._scheduleVars
protected function _scheduleVars() { global $argv; $path = $argv[2] . DS; $shellName = $argv[3]; $taskName = $argv[4]; if (isset($this->args[0]) && $this->hasMethod($this->args[0])) { $methodName = $this->args[0]; array_shift($this->args); } else { $methodName = null; } $command = implode(' ', array_filter(array( 'Console/cake', $shellName, $taskName, $methodName ))); $arguments = $this->args; foreach ($this->params as $name => $value) { if (in_array($name, array( 'scheduled', 'scheduled-depends-on', 'scheduled-wait-prev', 'skip-unlogged', 'scheduled-process-timeout' ), true)) { continue; } if (is_bool($value) && $value) { $arguments[] = '--' . $name; } elseif (!is_bool($value)) { $arguments['--' . $name] = $value; } } $options = array( 'timeout' => $this->params['scheduled-process-timeout'], 'dependsOn' => empty($this->params['scheduled-depends-on']) ? array() : explode(',', $this->params['scheduled-depends-on']) ); return array($command, $path, $arguments, $options); }
php
protected function _scheduleVars() { global $argv; $path = $argv[2] . DS; $shellName = $argv[3]; $taskName = $argv[4]; if (isset($this->args[0]) && $this->hasMethod($this->args[0])) { $methodName = $this->args[0]; array_shift($this->args); } else { $methodName = null; } $command = implode(' ', array_filter(array( 'Console/cake', $shellName, $taskName, $methodName ))); $arguments = $this->args; foreach ($this->params as $name => $value) { if (in_array($name, array( 'scheduled', 'scheduled-depends-on', 'scheduled-wait-prev', 'skip-unlogged', 'scheduled-process-timeout' ), true)) { continue; } if (is_bool($value) && $value) { $arguments[] = '--' . $name; } elseif (!is_bool($value)) { $arguments['--' . $name] = $value; } } $options = array( 'timeout' => $this->params['scheduled-process-timeout'], 'dependsOn' => empty($this->params['scheduled-depends-on']) ? array() : explode(',', $this->params['scheduled-depends-on']) ); return array($command, $path, $arguments, $options); }
[ "protected", "function", "_scheduleVars", "(", ")", "{", "global", "$", "argv", ";", "$", "path", "=", "$", "argv", "[", "2", "]", ".", "DS", ";", "$", "shellName", "=", "$", "argv", "[", "3", "]", ";", "$", "taskName", "=", "$", "argv", "[", "4", "]", ";", "if", "(", "isset", "(", "$", "this", "->", "args", "[", "0", "]", ")", "&&", "$", "this", "->", "hasMethod", "(", "$", "this", "->", "args", "[", "0", "]", ")", ")", "{", "$", "methodName", "=", "$", "this", "->", "args", "[", "0", "]", ";", "array_shift", "(", "$", "this", "->", "args", ")", ";", "}", "else", "{", "$", "methodName", "=", "null", ";", "}", "$", "command", "=", "implode", "(", "' '", ",", "array_filter", "(", "array", "(", "'Console/cake'", ",", "$", "shellName", ",", "$", "taskName", ",", "$", "methodName", ")", ")", ")", ";", "$", "arguments", "=", "$", "this", "->", "args", ";", "foreach", "(", "$", "this", "->", "params", "as", "$", "name", "=>", "$", "value", ")", "{", "if", "(", "in_array", "(", "$", "name", ",", "array", "(", "'scheduled'", ",", "'scheduled-depends-on'", ",", "'scheduled-wait-prev'", ",", "'skip-unlogged'", ",", "'scheduled-process-timeout'", ")", ",", "true", ")", ")", "{", "continue", ";", "}", "if", "(", "is_bool", "(", "$", "value", ")", "&&", "$", "value", ")", "{", "$", "arguments", "[", "]", "=", "'--'", ".", "$", "name", ";", "}", "elseif", "(", "!", "is_bool", "(", "$", "value", ")", ")", "{", "$", "arguments", "[", "'--'", ".", "$", "name", "]", "=", "$", "value", ";", "}", "}", "$", "options", "=", "array", "(", "'timeout'", "=>", "$", "this", "->", "params", "[", "'scheduled-process-timeout'", "]", ",", "'dependsOn'", "=>", "empty", "(", "$", "this", "->", "params", "[", "'scheduled-depends-on'", "]", ")", "?", "array", "(", ")", ":", "explode", "(", "','", ",", "$", "this", "->", "params", "[", "'scheduled-depends-on'", "]", ")", ")", ";", "return", "array", "(", "$", "command", ",", "$", "path", ",", "$", "arguments", ",", "$", "options", ")", ";", "}" ]
Returns variables for schedule @global array $argv @return array
[ "Returns", "variables", "for", "schedule" ]
train
https://github.com/imsamurai/CakePHP-AdvancedShell/blob/087d483742e2a76bee45e35b8d94957b0d20f857/Console/Command/Task/AdvancedTask.php#L181-L225
imsamurai/CakePHP-AdvancedShell
Console/Command/Task/AdvancedTask.php
AdvancedTask._schedule
protected function _schedule($command, $path, array $arguments, array $options) { $TaskClient = ClassRegistry::init('Task.TaskClient'); $task = $TaskClient->add($command, $path, $arguments, $options); if ($task) { $waitFor = empty($options['dependsOn']) ? 'none' : implode(', ', $options['dependsOn']) . ' task(s)'; $this->out("Task #{$TaskClient->id} successfuly added, wait for $waitFor"); } else { $this->err('Error! Task not added!'); } return $task; }
php
protected function _schedule($command, $path, array $arguments, array $options) { $TaskClient = ClassRegistry::init('Task.TaskClient'); $task = $TaskClient->add($command, $path, $arguments, $options); if ($task) { $waitFor = empty($options['dependsOn']) ? 'none' : implode(', ', $options['dependsOn']) . ' task(s)'; $this->out("Task #{$TaskClient->id} successfuly added, wait for $waitFor"); } else { $this->err('Error! Task not added!'); } return $task; }
[ "protected", "function", "_schedule", "(", "$", "command", ",", "$", "path", ",", "array", "$", "arguments", ",", "array", "$", "options", ")", "{", "$", "TaskClient", "=", "ClassRegistry", "::", "init", "(", "'Task.TaskClient'", ")", ";", "$", "task", "=", "$", "TaskClient", "->", "add", "(", "$", "command", ",", "$", "path", ",", "$", "arguments", ",", "$", "options", ")", ";", "if", "(", "$", "task", ")", "{", "$", "waitFor", "=", "empty", "(", "$", "options", "[", "'dependsOn'", "]", ")", "?", "'none'", ":", "implode", "(", "', '", ",", "$", "options", "[", "'dependsOn'", "]", ")", ".", "' task(s)'", ";", "$", "this", "->", "out", "(", "\"Task #{$TaskClient->id} successfuly added, wait for $waitFor\"", ")", ";", "}", "else", "{", "$", "this", "->", "err", "(", "'Error! Task not added!'", ")", ";", "}", "return", "$", "task", ";", "}" ]
Adds script to sceduler @param string $command @param string $path @param array $arguments @param array $options
[ "Adds", "script", "to", "sceduler" ]
train
https://github.com/imsamurai/CakePHP-AdvancedShell/blob/087d483742e2a76bee45e35b8d94957b0d20f857/Console/Command/Task/AdvancedTask.php#L235-L245
imsamurai/CakePHP-AdvancedShell
Console/Command/Task/AdvancedTask.php
AdvancedTask._getPeriod
protected function _getPeriod(DateTime $Date = null, $defaultShift = '', $interval = null) { return $this->_getRange($Date, $defaultShift, $interval)->period($this->_getInterval($interval)); }
php
protected function _getPeriod(DateTime $Date = null, $defaultShift = '', $interval = null) { return $this->_getRange($Date, $defaultShift, $interval)->period($this->_getInterval($interval)); }
[ "protected", "function", "_getPeriod", "(", "DateTime", "$", "Date", "=", "null", ",", "$", "defaultShift", "=", "''", ",", "$", "interval", "=", "null", ")", "{", "return", "$", "this", "->", "_getRange", "(", "$", "Date", ",", "$", "defaultShift", ",", "$", "interval", ")", "->", "period", "(", "$", "this", "->", "_getInterval", "(", "$", "interval", ")", ")", ";", "}" ]
Returns DatePeriod starting from $Date or now with $default_shift splitted by $interval @param DateTime $Date Start date @param string $defaultShift Shift date if $Date is null, for ex. "1 day" @param string $interval Interval, for ex. "1 hour" @return DatePeriod
[ "Returns", "DatePeriod", "starting", "from", "$Date", "or", "now", "with", "$default_shift", "splitted", "by", "$interval" ]
train
https://github.com/imsamurai/CakePHP-AdvancedShell/blob/087d483742e2a76bee45e35b8d94957b0d20f857/Console/Command/Task/AdvancedTask.php#L256-L258
imsamurai/CakePHP-AdvancedShell
Console/Command/Task/AdvancedTask.php
AdvancedTask._getRange
protected function _getRange(DateTime $Date = null, $defaultShift = '', $interval = null) { if ($Date !== null) { return $this->_getPeriodByDate($Date, $interval); } if (!empty($this->params['range'])) { $range = explode('-', $this->params['range']); $Range = new DateRange($range[0], empty($range[1]) ? null : $range[1]); } else { $Range = new DateRange('now ' . $defaultShift, 'now ' . $defaultShift); } return $Range; }
php
protected function _getRange(DateTime $Date = null, $defaultShift = '', $interval = null) { if ($Date !== null) { return $this->_getPeriodByDate($Date, $interval); } if (!empty($this->params['range'])) { $range = explode('-', $this->params['range']); $Range = new DateRange($range[0], empty($range[1]) ? null : $range[1]); } else { $Range = new DateRange('now ' . $defaultShift, 'now ' . $defaultShift); } return $Range; }
[ "protected", "function", "_getRange", "(", "DateTime", "$", "Date", "=", "null", ",", "$", "defaultShift", "=", "''", ",", "$", "interval", "=", "null", ")", "{", "if", "(", "$", "Date", "!==", "null", ")", "{", "return", "$", "this", "->", "_getPeriodByDate", "(", "$", "Date", ",", "$", "interval", ")", ";", "}", "if", "(", "!", "empty", "(", "$", "this", "->", "params", "[", "'range'", "]", ")", ")", "{", "$", "range", "=", "explode", "(", "'-'", ",", "$", "this", "->", "params", "[", "'range'", "]", ")", ";", "$", "Range", "=", "new", "DateRange", "(", "$", "range", "[", "0", "]", ",", "empty", "(", "$", "range", "[", "1", "]", ")", "?", "null", ":", "$", "range", "[", "1", "]", ")", ";", "}", "else", "{", "$", "Range", "=", "new", "DateRange", "(", "'now '", ".", "$", "defaultShift", ",", "'now '", ".", "$", "defaultShift", ")", ";", "}", "return", "$", "Range", ";", "}" ]
Returns DateRange starting from $Date or now with $default_shift splitted by $interval @param DateTime $Date Start date @param string $defaultShift Shift date if $Date is null, for ex. "1 day" @param string $interval Interval, for ex. "1 hour" @return DatePeriod
[ "Returns", "DateRange", "starting", "from", "$Date", "or", "now", "with", "$default_shift", "splitted", "by", "$interval" ]
train
https://github.com/imsamurai/CakePHP-AdvancedShell/blob/087d483742e2a76bee45e35b8d94957b0d20f857/Console/Command/Task/AdvancedTask.php#L269-L281
imsamurai/CakePHP-AdvancedShell
Console/Command/Task/AdvancedTask.php
AdvancedTask._getPeriodByDate
protected function _getPeriodByDate(DateTime $Date, $interval = null) { $Range = new DateRange(clone $Date); return $Range->period($this->_getInterval($interval)); }
php
protected function _getPeriodByDate(DateTime $Date, $interval = null) { $Range = new DateRange(clone $Date); return $Range->period($this->_getInterval($interval)); }
[ "protected", "function", "_getPeriodByDate", "(", "DateTime", "$", "Date", ",", "$", "interval", "=", "null", ")", "{", "$", "Range", "=", "new", "DateRange", "(", "clone", "$", "Date", ")", ";", "return", "$", "Range", "->", "period", "(", "$", "this", "->", "_getInterval", "(", "$", "interval", ")", ")", ";", "}" ]
Returns DatePeriod starting from $Date splitted by $interval @param DateTime $Date Start date @param string $interval Interval, for ex. "1 hour" @return DatePeriod
[ "Returns", "DatePeriod", "starting", "from", "$Date", "splitted", "by", "$interval" ]
train
https://github.com/imsamurai/CakePHP-AdvancedShell/blob/087d483742e2a76bee45e35b8d94957b0d20f857/Console/Command/Task/AdvancedTask.php#L290-L293
imsamurai/CakePHP-AdvancedShell
Console/Command/Task/AdvancedTask.php
AdvancedTask._getInterval
protected function _getInterval($interval) { if ($interval !== null) { return $interval; } elseif (!empty($this->params['interval'])) { return $this->params['interval']; } else { return '1 day'; } }
php
protected function _getInterval($interval) { if ($interval !== null) { return $interval; } elseif (!empty($this->params['interval'])) { return $this->params['interval']; } else { return '1 day'; } }
[ "protected", "function", "_getInterval", "(", "$", "interval", ")", "{", "if", "(", "$", "interval", "!==", "null", ")", "{", "return", "$", "interval", ";", "}", "elseif", "(", "!", "empty", "(", "$", "this", "->", "params", "[", "'interval'", "]", ")", ")", "{", "return", "$", "this", "->", "params", "[", "'interval'", "]", ";", "}", "else", "{", "return", "'1 day'", ";", "}", "}" ]
Returns interval value specified by parameter or default value @param string $interval If not null method return this value @return string
[ "Returns", "interval", "value", "specified", "by", "parameter", "or", "default", "value" ]
train
https://github.com/imsamurai/CakePHP-AdvancedShell/blob/087d483742e2a76bee45e35b8d94957b0d20f857/Console/Command/Task/AdvancedTask.php#L302-L310
octolabot/Common
src/Composer/Script/Asset/Publisher.php
Publisher.publish
public static function publish(Event $event) { $publisher = new static(); $config = $publisher->getConfig($event); $assetPackage = $publisher->getAssetPackage($config); $composerPackage = $publisher->getComposerPackage($event); (new Processor(new Filesystem(), $event->getIO()))->publish( $event->getComposer()->getInstallationManager()->getInstallPath($composerPackage), $publisher->getPublishingMap($assetPackage, $config), $config->isSymlink(), $config->isRelative() ); }
php
public static function publish(Event $event) { $publisher = new static(); $config = $publisher->getConfig($event); $assetPackage = $publisher->getAssetPackage($config); $composerPackage = $publisher->getComposerPackage($event); (new Processor(new Filesystem(), $event->getIO()))->publish( $event->getComposer()->getInstallationManager()->getInstallPath($composerPackage), $publisher->getPublishingMap($assetPackage, $config), $config->isSymlink(), $config->isRelative() ); }
[ "public", "static", "function", "publish", "(", "Event", "$", "event", ")", "{", "$", "publisher", "=", "new", "static", "(", ")", ";", "$", "config", "=", "$", "publisher", "->", "getConfig", "(", "$", "event", ")", ";", "$", "assetPackage", "=", "$", "publisher", "->", "getAssetPackage", "(", "$", "config", ")", ";", "$", "composerPackage", "=", "$", "publisher", "->", "getComposerPackage", "(", "$", "event", ")", ";", "(", "new", "Processor", "(", "new", "Filesystem", "(", ")", ",", "$", "event", "->", "getIO", "(", ")", ")", ")", "->", "publish", "(", "$", "event", "->", "getComposer", "(", ")", "->", "getInstallationManager", "(", ")", "->", "getInstallPath", "(", "$", "composerPackage", ")", ",", "$", "publisher", "->", "getPublishingMap", "(", "$", "assetPackage", ",", "$", "config", ")", ",", "$", "config", "->", "isSymlink", "(", ")", ",", "$", "config", "->", "isRelative", "(", ")", ")", ";", "}" ]
@param Event $event @throws \InvalidArgumentException @throws \RuntimeException @throws \Symfony\Component\Filesystem\Exception\IOException @api
[ "@param", "Event", "$event" ]
train
https://github.com/octolabot/Common/blob/fb41f9c6736139e651de5e3ed1a7f4bd422c8e5b/src/Composer/Script/Asset/Publisher.php#L26-L38
ekyna/Sale
PriceableTrait.php
PriceableTrait.getTaxesAmounts
public function getTaxesAmounts() { $amounts = new TaxesAmounts(); $amounts->addTaxAmount(new TaxAmount($this->tax, $this->getTaxAmount())); return $amounts; }
php
public function getTaxesAmounts() { $amounts = new TaxesAmounts(); $amounts->addTaxAmount(new TaxAmount($this->tax, $this->getTaxAmount())); return $amounts; }
[ "public", "function", "getTaxesAmounts", "(", ")", "{", "$", "amounts", "=", "new", "TaxesAmounts", "(", ")", ";", "$", "amounts", "->", "addTaxAmount", "(", "new", "TaxAmount", "(", "$", "this", "->", "tax", ",", "$", "this", "->", "getTaxAmount", "(", ")", ")", ")", ";", "return", "$", "amounts", ";", "}" ]
Returns the taxes amounts. @return TaxesAmounts
[ "Returns", "the", "taxes", "amounts", "." ]
train
https://github.com/ekyna/Sale/blob/434093b658628e88b59a156e21239df0b1855e89/PriceableTrait.php#L89-L94
JanoCodes/cacheable
src/Cache/SecureFileStore.php
SecureFileStore.getPayload
protected function getPayload($key) { $path = $this->path($key); // If the file doesn't exists, we obviously can't return the cache so we will // just return null. Otherwise, we'll get the contents of the file and get // the expiration UNIX timestamps from the start of the file's contents. try { $expire = substr( $contents = $this->files->get($path, true), 0, 10 ); } catch (Exception $e) { return $this->emptyPayload(); } // If the current time is greater than expiration timestamps we will delete // the file and return null. This helps clean up the old files and keeps // this directory much cleaner for us as old files aren't hanging out. if (Carbon::now()->getTimestamp() >= $expire) { $this->forget($key); return $this->emptyPayload(); } try { $data = decrypt(substr($contents, 10)); } catch (DecryptException $e) { $this->forget($key); return $this->emptyPayload(); } // Next, we'll extract the number of minutes that are remaining for a cache // so that we can properly retain the time for things like the increment // operation that may be performed on this cache on a later operation. $time = ($expire - Carbon::now()->getTimestamp()) / 60; return compact('data', 'time'); }
php
protected function getPayload($key) { $path = $this->path($key); // If the file doesn't exists, we obviously can't return the cache so we will // just return null. Otherwise, we'll get the contents of the file and get // the expiration UNIX timestamps from the start of the file's contents. try { $expire = substr( $contents = $this->files->get($path, true), 0, 10 ); } catch (Exception $e) { return $this->emptyPayload(); } // If the current time is greater than expiration timestamps we will delete // the file and return null. This helps clean up the old files and keeps // this directory much cleaner for us as old files aren't hanging out. if (Carbon::now()->getTimestamp() >= $expire) { $this->forget($key); return $this->emptyPayload(); } try { $data = decrypt(substr($contents, 10)); } catch (DecryptException $e) { $this->forget($key); return $this->emptyPayload(); } // Next, we'll extract the number of minutes that are remaining for a cache // so that we can properly retain the time for things like the increment // operation that may be performed on this cache on a later operation. $time = ($expire - Carbon::now()->getTimestamp()) / 60; return compact('data', 'time'); }
[ "protected", "function", "getPayload", "(", "$", "key", ")", "{", "$", "path", "=", "$", "this", "->", "path", "(", "$", "key", ")", ";", "// If the file doesn't exists, we obviously can't return the cache so we will", "// just return null. Otherwise, we'll get the contents of the file and get", "// the expiration UNIX timestamps from the start of the file's contents.", "try", "{", "$", "expire", "=", "substr", "(", "$", "contents", "=", "$", "this", "->", "files", "->", "get", "(", "$", "path", ",", "true", ")", ",", "0", ",", "10", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "return", "$", "this", "->", "emptyPayload", "(", ")", ";", "}", "// If the current time is greater than expiration timestamps we will delete", "// the file and return null. This helps clean up the old files and keeps", "// this directory much cleaner for us as old files aren't hanging out.", "if", "(", "Carbon", "::", "now", "(", ")", "->", "getTimestamp", "(", ")", ">=", "$", "expire", ")", "{", "$", "this", "->", "forget", "(", "$", "key", ")", ";", "return", "$", "this", "->", "emptyPayload", "(", ")", ";", "}", "try", "{", "$", "data", "=", "decrypt", "(", "substr", "(", "$", "contents", ",", "10", ")", ")", ";", "}", "catch", "(", "DecryptException", "$", "e", ")", "{", "$", "this", "->", "forget", "(", "$", "key", ")", ";", "return", "$", "this", "->", "emptyPayload", "(", ")", ";", "}", "// Next, we'll extract the number of minutes that are remaining for a cache", "// so that we can properly retain the time for things like the increment", "// operation that may be performed on this cache on a later operation.", "$", "time", "=", "(", "$", "expire", "-", "Carbon", "::", "now", "(", ")", "->", "getTimestamp", "(", ")", ")", "/", "60", ";", "return", "compact", "(", "'data'", ",", "'time'", ")", ";", "}" ]
Retrieve an item and expiry time from the cache by key. @param string $key @return array
[ "Retrieve", "an", "item", "and", "expiry", "time", "from", "the", "cache", "by", "key", "." ]
train
https://github.com/JanoCodes/cacheable/blob/43b1d51b914dab290c3382d188f7aa74efa08338/src/Cache/SecureFileStore.php#L65-L101
Xsaven/laravel-intelect-admin
src/Addons/Terminal/Console/Commands/CD.php
CD.handle
public function handle() { $path = $this->argument('path'); $path = str_replace('//', '/', $path); if($path=='/'){ cookie('cd_base_path', base_path(), 45000); $this->info(base_path()); return true; } $root = cookie('cd_base_path'); if(strrpos($path, "../")!==false){ $clear = str_replace(base_path(),'',$root); $clear = str_replace("\\","",$clear); $clear = trim($clear, '/'); $root = explode('/', $clear); foreach (explode('/', $path) as $pat) if($pat=='..') {array_pop($root);} $root = array_diff($root, array('')); $root = trim(implode('/', $root), '/'); $root = base_path($root); $path = str_replace('../','',$path); } $path = trim($root, '/').($path && !empty($path)!=='/'?'/':'').$path; $path = str_replace('//', '/', $path); if(!is_dir($path)){ $this->error("Path \"{$path}\" not found!"); return true; } $path = str_replace("\\\\","\\", $path); cookie('cd_base_path', $path, 45000); $this->info($path); }
php
public function handle() { $path = $this->argument('path'); $path = str_replace('//', '/', $path); if($path=='/'){ cookie('cd_base_path', base_path(), 45000); $this->info(base_path()); return true; } $root = cookie('cd_base_path'); if(strrpos($path, "../")!==false){ $clear = str_replace(base_path(),'',$root); $clear = str_replace("\\","",$clear); $clear = trim($clear, '/'); $root = explode('/', $clear); foreach (explode('/', $path) as $pat) if($pat=='..') {array_pop($root);} $root = array_diff($root, array('')); $root = trim(implode('/', $root), '/'); $root = base_path($root); $path = str_replace('../','',$path); } $path = trim($root, '/').($path && !empty($path)!=='/'?'/':'').$path; $path = str_replace('//', '/', $path); if(!is_dir($path)){ $this->error("Path \"{$path}\" not found!"); return true; } $path = str_replace("\\\\","\\", $path); cookie('cd_base_path', $path, 45000); $this->info($path); }
[ "public", "function", "handle", "(", ")", "{", "$", "path", "=", "$", "this", "->", "argument", "(", "'path'", ")", ";", "$", "path", "=", "str_replace", "(", "'//'", ",", "'/'", ",", "$", "path", ")", ";", "if", "(", "$", "path", "==", "'/'", ")", "{", "cookie", "(", "'cd_base_path'", ",", "base_path", "(", ")", ",", "45000", ")", ";", "$", "this", "->", "info", "(", "base_path", "(", ")", ")", ";", "return", "true", ";", "}", "$", "root", "=", "cookie", "(", "'cd_base_path'", ")", ";", "if", "(", "strrpos", "(", "$", "path", ",", "\"../\"", ")", "!==", "false", ")", "{", "$", "clear", "=", "str_replace", "(", "base_path", "(", ")", ",", "''", ",", "$", "root", ")", ";", "$", "clear", "=", "str_replace", "(", "\"\\\\\"", ",", "\"\"", ",", "$", "clear", ")", ";", "$", "clear", "=", "trim", "(", "$", "clear", ",", "'/'", ")", ";", "$", "root", "=", "explode", "(", "'/'", ",", "$", "clear", ")", ";", "foreach", "(", "explode", "(", "'/'", ",", "$", "path", ")", "as", "$", "pat", ")", "if", "(", "$", "pat", "==", "'..'", ")", "{", "array_pop", "(", "$", "root", ")", ";", "}", "$", "root", "=", "array_diff", "(", "$", "root", ",", "array", "(", "''", ")", ")", ";", "$", "root", "=", "trim", "(", "implode", "(", "'/'", ",", "$", "root", ")", ",", "'/'", ")", ";", "$", "root", "=", "base_path", "(", "$", "root", ")", ";", "$", "path", "=", "str_replace", "(", "'../'", ",", "''", ",", "$", "path", ")", ";", "}", "$", "path", "=", "trim", "(", "$", "root", ",", "'/'", ")", ".", "(", "$", "path", "&&", "!", "empty", "(", "$", "path", ")", "!==", "'/'", "?", "'/'", ":", "''", ")", ".", "$", "path", ";", "$", "path", "=", "str_replace", "(", "'//'", ",", "'/'", ",", "$", "path", ")", ";", "if", "(", "!", "is_dir", "(", "$", "path", ")", ")", "{", "$", "this", "->", "error", "(", "\"Path \\\"{$path}\\\" not found!\"", ")", ";", "return", "true", ";", "}", "$", "path", "=", "str_replace", "(", "\"\\\\\\\\\"", ",", "\"\\\\\"", ",", "$", "path", ")", ";", "cookie", "(", "'cd_base_path'", ",", "$", "path", ",", "45000", ")", ";", "$", "this", "->", "info", "(", "$", "path", ")", ";", "}" ]
Handle the command. @throws \InvalidArgumentException
[ "Handle", "the", "command", "." ]
train
https://github.com/Xsaven/laravel-intelect-admin/blob/592574633d12c74cf25b43dd6694fee496abefcb/src/Addons/Terminal/Console/Commands/CD.php#L43-L73
SCLInternet/SclCurrency
spec/SCL/Currency/Money/FormatterSpec.php
FormatterSpec.createMoney
private function createMoney($amount, $currency) { $precision = isset($this->config[$currency]) ? $this->config[$currency]['precision'] : 2; return new Money($amount, new Currency($currency, $precision)); }
php
private function createMoney($amount, $currency) { $precision = isset($this->config[$currency]) ? $this->config[$currency]['precision'] : 2; return new Money($amount, new Currency($currency, $precision)); }
[ "private", "function", "createMoney", "(", "$", "amount", ",", "$", "currency", ")", "{", "$", "precision", "=", "isset", "(", "$", "this", "->", "config", "[", "$", "currency", "]", ")", "?", "$", "this", "->", "config", "[", "$", "currency", "]", "[", "'precision'", "]", ":", "2", ";", "return", "new", "Money", "(", "$", "amount", ",", "new", "Currency", "(", "$", "currency", ",", "$", "precision", ")", ")", ";", "}" ]
@param int $amount @param string $currency @return Money
[ "@param", "int", "$amount", "@param", "string", "$currency" ]
train
https://github.com/SCLInternet/SclCurrency/blob/788f0ff5d4a3146368a09eb3869cbb0559a9866a/spec/SCL/Currency/Money/FormatterSpec.php#L99-L101
975L/ConfigBundle
Twig/Config.php
Config.config
public function config($parameter) { $value = $this->configService->getParameter($parameter); return is_array($value) ? json_encode($value) : $value; }
php
public function config($parameter) { $value = $this->configService->getParameter($parameter); return is_array($value) ? json_encode($value) : $value; }
[ "public", "function", "config", "(", "$", "parameter", ")", "{", "$", "value", "=", "$", "this", "->", "configService", "->", "getParameter", "(", "$", "parameter", ")", ";", "return", "is_array", "(", "$", "value", ")", "?", "json_encode", "(", "$", "value", ")", ":", "$", "value", ";", "}" ]
Returns the specified parameter @return string
[ "Returns", "the", "specified", "parameter" ]
train
https://github.com/975L/ConfigBundle/blob/1f9a9e937dbb79ad06fe5d456e7536d58bd56e19/Twig/Config.php#L48-L53
PenoaksDev/Milky-Framework
src/Milky/Exceptions/Displayers/HtmlDisplayer.php
HtmlDisplayer.display
public function display( Exception $exception, $id, $code, array $headers ) { $info = $this->info->generate( $exception, $id, $code ); return new Response( $this->render( $info ), $code, array_merge( $headers, ['Content-Type' => $this->contentType()] ) ); }
php
public function display( Exception $exception, $id, $code, array $headers ) { $info = $this->info->generate( $exception, $id, $code ); return new Response( $this->render( $info ), $code, array_merge( $headers, ['Content-Type' => $this->contentType()] ) ); }
[ "public", "function", "display", "(", "Exception", "$", "exception", ",", "$", "id", ",", "$", "code", ",", "array", "$", "headers", ")", "{", "$", "info", "=", "$", "this", "->", "info", "->", "generate", "(", "$", "exception", ",", "$", "id", ",", "$", "code", ")", ";", "return", "new", "Response", "(", "$", "this", "->", "render", "(", "$", "info", ")", ",", "$", "code", ",", "array_merge", "(", "$", "headers", ",", "[", "'Content-Type'", "=>", "$", "this", "->", "contentType", "(", ")", "]", ")", ")", ";", "}" ]
Get the error response associated with the given exception. @param \Exception $exception @param string $id @param int $code @param string[] $headers @return Response
[ "Get", "the", "error", "response", "associated", "with", "the", "given", "exception", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Exceptions/Displayers/HtmlDisplayer.php#L50-L55
PenoaksDev/Milky-Framework
src/Milky/Exceptions/Displayers/HtmlDisplayer.php
HtmlDisplayer.render
protected function render( array $info ) { $content = file_get_contents( $this->path ); $info['home_url'] = asset( '/' ); $info['favicon_url'] = asset( 'favicon.ico' ); foreach ( $info as $key => $val ) { $content = str_replace( "{{ $$key }}", $val, $content ); } return $content; }
php
protected function render( array $info ) { $content = file_get_contents( $this->path ); $info['home_url'] = asset( '/' ); $info['favicon_url'] = asset( 'favicon.ico' ); foreach ( $info as $key => $val ) { $content = str_replace( "{{ $$key }}", $val, $content ); } return $content; }
[ "protected", "function", "render", "(", "array", "$", "info", ")", "{", "$", "content", "=", "file_get_contents", "(", "$", "this", "->", "path", ")", ";", "$", "info", "[", "'home_url'", "]", "=", "asset", "(", "'/'", ")", ";", "$", "info", "[", "'favicon_url'", "]", "=", "asset", "(", "'favicon.ico'", ")", ";", "foreach", "(", "$", "info", "as", "$", "key", "=>", "$", "val", ")", "{", "$", "content", "=", "str_replace", "(", "\"{{ $$key }}\"", ",", "$", "val", ",", "$", "content", ")", ";", "}", "return", "$", "content", ";", "}" ]
Render the page with given info. @param array $info @return string
[ "Render", "the", "page", "with", "given", "info", "." ]
train
https://github.com/PenoaksDev/Milky-Framework/blob/8afd7156610a70371aa5b1df50b8a212bf7b142c/src/Milky/Exceptions/Displayers/HtmlDisplayer.php#L64-L77
linkeddatacenter/BOTK-context
library/BOTK/Context/PagedResourceContext.php
PagedResourceContext.getSinglePageResourceUri
public function getSinglePageResourceUri( $pagenum = null, $pagesize=null) { if( is_null($pagenum) ) $pagenum =$this->pagenum; if( is_null($pagesize)) $pagesize =$this->pagesize; //rebuild query string from already parsed _GET superglobal but do not override it. $vars = $_GET; $o=$this->ns(self::LOCAL); $vars[$o->getValue('plabel')] = $pagenum; $vars[$o->getValue('pslabel')] = $pagesize; return $this->getQueryStrippedUri() . '?'. http_build_query($vars); }
php
public function getSinglePageResourceUri( $pagenum = null, $pagesize=null) { if( is_null($pagenum) ) $pagenum =$this->pagenum; if( is_null($pagesize)) $pagesize =$this->pagesize; //rebuild query string from already parsed _GET superglobal but do not override it. $vars = $_GET; $o=$this->ns(self::LOCAL); $vars[$o->getValue('plabel')] = $pagenum; $vars[$o->getValue('pslabel')] = $pagesize; return $this->getQueryStrippedUri() . '?'. http_build_query($vars); }
[ "public", "function", "getSinglePageResourceUri", "(", "$", "pagenum", "=", "null", ",", "$", "pagesize", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "pagenum", ")", ")", "$", "pagenum", "=", "$", "this", "->", "pagenum", ";", "if", "(", "is_null", "(", "$", "pagesize", ")", ")", "$", "pagesize", "=", "$", "this", "->", "pagesize", ";", "//rebuild query string from already parsed _GET superglobal but do not override it.", "$", "vars", "=", "$", "_GET", ";", "$", "o", "=", "$", "this", "->", "ns", "(", "self", "::", "LOCAL", ")", ";", "$", "vars", "[", "$", "o", "->", "getValue", "(", "'plabel'", ")", "]", "=", "$", "pagenum", ";", "$", "vars", "[", "$", "o", "->", "getValue", "(", "'pslabel'", ")", "]", "=", "$", "pagesize", ";", "return", "$", "this", "->", "getQueryStrippedUri", "(", ")", ".", "'?'", ".", "http_build_query", "(", "$", "vars", ")", ";", "}" ]
/* Returns resource canonical uri with page info data in quesry string. You can override request page info with passed paramethers
[ "/", "*", "Returns", "resource", "canonical", "uri", "with", "page", "info", "data", "in", "quesry", "string", ".", "You", "can", "override", "request", "page", "info", "with", "passed", "paramethers" ]
train
https://github.com/linkeddatacenter/BOTK-context/blob/82d1cb85230d2840aba6574c534830199bd45cf3/library/BOTK/Context/PagedResourceContext.php#L37-L49
ommu/mod-banner
models/BannerSetting.php
BannerSetting.search
public function search() { // @todo Please modify the following code to remove attributes that should not be searched. $criteria=new CDbCriteria; // Custom Search $criteria->with = array( 'modified' => array( 'alias' => 'modified', 'select' => 'displayname', ), ); $criteria->compare('t.id', $this->id); $criteria->compare('t.license', strtolower($this->license), true); $criteria->compare('t.permission', $this->permission); $criteria->compare('t.meta_keyword', strtolower($this->meta_keyword), true); $criteria->compare('t.meta_description', strtolower($this->meta_description), true); $criteria->compare('t.banner_validation', $this->banner_validation); $criteria->compare('t.banner_resize', $this->banner_resize); $criteria->compare('t.banner_file_type', strtolower($this->banner_file_type), true); if($this->modified_date != null && !in_array($this->modified_date, array('0000-00-00 00:00:00','1970-01-01 00:00:00','0002-12-02 07:07:12','-0001-11-30 00:00:00'))) $criteria->compare('date(t.modified_date)', date('Y-m-d', strtotime($this->modified_date))); $criteria->compare('t.modified_id', Yii::app()->getRequest()->getParam('modified') ? Yii::app()->getRequest()->getParam('modified') : $this->modified_id); $criteria->compare('modified.displayname', strtolower($this->modified_search), true); if(!Yii::app()->getRequest()->getParam('BannerSetting_sort')) $criteria->order = 't.id DESC'; return new CActiveDataProvider($this, array( 'criteria'=>$criteria, 'pagination'=>array( 'pageSize'=>Yii::app()->params['grid-view'] ? Yii::app()->params['grid-view']['pageSize'] : 50, ), )); }
php
public function search() { // @todo Please modify the following code to remove attributes that should not be searched. $criteria=new CDbCriteria; // Custom Search $criteria->with = array( 'modified' => array( 'alias' => 'modified', 'select' => 'displayname', ), ); $criteria->compare('t.id', $this->id); $criteria->compare('t.license', strtolower($this->license), true); $criteria->compare('t.permission', $this->permission); $criteria->compare('t.meta_keyword', strtolower($this->meta_keyword), true); $criteria->compare('t.meta_description', strtolower($this->meta_description), true); $criteria->compare('t.banner_validation', $this->banner_validation); $criteria->compare('t.banner_resize', $this->banner_resize); $criteria->compare('t.banner_file_type', strtolower($this->banner_file_type), true); if($this->modified_date != null && !in_array($this->modified_date, array('0000-00-00 00:00:00','1970-01-01 00:00:00','0002-12-02 07:07:12','-0001-11-30 00:00:00'))) $criteria->compare('date(t.modified_date)', date('Y-m-d', strtotime($this->modified_date))); $criteria->compare('t.modified_id', Yii::app()->getRequest()->getParam('modified') ? Yii::app()->getRequest()->getParam('modified') : $this->modified_id); $criteria->compare('modified.displayname', strtolower($this->modified_search), true); if(!Yii::app()->getRequest()->getParam('BannerSetting_sort')) $criteria->order = 't.id DESC'; return new CActiveDataProvider($this, array( 'criteria'=>$criteria, 'pagination'=>array( 'pageSize'=>Yii::app()->params['grid-view'] ? Yii::app()->params['grid-view']['pageSize'] : 50, ), )); }
[ "public", "function", "search", "(", ")", "{", "// @todo Please modify the following code to remove attributes that should not be searched.\r", "$", "criteria", "=", "new", "CDbCriteria", ";", "// Custom Search\r", "$", "criteria", "->", "with", "=", "array", "(", "'modified'", "=>", "array", "(", "'alias'", "=>", "'modified'", ",", "'select'", "=>", "'displayname'", ",", ")", ",", ")", ";", "$", "criteria", "->", "compare", "(", "'t.id'", ",", "$", "this", "->", "id", ")", ";", "$", "criteria", "->", "compare", "(", "'t.license'", ",", "strtolower", "(", "$", "this", "->", "license", ")", ",", "true", ")", ";", "$", "criteria", "->", "compare", "(", "'t.permission'", ",", "$", "this", "->", "permission", ")", ";", "$", "criteria", "->", "compare", "(", "'t.meta_keyword'", ",", "strtolower", "(", "$", "this", "->", "meta_keyword", ")", ",", "true", ")", ";", "$", "criteria", "->", "compare", "(", "'t.meta_description'", ",", "strtolower", "(", "$", "this", "->", "meta_description", ")", ",", "true", ")", ";", "$", "criteria", "->", "compare", "(", "'t.banner_validation'", ",", "$", "this", "->", "banner_validation", ")", ";", "$", "criteria", "->", "compare", "(", "'t.banner_resize'", ",", "$", "this", "->", "banner_resize", ")", ";", "$", "criteria", "->", "compare", "(", "'t.banner_file_type'", ",", "strtolower", "(", "$", "this", "->", "banner_file_type", ")", ",", "true", ")", ";", "if", "(", "$", "this", "->", "modified_date", "!=", "null", "&&", "!", "in_array", "(", "$", "this", "->", "modified_date", ",", "array", "(", "'0000-00-00 00:00:00'", ",", "'1970-01-01 00:00:00'", ",", "'0002-12-02 07:07:12'", ",", "'-0001-11-30 00:00:00'", ")", ")", ")", "$", "criteria", "->", "compare", "(", "'date(t.modified_date)'", ",", "date", "(", "'Y-m-d'", ",", "strtotime", "(", "$", "this", "->", "modified_date", ")", ")", ")", ";", "$", "criteria", "->", "compare", "(", "'t.modified_id'", ",", "Yii", "::", "app", "(", ")", "->", "getRequest", "(", ")", "->", "getParam", "(", "'modified'", ")", "?", "Yii", "::", "app", "(", ")", "->", "getRequest", "(", ")", "->", "getParam", "(", "'modified'", ")", ":", "$", "this", "->", "modified_id", ")", ";", "$", "criteria", "->", "compare", "(", "'modified.displayname'", ",", "strtolower", "(", "$", "this", "->", "modified_search", ")", ",", "true", ")", ";", "if", "(", "!", "Yii", "::", "app", "(", ")", "->", "getRequest", "(", ")", "->", "getParam", "(", "'BannerSetting_sort'", ")", ")", "$", "criteria", "->", "order", "=", "'t.id DESC'", ";", "return", "new", "CActiveDataProvider", "(", "$", "this", ",", "array", "(", "'criteria'", "=>", "$", "criteria", ",", "'pagination'", "=>", "array", "(", "'pageSize'", "=>", "Yii", "::", "app", "(", ")", "->", "params", "[", "'grid-view'", "]", "?", "Yii", "::", "app", "(", ")", "->", "params", "[", "'grid-view'", "]", "[", "'pageSize'", "]", ":", "50", ",", ")", ",", ")", ")", ";", "}" ]
Retrieves a list of models based on the current search/filter conditions. Typical usecase: - Initialize the model fields with values from filter form. - Execute this method to get CActiveDataProvider instance which will filter models according to data in model fields. - Pass data provider to CGridView, CListView or any similar widget. @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
[ "Retrieves", "a", "list", "of", "models", "based", "on", "the", "current", "search", "/", "filter", "conditions", "." ]
train
https://github.com/ommu/mod-banner/blob/eb1c9fbb25a0a6be31749d5f32816de87fed8fdf/models/BannerSetting.php#L118-L155
ommu/mod-banner
models/BannerSetting.php
BannerSetting.beforeValidate
protected function beforeValidate() { if(parent::beforeValidate()) { $this->modified_id = !Yii::app()->user->isGuest ? Yii::app()->user->id : null; } return true; }
php
protected function beforeValidate() { if(parent::beforeValidate()) { $this->modified_id = !Yii::app()->user->isGuest ? Yii::app()->user->id : null; } return true; }
[ "protected", "function", "beforeValidate", "(", ")", "{", "if", "(", "parent", "::", "beforeValidate", "(", ")", ")", "{", "$", "this", "->", "modified_id", "=", "!", "Yii", "::", "app", "(", ")", "->", "user", "->", "isGuest", "?", "Yii", "::", "app", "(", ")", "->", "user", "->", "id", ":", "null", ";", "}", "return", "true", ";", "}" ]
before validate attributes
[ "before", "validate", "attributes" ]
train
https://github.com/ommu/mod-banner/blob/eb1c9fbb25a0a6be31749d5f32816de87fed8fdf/models/BannerSetting.php#L259-L265
ommu/mod-banner
models/BannerSetting.php
BannerSetting.beforeSave
protected function beforeSave() { if(parent::beforeSave()) { $this->banner_file_type = serialize(Utility::formatFileType($this->banner_file_type)); } return true; }
php
protected function beforeSave() { if(parent::beforeSave()) { $this->banner_file_type = serialize(Utility::formatFileType($this->banner_file_type)); } return true; }
[ "protected", "function", "beforeSave", "(", ")", "{", "if", "(", "parent", "::", "beforeSave", "(", ")", ")", "{", "$", "this", "->", "banner_file_type", "=", "serialize", "(", "Utility", "::", "formatFileType", "(", "$", "this", "->", "banner_file_type", ")", ")", ";", "}", "return", "true", ";", "}" ]
before save attributes
[ "before", "save", "attributes" ]
train
https://github.com/ommu/mod-banner/blob/eb1c9fbb25a0a6be31749d5f32816de87fed8fdf/models/BannerSetting.php#L270-L276
mcustiel/phiremock-server
src/Utils/ResponseStrategyLocator.php
ResponseStrategyLocator.getStrategyForExpectation
public function getStrategyForExpectation(MockConfig $expectation) { if ($expectation->getResponse()->isProxyResponse()) { return $this->factory->createProxyResponseStrategy(); } if ($this->requestBodyOrUrlAreRegexp($expectation)) { return $this->factory->createRegexResponseStrategy(); } return $this->factory->createHttpResponseStrategy(); }
php
public function getStrategyForExpectation(MockConfig $expectation) { if ($expectation->getResponse()->isProxyResponse()) { return $this->factory->createProxyResponseStrategy(); } if ($this->requestBodyOrUrlAreRegexp($expectation)) { return $this->factory->createRegexResponseStrategy(); } return $this->factory->createHttpResponseStrategy(); }
[ "public", "function", "getStrategyForExpectation", "(", "MockConfig", "$", "expectation", ")", "{", "if", "(", "$", "expectation", "->", "getResponse", "(", ")", "->", "isProxyResponse", "(", ")", ")", "{", "return", "$", "this", "->", "factory", "->", "createProxyResponseStrategy", "(", ")", ";", "}", "if", "(", "$", "this", "->", "requestBodyOrUrlAreRegexp", "(", "$", "expectation", ")", ")", "{", "return", "$", "this", "->", "factory", "->", "createRegexResponseStrategy", "(", ")", ";", "}", "return", "$", "this", "->", "factory", "->", "createHttpResponseStrategy", "(", ")", ";", "}" ]
@param \Mcustiel\Phiremock\Domain\MockConfig $expectation @return \Mcustiel\Phiremock\Server\Utils\Strategies\ResponseStrategyInterface
[ "@param", "\\", "Mcustiel", "\\", "Phiremock", "\\", "Domain", "\\", "MockConfig", "$expectation" ]
train
https://github.com/mcustiel/phiremock-server/blob/7be42ce7c5c4d441410d80e158477910924cfbd9/src/Utils/ResponseStrategyLocator.php#L45-L55
mcustiel/phiremock-server
src/Utils/ResponseStrategyLocator.php
ResponseStrategyLocator.requestBodyOrUrlAreRegexp
private function requestBodyOrUrlAreRegexp(MockConfig $expectation) { return $expectation->getRequest()->getBody() && Matchers::MATCHES === $expectation->getRequest()->getBody()->getMatcher()->asString() || $expectation->getRequest()->getUrl() && Matchers::MATCHES === $expectation->getRequest()->getUrl()->getMatcher()->asString(); }
php
private function requestBodyOrUrlAreRegexp(MockConfig $expectation) { return $expectation->getRequest()->getBody() && Matchers::MATCHES === $expectation->getRequest()->getBody()->getMatcher()->asString() || $expectation->getRequest()->getUrl() && Matchers::MATCHES === $expectation->getRequest()->getUrl()->getMatcher()->asString(); }
[ "private", "function", "requestBodyOrUrlAreRegexp", "(", "MockConfig", "$", "expectation", ")", "{", "return", "$", "expectation", "->", "getRequest", "(", ")", "->", "getBody", "(", ")", "&&", "Matchers", "::", "MATCHES", "===", "$", "expectation", "->", "getRequest", "(", ")", "->", "getBody", "(", ")", "->", "getMatcher", "(", ")", "->", "asString", "(", ")", "||", "$", "expectation", "->", "getRequest", "(", ")", "->", "getUrl", "(", ")", "&&", "Matchers", "::", "MATCHES", "===", "$", "expectation", "->", "getRequest", "(", ")", "->", "getUrl", "(", ")", "->", "getMatcher", "(", ")", "->", "asString", "(", ")", ";", "}" ]
@param MockConfig $expectation @return bool
[ "@param", "MockConfig", "$expectation" ]
train
https://github.com/mcustiel/phiremock-server/blob/7be42ce7c5c4d441410d80e158477910924cfbd9/src/Utils/ResponseStrategyLocator.php#L62-L68
black-lamp/blcms-payment
frontend/controllers/DefaultController.php
DefaultController.actionGetPaymentMethodInfo
public function actionGetPaymentMethodInfo($id) { if (\Yii::$app->request->isAjax) { if (!empty($id)) { $method = PaymentMethod::findOne($id); $methodTranslation = $method->translation; $method = ArrayHelper::toArray($method); $method['translation'] = ArrayHelper::toArray($methodTranslation); $method['image'] = '/images/payment/' . FileHelper::getFullName( \Yii::$app->shop_imagable->get('payment', 'small', $method['image'] )); return json_encode([ 'paymentMethod' => $method, ]); } } throw new NotFoundHttpException(); }
php
public function actionGetPaymentMethodInfo($id) { if (\Yii::$app->request->isAjax) { if (!empty($id)) { $method = PaymentMethod::findOne($id); $methodTranslation = $method->translation; $method = ArrayHelper::toArray($method); $method['translation'] = ArrayHelper::toArray($methodTranslation); $method['image'] = '/images/payment/' . FileHelper::getFullName( \Yii::$app->shop_imagable->get('payment', 'small', $method['image'] )); return json_encode([ 'paymentMethod' => $method, ]); } } throw new NotFoundHttpException(); }
[ "public", "function", "actionGetPaymentMethodInfo", "(", "$", "id", ")", "{", "if", "(", "\\", "Yii", "::", "$", "app", "->", "request", "->", "isAjax", ")", "{", "if", "(", "!", "empty", "(", "$", "id", ")", ")", "{", "$", "method", "=", "PaymentMethod", "::", "findOne", "(", "$", "id", ")", ";", "$", "methodTranslation", "=", "$", "method", "->", "translation", ";", "$", "method", "=", "ArrayHelper", "::", "toArray", "(", "$", "method", ")", ";", "$", "method", "[", "'translation'", "]", "=", "ArrayHelper", "::", "toArray", "(", "$", "methodTranslation", ")", ";", "$", "method", "[", "'image'", "]", "=", "'/images/payment/'", ".", "FileHelper", "::", "getFullName", "(", "\\", "Yii", "::", "$", "app", "->", "shop_imagable", "->", "get", "(", "'payment'", ",", "'small'", ",", "$", "method", "[", "'image'", "]", ")", ")", ";", "return", "json_encode", "(", "[", "'paymentMethod'", "=>", "$", "method", ",", "]", ")", ";", "}", "}", "throw", "new", "NotFoundHttpException", "(", ")", ";", "}" ]
Returns payment method model if request is Ajax. @param integer $id @return PaymentMethod @throws NotFoundHttpException
[ "Returns", "payment", "method", "model", "if", "request", "is", "Ajax", "." ]
train
https://github.com/black-lamp/blcms-payment/blob/6d139e0bb5a4e7733382cc6fe083173551905b92/frontend/controllers/DefaultController.php#L25-L45
MichaelJ2324/PHP-REST-Client
src/Storage/StaticStorage.php
StaticStorage.getItem
public static function getItem($namespace,$key){ if (isset(static::$_STORAGE[$namespace])){ if (isset(static::$_STORAGE[$namespace][$key])){ return static::$_STORAGE[$namespace][$key]; } } return NULL; }
php
public static function getItem($namespace,$key){ if (isset(static::$_STORAGE[$namespace])){ if (isset(static::$_STORAGE[$namespace][$key])){ return static::$_STORAGE[$namespace][$key]; } } return NULL; }
[ "public", "static", "function", "getItem", "(", "$", "namespace", ",", "$", "key", ")", "{", "if", "(", "isset", "(", "static", "::", "$", "_STORAGE", "[", "$", "namespace", "]", ")", ")", "{", "if", "(", "isset", "(", "static", "::", "$", "_STORAGE", "[", "$", "namespace", "]", "[", "$", "key", "]", ")", ")", "{", "return", "static", "::", "$", "_STORAGE", "[", "$", "namespace", "]", "[", "$", "key", "]", ";", "}", "}", "return", "NULL", ";", "}" ]
Get an Item from the Static Storage array @param $namespace @param $key @return mixed|null
[ "Get", "an", "Item", "from", "the", "Static", "Storage", "array" ]
train
https://github.com/MichaelJ2324/PHP-REST-Client/blob/b8a2caaf6456eccaa845ba5c5098608aa9645c92/src/Storage/StaticStorage.php#L46-L53
MichaelJ2324/PHP-REST-Client
src/Storage/StaticStorage.php
StaticStorage.setItem
public static function setItem($namespace,$key,$value){ if (!isset(static::$_STORAGE[$namespace])){ static::$_STORAGE[$namespace] = array(); } static::$_STORAGE[$namespace][$key] = $value; return TRUE; }
php
public static function setItem($namespace,$key,$value){ if (!isset(static::$_STORAGE[$namespace])){ static::$_STORAGE[$namespace] = array(); } static::$_STORAGE[$namespace][$key] = $value; return TRUE; }
[ "public", "static", "function", "setItem", "(", "$", "namespace", ",", "$", "key", ",", "$", "value", ")", "{", "if", "(", "!", "isset", "(", "static", "::", "$", "_STORAGE", "[", "$", "namespace", "]", ")", ")", "{", "static", "::", "$", "_STORAGE", "[", "$", "namespace", "]", "=", "array", "(", ")", ";", "}", "static", "::", "$", "_STORAGE", "[", "$", "namespace", "]", "[", "$", "key", "]", "=", "$", "value", ";", "return", "TRUE", ";", "}" ]
Set an Item in the Static Storage array for a particular Namespace @param $namespace @param $key @return bool
[ "Set", "an", "Item", "in", "the", "Static", "Storage", "array", "for", "a", "particular", "Namespace" ]
train
https://github.com/MichaelJ2324/PHP-REST-Client/blob/b8a2caaf6456eccaa845ba5c5098608aa9645c92/src/Storage/StaticStorage.php#L61-L67
modulusphp/http
Request/HasValidation.php
HasValidation.validate
public function validate(?Closure $closure = null) { /** * Create a new validation factory */ $factory = new ValidatorFactory(); $response = $factory->make($this->data(), isset($this->rules) ? $this->rules : []); if (is_callable($closure)) { $custom = call_user_func($closure, $response); if ($custom instanceOf Model) return $custom; if (is_array($custom)) { foreach($custom as $key => $unique) { $response->errors()->add($key, $unique); } } } if (count($response->errors()) > 0 || $response->fails()) { if ($this->headers->has('Content-Type') && str_contains(strtolower($this->headers->get('Content-Type')), 'json')) { Rest::response()->json($response->errors()->toArray(), 422); die(); } $url = ($this->server->has('HTTPS') ? 'https://' : 'http://') . $this->server->get('HTTP_HOST'); if ($this->server->has('HTTP_ORIGIN') && $this->server->get('HTTP_ORIGIN') == $url) { $referer = $this->headers->get('Referer'); Redirect::to($referer) ->with('validation.errors', $response->errors()) ->with('form.old', $this->all()) ->code(302) ->send(); } else { Rest::response()->json($response->errors()->toArray(), 422); die(); } } }
php
public function validate(?Closure $closure = null) { /** * Create a new validation factory */ $factory = new ValidatorFactory(); $response = $factory->make($this->data(), isset($this->rules) ? $this->rules : []); if (is_callable($closure)) { $custom = call_user_func($closure, $response); if ($custom instanceOf Model) return $custom; if (is_array($custom)) { foreach($custom as $key => $unique) { $response->errors()->add($key, $unique); } } } if (count($response->errors()) > 0 || $response->fails()) { if ($this->headers->has('Content-Type') && str_contains(strtolower($this->headers->get('Content-Type')), 'json')) { Rest::response()->json($response->errors()->toArray(), 422); die(); } $url = ($this->server->has('HTTPS') ? 'https://' : 'http://') . $this->server->get('HTTP_HOST'); if ($this->server->has('HTTP_ORIGIN') && $this->server->get('HTTP_ORIGIN') == $url) { $referer = $this->headers->get('Referer'); Redirect::to($referer) ->with('validation.errors', $response->errors()) ->with('form.old', $this->all()) ->code(302) ->send(); } else { Rest::response()->json($response->errors()->toArray(), 422); die(); } } }
[ "public", "function", "validate", "(", "?", "Closure", "$", "closure", "=", "null", ")", "{", "/**\n * Create a new validation factory\n */", "$", "factory", "=", "new", "ValidatorFactory", "(", ")", ";", "$", "response", "=", "$", "factory", "->", "make", "(", "$", "this", "->", "data", "(", ")", ",", "isset", "(", "$", "this", "->", "rules", ")", "?", "$", "this", "->", "rules", ":", "[", "]", ")", ";", "if", "(", "is_callable", "(", "$", "closure", ")", ")", "{", "$", "custom", "=", "call_user_func", "(", "$", "closure", ",", "$", "response", ")", ";", "if", "(", "$", "custom", "instanceOf", "Model", ")", "return", "$", "custom", ";", "if", "(", "is_array", "(", "$", "custom", ")", ")", "{", "foreach", "(", "$", "custom", "as", "$", "key", "=>", "$", "unique", ")", "{", "$", "response", "->", "errors", "(", ")", "->", "add", "(", "$", "key", ",", "$", "unique", ")", ";", "}", "}", "}", "if", "(", "count", "(", "$", "response", "->", "errors", "(", ")", ")", ">", "0", "||", "$", "response", "->", "fails", "(", ")", ")", "{", "if", "(", "$", "this", "->", "headers", "->", "has", "(", "'Content-Type'", ")", "&&", "str_contains", "(", "strtolower", "(", "$", "this", "->", "headers", "->", "get", "(", "'Content-Type'", ")", ")", ",", "'json'", ")", ")", "{", "Rest", "::", "response", "(", ")", "->", "json", "(", "$", "response", "->", "errors", "(", ")", "->", "toArray", "(", ")", ",", "422", ")", ";", "die", "(", ")", ";", "}", "$", "url", "=", "(", "$", "this", "->", "server", "->", "has", "(", "'HTTPS'", ")", "?", "'https://'", ":", "'http://'", ")", ".", "$", "this", "->", "server", "->", "get", "(", "'HTTP_HOST'", ")", ";", "if", "(", "$", "this", "->", "server", "->", "has", "(", "'HTTP_ORIGIN'", ")", "&&", "$", "this", "->", "server", "->", "get", "(", "'HTTP_ORIGIN'", ")", "==", "$", "url", ")", "{", "$", "referer", "=", "$", "this", "->", "headers", "->", "get", "(", "'Referer'", ")", ";", "Redirect", "::", "to", "(", "$", "referer", ")", "->", "with", "(", "'validation.errors'", ",", "$", "response", "->", "errors", "(", ")", ")", "->", "with", "(", "'form.old'", ",", "$", "this", "->", "all", "(", ")", ")", "->", "code", "(", "302", ")", "->", "send", "(", ")", ";", "}", "else", "{", "Rest", "::", "response", "(", ")", "->", "json", "(", "$", "response", "->", "errors", "(", ")", "->", "toArray", "(", ")", ",", "422", ")", ";", "die", "(", ")", ";", "}", "}", "}" ]
Run validation @return mixed
[ "Run", "validation" ]
train
https://github.com/modulusphp/http/blob/fc5c0f2b582a04de1685578d3fb790686a0a240c/Request/HasValidation.php#L35-L76
railken/lem
src/Result.php
Result.addErrors
public function addErrors(Collection $errors) { $this->errors = $this->getErrors()->merge($errors); return $this; }
php
public function addErrors(Collection $errors) { $this->errors = $this->getErrors()->merge($errors); return $this; }
[ "public", "function", "addErrors", "(", "Collection", "$", "errors", ")", "{", "$", "this", "->", "errors", "=", "$", "this", "->", "getErrors", "(", ")", "->", "merge", "(", "$", "errors", ")", ";", "return", "$", "this", ";", "}" ]
Add errors. @param Collection $errors @return $this
[ "Add", "errors", "." ]
train
https://github.com/railken/lem/blob/cff1efcd090a9504b2faf5594121885786dea67a/src/Result.php#L104-L109
phossa/phossa-cache
src/Phossa/Cache/CachePool.php
CachePool.clear
public function clear()/*# : bool */ { // before clear if (!$this->runExtensions(ES::STAGE_PRE_CLEAR)) { return false; } // clear the pool if (!$this->driver->clear()) { return $this->falseAndSetError( $this->driver->getError(), $this->driver->getErrorCode() ); } // after clear if (!$this->runExtensions(ES::STAGE_POST_CLEAR)) { return false; } return $this->trueAndFlushError(); }
php
public function clear()/*# : bool */ { // before clear if (!$this->runExtensions(ES::STAGE_PRE_CLEAR)) { return false; } // clear the pool if (!$this->driver->clear()) { return $this->falseAndSetError( $this->driver->getError(), $this->driver->getErrorCode() ); } // after clear if (!$this->runExtensions(ES::STAGE_POST_CLEAR)) { return false; } return $this->trueAndFlushError(); }
[ "public", "function", "clear", "(", ")", "/*# : bool */", "{", "// before clear", "if", "(", "!", "$", "this", "->", "runExtensions", "(", "ES", "::", "STAGE_PRE_CLEAR", ")", ")", "{", "return", "false", ";", "}", "// clear the pool", "if", "(", "!", "$", "this", "->", "driver", "->", "clear", "(", ")", ")", "{", "return", "$", "this", "->", "falseAndSetError", "(", "$", "this", "->", "driver", "->", "getError", "(", ")", ",", "$", "this", "->", "driver", "->", "getErrorCode", "(", ")", ")", ";", "}", "// after clear", "if", "(", "!", "$", "this", "->", "runExtensions", "(", "ES", "::", "STAGE_POST_CLEAR", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "trueAndFlushError", "(", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/phossa/phossa-cache/blob/ad86bee9c5c646fbae09f6f58a346b379d16276e/src/Phossa/Cache/CachePool.php#L148-L169
phossa/phossa-cache
src/Phossa/Cache/CachePool.php
CachePool.deleteItem
public function deleteItem(/*# string */ $key)/*# : bool */ { // create item object $item = $this->createItem($key); // before delete if (!$this->runExtensions(ES::STAGE_PRE_DEL, $item)) { return false; } // delete from pool if (!$this->driver->delete($item->getKey())) { return $this->falseAndSetError( $this->driver->getError(), $this->driver->getErrorCode() ); } // after delete if (!$this->runExtensions(ES::STAGE_POST_DEL, $item)) { return false; } return $this->trueAndFlushError(); }
php
public function deleteItem(/*# string */ $key)/*# : bool */ { // create item object $item = $this->createItem($key); // before delete if (!$this->runExtensions(ES::STAGE_PRE_DEL, $item)) { return false; } // delete from pool if (!$this->driver->delete($item->getKey())) { return $this->falseAndSetError( $this->driver->getError(), $this->driver->getErrorCode() ); } // after delete if (!$this->runExtensions(ES::STAGE_POST_DEL, $item)) { return false; } return $this->trueAndFlushError(); }
[ "public", "function", "deleteItem", "(", "/*# string */", "$", "key", ")", "/*# : bool */", "{", "// create item object", "$", "item", "=", "$", "this", "->", "createItem", "(", "$", "key", ")", ";", "// before delete", "if", "(", "!", "$", "this", "->", "runExtensions", "(", "ES", "::", "STAGE_PRE_DEL", ",", "$", "item", ")", ")", "{", "return", "false", ";", "}", "// delete from pool", "if", "(", "!", "$", "this", "->", "driver", "->", "delete", "(", "$", "item", "->", "getKey", "(", ")", ")", ")", "{", "return", "$", "this", "->", "falseAndSetError", "(", "$", "this", "->", "driver", "->", "getError", "(", ")", ",", "$", "this", "->", "driver", "->", "getErrorCode", "(", ")", ")", ";", "}", "// after delete", "if", "(", "!", "$", "this", "->", "runExtensions", "(", "ES", "::", "STAGE_POST_DEL", ",", "$", "item", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "trueAndFlushError", "(", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/phossa/phossa-cache/blob/ad86bee9c5c646fbae09f6f58a346b379d16276e/src/Phossa/Cache/CachePool.php#L174-L198
phossa/phossa-cache
src/Phossa/Cache/CachePool.php
CachePool.deleteItems
public function deleteItems(array $keys)/*# : bool */ { foreach ($keys as $key) { if (!$this->deleteItem($key)) { return false; } } return $this->trueAndFlushError(); }
php
public function deleteItems(array $keys)/*# : bool */ { foreach ($keys as $key) { if (!$this->deleteItem($key)) { return false; } } return $this->trueAndFlushError(); }
[ "public", "function", "deleteItems", "(", "array", "$", "keys", ")", "/*# : bool */", "{", "foreach", "(", "$", "keys", "as", "$", "key", ")", "{", "if", "(", "!", "$", "this", "->", "deleteItem", "(", "$", "key", ")", ")", "{", "return", "false", ";", "}", "}", "return", "$", "this", "->", "trueAndFlushError", "(", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/phossa/phossa-cache/blob/ad86bee9c5c646fbae09f6f58a346b379d16276e/src/Phossa/Cache/CachePool.php#L203-L211
phossa/phossa-cache
src/Phossa/Cache/CachePool.php
CachePool.save
public function save(\Psr\Cache\CacheItemInterface $item)/*# : bool */ { // extensions may change $item $clone = clone $item; // before save if (!$this->runExtensions(ES::STAGE_PRE_SAVE, $clone)) { return false; } // write to the pool if (!$this->driver->save($clone)) { return $this->falseAndSetError( $this->driver->getError(), $this->driver->getErrorCode() ); } // after save if (!$this->runExtensions(ES::STAGE_POST_SAVE, $clone)) { return false; } return $this->trueAndFlushError(); }
php
public function save(\Psr\Cache\CacheItemInterface $item)/*# : bool */ { // extensions may change $item $clone = clone $item; // before save if (!$this->runExtensions(ES::STAGE_PRE_SAVE, $clone)) { return false; } // write to the pool if (!$this->driver->save($clone)) { return $this->falseAndSetError( $this->driver->getError(), $this->driver->getErrorCode() ); } // after save if (!$this->runExtensions(ES::STAGE_POST_SAVE, $clone)) { return false; } return $this->trueAndFlushError(); }
[ "public", "function", "save", "(", "\\", "Psr", "\\", "Cache", "\\", "CacheItemInterface", "$", "item", ")", "/*# : bool */", "{", "// extensions may change $item", "$", "clone", "=", "clone", "$", "item", ";", "// before save", "if", "(", "!", "$", "this", "->", "runExtensions", "(", "ES", "::", "STAGE_PRE_SAVE", ",", "$", "clone", ")", ")", "{", "return", "false", ";", "}", "// write to the pool", "if", "(", "!", "$", "this", "->", "driver", "->", "save", "(", "$", "clone", ")", ")", "{", "return", "$", "this", "->", "falseAndSetError", "(", "$", "this", "->", "driver", "->", "getError", "(", ")", ",", "$", "this", "->", "driver", "->", "getErrorCode", "(", ")", ")", ";", "}", "// after save", "if", "(", "!", "$", "this", "->", "runExtensions", "(", "ES", "::", "STAGE_POST_SAVE", ",", "$", "clone", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "trueAndFlushError", "(", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/phossa/phossa-cache/blob/ad86bee9c5c646fbae09f6f58a346b379d16276e/src/Phossa/Cache/CachePool.php#L216-L240
phossa/phossa-cache
src/Phossa/Cache/CachePool.php
CachePool.saveDeferred
public function saveDeferred( \Psr\Cache\CacheItemInterface $item )/*# : bool */ { // extensions may change $item $clone = clone $item; // before deferred if (!$this->runExtensions(ES::STAGE_PRE_DEFER, $clone)) { return false; } // write to the pool if (!$this->driver->saveDeferred($clone)) { return $this->falseAndSetError( $this->driver->getError(), $this->driver->getErrorCode() ); } // after deferred if (!$this->runExtensions(ES::STAGE_POST_DEFER, $clone)) { return false; } return $this->trueAndFlushError(); }
php
public function saveDeferred( \Psr\Cache\CacheItemInterface $item )/*# : bool */ { // extensions may change $item $clone = clone $item; // before deferred if (!$this->runExtensions(ES::STAGE_PRE_DEFER, $clone)) { return false; } // write to the pool if (!$this->driver->saveDeferred($clone)) { return $this->falseAndSetError( $this->driver->getError(), $this->driver->getErrorCode() ); } // after deferred if (!$this->runExtensions(ES::STAGE_POST_DEFER, $clone)) { return false; } return $this->trueAndFlushError(); }
[ "public", "function", "saveDeferred", "(", "\\", "Psr", "\\", "Cache", "\\", "CacheItemInterface", "$", "item", ")", "/*# : bool */", "{", "// extensions may change $item", "$", "clone", "=", "clone", "$", "item", ";", "// before deferred", "if", "(", "!", "$", "this", "->", "runExtensions", "(", "ES", "::", "STAGE_PRE_DEFER", ",", "$", "clone", ")", ")", "{", "return", "false", ";", "}", "// write to the pool", "if", "(", "!", "$", "this", "->", "driver", "->", "saveDeferred", "(", "$", "clone", ")", ")", "{", "return", "$", "this", "->", "falseAndSetError", "(", "$", "this", "->", "driver", "->", "getError", "(", ")", ",", "$", "this", "->", "driver", "->", "getErrorCode", "(", ")", ")", ";", "}", "// after deferred", "if", "(", "!", "$", "this", "->", "runExtensions", "(", "ES", "::", "STAGE_POST_DEFER", ",", "$", "clone", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "trueAndFlushError", "(", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/phossa/phossa-cache/blob/ad86bee9c5c646fbae09f6f58a346b379d16276e/src/Phossa/Cache/CachePool.php#L245-L270
phossa/phossa-cache
src/Phossa/Cache/CachePool.php
CachePool.commit
public function commit()/*# : bool */ { // before commit if (!$this->runExtensions(ES::STAGE_PRE_COMMIT)) { return false; } // commit to pool if (!$this->driver->commit()) { return $this->falseAndSetError( $this->driver->getError(), $this->driver->getErrorCode() ); } // after commit if (!$this->runExtensions(ES::STAGE_POST_COMMIT)) { return false; } return $this->trueAndFlushError(); }
php
public function commit()/*# : bool */ { // before commit if (!$this->runExtensions(ES::STAGE_PRE_COMMIT)) { return false; } // commit to pool if (!$this->driver->commit()) { return $this->falseAndSetError( $this->driver->getError(), $this->driver->getErrorCode() ); } // after commit if (!$this->runExtensions(ES::STAGE_POST_COMMIT)) { return false; } return $this->trueAndFlushError(); }
[ "public", "function", "commit", "(", ")", "/*# : bool */", "{", "// before commit", "if", "(", "!", "$", "this", "->", "runExtensions", "(", "ES", "::", "STAGE_PRE_COMMIT", ")", ")", "{", "return", "false", ";", "}", "// commit to pool", "if", "(", "!", "$", "this", "->", "driver", "->", "commit", "(", ")", ")", "{", "return", "$", "this", "->", "falseAndSetError", "(", "$", "this", "->", "driver", "->", "getError", "(", ")", ",", "$", "this", "->", "driver", "->", "getErrorCode", "(", ")", ")", ";", "}", "// after commit", "if", "(", "!", "$", "this", "->", "runExtensions", "(", "ES", "::", "STAGE_POST_COMMIT", ")", ")", "{", "return", "false", ";", "}", "return", "$", "this", "->", "trueAndFlushError", "(", ")", ";", "}" ]
{@inheritDoc}
[ "{" ]
train
https://github.com/phossa/phossa-cache/blob/ad86bee9c5c646fbae09f6f58a346b379d16276e/src/Phossa/Cache/CachePool.php#L275-L296
phossa/phossa-cache
src/Phossa/Cache/CachePool.php
CachePool.createItem
protected function createItem(/*# string */ $key)/*# : CacheItemInterface */ { // validate key first $this->validateKey($key); // use item factory if (is_callable($this->item_factory)) { $func = $this->item_factory; $item = $func($key, $this, $this->item_config); // default CacheItem class } else { $item = new CacheItem($key, $this, $this->item_config); } return $item; }
php
protected function createItem(/*# string */ $key)/*# : CacheItemInterface */ { // validate key first $this->validateKey($key); // use item factory if (is_callable($this->item_factory)) { $func = $this->item_factory; $item = $func($key, $this, $this->item_config); // default CacheItem class } else { $item = new CacheItem($key, $this, $this->item_config); } return $item; }
[ "protected", "function", "createItem", "(", "/*# string */", "$", "key", ")", "/*# : CacheItemInterface */", "{", "// validate key first", "$", "this", "->", "validateKey", "(", "$", "key", ")", ";", "// use item factory", "if", "(", "is_callable", "(", "$", "this", "->", "item_factory", ")", ")", "{", "$", "func", "=", "$", "this", "->", "item_factory", ";", "$", "item", "=", "$", "func", "(", "$", "key", ",", "$", "this", ",", "$", "this", "->", "item_config", ")", ";", "// default CacheItem class", "}", "else", "{", "$", "item", "=", "new", "CacheItem", "(", "$", "key", ",", "$", "this", ",", "$", "this", "->", "item_config", ")", ";", "}", "return", "$", "item", ";", "}" ]
Create item object @param string $key item key @return CacheItemInterface @throws Exception\InvalidArgumentException @access protected
[ "Create", "item", "object" ]
train
https://github.com/phossa/phossa-cache/blob/ad86bee9c5c646fbae09f6f58a346b379d16276e/src/Phossa/Cache/CachePool.php#L306-L322
picturae/php-composition-utils
src/WithArrayTransform.php
WithArrayTransform.toArray
public function toArray() { $classData = []; foreach ($this->getReflector()->getProperties(\ReflectionProperty::IS_PROTECTED) as $reflectionProperty) { if (!$reflectionProperty->isStatic()) { $reflectionProperty->setAccessible(true); $classData[$reflectionProperty->getName()] = $reflectionProperty->getValue($this); } } return $classData; }
php
public function toArray() { $classData = []; foreach ($this->getReflector()->getProperties(\ReflectionProperty::IS_PROTECTED) as $reflectionProperty) { if (!$reflectionProperty->isStatic()) { $reflectionProperty->setAccessible(true); $classData[$reflectionProperty->getName()] = $reflectionProperty->getValue($this); } } return $classData; }
[ "public", "function", "toArray", "(", ")", "{", "$", "classData", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getReflector", "(", ")", "->", "getProperties", "(", "\\", "ReflectionProperty", "::", "IS_PROTECTED", ")", "as", "$", "reflectionProperty", ")", "{", "if", "(", "!", "$", "reflectionProperty", "->", "isStatic", "(", ")", ")", "{", "$", "reflectionProperty", "->", "setAccessible", "(", "true", ")", ";", "$", "classData", "[", "$", "reflectionProperty", "->", "getName", "(", ")", "]", "=", "$", "reflectionProperty", "->", "getValue", "(", "$", "this", ")", ";", "}", "}", "return", "$", "classData", ";", "}" ]
Fetch the array representation of the protected properties of an object. @return array
[ "Fetch", "the", "array", "representation", "of", "the", "protected", "properties", "of", "an", "object", "." ]
train
https://github.com/picturae/php-composition-utils/blob/59a8191066c27687daabc8c5b33addb3599826ab/src/WithArrayTransform.php#L30-L40
picturae/php-composition-utils
src/WithArrayTransform.php
WithArrayTransform.fromArray
public function fromArray(array $source) { foreach ($this->getReflector()->getProperties(\ReflectionProperty::IS_PROTECTED) as $reflectionProperty) { if (!$reflectionProperty->isStatic() && isset($source[$reflectionProperty->getName()])) { $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this, $source[$reflectionProperty->getName()]); } } return $this; }
php
public function fromArray(array $source) { foreach ($this->getReflector()->getProperties(\ReflectionProperty::IS_PROTECTED) as $reflectionProperty) { if (!$reflectionProperty->isStatic() && isset($source[$reflectionProperty->getName()])) { $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this, $source[$reflectionProperty->getName()]); } } return $this; }
[ "public", "function", "fromArray", "(", "array", "$", "source", ")", "{", "foreach", "(", "$", "this", "->", "getReflector", "(", ")", "->", "getProperties", "(", "\\", "ReflectionProperty", "::", "IS_PROTECTED", ")", "as", "$", "reflectionProperty", ")", "{", "if", "(", "!", "$", "reflectionProperty", "->", "isStatic", "(", ")", "&&", "isset", "(", "$", "source", "[", "$", "reflectionProperty", "->", "getName", "(", ")", "]", ")", ")", "{", "$", "reflectionProperty", "->", "setAccessible", "(", "true", ")", ";", "$", "reflectionProperty", "->", "setValue", "(", "$", "this", ",", "$", "source", "[", "$", "reflectionProperty", "->", "getName", "(", ")", "]", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Set protected propertie according to provided source. @param array source data. @return $this
[ "Set", "protected", "propertie", "according", "to", "provided", "source", "." ]
train
https://github.com/picturae/php-composition-utils/blob/59a8191066c27687daabc8c5b33addb3599826ab/src/WithArrayTransform.php#L47-L56
picturae/php-composition-utils
src/WithArrayTransform.php
WithArrayTransform.getFieldsConfig
public function getFieldsConfig() { if (null === $this->fieldsConfigList) { $this->fieldsConfigList = []; foreach ($this->getFields() as $field) { $reflectionProperty = $this->getReflector()->getProperty($field); $docBlock = $reflectionProperty->getDocComment(); preg_match('/@var\s([a-z]*).*/', $docBlock, $matches); $this->fieldsConfigList[$field] = [ 'type' => isset($matches[1]) ? $matches[1] : null ]; } } return $this->fieldsConfigList; }
php
public function getFieldsConfig() { if (null === $this->fieldsConfigList) { $this->fieldsConfigList = []; foreach ($this->getFields() as $field) { $reflectionProperty = $this->getReflector()->getProperty($field); $docBlock = $reflectionProperty->getDocComment(); preg_match('/@var\s([a-z]*).*/', $docBlock, $matches); $this->fieldsConfigList[$field] = [ 'type' => isset($matches[1]) ? $matches[1] : null ]; } } return $this->fieldsConfigList; }
[ "public", "function", "getFieldsConfig", "(", ")", "{", "if", "(", "null", "===", "$", "this", "->", "fieldsConfigList", ")", "{", "$", "this", "->", "fieldsConfigList", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getFields", "(", ")", "as", "$", "field", ")", "{", "$", "reflectionProperty", "=", "$", "this", "->", "getReflector", "(", ")", "->", "getProperty", "(", "$", "field", ")", ";", "$", "docBlock", "=", "$", "reflectionProperty", "->", "getDocComment", "(", ")", ";", "preg_match", "(", "'/@var\\s([a-z]*).*/'", ",", "$", "docBlock", ",", "$", "matches", ")", ";", "$", "this", "->", "fieldsConfigList", "[", "$", "field", "]", "=", "[", "'type'", "=>", "isset", "(", "$", "matches", "[", "1", "]", ")", "?", "$", "matches", "[", "1", "]", ":", "null", "]", ";", "}", "}", "return", "$", "this", "->", "fieldsConfigList", ";", "}" ]
Fetch the var metadata for a field and store it in the config. @return array
[ "Fetch", "the", "var", "metadata", "for", "a", "field", "and", "store", "it", "in", "the", "config", "." ]
train
https://github.com/picturae/php-composition-utils/blob/59a8191066c27687daabc8c5b33addb3599826ab/src/WithArrayTransform.php#L80-L98
picturae/php-composition-utils
src/WithArrayTransform.php
WithArrayTransform.getFieldType
public function getFieldType($field) { return isset($this->getFieldsConfig()[$field]) ? $this->getFieldsConfig()[$field]['type'] : null; }
php
public function getFieldType($field) { return isset($this->getFieldsConfig()[$field]) ? $this->getFieldsConfig()[$field]['type'] : null; }
[ "public", "function", "getFieldType", "(", "$", "field", ")", "{", "return", "isset", "(", "$", "this", "->", "getFieldsConfig", "(", ")", "[", "$", "field", "]", ")", "?", "$", "this", "->", "getFieldsConfig", "(", ")", "[", "$", "field", "]", "[", "'type'", "]", ":", "null", ";", "}" ]
Fetch a field type according to var metadata. @param string $field @return string
[ "Fetch", "a", "field", "type", "according", "to", "var", "metadata", "." ]
train
https://github.com/picturae/php-composition-utils/blob/59a8191066c27687daabc8c5b33addb3599826ab/src/WithArrayTransform.php#L105-L108
hamjoint/mustard-media
src/lib/Photo.php
Photo.getUrlAttribute
public function getUrlAttribute($suffix = '') { if (!$this->exists) { return Cache::rememberForever('missing_photo', function () { return static::placeholder('No photo provided'); }); } if (!$this->processed) { return Cache::rememberForever('processing_photo', function () { return static::placeholder( "This photo is\nbeing processed\nand will appear\nshortly" ); }); } return "/photo/{$this->photoId}$suffix.jpg"; }
php
public function getUrlAttribute($suffix = '') { if (!$this->exists) { return Cache::rememberForever('missing_photo', function () { return static::placeholder('No photo provided'); }); } if (!$this->processed) { return Cache::rememberForever('processing_photo', function () { return static::placeholder( "This photo is\nbeing processed\nand will appear\nshortly" ); }); } return "/photo/{$this->photoId}$suffix.jpg"; }
[ "public", "function", "getUrlAttribute", "(", "$", "suffix", "=", "''", ")", "{", "if", "(", "!", "$", "this", "->", "exists", ")", "{", "return", "Cache", "::", "rememberForever", "(", "'missing_photo'", ",", "function", "(", ")", "{", "return", "static", "::", "placeholder", "(", "'No photo provided'", ")", ";", "}", ")", ";", "}", "if", "(", "!", "$", "this", "->", "processed", ")", "{", "return", "Cache", "::", "rememberForever", "(", "'processing_photo'", ",", "function", "(", ")", "{", "return", "static", "::", "placeholder", "(", "\"This photo is\\nbeing processed\\nand will appear\\nshortly\"", ")", ";", "}", ")", ";", "}", "return", "\"/photo/{$this->photoId}$suffix.jpg\"", ";", "}" ]
Return the public URL for the photo. @param string $suffix @return string
[ "Return", "the", "public", "URL", "for", "the", "photo", "." ]
train
https://github.com/hamjoint/mustard-media/blob/d3c799dbc3578e1e1022bb4eccae7a20e285ba06/src/lib/Photo.php#L94-L111
hamjoint/mustard-media
src/lib/Photo.php
Photo.delete
public function delete() { $disk = Storage::disk(config('mustard.storage.disk', 'local')); $disk->delete($this->getPath()); $disk->delete($this->getSmallPath()); $disk->delete($this->getLargePath()); parent::delete(); }
php
public function delete() { $disk = Storage::disk(config('mustard.storage.disk', 'local')); $disk->delete($this->getPath()); $disk->delete($this->getSmallPath()); $disk->delete($this->getLargePath()); parent::delete(); }
[ "public", "function", "delete", "(", ")", "{", "$", "disk", "=", "Storage", "::", "disk", "(", "config", "(", "'mustard.storage.disk'", ",", "'local'", ")", ")", ";", "$", "disk", "->", "delete", "(", "$", "this", "->", "getPath", "(", ")", ")", ";", "$", "disk", "->", "delete", "(", "$", "this", "->", "getSmallPath", "(", ")", ")", ";", "$", "disk", "->", "delete", "(", "$", "this", "->", "getLargePath", "(", ")", ")", ";", "parent", "::", "delete", "(", ")", ";", "}" ]
Delete the record and data from the filesystem. @return void
[ "Delete", "the", "record", "and", "data", "from", "the", "filesystem", "." ]
train
https://github.com/hamjoint/mustard-media/blob/d3c799dbc3578e1e1022bb4eccae7a20e285ba06/src/lib/Photo.php#L138-L147
hamjoint/mustard-media
src/lib/Photo.php
Photo.placeholder
private static function placeholder($text) { $image_manager = new ImageManager(['driver' => 'imagick']); $image = $image_manager->canvas(640, 480, '#efefef'); $image->text($text, 320, 240 - (70 * substr_count($text, "\n")), function ($font) { $font->file(base_path('vendor/webfontkit/open-sans/fonts/opensans-regular.woff')); $font->size(60); $font->color('#cbcbcb'); $font->align('center'); $font->valign('center'); }); $image_data = (string) $image->encode('gif'); return 'data:image/gif;base64,'.base64_encode($image_data); }
php
private static function placeholder($text) { $image_manager = new ImageManager(['driver' => 'imagick']); $image = $image_manager->canvas(640, 480, '#efefef'); $image->text($text, 320, 240 - (70 * substr_count($text, "\n")), function ($font) { $font->file(base_path('vendor/webfontkit/open-sans/fonts/opensans-regular.woff')); $font->size(60); $font->color('#cbcbcb'); $font->align('center'); $font->valign('center'); }); $image_data = (string) $image->encode('gif'); return 'data:image/gif;base64,'.base64_encode($image_data); }
[ "private", "static", "function", "placeholder", "(", "$", "text", ")", "{", "$", "image_manager", "=", "new", "ImageManager", "(", "[", "'driver'", "=>", "'imagick'", "]", ")", ";", "$", "image", "=", "$", "image_manager", "->", "canvas", "(", "640", ",", "480", ",", "'#efefef'", ")", ";", "$", "image", "->", "text", "(", "$", "text", ",", "320", ",", "240", "-", "(", "70", "*", "substr_count", "(", "$", "text", ",", "\"\\n\"", ")", ")", ",", "function", "(", "$", "font", ")", "{", "$", "font", "->", "file", "(", "base_path", "(", "'vendor/webfontkit/open-sans/fonts/opensans-regular.woff'", ")", ")", ";", "$", "font", "->", "size", "(", "60", ")", ";", "$", "font", "->", "color", "(", "'#cbcbcb'", ")", ";", "$", "font", "->", "align", "(", "'center'", ")", ";", "$", "font", "->", "valign", "(", "'center'", ")", ";", "}", ")", ";", "$", "image_data", "=", "(", "string", ")", "$", "image", "->", "encode", "(", "'gif'", ")", ";", "return", "'data:image/gif;base64,'", ".", "base64_encode", "(", "$", "image_data", ")", ";", "}" ]
Return a placeholder image containing the provided text. @param string $text @return string
[ "Return", "a", "placeholder", "image", "containing", "the", "provided", "text", "." ]
train
https://github.com/hamjoint/mustard-media/blob/d3c799dbc3578e1e1022bb4eccae7a20e285ba06/src/lib/Photo.php#L166-L183
hamjoint/mustard-media
src/lib/Photo.php
Photo.upload
public static function upload($file) { $photo = self::create(); $image_manager = new ImageManager(['driver' => 'imagick']); $disk = Storage::disk(config('mustard.storage.disk', 'local')); if (!file_exists($file)) { RuntimeException("File $file does not exist"); } $dest_dir = config('mustard.storage.photo.dir', 'mustard/photos'); $quality = config('mustard.storage.photo.quality', 90); $disk->makeDirectory($dest_dir); $photo_id = $photo->getKey(); Queue::push(function ($job) use ($file, $quality, $dest_dir, $photo_id) { if (!file_exists($file)) { RuntimeException("File $file no longer exists"); } $image_manager = new ImageManager(['driver' => 'imagick']); $disk = Storage::disk(config('mustard.storage.disk', 'local')); if ($file != "$dest_dir/$photo_id.jpg") { $image = $image_manager->make($file); $disk->put("$dest_dir/$photo_id.jpg", (string) $image->encode('jpg', $quality)); $image->destroy(); } $image = $image_manager->make($file)->heighten(83); $disk->put("$dest_dir/{$photo_id}_s.jpg", (string) $image->encode('jpg', $quality)); $image->destroy(); $image = $image_manager->make($file)->widen(500); $disk->put("$dest_dir/{$photo_id}_l.jpg", (string) $image->encode('jpg', $quality)); $image->destroy(); $photo = Photo::find($photo_id); $photo->processed = true; $photo->save(); $job->delete(); }); return $photo; }
php
public static function upload($file) { $photo = self::create(); $image_manager = new ImageManager(['driver' => 'imagick']); $disk = Storage::disk(config('mustard.storage.disk', 'local')); if (!file_exists($file)) { RuntimeException("File $file does not exist"); } $dest_dir = config('mustard.storage.photo.dir', 'mustard/photos'); $quality = config('mustard.storage.photo.quality', 90); $disk->makeDirectory($dest_dir); $photo_id = $photo->getKey(); Queue::push(function ($job) use ($file, $quality, $dest_dir, $photo_id) { if (!file_exists($file)) { RuntimeException("File $file no longer exists"); } $image_manager = new ImageManager(['driver' => 'imagick']); $disk = Storage::disk(config('mustard.storage.disk', 'local')); if ($file != "$dest_dir/$photo_id.jpg") { $image = $image_manager->make($file); $disk->put("$dest_dir/$photo_id.jpg", (string) $image->encode('jpg', $quality)); $image->destroy(); } $image = $image_manager->make($file)->heighten(83); $disk->put("$dest_dir/{$photo_id}_s.jpg", (string) $image->encode('jpg', $quality)); $image->destroy(); $image = $image_manager->make($file)->widen(500); $disk->put("$dest_dir/{$photo_id}_l.jpg", (string) $image->encode('jpg', $quality)); $image->destroy(); $photo = Photo::find($photo_id); $photo->processed = true; $photo->save(); $job->delete(); }); return $photo; }
[ "public", "static", "function", "upload", "(", "$", "file", ")", "{", "$", "photo", "=", "self", "::", "create", "(", ")", ";", "$", "image_manager", "=", "new", "ImageManager", "(", "[", "'driver'", "=>", "'imagick'", "]", ")", ";", "$", "disk", "=", "Storage", "::", "disk", "(", "config", "(", "'mustard.storage.disk'", ",", "'local'", ")", ")", ";", "if", "(", "!", "file_exists", "(", "$", "file", ")", ")", "{", "RuntimeException", "(", "\"File $file does not exist\"", ")", ";", "}", "$", "dest_dir", "=", "config", "(", "'mustard.storage.photo.dir'", ",", "'mustard/photos'", ")", ";", "$", "quality", "=", "config", "(", "'mustard.storage.photo.quality'", ",", "90", ")", ";", "$", "disk", "->", "makeDirectory", "(", "$", "dest_dir", ")", ";", "$", "photo_id", "=", "$", "photo", "->", "getKey", "(", ")", ";", "Queue", "::", "push", "(", "function", "(", "$", "job", ")", "use", "(", "$", "file", ",", "$", "quality", ",", "$", "dest_dir", ",", "$", "photo_id", ")", "{", "if", "(", "!", "file_exists", "(", "$", "file", ")", ")", "{", "RuntimeException", "(", "\"File $file no longer exists\"", ")", ";", "}", "$", "image_manager", "=", "new", "ImageManager", "(", "[", "'driver'", "=>", "'imagick'", "]", ")", ";", "$", "disk", "=", "Storage", "::", "disk", "(", "config", "(", "'mustard.storage.disk'", ",", "'local'", ")", ")", ";", "if", "(", "$", "file", "!=", "\"$dest_dir/$photo_id.jpg\"", ")", "{", "$", "image", "=", "$", "image_manager", "->", "make", "(", "$", "file", ")", ";", "$", "disk", "->", "put", "(", "\"$dest_dir/$photo_id.jpg\"", ",", "(", "string", ")", "$", "image", "->", "encode", "(", "'jpg'", ",", "$", "quality", ")", ")", ";", "$", "image", "->", "destroy", "(", ")", ";", "}", "$", "image", "=", "$", "image_manager", "->", "make", "(", "$", "file", ")", "->", "heighten", "(", "83", ")", ";", "$", "disk", "->", "put", "(", "\"$dest_dir/{$photo_id}_s.jpg\"", ",", "(", "string", ")", "$", "image", "->", "encode", "(", "'jpg'", ",", "$", "quality", ")", ")", ";", "$", "image", "->", "destroy", "(", ")", ";", "$", "image", "=", "$", "image_manager", "->", "make", "(", "$", "file", ")", "->", "widen", "(", "500", ")", ";", "$", "disk", "->", "put", "(", "\"$dest_dir/{$photo_id}_l.jpg\"", ",", "(", "string", ")", "$", "image", "->", "encode", "(", "'jpg'", ",", "$", "quality", ")", ")", ";", "$", "image", "->", "destroy", "(", ")", ";", "$", "photo", "=", "Photo", "::", "find", "(", "$", "photo_id", ")", ";", "$", "photo", "->", "processed", "=", "true", ";", "$", "photo", "->", "save", "(", ")", ";", "$", "job", "->", "delete", "(", ")", ";", "}", ")", ";", "return", "$", "photo", ";", "}" ]
Process a photo and create a record. @param string $file @return self
[ "Process", "a", "photo", "and", "create", "a", "record", "." ]
train
https://github.com/hamjoint/mustard-media/blob/d3c799dbc3578e1e1022bb4eccae7a20e285ba06/src/lib/Photo.php#L192-L250
MinyFramework/Miny-Core
src/Log/Log.php
Log.createProfiler
private function createProfiler($category, $name) { $key = $category . '.' . $name; if (!isset($this->profilers[$key])) { $this->profilers[$key] = new Profiler($this, $category, $name); } return $this->profilers[$key]; }
php
private function createProfiler($category, $name) { $key = $category . '.' . $name; if (!isset($this->profilers[$key])) { $this->profilers[$key] = new Profiler($this, $category, $name); } return $this->profilers[$key]; }
[ "private", "function", "createProfiler", "(", "$", "category", ",", "$", "name", ")", "{", "$", "key", "=", "$", "category", ".", "'.'", ".", "$", "name", ";", "if", "(", "!", "isset", "(", "$", "this", "->", "profilers", "[", "$", "key", "]", ")", ")", "{", "$", "this", "->", "profilers", "[", "$", "key", "]", "=", "new", "Profiler", "(", "$", "this", ",", "$", "category", ",", "$", "name", ")", ";", "}", "return", "$", "this", "->", "profilers", "[", "$", "key", "]", ";", "}" ]
@param string $category @param string $name @return Profiler
[ "@param", "string", "$category", "@param", "string", "$name" ]
train
https://github.com/MinyFramework/Miny-Core/blob/a1bfe801a44a49cf01f16411cb4663473e9c827c/src/Log/Log.php#L97-L105
fivesqrd/mutex
src/Laravel/MutexServiceProvider.php
MutexServiceProvider.boot
public function boot() { $source = realpath($raw = __DIR__ . '/Config.php') ?: $raw; if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) { $this->publishes([$source => config_path('mutex.php')]); } elseif ($this->app instanceof LumenApplication) { $this->app->configure('mutex'); } $this->mergeConfigFrom($source, 'mutex'); }
php
public function boot() { $source = realpath($raw = __DIR__ . '/Config.php') ?: $raw; if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) { $this->publishes([$source => config_path('mutex.php')]); } elseif ($this->app instanceof LumenApplication) { $this->app->configure('mutex'); } $this->mergeConfigFrom($source, 'mutex'); }
[ "public", "function", "boot", "(", ")", "{", "$", "source", "=", "realpath", "(", "$", "raw", "=", "__DIR__", ".", "'/Config.php'", ")", "?", ":", "$", "raw", ";", "if", "(", "$", "this", "->", "app", "instanceof", "LaravelApplication", "&&", "$", "this", "->", "app", "->", "runningInConsole", "(", ")", ")", "{", "$", "this", "->", "publishes", "(", "[", "$", "source", "=>", "config_path", "(", "'mutex.php'", ")", "]", ")", ";", "}", "elseif", "(", "$", "this", "->", "app", "instanceof", "LumenApplication", ")", "{", "$", "this", "->", "app", "->", "configure", "(", "'mutex'", ")", ";", "}", "$", "this", "->", "mergeConfigFrom", "(", "$", "source", ",", "'mutex'", ")", ";", "}" ]
Bootstrap the configuration @return void
[ "Bootstrap", "the", "configuration" ]
train
https://github.com/fivesqrd/mutex/blob/46ec93b5503e5c142da97379e744e4006a717643/src/Laravel/MutexServiceProvider.php#L22-L33
fivesqrd/mutex
src/Laravel/MutexServiceProvider.php
MutexServiceProvider.register
public function register() { $this->app->singleton('mutex', function ($app) { return new Mutex\Factory( $app->make('config')->get('mutex') ); }); $this->commands([ Console\Test::class, ]); }
php
public function register() { $this->app->singleton('mutex', function ($app) { return new Mutex\Factory( $app->make('config')->get('mutex') ); }); $this->commands([ Console\Test::class, ]); }
[ "public", "function", "register", "(", ")", "{", "$", "this", "->", "app", "->", "singleton", "(", "'mutex'", ",", "function", "(", "$", "app", ")", "{", "return", "new", "Mutex", "\\", "Factory", "(", "$", "app", "->", "make", "(", "'config'", ")", "->", "get", "(", "'mutex'", ")", ")", ";", "}", ")", ";", "$", "this", "->", "commands", "(", "[", "Console", "\\", "Test", "::", "class", ",", "]", ")", ";", "}" ]
Register the service provider. @return void
[ "Register", "the", "service", "provider", "." ]
train
https://github.com/fivesqrd/mutex/blob/46ec93b5503e5c142da97379e744e4006a717643/src/Laravel/MutexServiceProvider.php#L40-L51
dsv-su/daisy-api-client-php
src/Employee.php
Employee.find
public static function find(array $query) { $employees = Client::get("employee", $query); return array_map(function ($data) { return new self($data); }, $employees); }
php
public static function find(array $query) { $employees = Client::get("employee", $query); return array_map(function ($data) { return new self($data); }, $employees); }
[ "public", "static", "function", "find", "(", "array", "$", "query", ")", "{", "$", "employees", "=", "Client", "::", "get", "(", "\"employee\"", ",", "$", "query", ")", ";", "return", "array_map", "(", "function", "(", "$", "data", ")", "{", "return", "new", "self", "(", "$", "data", ")", ";", "}", ",", "$", "employees", ")", ";", "}" ]
Retrieve an array of Employee objects according to a search query. @param array $query The query. @return Employee[]
[ "Retrieve", "an", "array", "of", "Employee", "objects", "according", "to", "a", "search", "query", "." ]
train
https://github.com/dsv-su/daisy-api-client-php/blob/aa6817ed45fdf3629c9683ea8a8e70a80f59b441/src/Employee.php#L62-L66
dsv-su/daisy-api-client-php
src/Employee.php
Employee.getWorkPhone
public function getWorkPhone() { if (!isset($this->workPhone)) { $wp = trim($this->getRawWorkPhone()); if (empty($wp)) { $this->workPhone = null; } else { if (preg_match('/^\+?[-\d\s()]+/', $wp, $matches)) { $wp = $matches[0]; $wp = trim(str_replace(['(', ')'], '', $wp)); if (strlen(str_replace(' ', '', $wp)) === 4) { $wp = self::phonePrefixForExt($wp) . $wp; } if ($wp[0] !== '0' && $wp[0] !== '+') { $wp = '08' . $wp; } $phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance(); try { $this->workPhone = $phoneUtil->parse($wp, 'SE'); } catch (\libphonenumber\NumberParseException $e) { $this->workPhone = $this->getRawWorkPhone(); } } else { $this->workPhone = $this->getRawWorkPhone(); } } } return $this->workPhone; }
php
public function getWorkPhone() { if (!isset($this->workPhone)) { $wp = trim($this->getRawWorkPhone()); if (empty($wp)) { $this->workPhone = null; } else { if (preg_match('/^\+?[-\d\s()]+/', $wp, $matches)) { $wp = $matches[0]; $wp = trim(str_replace(['(', ')'], '', $wp)); if (strlen(str_replace(' ', '', $wp)) === 4) { $wp = self::phonePrefixForExt($wp) . $wp; } if ($wp[0] !== '0' && $wp[0] !== '+') { $wp = '08' . $wp; } $phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance(); try { $this->workPhone = $phoneUtil->parse($wp, 'SE'); } catch (\libphonenumber\NumberParseException $e) { $this->workPhone = $this->getRawWorkPhone(); } } else { $this->workPhone = $this->getRawWorkPhone(); } } } return $this->workPhone; }
[ "public", "function", "getWorkPhone", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "workPhone", ")", ")", "{", "$", "wp", "=", "trim", "(", "$", "this", "->", "getRawWorkPhone", "(", ")", ")", ";", "if", "(", "empty", "(", "$", "wp", ")", ")", "{", "$", "this", "->", "workPhone", "=", "null", ";", "}", "else", "{", "if", "(", "preg_match", "(", "'/^\\+?[-\\d\\s()]+/'", ",", "$", "wp", ",", "$", "matches", ")", ")", "{", "$", "wp", "=", "$", "matches", "[", "0", "]", ";", "$", "wp", "=", "trim", "(", "str_replace", "(", "[", "'('", ",", "')'", "]", ",", "''", ",", "$", "wp", ")", ")", ";", "if", "(", "strlen", "(", "str_replace", "(", "' '", ",", "''", ",", "$", "wp", ")", ")", "===", "4", ")", "{", "$", "wp", "=", "self", "::", "phonePrefixForExt", "(", "$", "wp", ")", ".", "$", "wp", ";", "}", "if", "(", "$", "wp", "[", "0", "]", "!==", "'0'", "&&", "$", "wp", "[", "0", "]", "!==", "'+'", ")", "{", "$", "wp", "=", "'08'", ".", "$", "wp", ";", "}", "$", "phoneUtil", "=", "\\", "libphonenumber", "\\", "PhoneNumberUtil", "::", "getInstance", "(", ")", ";", "try", "{", "$", "this", "->", "workPhone", "=", "$", "phoneUtil", "->", "parse", "(", "$", "wp", ",", "'SE'", ")", ";", "}", "catch", "(", "\\", "libphonenumber", "\\", "NumberParseException", "$", "e", ")", "{", "$", "this", "->", "workPhone", "=", "$", "this", "->", "getRawWorkPhone", "(", ")", ";", "}", "}", "else", "{", "$", "this", "->", "workPhone", "=", "$", "this", "->", "getRawWorkPhone", "(", ")", ";", "}", "}", "}", "return", "$", "this", "->", "workPhone", ";", "}" ]
Get work phone number of this employee. Try to parse it to a PhoneNumber, otherwise return the raw string. @return PhoneNumber|string|null The work phone number, or null if missing.
[ "Get", "work", "phone", "number", "of", "this", "employee", ".", "Try", "to", "parse", "it", "to", "a", "PhoneNumber", "otherwise", "return", "the", "raw", "string", "." ]
train
https://github.com/dsv-su/daisy-api-client-php/blob/aa6817ed45fdf3629c9683ea8a8e70a80f59b441/src/Employee.php#L105-L133
RocketPropelledTortoise/Core
src/Taxonomy/Model/TermData.php
TermData.save
public function save(array $options = []) { if ($this->translated === false) { $this->translated = true; } T::uncacheTerm($this->term_id); parent::save($options); }
php
public function save(array $options = []) { if ($this->translated === false) { $this->translated = true; } T::uncacheTerm($this->term_id); parent::save($options); }
[ "public", "function", "save", "(", "array", "$", "options", "=", "[", "]", ")", "{", "if", "(", "$", "this", "->", "translated", "===", "false", ")", "{", "$", "this", "->", "translated", "=", "true", ";", "}", "T", "::", "uncacheTerm", "(", "$", "this", "->", "term_id", ")", ";", "parent", "::", "save", "(", "$", "options", ")", ";", "}" ]
Save the model to the database. @param array $options @return bool
[ "Save", "the", "model", "to", "the", "database", "." ]
train
https://github.com/RocketPropelledTortoise/Core/blob/78b65663fc463e21e494257140ddbed0a9ccb3c3/src/Taxonomy/Model/TermData.php#L59-L68
ommu/mod-banner
models/ViewBanners.php
ViewBanners.search
public function search() { // @todo Please modify the following code to remove attributes that should not be searched. $criteria=new CDbCriteria; $criteria->compare('t.banner_id', strtolower($this->banner_id), true); $criteria->compare('t.publish', $this->publish); $criteria->compare('t.permanent', $this->permanent); $criteria->compare('t.views', strtolower($this->views), true); $criteria->compare('t.clicks', strtolower($this->clicks), true); if(!Yii::app()->getRequest()->getParam('ViewBanners_sort')) $criteria->order = 't.banner_id DESC'; return new CActiveDataProvider($this, array( 'criteria'=>$criteria, 'pagination'=>array( 'pageSize'=>Yii::app()->params['grid-view'] ? Yii::app()->params['grid-view']['pageSize'] : 50, ), )); }
php
public function search() { // @todo Please modify the following code to remove attributes that should not be searched. $criteria=new CDbCriteria; $criteria->compare('t.banner_id', strtolower($this->banner_id), true); $criteria->compare('t.publish', $this->publish); $criteria->compare('t.permanent', $this->permanent); $criteria->compare('t.views', strtolower($this->views), true); $criteria->compare('t.clicks', strtolower($this->clicks), true); if(!Yii::app()->getRequest()->getParam('ViewBanners_sort')) $criteria->order = 't.banner_id DESC'; return new CActiveDataProvider($this, array( 'criteria'=>$criteria, 'pagination'=>array( 'pageSize'=>Yii::app()->params['grid-view'] ? Yii::app()->params['grid-view']['pageSize'] : 50, ), )); }
[ "public", "function", "search", "(", ")", "{", "// @todo Please modify the following code to remove attributes that should not be searched.\r", "$", "criteria", "=", "new", "CDbCriteria", ";", "$", "criteria", "->", "compare", "(", "'t.banner_id'", ",", "strtolower", "(", "$", "this", "->", "banner_id", ")", ",", "true", ")", ";", "$", "criteria", "->", "compare", "(", "'t.publish'", ",", "$", "this", "->", "publish", ")", ";", "$", "criteria", "->", "compare", "(", "'t.permanent'", ",", "$", "this", "->", "permanent", ")", ";", "$", "criteria", "->", "compare", "(", "'t.views'", ",", "strtolower", "(", "$", "this", "->", "views", ")", ",", "true", ")", ";", "$", "criteria", "->", "compare", "(", "'t.clicks'", ",", "strtolower", "(", "$", "this", "->", "clicks", ")", ",", "true", ")", ";", "if", "(", "!", "Yii", "::", "app", "(", ")", "->", "getRequest", "(", ")", "->", "getParam", "(", "'ViewBanners_sort'", ")", ")", "$", "criteria", "->", "order", "=", "'t.banner_id DESC'", ";", "return", "new", "CActiveDataProvider", "(", "$", "this", ",", "array", "(", "'criteria'", "=>", "$", "criteria", ",", "'pagination'", "=>", "array", "(", "'pageSize'", "=>", "Yii", "::", "app", "(", ")", "->", "params", "[", "'grid-view'", "]", "?", "Yii", "::", "app", "(", ")", "->", "params", "[", "'grid-view'", "]", "[", "'pageSize'", "]", ":", "50", ",", ")", ",", ")", ")", ";", "}" ]
Retrieves a list of models based on the current search/filter conditions. Typical usecase: - Initialize the model fields with values from filter form. - Execute this method to get CActiveDataProvider instance which will filter models according to data in model fields. - Pass data provider to CGridView, CListView or any similar widget. @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
[ "Retrieves", "a", "list", "of", "models", "based", "on", "the", "current", "search", "/", "filter", "conditions", "." ]
train
https://github.com/ommu/mod-banner/blob/eb1c9fbb25a0a6be31749d5f32816de87fed8fdf/models/ViewBanners.php#L107-L128
PatrolServer/patrolsdk-php
lib/Software.php
Software.find
public function find($id, $scopes = []) { return $this->_get('servers/' . $this->server_id . '/software/' . $id, null, $scopes); }
php
public function find($id, $scopes = []) { return $this->_get('servers/' . $this->server_id . '/software/' . $id, null, $scopes); }
[ "public", "function", "find", "(", "$", "id", ",", "$", "scopes", "=", "[", "]", ")", "{", "return", "$", "this", "->", "_get", "(", "'servers/'", ".", "$", "this", "->", "server_id", ".", "'/software/'", ".", "$", "id", ",", "null", ",", "$", "scopes", ")", ";", "}" ]
Gets a single software object on the server @param integer $id @param array $scopes optional @return Software
[ "Gets", "a", "single", "software", "object", "on", "the", "server" ]
train
https://github.com/PatrolServer/patrolsdk-php/blob/2451f0d2ba2bb5bc3d7e47cfc110f7f272620db2/lib/Software.php#L38-L40
PatrolServer/patrolsdk-php
lib/Software.php
Software.exploits
public function exploits($scopes = []) { if (!$this->id) { throw new Exception("The software has no ID, can\'t get exploits"); } if (!$this->server_id) { throw new Exception("The software has no server ID, can\'t get exploits"); } $exploit = new Exploit($this->patrol); $exploit->defaults([ 'software_id' => $this->id, 'server_id' => $this->server_id ]); return $exploit->all(); }
php
public function exploits($scopes = []) { if (!$this->id) { throw new Exception("The software has no ID, can\'t get exploits"); } if (!$this->server_id) { throw new Exception("The software has no server ID, can\'t get exploits"); } $exploit = new Exploit($this->patrol); $exploit->defaults([ 'software_id' => $this->id, 'server_id' => $this->server_id ]); return $exploit->all(); }
[ "public", "function", "exploits", "(", "$", "scopes", "=", "[", "]", ")", "{", "if", "(", "!", "$", "this", "->", "id", ")", "{", "throw", "new", "Exception", "(", "\"The software has no ID, can\\'t get exploits\"", ")", ";", "}", "if", "(", "!", "$", "this", "->", "server_id", ")", "{", "throw", "new", "Exception", "(", "\"The software has no server ID, can\\'t get exploits\"", ")", ";", "}", "$", "exploit", "=", "new", "Exploit", "(", "$", "this", "->", "patrol", ")", ";", "$", "exploit", "->", "defaults", "(", "[", "'software_id'", "=>", "$", "this", "->", "id", ",", "'server_id'", "=>", "$", "this", "->", "server_id", "]", ")", ";", "return", "$", "exploit", "->", "all", "(", ")", ";", "}" ]
Gets a list of exploits from this software @param array $scopes optional @return array List of PatrolSdk\Exploit
[ "Gets", "a", "list", "of", "exploits", "from", "this", "software" ]
train
https://github.com/PatrolServer/patrolsdk-php/blob/2451f0d2ba2bb5bc3d7e47cfc110f7f272620db2/lib/Software.php#L49-L66
PatrolServer/patrolsdk-php
lib/Software.php
Software.__valueSet
protected function __valueSet($key, $value) { if ($key === "exploits") { $casted = []; foreach ($value as $exploit) { $casted[] = new Exploit($this->patrol, $exploit); } return $casted; } return $value; }
php
protected function __valueSet($key, $value) { if ($key === "exploits") { $casted = []; foreach ($value as $exploit) { $casted[] = new Exploit($this->patrol, $exploit); } return $casted; } return $value; }
[ "protected", "function", "__valueSet", "(", "$", "key", ",", "$", "value", ")", "{", "if", "(", "$", "key", "===", "\"exploits\"", ")", "{", "$", "casted", "=", "[", "]", ";", "foreach", "(", "$", "value", "as", "$", "exploit", ")", "{", "$", "casted", "[", "]", "=", "new", "Exploit", "(", "$", "this", "->", "patrol", ",", "$", "exploit", ")", ";", "}", "return", "$", "casted", ";", "}", "return", "$", "value", ";", "}" ]
This is a casting hook, when a new value is set in PatrolModel, this hook will be called, in this case, when "exploits" are set in the model, cast them to a PatrolSdk\Exploit object @param string $key @param object $value @return object $value Can be casted
[ "This", "is", "a", "casting", "hook", "when", "a", "new", "value", "is", "set", "in", "PatrolModel", "this", "hook", "will", "be", "called", "in", "this", "case", "when", "exploits", "are", "set", "in", "the", "model", "cast", "them", "to", "a", "PatrolSdk", "\\", "Exploit", "object" ]
train
https://github.com/PatrolServer/patrolsdk-php/blob/2451f0d2ba2bb5bc3d7e47cfc110f7f272620db2/lib/Software.php#L77-L87
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Db/Driver/Mysql.php
Mysql.parseDsn
protected function parseDsn($config){ $dsn = 'mysql:dbname='.$config['database'].';host='.$config['hostname']; if(!empty($config['hostport'])) { $dsn .= ';port='.$config['hostport']; }elseif(!empty($config['socket'])){ $dsn .= ';unix_socket='.$config['socket']; } if(!empty($config['charset'])){ //为兼容各版本PHP,用两种方式设置编码 $this->options[\PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES '.$config['charset']; $dsn .= ';charset='.$config['charset']; } return $dsn; }
php
protected function parseDsn($config){ $dsn = 'mysql:dbname='.$config['database'].';host='.$config['hostname']; if(!empty($config['hostport'])) { $dsn .= ';port='.$config['hostport']; }elseif(!empty($config['socket'])){ $dsn .= ';unix_socket='.$config['socket']; } if(!empty($config['charset'])){ //为兼容各版本PHP,用两种方式设置编码 $this->options[\PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES '.$config['charset']; $dsn .= ';charset='.$config['charset']; } return $dsn; }
[ "protected", "function", "parseDsn", "(", "$", "config", ")", "{", "$", "dsn", "=", "'mysql:dbname='", ".", "$", "config", "[", "'database'", "]", ".", "';host='", ".", "$", "config", "[", "'hostname'", "]", ";", "if", "(", "!", "empty", "(", "$", "config", "[", "'hostport'", "]", ")", ")", "{", "$", "dsn", ".=", "';port='", ".", "$", "config", "[", "'hostport'", "]", ";", "}", "elseif", "(", "!", "empty", "(", "$", "config", "[", "'socket'", "]", ")", ")", "{", "$", "dsn", ".=", "';unix_socket='", ".", "$", "config", "[", "'socket'", "]", ";", "}", "if", "(", "!", "empty", "(", "$", "config", "[", "'charset'", "]", ")", ")", "{", "//为兼容各版本PHP,用两种方式设置编码", "$", "this", "->", "options", "[", "\\", "PDO", "::", "MYSQL_ATTR_INIT_COMMAND", "]", "=", "'SET NAMES '", ".", "$", "config", "[", "'charset'", "]", ";", "$", "dsn", ".=", "';charset='", ".", "$", "config", "[", "'charset'", "]", ";", "}", "return", "$", "dsn", ";", "}" ]
解析pdo连接的dsn信息 @access public @param array $config 连接信息 @return string
[ "解析pdo连接的dsn信息" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Db/Driver/Mysql.php#L26-L40
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Db/Driver/Mysql.php
Mysql.getFields
public function getFields($tableName) { $this->initConnect(true); list($tableName) = explode(' ', $tableName); if(strpos($tableName,'.')){ list($dbName,$tableName) = explode('.',$tableName); $sql = 'SHOW COLUMNS FROM `'.$dbName.'`.`'.$tableName.'`'; }else{ $sql = 'SHOW COLUMNS FROM `'.$tableName.'`'; } $result = $this->query($sql); $info = array(); if($result) { foreach ($result as $key => $val) { if(\PDO::CASE_LOWER != $this->_linkID->getAttribute(\PDO::ATTR_CASE)){ $val = array_change_key_case ( $val , CASE_LOWER ); } $info[$val['field']] = array( 'name' => $val['field'], 'type' => $val['type'], 'notnull' => (bool) ($val['null'] === ''), // not null is empty, null is yes 'default' => $val['default'], 'primary' => (strtolower($val['key']) == 'pri'), 'autoinc' => (strtolower($val['extra']) == 'auto_increment'), ); } } return $info; }
php
public function getFields($tableName) { $this->initConnect(true); list($tableName) = explode(' ', $tableName); if(strpos($tableName,'.')){ list($dbName,$tableName) = explode('.',$tableName); $sql = 'SHOW COLUMNS FROM `'.$dbName.'`.`'.$tableName.'`'; }else{ $sql = 'SHOW COLUMNS FROM `'.$tableName.'`'; } $result = $this->query($sql); $info = array(); if($result) { foreach ($result as $key => $val) { if(\PDO::CASE_LOWER != $this->_linkID->getAttribute(\PDO::ATTR_CASE)){ $val = array_change_key_case ( $val , CASE_LOWER ); } $info[$val['field']] = array( 'name' => $val['field'], 'type' => $val['type'], 'notnull' => (bool) ($val['null'] === ''), // not null is empty, null is yes 'default' => $val['default'], 'primary' => (strtolower($val['key']) == 'pri'), 'autoinc' => (strtolower($val['extra']) == 'auto_increment'), ); } } return $info; }
[ "public", "function", "getFields", "(", "$", "tableName", ")", "{", "$", "this", "->", "initConnect", "(", "true", ")", ";", "list", "(", "$", "tableName", ")", "=", "explode", "(", "' '", ",", "$", "tableName", ")", ";", "if", "(", "strpos", "(", "$", "tableName", ",", "'.'", ")", ")", "{", "list", "(", "$", "dbName", ",", "$", "tableName", ")", "=", "explode", "(", "'.'", ",", "$", "tableName", ")", ";", "$", "sql", "=", "'SHOW COLUMNS FROM `'", ".", "$", "dbName", ".", "'`.`'", ".", "$", "tableName", ".", "'`'", ";", "}", "else", "{", "$", "sql", "=", "'SHOW COLUMNS FROM `'", ".", "$", "tableName", ".", "'`'", ";", "}", "$", "result", "=", "$", "this", "->", "query", "(", "$", "sql", ")", ";", "$", "info", "=", "array", "(", ")", ";", "if", "(", "$", "result", ")", "{", "foreach", "(", "$", "result", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "\\", "PDO", "::", "CASE_LOWER", "!=", "$", "this", "->", "_linkID", "->", "getAttribute", "(", "\\", "PDO", "::", "ATTR_CASE", ")", ")", "{", "$", "val", "=", "array_change_key_case", "(", "$", "val", ",", "CASE_LOWER", ")", ";", "}", "$", "info", "[", "$", "val", "[", "'field'", "]", "]", "=", "array", "(", "'name'", "=>", "$", "val", "[", "'field'", "]", ",", "'type'", "=>", "$", "val", "[", "'type'", "]", ",", "'notnull'", "=>", "(", "bool", ")", "(", "$", "val", "[", "'null'", "]", "===", "''", ")", ",", "// not null is empty, null is yes", "'default'", "=>", "$", "val", "[", "'default'", "]", ",", "'primary'", "=>", "(", "strtolower", "(", "$", "val", "[", "'key'", "]", ")", "==", "'pri'", ")", ",", "'autoinc'", "=>", "(", "strtolower", "(", "$", "val", "[", "'extra'", "]", ")", "==", "'auto_increment'", ")", ",", ")", ";", "}", "}", "return", "$", "info", ";", "}" ]
取得数据表的字段信息 @access public
[ "取得数据表的字段信息" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Db/Driver/Mysql.php#L46-L74
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Db/Driver/Mysql.php
Mysql.getTables
public function getTables($dbName='') { $sql = !empty($dbName)?'SHOW TABLES FROM '.$dbName:'SHOW TABLES '; $result = $this->query($sql); $info = array(); foreach ($result as $key => $val) { $info[$key] = current($val); } return $info; }
php
public function getTables($dbName='') { $sql = !empty($dbName)?'SHOW TABLES FROM '.$dbName:'SHOW TABLES '; $result = $this->query($sql); $info = array(); foreach ($result as $key => $val) { $info[$key] = current($val); } return $info; }
[ "public", "function", "getTables", "(", "$", "dbName", "=", "''", ")", "{", "$", "sql", "=", "!", "empty", "(", "$", "dbName", ")", "?", "'SHOW TABLES FROM '", ".", "$", "dbName", ":", "'SHOW TABLES '", ";", "$", "result", "=", "$", "this", "->", "query", "(", "$", "sql", ")", ";", "$", "info", "=", "array", "(", ")", ";", "foreach", "(", "$", "result", "as", "$", "key", "=>", "$", "val", ")", "{", "$", "info", "[", "$", "key", "]", "=", "current", "(", "$", "val", ")", ";", "}", "return", "$", "info", ";", "}" ]
取得数据库的表信息 @access public
[ "取得数据库的表信息" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Db/Driver/Mysql.php#L80-L88
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Db/Driver/Mysql.php
Mysql.insertAll
public function insertAll($dataSet,$options=array(),$replace=false) { $values = array(); $this->model = $options['model']; if(!is_array($dataSet[0])) return false; $this->parseBind(!empty($options['bind'])?$options['bind']:array()); $fields = array_map(array($this,'parseKey'),array_keys($dataSet[0])); foreach ($dataSet as $data){ $value = array(); foreach ($data as $key=>$val){ if(is_array($val) && 'exp' == $val[0]){ $value[] = $val[1]; }elseif(is_null($val)){ $value[] = 'NULL'; }elseif(is_scalar($val)){ if(0===strpos($val,':') && in_array($val,array_keys($this->bind))){ $value[] = $this->parseValue($val); }else{ $name = count($this->bind); $value[] = ':'.$name; $this->bindParam($name,$val); } } } $values[] = '('.implode(',', $value).')'; } // 兼容数字传入方式 $replace= (is_numeric($replace) && $replace>0)?true:$replace; $sql = (true===$replace?'REPLACE':'INSERT').' INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES '.implode(',',$values).$this->parseDuplicate($replace); $sql .= $this->parseComment(!empty($options['comment'])?$options['comment']:''); return $this->execute($sql,!empty($options['fetch_sql']) ? true : false); }
php
public function insertAll($dataSet,$options=array(),$replace=false) { $values = array(); $this->model = $options['model']; if(!is_array($dataSet[0])) return false; $this->parseBind(!empty($options['bind'])?$options['bind']:array()); $fields = array_map(array($this,'parseKey'),array_keys($dataSet[0])); foreach ($dataSet as $data){ $value = array(); foreach ($data as $key=>$val){ if(is_array($val) && 'exp' == $val[0]){ $value[] = $val[1]; }elseif(is_null($val)){ $value[] = 'NULL'; }elseif(is_scalar($val)){ if(0===strpos($val,':') && in_array($val,array_keys($this->bind))){ $value[] = $this->parseValue($val); }else{ $name = count($this->bind); $value[] = ':'.$name; $this->bindParam($name,$val); } } } $values[] = '('.implode(',', $value).')'; } // 兼容数字传入方式 $replace= (is_numeric($replace) && $replace>0)?true:$replace; $sql = (true===$replace?'REPLACE':'INSERT').' INTO '.$this->parseTable($options['table']).' ('.implode(',', $fields).') VALUES '.implode(',',$values).$this->parseDuplicate($replace); $sql .= $this->parseComment(!empty($options['comment'])?$options['comment']:''); return $this->execute($sql,!empty($options['fetch_sql']) ? true : false); }
[ "public", "function", "insertAll", "(", "$", "dataSet", ",", "$", "options", "=", "array", "(", ")", ",", "$", "replace", "=", "false", ")", "{", "$", "values", "=", "array", "(", ")", ";", "$", "this", "->", "model", "=", "$", "options", "[", "'model'", "]", ";", "if", "(", "!", "is_array", "(", "$", "dataSet", "[", "0", "]", ")", ")", "return", "false", ";", "$", "this", "->", "parseBind", "(", "!", "empty", "(", "$", "options", "[", "'bind'", "]", ")", "?", "$", "options", "[", "'bind'", "]", ":", "array", "(", ")", ")", ";", "$", "fields", "=", "array_map", "(", "array", "(", "$", "this", ",", "'parseKey'", ")", ",", "array_keys", "(", "$", "dataSet", "[", "0", "]", ")", ")", ";", "foreach", "(", "$", "dataSet", "as", "$", "data", ")", "{", "$", "value", "=", "array", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "is_array", "(", "$", "val", ")", "&&", "'exp'", "==", "$", "val", "[", "0", "]", ")", "{", "$", "value", "[", "]", "=", "$", "val", "[", "1", "]", ";", "}", "elseif", "(", "is_null", "(", "$", "val", ")", ")", "{", "$", "value", "[", "]", "=", "'NULL'", ";", "}", "elseif", "(", "is_scalar", "(", "$", "val", ")", ")", "{", "if", "(", "0", "===", "strpos", "(", "$", "val", ",", "':'", ")", "&&", "in_array", "(", "$", "val", ",", "array_keys", "(", "$", "this", "->", "bind", ")", ")", ")", "{", "$", "value", "[", "]", "=", "$", "this", "->", "parseValue", "(", "$", "val", ")", ";", "}", "else", "{", "$", "name", "=", "count", "(", "$", "this", "->", "bind", ")", ";", "$", "value", "[", "]", "=", "':'", ".", "$", "name", ";", "$", "this", "->", "bindParam", "(", "$", "name", ",", "$", "val", ")", ";", "}", "}", "}", "$", "values", "[", "]", "=", "'('", ".", "implode", "(", "','", ",", "$", "value", ")", ".", "')'", ";", "}", "// 兼容数字传入方式", "$", "replace", "=", "(", "is_numeric", "(", "$", "replace", ")", "&&", "$", "replace", ">", "0", ")", "?", "true", ":", "$", "replace", ";", "$", "sql", "=", "(", "true", "===", "$", "replace", "?", "'REPLACE'", ":", "'INSERT'", ")", ".", "' INTO '", ".", "$", "this", "->", "parseTable", "(", "$", "options", "[", "'table'", "]", ")", ".", "' ('", ".", "implode", "(", "','", ",", "$", "fields", ")", ".", "') VALUES '", ".", "implode", "(", "','", ",", "$", "values", ")", ".", "$", "this", "->", "parseDuplicate", "(", "$", "replace", ")", ";", "$", "sql", ".=", "$", "this", "->", "parseComment", "(", "!", "empty", "(", "$", "options", "[", "'comment'", "]", ")", "?", "$", "options", "[", "'comment'", "]", ":", "''", ")", ";", "return", "$", "this", "->", "execute", "(", "$", "sql", ",", "!", "empty", "(", "$", "options", "[", "'fetch_sql'", "]", ")", "?", "true", ":", "false", ")", ";", "}" ]
批量插入记录 @access public @param mixed $dataSet 数据集 @param array $options 参数表达式 @param boolean $replace 是否replace @return false | integer
[ "批量插入记录" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Db/Driver/Mysql.php#L112-L142
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Db/Driver/Mysql.php
Mysql.parseDuplicate
protected function parseDuplicate($duplicate){ // 布尔值或空则返回空字符串 if(is_bool($duplicate) || empty($duplicate)) return ''; if(is_string($duplicate)){ // field1,field2 转数组 $duplicate = explode(',', $duplicate); }elseif(is_object($duplicate)){ // 对象转数组 $duplicate = get_class_vars($duplicate); } $updates = array(); foreach((array) $duplicate as $key=>$val){ if(is_numeric($key)){ // array('field1', 'field2', 'field3') 解析为 ON DUPLICATE KEY UPDATE field1=VALUES(field1), field2=VALUES(field2), field3=VALUES(field3) $updates[] = $this->parseKey($val)."=VALUES(".$this->parseKey($val).")"; }else{ if(is_scalar($val)) // 兼容标量传值方式 $val = array('value', $val); if(!isset($val[1])) continue; switch($val[0]){ case 'exp': // 表达式 $updates[] = $this->parseKey($key)."=($val[1])"; break; case 'value': // 值 default: $name = count($this->bind); $updates[] = $this->parseKey($key)."=:".$name; $this->bindParam($name, $val[1]); break; } } } if(empty($updates)) return ''; return " ON DUPLICATE KEY UPDATE ".join(', ', $updates); }
php
protected function parseDuplicate($duplicate){ // 布尔值或空则返回空字符串 if(is_bool($duplicate) || empty($duplicate)) return ''; if(is_string($duplicate)){ // field1,field2 转数组 $duplicate = explode(',', $duplicate); }elseif(is_object($duplicate)){ // 对象转数组 $duplicate = get_class_vars($duplicate); } $updates = array(); foreach((array) $duplicate as $key=>$val){ if(is_numeric($key)){ // array('field1', 'field2', 'field3') 解析为 ON DUPLICATE KEY UPDATE field1=VALUES(field1), field2=VALUES(field2), field3=VALUES(field3) $updates[] = $this->parseKey($val)."=VALUES(".$this->parseKey($val).")"; }else{ if(is_scalar($val)) // 兼容标量传值方式 $val = array('value', $val); if(!isset($val[1])) continue; switch($val[0]){ case 'exp': // 表达式 $updates[] = $this->parseKey($key)."=($val[1])"; break; case 'value': // 值 default: $name = count($this->bind); $updates[] = $this->parseKey($key)."=:".$name; $this->bindParam($name, $val[1]); break; } } } if(empty($updates)) return ''; return " ON DUPLICATE KEY UPDATE ".join(', ', $updates); }
[ "protected", "function", "parseDuplicate", "(", "$", "duplicate", ")", "{", "// 布尔值或空则返回空字符串", "if", "(", "is_bool", "(", "$", "duplicate", ")", "||", "empty", "(", "$", "duplicate", ")", ")", "return", "''", ";", "if", "(", "is_string", "(", "$", "duplicate", ")", ")", "{", "// field1,field2 转数组", "$", "duplicate", "=", "explode", "(", "','", ",", "$", "duplicate", ")", ";", "}", "elseif", "(", "is_object", "(", "$", "duplicate", ")", ")", "{", "// 对象转数组", "$", "duplicate", "=", "get_class_vars", "(", "$", "duplicate", ")", ";", "}", "$", "updates", "=", "array", "(", ")", ";", "foreach", "(", "(", "array", ")", "$", "duplicate", "as", "$", "key", "=>", "$", "val", ")", "{", "if", "(", "is_numeric", "(", "$", "key", ")", ")", "{", "// array('field1', 'field2', 'field3') 解析为 ON DUPLICATE KEY UPDATE field1=VALUES(field1), field2=VALUES(field2), field3=VALUES(field3)", "$", "updates", "[", "]", "=", "$", "this", "->", "parseKey", "(", "$", "val", ")", ".", "\"=VALUES(\"", ".", "$", "this", "->", "parseKey", "(", "$", "val", ")", ".", "\")\"", ";", "}", "else", "{", "if", "(", "is_scalar", "(", "$", "val", ")", ")", "// 兼容标量传值方式", "$", "val", "=", "array", "(", "'value'", ",", "$", "val", ")", ";", "if", "(", "!", "isset", "(", "$", "val", "[", "1", "]", ")", ")", "continue", ";", "switch", "(", "$", "val", "[", "0", "]", ")", "{", "case", "'exp'", ":", "// 表达式", "$", "updates", "[", "]", "=", "$", "this", "->", "parseKey", "(", "$", "key", ")", ".", "\"=($val[1])\"", ";", "break", ";", "case", "'value'", ":", "// 值", "default", ":", "$", "name", "=", "count", "(", "$", "this", "->", "bind", ")", ";", "$", "updates", "[", "]", "=", "$", "this", "->", "parseKey", "(", "$", "key", ")", ".", "\"=:\"", ".", "$", "name", ";", "$", "this", "->", "bindParam", "(", "$", "name", ",", "$", "val", "[", "1", "]", ")", ";", "break", ";", "}", "}", "}", "if", "(", "empty", "(", "$", "updates", ")", ")", "return", "''", ";", "return", "\" ON DUPLICATE KEY UPDATE \"", ".", "join", "(", "', '", ",", "$", "updates", ")", ";", "}" ]
ON DUPLICATE KEY UPDATE 分析 @access protected @param mixed $duplicate @return string
[ "ON", "DUPLICATE", "KEY", "UPDATE", "分析" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Db/Driver/Mysql.php#L150-L184
KDF5000/EasyThink
src/ThinkPHP/Library/Think/Db/Driver/Mysql.php
Mysql.procedure
public function procedure($str,$fetchSql=false) { $this->initConnect(false); $this->_linkID->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING); if ( !$this->_linkID ) return false; $this->queryStr = $str; if($fetchSql){ return $this->queryStr; } //释放前次的查询结果 if ( !empty($this->PDOStatement) ) $this->free(); $this->queryTimes++; N('db_query',1); // 兼容代码 // 调试开始 $this->debug(true); $this->PDOStatement = $this->_linkID->prepare($str); if(false === $this->PDOStatement){ $this->error(); return false; } try{ $result = $this->PDOStatement->execute(); // 调试结束 $this->debug(false); do { $result = $this->PDOStatement->fetchAll(\PDO::FETCH_ASSOC); if ($result) { $resultArr[] = $result; } } while ($this->PDOStatement->nextRowset()); $this->_linkID->setAttribute(\PDO::ATTR_ERRMODE, $this->options[\PDO::ATTR_ERRMODE]); return $resultArr; }catch (\PDOException $e) { $this->error(); $this->_linkID->setAttribute(\PDO::ATTR_ERRMODE, $this->options[\PDO::ATTR_ERRMODE]); return false; } }
php
public function procedure($str,$fetchSql=false) { $this->initConnect(false); $this->_linkID->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_WARNING); if ( !$this->_linkID ) return false; $this->queryStr = $str; if($fetchSql){ return $this->queryStr; } //释放前次的查询结果 if ( !empty($this->PDOStatement) ) $this->free(); $this->queryTimes++; N('db_query',1); // 兼容代码 // 调试开始 $this->debug(true); $this->PDOStatement = $this->_linkID->prepare($str); if(false === $this->PDOStatement){ $this->error(); return false; } try{ $result = $this->PDOStatement->execute(); // 调试结束 $this->debug(false); do { $result = $this->PDOStatement->fetchAll(\PDO::FETCH_ASSOC); if ($result) { $resultArr[] = $result; } } while ($this->PDOStatement->nextRowset()); $this->_linkID->setAttribute(\PDO::ATTR_ERRMODE, $this->options[\PDO::ATTR_ERRMODE]); return $resultArr; }catch (\PDOException $e) { $this->error(); $this->_linkID->setAttribute(\PDO::ATTR_ERRMODE, $this->options[\PDO::ATTR_ERRMODE]); return false; } }
[ "public", "function", "procedure", "(", "$", "str", ",", "$", "fetchSql", "=", "false", ")", "{", "$", "this", "->", "initConnect", "(", "false", ")", ";", "$", "this", "->", "_linkID", "->", "setAttribute", "(", "\\", "PDO", "::", "ATTR_ERRMODE", ",", "\\", "PDO", "::", "ERRMODE_WARNING", ")", ";", "if", "(", "!", "$", "this", "->", "_linkID", ")", "return", "false", ";", "$", "this", "->", "queryStr", "=", "$", "str", ";", "if", "(", "$", "fetchSql", ")", "{", "return", "$", "this", "->", "queryStr", ";", "}", "//释放前次的查询结果", "if", "(", "!", "empty", "(", "$", "this", "->", "PDOStatement", ")", ")", "$", "this", "->", "free", "(", ")", ";", "$", "this", "->", "queryTimes", "++", ";", "N", "(", "'db_query'", ",", "1", ")", ";", "// 兼容代码", "// 调试开始", "$", "this", "->", "debug", "(", "true", ")", ";", "$", "this", "->", "PDOStatement", "=", "$", "this", "->", "_linkID", "->", "prepare", "(", "$", "str", ")", ";", "if", "(", "false", "===", "$", "this", "->", "PDOStatement", ")", "{", "$", "this", "->", "error", "(", ")", ";", "return", "false", ";", "}", "try", "{", "$", "result", "=", "$", "this", "->", "PDOStatement", "->", "execute", "(", ")", ";", "// 调试结束", "$", "this", "->", "debug", "(", "false", ")", ";", "do", "{", "$", "result", "=", "$", "this", "->", "PDOStatement", "->", "fetchAll", "(", "\\", "PDO", "::", "FETCH_ASSOC", ")", ";", "if", "(", "$", "result", ")", "{", "$", "resultArr", "[", "]", "=", "$", "result", ";", "}", "}", "while", "(", "$", "this", "->", "PDOStatement", "->", "nextRowset", "(", ")", ")", ";", "$", "this", "->", "_linkID", "->", "setAttribute", "(", "\\", "PDO", "::", "ATTR_ERRMODE", ",", "$", "this", "->", "options", "[", "\\", "PDO", "::", "ATTR_ERRMODE", "]", ")", ";", "return", "$", "resultArr", ";", "}", "catch", "(", "\\", "PDOException", "$", "e", ")", "{", "$", "this", "->", "error", "(", ")", ";", "$", "this", "->", "_linkID", "->", "setAttribute", "(", "\\", "PDO", "::", "ATTR_ERRMODE", ",", "$", "this", "->", "options", "[", "\\", "PDO", "::", "ATTR_ERRMODE", "]", ")", ";", "return", "false", ";", "}", "}" ]
执行存储过程查询 返回多个数据集 @access public @param string $str sql指令 @param boolean $fetchSql 不执行只是获取SQL @return mixed
[ "执行存储过程查询", "返回多个数据集" ]
train
https://github.com/KDF5000/EasyThink/blob/86efc9c8a0d504e01e2fea55868227fdc8928841/src/ThinkPHP/Library/Think/Db/Driver/Mysql.php#L195-L234
DaemonAlchemist/atp-core
src/ATPCore/Lessc.php
Lessc.compileBlock
protected function compileBlock($block) { switch ($block->type) { case "root": $this->compileRoot($block); break; case null: $this->compileCSSBlock($block); break; case "media": $this->compileMedia($block); break; case "directive": $name = "@" . $block->name; if (!empty($block->value)) { $name .= " " . $this->compileValue($this->reduce($block->value)); } $this->compileNestedBlock($block, array($name)); break; default: $this->throwError("unknown block type: $block->type\n"); } }
php
protected function compileBlock($block) { switch ($block->type) { case "root": $this->compileRoot($block); break; case null: $this->compileCSSBlock($block); break; case "media": $this->compileMedia($block); break; case "directive": $name = "@" . $block->name; if (!empty($block->value)) { $name .= " " . $this->compileValue($this->reduce($block->value)); } $this->compileNestedBlock($block, array($name)); break; default: $this->throwError("unknown block type: $block->type\n"); } }
[ "protected", "function", "compileBlock", "(", "$", "block", ")", "{", "switch", "(", "$", "block", "->", "type", ")", "{", "case", "\"root\"", ":", "$", "this", "->", "compileRoot", "(", "$", "block", ")", ";", "break", ";", "case", "null", ":", "$", "this", "->", "compileCSSBlock", "(", "$", "block", ")", ";", "break", ";", "case", "\"media\"", ":", "$", "this", "->", "compileMedia", "(", "$", "block", ")", ";", "break", ";", "case", "\"directive\"", ":", "$", "name", "=", "\"@\"", ".", "$", "block", "->", "name", ";", "if", "(", "!", "empty", "(", "$", "block", "->", "value", ")", ")", "{", "$", "name", ".=", "\" \"", ".", "$", "this", "->", "compileValue", "(", "$", "this", "->", "reduce", "(", "$", "block", "->", "value", ")", ")", ";", "}", "$", "this", "->", "compileNestedBlock", "(", "$", "block", ",", "array", "(", "$", "name", ")", ")", ";", "break", ";", "default", ":", "$", "this", "->", "throwError", "(", "\"unknown block type: $block->type\\n\"", ")", ";", "}", "}" ]
Recursively compiles a block. A block is analogous to a CSS block in most cases. A single LESS document is encapsulated in a block when parsed, but it does not have parent tags so all of it's children appear on the root level when compiled. Blocks are made up of props and children. Props are property instructions, array tuples which describe an action to be taken, eg. write a property, set a variable, mixin a block. The children of a block are just all the blocks that are defined within. This is used to look up mixins when performing a mixin. Compiling the block involves pushing a fresh environment on the stack, and iterating through the props, compiling each one. See lessc::compileProp()
[ "Recursively", "compiles", "a", "block", "." ]
train
https://github.com/DaemonAlchemist/atp-core/blob/47efa734b882c27aa2a59fbcba34653b4d2125c7/src/ATPCore/Lessc.php#L191-L213
DaemonAlchemist/atp-core
src/ATPCore/Lessc.php
Lessc.deduplicate
protected function deduplicate($lines) { $unique = array(); $comments = array(); foreach($lines as $line) { if (strpos($line, '/*') === 0) { $comments[] = $line; continue; } if (!in_array($line, $unique)) { $unique[] = $line; } array_splice($unique, array_search($line, $unique), 0, $comments); $comments = array(); } return array_merge($unique, $comments); }
php
protected function deduplicate($lines) { $unique = array(); $comments = array(); foreach($lines as $line) { if (strpos($line, '/*') === 0) { $comments[] = $line; continue; } if (!in_array($line, $unique)) { $unique[] = $line; } array_splice($unique, array_search($line, $unique), 0, $comments); $comments = array(); } return array_merge($unique, $comments); }
[ "protected", "function", "deduplicate", "(", "$", "lines", ")", "{", "$", "unique", "=", "array", "(", ")", ";", "$", "comments", "=", "array", "(", ")", ";", "foreach", "(", "$", "lines", "as", "$", "line", ")", "{", "if", "(", "strpos", "(", "$", "line", ",", "'/*'", ")", "===", "0", ")", "{", "$", "comments", "[", "]", "=", "$", "line", ";", "continue", ";", "}", "if", "(", "!", "in_array", "(", "$", "line", ",", "$", "unique", ")", ")", "{", "$", "unique", "[", "]", "=", "$", "line", ";", "}", "array_splice", "(", "$", "unique", ",", "array_search", "(", "$", "line", ",", "$", "unique", ")", ",", "0", ",", "$", "comments", ")", ";", "$", "comments", "=", "array", "(", ")", ";", "}", "return", "array_merge", "(", "$", "unique", ",", "$", "comments", ")", ";", "}" ]
Deduplicate lines in a block. Comments are not deduplicated. If a duplicate rule is detected, the comments immediately preceding each occurence are consolidated.
[ "Deduplicate", "lines", "in", "a", "block", ".", "Comments", "are", "not", "deduplicated", ".", "If", "a", "duplicate", "rule", "is", "detected", "the", "comments", "immediately", "preceding", "each", "occurence", "are", "consolidated", "." ]
train
https://github.com/DaemonAlchemist/atp-core/blob/47efa734b882c27aa2a59fbcba34653b4d2125c7/src/ATPCore/Lessc.php#L295-L311
DaemonAlchemist/atp-core
src/ATPCore/Lessc.php
Lessc.findBlocks
protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen=array()) { if ($searchIn == null) return null; if (isset($seen[$searchIn->id])) return null; $seen[$searchIn->id] = true; $name = $path[0]; if (isset($searchIn->children[$name])) { $blocks = $searchIn->children[$name]; if (count($path) == 1) { $matches = $this->patternMatchAll($blocks, $orderedArgs, $keywordArgs, $seen); if (!empty($matches)) { // This will return all blocks that match in the closest // scope that has any matching block, like lessjs return $matches; } } else { $matches = array(); foreach ($blocks as $subBlock) { $subMatches = $this->findBlocks($subBlock, array_slice($path, 1), $orderedArgs, $keywordArgs, $seen); if (!is_null($subMatches)) { foreach ($subMatches as $sm) { $matches[] = $sm; } } } return count($matches) > 0 ? $matches : null; } } if ($searchIn->parent === $searchIn) return null; return $this->findBlocks($searchIn->parent, $path, $orderedArgs, $keywordArgs, $seen); }
php
protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen=array()) { if ($searchIn == null) return null; if (isset($seen[$searchIn->id])) return null; $seen[$searchIn->id] = true; $name = $path[0]; if (isset($searchIn->children[$name])) { $blocks = $searchIn->children[$name]; if (count($path) == 1) { $matches = $this->patternMatchAll($blocks, $orderedArgs, $keywordArgs, $seen); if (!empty($matches)) { // This will return all blocks that match in the closest // scope that has any matching block, like lessjs return $matches; } } else { $matches = array(); foreach ($blocks as $subBlock) { $subMatches = $this->findBlocks($subBlock, array_slice($path, 1), $orderedArgs, $keywordArgs, $seen); if (!is_null($subMatches)) { foreach ($subMatches as $sm) { $matches[] = $sm; } } } return count($matches) > 0 ? $matches : null; } } if ($searchIn->parent === $searchIn) return null; return $this->findBlocks($searchIn->parent, $path, $orderedArgs, $keywordArgs, $seen); }
[ "protected", "function", "findBlocks", "(", "$", "searchIn", ",", "$", "path", ",", "$", "orderedArgs", ",", "$", "keywordArgs", ",", "$", "seen", "=", "array", "(", ")", ")", "{", "if", "(", "$", "searchIn", "==", "null", ")", "return", "null", ";", "if", "(", "isset", "(", "$", "seen", "[", "$", "searchIn", "->", "id", "]", ")", ")", "return", "null", ";", "$", "seen", "[", "$", "searchIn", "->", "id", "]", "=", "true", ";", "$", "name", "=", "$", "path", "[", "0", "]", ";", "if", "(", "isset", "(", "$", "searchIn", "->", "children", "[", "$", "name", "]", ")", ")", "{", "$", "blocks", "=", "$", "searchIn", "->", "children", "[", "$", "name", "]", ";", "if", "(", "count", "(", "$", "path", ")", "==", "1", ")", "{", "$", "matches", "=", "$", "this", "->", "patternMatchAll", "(", "$", "blocks", ",", "$", "orderedArgs", ",", "$", "keywordArgs", ",", "$", "seen", ")", ";", "if", "(", "!", "empty", "(", "$", "matches", ")", ")", "{", "// This will return all blocks that match in the closest\r", "// scope that has any matching block, like lessjs\r", "return", "$", "matches", ";", "}", "}", "else", "{", "$", "matches", "=", "array", "(", ")", ";", "foreach", "(", "$", "blocks", "as", "$", "subBlock", ")", "{", "$", "subMatches", "=", "$", "this", "->", "findBlocks", "(", "$", "subBlock", ",", "array_slice", "(", "$", "path", ",", "1", ")", ",", "$", "orderedArgs", ",", "$", "keywordArgs", ",", "$", "seen", ")", ";", "if", "(", "!", "is_null", "(", "$", "subMatches", ")", ")", "{", "foreach", "(", "$", "subMatches", "as", "$", "sm", ")", "{", "$", "matches", "[", "]", "=", "$", "sm", ";", "}", "}", "}", "return", "count", "(", "$", "matches", ")", ">", "0", "?", "$", "matches", ":", "null", ";", "}", "}", "if", "(", "$", "searchIn", "->", "parent", "===", "$", "searchIn", ")", "return", "null", ";", "return", "$", "this", "->", "findBlocks", "(", "$", "searchIn", "->", "parent", ",", "$", "path", ",", "$", "orderedArgs", ",", "$", "keywordArgs", ",", "$", "seen", ")", ";", "}" ]
attempt to find blocks matched by path and args
[ "attempt", "to", "find", "blocks", "matched", "by", "path", "and", "args" ]
train
https://github.com/DaemonAlchemist/atp-core/blob/47efa734b882c27aa2a59fbcba34653b4d2125c7/src/ATPCore/Lessc.php#L597-L631
DaemonAlchemist/atp-core
src/ATPCore/Lessc.php
Lessc.zipSetArgs
protected function zipSetArgs($args, $orderedValues, $keywordValues) { $assignedValues = array(); $i = 0; foreach ($args as $a) { if ($a[0] == "arg") { if (isset($keywordValues[$a[1]])) { // has keyword arg $value = $keywordValues[$a[1]]; } elseif (isset($orderedValues[$i])) { // has ordered arg $value = $orderedValues[$i]; $i++; } elseif (isset($a[2])) { // has default value $value = $a[2]; } else { $this->throwError("Failed to assign arg " . $a[1]); $value = null; // :( } $value = $this->reduce($value); $this->set($a[1], $value); $assignedValues[] = $value; } else { // a lit $i++; } } // check for a rest $last = end($args); if ($last[0] == "rest") { $rest = array_slice($orderedValues, count($args) - 1); $this->set($last[1], $this->reduce(array("list", " ", $rest))); } // wow is this the only true use of PHP's + operator for arrays? $this->env->arguments = $assignedValues + $orderedValues; }
php
protected function zipSetArgs($args, $orderedValues, $keywordValues) { $assignedValues = array(); $i = 0; foreach ($args as $a) { if ($a[0] == "arg") { if (isset($keywordValues[$a[1]])) { // has keyword arg $value = $keywordValues[$a[1]]; } elseif (isset($orderedValues[$i])) { // has ordered arg $value = $orderedValues[$i]; $i++; } elseif (isset($a[2])) { // has default value $value = $a[2]; } else { $this->throwError("Failed to assign arg " . $a[1]); $value = null; // :( } $value = $this->reduce($value); $this->set($a[1], $value); $assignedValues[] = $value; } else { // a lit $i++; } } // check for a rest $last = end($args); if ($last[0] == "rest") { $rest = array_slice($orderedValues, count($args) - 1); $this->set($last[1], $this->reduce(array("list", " ", $rest))); } // wow is this the only true use of PHP's + operator for arrays? $this->env->arguments = $assignedValues + $orderedValues; }
[ "protected", "function", "zipSetArgs", "(", "$", "args", ",", "$", "orderedValues", ",", "$", "keywordValues", ")", "{", "$", "assignedValues", "=", "array", "(", ")", ";", "$", "i", "=", "0", ";", "foreach", "(", "$", "args", "as", "$", "a", ")", "{", "if", "(", "$", "a", "[", "0", "]", "==", "\"arg\"", ")", "{", "if", "(", "isset", "(", "$", "keywordValues", "[", "$", "a", "[", "1", "]", "]", ")", ")", "{", "// has keyword arg\r", "$", "value", "=", "$", "keywordValues", "[", "$", "a", "[", "1", "]", "]", ";", "}", "elseif", "(", "isset", "(", "$", "orderedValues", "[", "$", "i", "]", ")", ")", "{", "// has ordered arg\r", "$", "value", "=", "$", "orderedValues", "[", "$", "i", "]", ";", "$", "i", "++", ";", "}", "elseif", "(", "isset", "(", "$", "a", "[", "2", "]", ")", ")", "{", "// has default value\r", "$", "value", "=", "$", "a", "[", "2", "]", ";", "}", "else", "{", "$", "this", "->", "throwError", "(", "\"Failed to assign arg \"", ".", "$", "a", "[", "1", "]", ")", ";", "$", "value", "=", "null", ";", "// :(\r", "}", "$", "value", "=", "$", "this", "->", "reduce", "(", "$", "value", ")", ";", "$", "this", "->", "set", "(", "$", "a", "[", "1", "]", ",", "$", "value", ")", ";", "$", "assignedValues", "[", "]", "=", "$", "value", ";", "}", "else", "{", "// a lit\r", "$", "i", "++", ";", "}", "}", "// check for a rest\r", "$", "last", "=", "end", "(", "$", "args", ")", ";", "if", "(", "$", "last", "[", "0", "]", "==", "\"rest\"", ")", "{", "$", "rest", "=", "array_slice", "(", "$", "orderedValues", ",", "count", "(", "$", "args", ")", "-", "1", ")", ";", "$", "this", "->", "set", "(", "$", "last", "[", "1", "]", ",", "$", "this", "->", "reduce", "(", "array", "(", "\"list\"", ",", "\" \"", ",", "$", "rest", ")", ")", ")", ";", "}", "// wow is this the only true use of PHP's + operator for arrays?\r", "$", "this", "->", "env", "->", "arguments", "=", "$", "assignedValues", "+", "$", "orderedValues", ";", "}" ]
or the one passed in through $values
[ "or", "the", "one", "passed", "in", "through", "$values" ]
train
https://github.com/DaemonAlchemist/atp-core/blob/47efa734b882c27aa2a59fbcba34653b4d2125c7/src/ATPCore/Lessc.php#L635-L674
DaemonAlchemist/atp-core
src/ATPCore/Lessc.php
Lessc.lib_data_uri
protected function lib_data_uri($value) { $mime = ($value[0] === 'list') ? $value[2][0][2] : null; $url = ($value[0] === 'list') ? $value[2][1][2][0] : $value[2][0]; $fullpath = $this->findImport($url); if($fullpath && ($fsize = filesize($fullpath)) !== false) { // IE8 can't handle data uris larger than 32KB if($fsize/1024 < 32) { if(is_null($mime)) { if(class_exists('finfo')) { // php 5.3+ $finfo = new finfo(FILEINFO_MIME); $mime = explode('; ', $finfo->file($fullpath)); $mime = $mime[0]; } elseif(function_exists('mime_content_type')) { // PHP 5.2 $mime = mime_content_type($fullpath); } } if(!is_null($mime)) // fallback if the mime type is still unknown $url = sprintf('data:%s;base64,%s', $mime, base64_encode(file_get_contents($fullpath))); } } return 'url("'.$url.'")'; }
php
protected function lib_data_uri($value) { $mime = ($value[0] === 'list') ? $value[2][0][2] : null; $url = ($value[0] === 'list') ? $value[2][1][2][0] : $value[2][0]; $fullpath = $this->findImport($url); if($fullpath && ($fsize = filesize($fullpath)) !== false) { // IE8 can't handle data uris larger than 32KB if($fsize/1024 < 32) { if(is_null($mime)) { if(class_exists('finfo')) { // php 5.3+ $finfo = new finfo(FILEINFO_MIME); $mime = explode('; ', $finfo->file($fullpath)); $mime = $mime[0]; } elseif(function_exists('mime_content_type')) { // PHP 5.2 $mime = mime_content_type($fullpath); } } if(!is_null($mime)) // fallback if the mime type is still unknown $url = sprintf('data:%s;base64,%s', $mime, base64_encode(file_get_contents($fullpath))); } } return 'url("'.$url.'")'; }
[ "protected", "function", "lib_data_uri", "(", "$", "value", ")", "{", "$", "mime", "=", "(", "$", "value", "[", "0", "]", "===", "'list'", ")", "?", "$", "value", "[", "2", "]", "[", "0", "]", "[", "2", "]", ":", "null", ";", "$", "url", "=", "(", "$", "value", "[", "0", "]", "===", "'list'", ")", "?", "$", "value", "[", "2", "]", "[", "1", "]", "[", "2", "]", "[", "0", "]", ":", "$", "value", "[", "2", "]", "[", "0", "]", ";", "$", "fullpath", "=", "$", "this", "->", "findImport", "(", "$", "url", ")", ";", "if", "(", "$", "fullpath", "&&", "(", "$", "fsize", "=", "filesize", "(", "$", "fullpath", ")", ")", "!==", "false", ")", "{", "// IE8 can't handle data uris larger than 32KB\r", "if", "(", "$", "fsize", "/", "1024", "<", "32", ")", "{", "if", "(", "is_null", "(", "$", "mime", ")", ")", "{", "if", "(", "class_exists", "(", "'finfo'", ")", ")", "{", "// php 5.3+\r", "$", "finfo", "=", "new", "finfo", "(", "FILEINFO_MIME", ")", ";", "$", "mime", "=", "explode", "(", "'; '", ",", "$", "finfo", "->", "file", "(", "$", "fullpath", ")", ")", ";", "$", "mime", "=", "$", "mime", "[", "0", "]", ";", "}", "elseif", "(", "function_exists", "(", "'mime_content_type'", ")", ")", "{", "// PHP 5.2\r", "$", "mime", "=", "mime_content_type", "(", "$", "fullpath", ")", ";", "}", "}", "if", "(", "!", "is_null", "(", "$", "mime", ")", ")", "// fallback if the mime type is still unknown\r", "$", "url", "=", "sprintf", "(", "'data:%s;base64,%s'", ",", "$", "mime", ",", "base64_encode", "(", "file_get_contents", "(", "$", "fullpath", ")", ")", ")", ";", "}", "}", "return", "'url(\"'", ".", "$", "url", ".", "'\")'", ";", "}" ]
Given an url, decide whether to output a regular link or the base64-encoded contents of the file @param array $value either an argument list (two strings) or a single string @return string formatted url(), either as a link or base64-encoded
[ "Given", "an", "url", "decide", "whether", "to", "output", "a", "regular", "link", "or", "the", "base64", "-", "encoded", "contents", "of", "the", "file" ]
train
https://github.com/DaemonAlchemist/atp-core/blob/47efa734b882c27aa2a59fbcba34653b4d2125c7/src/ATPCore/Lessc.php#L994-L1019
DaemonAlchemist/atp-core
src/ATPCore/Lessc.php
Lessc.lib_e
protected function lib_e($arg) { switch ($arg[0]) { case "list": $items = $arg[2]; if (isset($items[0])) { return $this->lib_e($items[0]); } $this->throwError("unrecognised input"); case "string": $arg[1] = ""; return $arg; case "keyword": return $arg; default: return array("keyword", $this->compileValue($arg)); } }
php
protected function lib_e($arg) { switch ($arg[0]) { case "list": $items = $arg[2]; if (isset($items[0])) { return $this->lib_e($items[0]); } $this->throwError("unrecognised input"); case "string": $arg[1] = ""; return $arg; case "keyword": return $arg; default: return array("keyword", $this->compileValue($arg)); } }
[ "protected", "function", "lib_e", "(", "$", "arg", ")", "{", "switch", "(", "$", "arg", "[", "0", "]", ")", "{", "case", "\"list\"", ":", "$", "items", "=", "$", "arg", "[", "2", "]", ";", "if", "(", "isset", "(", "$", "items", "[", "0", "]", ")", ")", "{", "return", "$", "this", "->", "lib_e", "(", "$", "items", "[", "0", "]", ")", ";", "}", "$", "this", "->", "throwError", "(", "\"unrecognised input\"", ")", ";", "case", "\"string\"", ":", "$", "arg", "[", "1", "]", "=", "\"\"", ";", "return", "$", "arg", ";", "case", "\"keyword\"", ":", "return", "$", "arg", ";", "default", ":", "return", "array", "(", "\"keyword\"", ",", "$", "this", "->", "compileValue", "(", "$", "arg", ")", ")", ";", "}", "}" ]
utility func to unquote a string
[ "utility", "func", "to", "unquote", "a", "string" ]
train
https://github.com/DaemonAlchemist/atp-core/blob/47efa734b882c27aa2a59fbcba34653b4d2125c7/src/ATPCore/Lessc.php#L1022-L1038
DaemonAlchemist/atp-core
src/ATPCore/Lessc.php
Lessc.lib_mix
protected function lib_mix($args) { if ($args[0] != "list" || count($args[2]) < 2) $this->throwError("mix expects (color1, color2, weight)"); list($first, $second) = $args[2]; $first = $this->assertColor($first); $second = $this->assertColor($second); $first_a = $this->lib_alpha($first); $second_a = $this->lib_alpha($second); if (isset($args[2][2])) { $weight = $args[2][2][1] / 100.0; } else { $weight = 0.5; } $w = $weight * 2 - 1; $a = $first_a - $second_a; $w1 = (($w * $a == -1 ? $w : ($w + $a)/(1 + $w * $a)) + 1) / 2.0; $w2 = 1.0 - $w1; $new = array('color', $w1 * $first[1] + $w2 * $second[1], $w1 * $first[2] + $w2 * $second[2], $w1 * $first[3] + $w2 * $second[3], ); if ($first_a != 1.0 || $second_a != 1.0) { $new[] = $first_a * $weight + $second_a * ($weight - 1); } return $this->fixColor($new); }
php
protected function lib_mix($args) { if ($args[0] != "list" || count($args[2]) < 2) $this->throwError("mix expects (color1, color2, weight)"); list($first, $second) = $args[2]; $first = $this->assertColor($first); $second = $this->assertColor($second); $first_a = $this->lib_alpha($first); $second_a = $this->lib_alpha($second); if (isset($args[2][2])) { $weight = $args[2][2][1] / 100.0; } else { $weight = 0.5; } $w = $weight * 2 - 1; $a = $first_a - $second_a; $w1 = (($w * $a == -1 ? $w : ($w + $a)/(1 + $w * $a)) + 1) / 2.0; $w2 = 1.0 - $w1; $new = array('color', $w1 * $first[1] + $w2 * $second[1], $w1 * $first[2] + $w2 * $second[2], $w1 * $first[3] + $w2 * $second[3], ); if ($first_a != 1.0 || $second_a != 1.0) { $new[] = $first_a * $weight + $second_a * ($weight - 1); } return $this->fixColor($new); }
[ "protected", "function", "lib_mix", "(", "$", "args", ")", "{", "if", "(", "$", "args", "[", "0", "]", "!=", "\"list\"", "||", "count", "(", "$", "args", "[", "2", "]", ")", "<", "2", ")", "$", "this", "->", "throwError", "(", "\"mix expects (color1, color2, weight)\"", ")", ";", "list", "(", "$", "first", ",", "$", "second", ")", "=", "$", "args", "[", "2", "]", ";", "$", "first", "=", "$", "this", "->", "assertColor", "(", "$", "first", ")", ";", "$", "second", "=", "$", "this", "->", "assertColor", "(", "$", "second", ")", ";", "$", "first_a", "=", "$", "this", "->", "lib_alpha", "(", "$", "first", ")", ";", "$", "second_a", "=", "$", "this", "->", "lib_alpha", "(", "$", "second", ")", ";", "if", "(", "isset", "(", "$", "args", "[", "2", "]", "[", "2", "]", ")", ")", "{", "$", "weight", "=", "$", "args", "[", "2", "]", "[", "2", "]", "[", "1", "]", "/", "100.0", ";", "}", "else", "{", "$", "weight", "=", "0.5", ";", "}", "$", "w", "=", "$", "weight", "*", "2", "-", "1", ";", "$", "a", "=", "$", "first_a", "-", "$", "second_a", ";", "$", "w1", "=", "(", "(", "$", "w", "*", "$", "a", "==", "-", "1", "?", "$", "w", ":", "(", "$", "w", "+", "$", "a", ")", "/", "(", "1", "+", "$", "w", "*", "$", "a", ")", ")", "+", "1", ")", "/", "2.0", ";", "$", "w2", "=", "1.0", "-", "$", "w1", ";", "$", "new", "=", "array", "(", "'color'", ",", "$", "w1", "*", "$", "first", "[", "1", "]", "+", "$", "w2", "*", "$", "second", "[", "1", "]", ",", "$", "w1", "*", "$", "first", "[", "2", "]", "+", "$", "w2", "*", "$", "second", "[", "2", "]", ",", "$", "w1", "*", "$", "first", "[", "3", "]", "+", "$", "w2", "*", "$", "second", "[", "3", "]", ",", ")", ";", "if", "(", "$", "first_a", "!=", "1.0", "||", "$", "second_a", "!=", "1.0", ")", "{", "$", "new", "[", "]", "=", "$", "first_a", "*", "$", "weight", "+", "$", "second_a", "*", "(", "$", "weight", "-", "1", ")", ";", "}", "return", "$", "this", "->", "fixColor", "(", "$", "new", ")", ";", "}" ]
http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method
[ "http", ":", "//", "sass", "-", "lang", ".", "com", "/", "docs", "/", "yardoc", "/", "Sass", "/", "Script", "/", "Functions", ".", "html#mix", "-", "instance_method" ]
train
https://github.com/DaemonAlchemist/atp-core/blob/47efa734b882c27aa2a59fbcba34653b4d2125c7/src/ATPCore/Lessc.php#L1207-L1241
DaemonAlchemist/atp-core
src/ATPCore/Lessc.php
Lessc.toRGB
protected function toRGB($color) { if ($color[0] == 'color') return $color; $H = $color[1] / 360; $S = $color[2] / 100; $L = $color[3] / 100; if ($S == 0) { $r = $g = $b = $L; } else { $temp2 = $L < 0.5 ? $L*(1.0 + $S) : $L + $S - $L * $S; $temp1 = 2.0 * $L - $temp2; $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2); $g = $this->toRGB_helper($H, $temp1, $temp2); $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2); } // $out = array('color', round($r*255), round($g*255), round($b*255)); $out = array('color', $r*255, $g*255, $b*255); if (count($color) > 4) $out[] = $color[4]; // copy alpha return $out; }
php
protected function toRGB($color) { if ($color[0] == 'color') return $color; $H = $color[1] / 360; $S = $color[2] / 100; $L = $color[3] / 100; if ($S == 0) { $r = $g = $b = $L; } else { $temp2 = $L < 0.5 ? $L*(1.0 + $S) : $L + $S - $L * $S; $temp1 = 2.0 * $L - $temp2; $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2); $g = $this->toRGB_helper($H, $temp1, $temp2); $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2); } // $out = array('color', round($r*255), round($g*255), round($b*255)); $out = array('color', $r*255, $g*255, $b*255); if (count($color) > 4) $out[] = $color[4]; // copy alpha return $out; }
[ "protected", "function", "toRGB", "(", "$", "color", ")", "{", "if", "(", "$", "color", "[", "0", "]", "==", "'color'", ")", "return", "$", "color", ";", "$", "H", "=", "$", "color", "[", "1", "]", "/", "360", ";", "$", "S", "=", "$", "color", "[", "2", "]", "/", "100", ";", "$", "L", "=", "$", "color", "[", "3", "]", "/", "100", ";", "if", "(", "$", "S", "==", "0", ")", "{", "$", "r", "=", "$", "g", "=", "$", "b", "=", "$", "L", ";", "}", "else", "{", "$", "temp2", "=", "$", "L", "<", "0.5", "?", "$", "L", "*", "(", "1.0", "+", "$", "S", ")", ":", "$", "L", "+", "$", "S", "-", "$", "L", "*", "$", "S", ";", "$", "temp1", "=", "2.0", "*", "$", "L", "-", "$", "temp2", ";", "$", "r", "=", "$", "this", "->", "toRGB_helper", "(", "$", "H", "+", "1", "/", "3", ",", "$", "temp1", ",", "$", "temp2", ")", ";", "$", "g", "=", "$", "this", "->", "toRGB_helper", "(", "$", "H", ",", "$", "temp1", ",", "$", "temp2", ")", ";", "$", "b", "=", "$", "this", "->", "toRGB_helper", "(", "$", "H", "-", "1", "/", "3", ",", "$", "temp1", ",", "$", "temp2", ")", ";", "}", "// $out = array('color', round($r*255), round($g*255), round($b*255));\r", "$", "out", "=", "array", "(", "'color'", ",", "$", "r", "*", "255", ",", "$", "g", "*", "255", ",", "$", "b", "*", "255", ")", ";", "if", "(", "count", "(", "$", "color", ")", ">", "4", ")", "$", "out", "[", "]", "=", "$", "color", "[", "4", "]", ";", "// copy alpha\r", "return", "$", "out", ";", "}" ]
Converts a hsl array into a color value in rgb. Expects H to be in range of 0 to 360, S and L in 0 to 100
[ "Converts", "a", "hsl", "array", "into", "a", "color", "value", "in", "rgb", ".", "Expects", "H", "to", "be", "in", "range", "of", "0", "to", "360", "S", "and", "L", "in", "0", "to", "100" ]
train
https://github.com/DaemonAlchemist/atp-core/blob/47efa734b882c27aa2a59fbcba34653b4d2125c7/src/ATPCore/Lessc.php#L1362-L1387
DaemonAlchemist/atp-core
src/ATPCore/Lessc.php
Lessc.funcToColor
protected function funcToColor($func) { $fname = $func[1]; if ($func[2][0] != 'list') return false; // need a list of arguments $rawComponents = $func[2][2]; if ($fname == 'hsl' || $fname == 'hsla') { $hsl = array('hsl'); $i = 0; foreach ($rawComponents as $c) { $val = $this->reduce($c); $val = isset($val[1]) ? floatval($val[1]) : 0; if ($i == 0) $clamp = 360; elseif ($i < 3) $clamp = 100; else $clamp = 1; $hsl[] = $this->clamp($val, $clamp); $i++; } while (count($hsl) < 4) $hsl[] = 0; return $this->toRGB($hsl); } elseif ($fname == 'rgb' || $fname == 'rgba') { $components = array(); $i = 1; foreach ($rawComponents as $c) { $c = $this->reduce($c); if ($i < 4) { if ($c[0] == "number" && $c[2] == "%") { $components[] = 255 * ($c[1] / 100); } else { $components[] = floatval($c[1]); } } elseif ($i == 4) { if ($c[0] == "number" && $c[2] == "%") { $components[] = 1.0 * ($c[1] / 100); } else { $components[] = floatval($c[1]); } } else break; $i++; } while (count($components) < 3) $components[] = 0; array_unshift($components, 'color'); return $this->fixColor($components); } return false; }
php
protected function funcToColor($func) { $fname = $func[1]; if ($func[2][0] != 'list') return false; // need a list of arguments $rawComponents = $func[2][2]; if ($fname == 'hsl' || $fname == 'hsla') { $hsl = array('hsl'); $i = 0; foreach ($rawComponents as $c) { $val = $this->reduce($c); $val = isset($val[1]) ? floatval($val[1]) : 0; if ($i == 0) $clamp = 360; elseif ($i < 3) $clamp = 100; else $clamp = 1; $hsl[] = $this->clamp($val, $clamp); $i++; } while (count($hsl) < 4) $hsl[] = 0; return $this->toRGB($hsl); } elseif ($fname == 'rgb' || $fname == 'rgba') { $components = array(); $i = 1; foreach ($rawComponents as $c) { $c = $this->reduce($c); if ($i < 4) { if ($c[0] == "number" && $c[2] == "%") { $components[] = 255 * ($c[1] / 100); } else { $components[] = floatval($c[1]); } } elseif ($i == 4) { if ($c[0] == "number" && $c[2] == "%") { $components[] = 1.0 * ($c[1] / 100); } else { $components[] = floatval($c[1]); } } else break; $i++; } while (count($components) < 3) $components[] = 0; array_unshift($components, 'color'); return $this->fixColor($components); } return false; }
[ "protected", "function", "funcToColor", "(", "$", "func", ")", "{", "$", "fname", "=", "$", "func", "[", "1", "]", ";", "if", "(", "$", "func", "[", "2", "]", "[", "0", "]", "!=", "'list'", ")", "return", "false", ";", "// need a list of arguments\r", "$", "rawComponents", "=", "$", "func", "[", "2", "]", "[", "2", "]", ";", "if", "(", "$", "fname", "==", "'hsl'", "||", "$", "fname", "==", "'hsla'", ")", "{", "$", "hsl", "=", "array", "(", "'hsl'", ")", ";", "$", "i", "=", "0", ";", "foreach", "(", "$", "rawComponents", "as", "$", "c", ")", "{", "$", "val", "=", "$", "this", "->", "reduce", "(", "$", "c", ")", ";", "$", "val", "=", "isset", "(", "$", "val", "[", "1", "]", ")", "?", "floatval", "(", "$", "val", "[", "1", "]", ")", ":", "0", ";", "if", "(", "$", "i", "==", "0", ")", "$", "clamp", "=", "360", ";", "elseif", "(", "$", "i", "<", "3", ")", "$", "clamp", "=", "100", ";", "else", "$", "clamp", "=", "1", ";", "$", "hsl", "[", "]", "=", "$", "this", "->", "clamp", "(", "$", "val", ",", "$", "clamp", ")", ";", "$", "i", "++", ";", "}", "while", "(", "count", "(", "$", "hsl", ")", "<", "4", ")", "$", "hsl", "[", "]", "=", "0", ";", "return", "$", "this", "->", "toRGB", "(", "$", "hsl", ")", ";", "}", "elseif", "(", "$", "fname", "==", "'rgb'", "||", "$", "fname", "==", "'rgba'", ")", "{", "$", "components", "=", "array", "(", ")", ";", "$", "i", "=", "1", ";", "foreach", "(", "$", "rawComponents", "as", "$", "c", ")", "{", "$", "c", "=", "$", "this", "->", "reduce", "(", "$", "c", ")", ";", "if", "(", "$", "i", "<", "4", ")", "{", "if", "(", "$", "c", "[", "0", "]", "==", "\"number\"", "&&", "$", "c", "[", "2", "]", "==", "\"%\"", ")", "{", "$", "components", "[", "]", "=", "255", "*", "(", "$", "c", "[", "1", "]", "/", "100", ")", ";", "}", "else", "{", "$", "components", "[", "]", "=", "floatval", "(", "$", "c", "[", "1", "]", ")", ";", "}", "}", "elseif", "(", "$", "i", "==", "4", ")", "{", "if", "(", "$", "c", "[", "0", "]", "==", "\"number\"", "&&", "$", "c", "[", "2", "]", "==", "\"%\"", ")", "{", "$", "components", "[", "]", "=", "1.0", "*", "(", "$", "c", "[", "1", "]", "/", "100", ")", ";", "}", "else", "{", "$", "components", "[", "]", "=", "floatval", "(", "$", "c", "[", "1", "]", ")", ";", "}", "}", "else", "break", ";", "$", "i", "++", ";", "}", "while", "(", "count", "(", "$", "components", ")", "<", "3", ")", "$", "components", "[", "]", "=", "0", ";", "array_unshift", "(", "$", "components", ",", "'color'", ")", ";", "return", "$", "this", "->", "fixColor", "(", "$", "components", ")", ";", "}", "return", "false", ";", "}" ]
Convert the rgb, rgba, hsl color literals of function type as returned by the parser into values of color type.
[ "Convert", "the", "rgb", "rgba", "hsl", "color", "literals", "of", "function", "type", "as", "returned", "by", "the", "parser", "into", "values", "of", "color", "type", "." ]
train
https://github.com/DaemonAlchemist/atp-core/blob/47efa734b882c27aa2a59fbcba34653b4d2125c7/src/ATPCore/Lessc.php#L1397-L1447
DaemonAlchemist/atp-core
src/ATPCore/Lessc.php
Lessc.coerceColor
protected function coerceColor($value) { switch($value[0]) { case 'color': return $value; case 'raw_color': $c = array("color", 0, 0, 0); $colorStr = substr($value[1], 1); $num = hexdec($colorStr); $width = strlen($colorStr) == 3 ? 16 : 256; for ($i = 3; $i > 0; $i--) { // 3 2 1 $t = $num % $width; $num /= $width; $c[$i] = $t * (256/$width) + $t * floor(16/$width); } return $c; case 'keyword': $name = $value[1]; if (isset(self::$cssColors[$name])) { $rgba = explode(',', self::$cssColors[$name]); if(isset($rgba[3])) return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]); return array('color', $rgba[0], $rgba[1], $rgba[2]); } return null; } }
php
protected function coerceColor($value) { switch($value[0]) { case 'color': return $value; case 'raw_color': $c = array("color", 0, 0, 0); $colorStr = substr($value[1], 1); $num = hexdec($colorStr); $width = strlen($colorStr) == 3 ? 16 : 256; for ($i = 3; $i > 0; $i--) { // 3 2 1 $t = $num % $width; $num /= $width; $c[$i] = $t * (256/$width) + $t * floor(16/$width); } return $c; case 'keyword': $name = $value[1]; if (isset(self::$cssColors[$name])) { $rgba = explode(',', self::$cssColors[$name]); if(isset($rgba[3])) return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]); return array('color', $rgba[0], $rgba[1], $rgba[2]); } return null; } }
[ "protected", "function", "coerceColor", "(", "$", "value", ")", "{", "switch", "(", "$", "value", "[", "0", "]", ")", "{", "case", "'color'", ":", "return", "$", "value", ";", "case", "'raw_color'", ":", "$", "c", "=", "array", "(", "\"color\"", ",", "0", ",", "0", ",", "0", ")", ";", "$", "colorStr", "=", "substr", "(", "$", "value", "[", "1", "]", ",", "1", ")", ";", "$", "num", "=", "hexdec", "(", "$", "colorStr", ")", ";", "$", "width", "=", "strlen", "(", "$", "colorStr", ")", "==", "3", "?", "16", ":", "256", ";", "for", "(", "$", "i", "=", "3", ";", "$", "i", ">", "0", ";", "$", "i", "--", ")", "{", "// 3 2 1\r", "$", "t", "=", "$", "num", "%", "$", "width", ";", "$", "num", "/=", "$", "width", ";", "$", "c", "[", "$", "i", "]", "=", "$", "t", "*", "(", "256", "/", "$", "width", ")", "+", "$", "t", "*", "floor", "(", "16", "/", "$", "width", ")", ";", "}", "return", "$", "c", ";", "case", "'keyword'", ":", "$", "name", "=", "$", "value", "[", "1", "]", ";", "if", "(", "isset", "(", "self", "::", "$", "cssColors", "[", "$", "name", "]", ")", ")", "{", "$", "rgba", "=", "explode", "(", "','", ",", "self", "::", "$", "cssColors", "[", "$", "name", "]", ")", ";", "if", "(", "isset", "(", "$", "rgba", "[", "3", "]", ")", ")", "return", "array", "(", "'color'", ",", "$", "rgba", "[", "0", "]", ",", "$", "rgba", "[", "1", "]", ",", "$", "rgba", "[", "2", "]", ",", "$", "rgba", "[", "3", "]", ")", ";", "return", "array", "(", "'color'", ",", "$", "rgba", "[", "0", "]", ",", "$", "rgba", "[", "1", "]", ",", "$", "rgba", "[", "2", "]", ")", ";", "}", "return", "null", ";", "}", "}" ]
coerce a value for use in color operation
[ "coerce", "a", "value", "for", "use", "in", "color", "operation" ]
train
https://github.com/DaemonAlchemist/atp-core/blob/47efa734b882c27aa2a59fbcba34653b4d2125c7/src/ATPCore/Lessc.php#L1564-L1593
DaemonAlchemist/atp-core
src/ATPCore/Lessc.php
Lessc.get
protected function get($name) { $current = $this->env; $isArguments = $name == $this->vPrefix . 'arguments'; while ($current) { if ($isArguments && isset($current->arguments)) { return array('list', ' ', $current->arguments); } if (isset($current->store[$name])) return $current->store[$name]; else { $current = isset($current->storeParent) ? $current->storeParent : $current->parent; } } $this->throwError("variable $name is undefined"); }
php
protected function get($name) { $current = $this->env; $isArguments = $name == $this->vPrefix . 'arguments'; while ($current) { if ($isArguments && isset($current->arguments)) { return array('list', ' ', $current->arguments); } if (isset($current->store[$name])) return $current->store[$name]; else { $current = isset($current->storeParent) ? $current->storeParent : $current->parent; } } $this->throwError("variable $name is undefined"); }
[ "protected", "function", "get", "(", "$", "name", ")", "{", "$", "current", "=", "$", "this", "->", "env", ";", "$", "isArguments", "=", "$", "name", "==", "$", "this", "->", "vPrefix", ".", "'arguments'", ";", "while", "(", "$", "current", ")", "{", "if", "(", "$", "isArguments", "&&", "isset", "(", "$", "current", "->", "arguments", ")", ")", "{", "return", "array", "(", "'list'", ",", "' '", ",", "$", "current", "->", "arguments", ")", ";", "}", "if", "(", "isset", "(", "$", "current", "->", "store", "[", "$", "name", "]", ")", ")", "return", "$", "current", "->", "store", "[", "$", "name", "]", ";", "else", "{", "$", "current", "=", "isset", "(", "$", "current", "->", "storeParent", ")", "?", "$", "current", "->", "storeParent", ":", "$", "current", "->", "parent", ";", "}", "}", "$", "this", "->", "throwError", "(", "\"variable $name is undefined\"", ")", ";", "}" ]
get the highest occurrence entry for a name
[ "get", "the", "highest", "occurrence", "entry", "for", "a", "name" ]
train
https://github.com/DaemonAlchemist/atp-core/blob/47efa734b882c27aa2a59fbcba34653b4d2125c7/src/ATPCore/Lessc.php#L1837-L1855
DaemonAlchemist/atp-core
src/ATPCore/Lessc.php
Lessc.throwError
public function throwError($msg = null) { if ($this->sourceLoc >= 0) { $this->sourceParser->throwError($msg, $this->sourceLoc); } throw new \Exception($msg); }
php
public function throwError($msg = null) { if ($this->sourceLoc >= 0) { $this->sourceParser->throwError($msg, $this->sourceLoc); } throw new \Exception($msg); }
[ "public", "function", "throwError", "(", "$", "msg", "=", "null", ")", "{", "if", "(", "$", "this", "->", "sourceLoc", ">=", "0", ")", "{", "$", "this", "->", "sourceParser", "->", "throwError", "(", "$", "msg", ",", "$", "this", "->", "sourceLoc", ")", ";", "}", "throw", "new", "\\", "Exception", "(", "$", "msg", ")", ";", "}" ]
Uses the current value of $this->count to show line and line number
[ "Uses", "the", "current", "value", "of", "$this", "-", ">", "count", "to", "show", "line", "and", "line", "number" ]
train
https://github.com/DaemonAlchemist/atp-core/blob/47efa734b882c27aa2a59fbcba34653b4d2125c7/src/ATPCore/Lessc.php#L2097-L2102
DaemonAlchemist/atp-core
src/ATPCore/Lessc.php
lessc_parser.expressionList
protected function expressionList(&$exps) { $values = array(); while ($this->expression($exp)) { $values[] = $exp; } if (count($values) == 0) return false; $exps = \ATPCore\Lessc::compressList($values, ' '); return true; }
php
protected function expressionList(&$exps) { $values = array(); while ($this->expression($exp)) { $values[] = $exp; } if (count($values) == 0) return false; $exps = \ATPCore\Lessc::compressList($values, ' '); return true; }
[ "protected", "function", "expressionList", "(", "&", "$", "exps", ")", "{", "$", "values", "=", "array", "(", ")", ";", "while", "(", "$", "this", "->", "expression", "(", "$", "exp", ")", ")", "{", "$", "values", "[", "]", "=", "$", "exp", ";", "}", "if", "(", "count", "(", "$", "values", ")", "==", "0", ")", "return", "false", ";", "$", "exps", "=", "\\", "ATPCore", "\\", "Lessc", "::", "compressList", "(", "$", "values", ",", "' '", ")", ";", "return", "true", ";", "}" ]
a list of expressions
[ "a", "list", "of", "expressions" ]
train
https://github.com/DaemonAlchemist/atp-core/blob/47efa734b882c27aa2a59fbcba34653b4d2125c7/src/ATPCore/Lessc.php#L2582-L2593
DaemonAlchemist/atp-core
src/ATPCore/Lessc.php
lessc_parser.propertyValue
public function propertyValue(&$value, $keyName = null) { $values = array(); if ($keyName !== null) $this->env->currentProperty = $keyName; $s = null; while ($this->expressionList($v)) { $values[] = $v; $s = $this->seek(); if (!$this->literal(',')) break; } if ($s) $this->seek($s); if ($keyName !== null) unset($this->env->currentProperty); if (count($values) == 0) return false; $value = \ATPCore\Lessc::compressList($values, ', '); return true; }
php
public function propertyValue(&$value, $keyName = null) { $values = array(); if ($keyName !== null) $this->env->currentProperty = $keyName; $s = null; while ($this->expressionList($v)) { $values[] = $v; $s = $this->seek(); if (!$this->literal(',')) break; } if ($s) $this->seek($s); if ($keyName !== null) unset($this->env->currentProperty); if (count($values) == 0) return false; $value = \ATPCore\Lessc::compressList($values, ', '); return true; }
[ "public", "function", "propertyValue", "(", "&", "$", "value", ",", "$", "keyName", "=", "null", ")", "{", "$", "values", "=", "array", "(", ")", ";", "if", "(", "$", "keyName", "!==", "null", ")", "$", "this", "->", "env", "->", "currentProperty", "=", "$", "keyName", ";", "$", "s", "=", "null", ";", "while", "(", "$", "this", "->", "expressionList", "(", "$", "v", ")", ")", "{", "$", "values", "[", "]", "=", "$", "v", ";", "$", "s", "=", "$", "this", "->", "seek", "(", ")", ";", "if", "(", "!", "$", "this", "->", "literal", "(", "','", ")", ")", "break", ";", "}", "if", "(", "$", "s", ")", "$", "this", "->", "seek", "(", "$", "s", ")", ";", "if", "(", "$", "keyName", "!==", "null", ")", "unset", "(", "$", "this", "->", "env", "->", "currentProperty", ")", ";", "if", "(", "count", "(", "$", "values", ")", "==", "0", ")", "return", "false", ";", "$", "value", "=", "\\", "ATPCore", "\\", "Lessc", "::", "compressList", "(", "$", "values", ",", "', '", ")", ";", "return", "true", ";", "}" ]
consume a list of values for a property
[ "consume", "a", "list", "of", "values", "for", "a", "property" ]
train
https://github.com/DaemonAlchemist/atp-core/blob/47efa734b882c27aa2a59fbcba34653b4d2125c7/src/ATPCore/Lessc.php#L2671-L2691
DaemonAlchemist/atp-core
src/ATPCore/Lessc.php
lessc_parser.openString
protected function openString($end, &$out, $nestingOpen=null, $rejectStrs = null) { $oldWhite = $this->eatWhiteDefault; $this->eatWhiteDefault = false; $stop = array("'", '"', "@{", $end); $stop = array_map(array("\ATPCore\Lessc", "preg_quote"), $stop); // $stop[] = self::$commentMulti; if (!is_null($rejectStrs)) { $stop = array_merge($stop, $rejectStrs); } $patt = '(.*?)('.implode("|", $stop).')'; $nestingLevel = 0; $content = array(); while ($this->match($patt, $m, false)) { if (!empty($m[1])) { $content[] = $m[1]; if ($nestingOpen) { $nestingLevel += substr_count($m[1], $nestingOpen); } } $tok = $m[2]; $this->count-= strlen($tok); if ($tok == $end) { if ($nestingLevel == 0) { break; } else { $nestingLevel--; } } if (($tok == "'" || $tok == '"') && $this->string($str)) { $content[] = $str; continue; } if ($tok == "@{" && $this->interpolation($inter)) { $content[] = $inter; continue; } if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) { break; } $content[] = $tok; $this->count+= strlen($tok); } $this->eatWhiteDefault = $oldWhite; if (count($content) == 0) return false; // trim the end if (is_string(end($content))) { $content[count($content) - 1] = rtrim(end($content)); } $out = array("string", "", $content); return true; }
php
protected function openString($end, &$out, $nestingOpen=null, $rejectStrs = null) { $oldWhite = $this->eatWhiteDefault; $this->eatWhiteDefault = false; $stop = array("'", '"', "@{", $end); $stop = array_map(array("\ATPCore\Lessc", "preg_quote"), $stop); // $stop[] = self::$commentMulti; if (!is_null($rejectStrs)) { $stop = array_merge($stop, $rejectStrs); } $patt = '(.*?)('.implode("|", $stop).')'; $nestingLevel = 0; $content = array(); while ($this->match($patt, $m, false)) { if (!empty($m[1])) { $content[] = $m[1]; if ($nestingOpen) { $nestingLevel += substr_count($m[1], $nestingOpen); } } $tok = $m[2]; $this->count-= strlen($tok); if ($tok == $end) { if ($nestingLevel == 0) { break; } else { $nestingLevel--; } } if (($tok == "'" || $tok == '"') && $this->string($str)) { $content[] = $str; continue; } if ($tok == "@{" && $this->interpolation($inter)) { $content[] = $inter; continue; } if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) { break; } $content[] = $tok; $this->count+= strlen($tok); } $this->eatWhiteDefault = $oldWhite; if (count($content) == 0) return false; // trim the end if (is_string(end($content))) { $content[count($content) - 1] = rtrim(end($content)); } $out = array("string", "", $content); return true; }
[ "protected", "function", "openString", "(", "$", "end", ",", "&", "$", "out", ",", "$", "nestingOpen", "=", "null", ",", "$", "rejectStrs", "=", "null", ")", "{", "$", "oldWhite", "=", "$", "this", "->", "eatWhiteDefault", ";", "$", "this", "->", "eatWhiteDefault", "=", "false", ";", "$", "stop", "=", "array", "(", "\"'\"", ",", "'\"'", ",", "\"@{\"", ",", "$", "end", ")", ";", "$", "stop", "=", "array_map", "(", "array", "(", "\"\\ATPCore\\Lessc\"", ",", "\"preg_quote\"", ")", ",", "$", "stop", ")", ";", "// $stop[] = self::$commentMulti;\r", "if", "(", "!", "is_null", "(", "$", "rejectStrs", ")", ")", "{", "$", "stop", "=", "array_merge", "(", "$", "stop", ",", "$", "rejectStrs", ")", ";", "}", "$", "patt", "=", "'(.*?)('", ".", "implode", "(", "\"|\"", ",", "$", "stop", ")", ".", "')'", ";", "$", "nestingLevel", "=", "0", ";", "$", "content", "=", "array", "(", ")", ";", "while", "(", "$", "this", "->", "match", "(", "$", "patt", ",", "$", "m", ",", "false", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "m", "[", "1", "]", ")", ")", "{", "$", "content", "[", "]", "=", "$", "m", "[", "1", "]", ";", "if", "(", "$", "nestingOpen", ")", "{", "$", "nestingLevel", "+=", "substr_count", "(", "$", "m", "[", "1", "]", ",", "$", "nestingOpen", ")", ";", "}", "}", "$", "tok", "=", "$", "m", "[", "2", "]", ";", "$", "this", "->", "count", "-=", "strlen", "(", "$", "tok", ")", ";", "if", "(", "$", "tok", "==", "$", "end", ")", "{", "if", "(", "$", "nestingLevel", "==", "0", ")", "{", "break", ";", "}", "else", "{", "$", "nestingLevel", "--", ";", "}", "}", "if", "(", "(", "$", "tok", "==", "\"'\"", "||", "$", "tok", "==", "'\"'", ")", "&&", "$", "this", "->", "string", "(", "$", "str", ")", ")", "{", "$", "content", "[", "]", "=", "$", "str", ";", "continue", ";", "}", "if", "(", "$", "tok", "==", "\"@{\"", "&&", "$", "this", "->", "interpolation", "(", "$", "inter", ")", ")", "{", "$", "content", "[", "]", "=", "$", "inter", ";", "continue", ";", "}", "if", "(", "!", "empty", "(", "$", "rejectStrs", ")", "&&", "in_array", "(", "$", "tok", ",", "$", "rejectStrs", ")", ")", "{", "break", ";", "}", "$", "content", "[", "]", "=", "$", "tok", ";", "$", "this", "->", "count", "+=", "strlen", "(", "$", "tok", ")", ";", "}", "$", "this", "->", "eatWhiteDefault", "=", "$", "oldWhite", ";", "if", "(", "count", "(", "$", "content", ")", "==", "0", ")", "return", "false", ";", "// trim the end\r", "if", "(", "is_string", "(", "end", "(", "$", "content", ")", ")", ")", "{", "$", "content", "[", "count", "(", "$", "content", ")", "-", "1", "]", "=", "rtrim", "(", "end", "(", "$", "content", ")", ")", ";", "}", "$", "out", "=", "array", "(", "\"string\"", ",", "\"\"", ",", "$", "content", ")", ";", "return", "true", ";", "}" ]
an unbounded string stopped by $end
[ "an", "unbounded", "string", "stopped", "by", "$end" ]
train
https://github.com/DaemonAlchemist/atp-core/blob/47efa734b882c27aa2a59fbcba34653b4d2125c7/src/ATPCore/Lessc.php#L2848-L2913