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_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
PhoxPHP/Glider
src/Console/Command/Seed.php
Seed.runSeed
protected function runSeed(String $className) { if (!class_exists($className)) { throw new SeederNotFoundException( sprintf( '[%s] seeder class not found.', $className ) ); } $seeder = new $className(); return $seeder->run(); }
php
protected function runSeed(String $className) { if (!class_exists($className)) { throw new SeederNotFoundException( sprintf( '[%s] seeder class not found.', $className ) ); } $seeder = new $className(); return $seeder->run(); }
Runs a single seeder. @param $className <String> @access protected @return <void>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Console/Command/Seed.php#L155-L168
PhoxPHP/Glider
src/Console/Command/Seed.php
Seed.getSeeders
protected function getSeeders() : Array { $seeders = []; $seedsDirectory = $this->cmd->getConfigOpt('seeds_storage'); foreach(glob($seedsDirectory . '/*' . '.php') as $file) { $seeders[] = $file; } return $seeders; }
php
protected function getSeeders() : Array { $seeders = []; $seedsDirectory = $this->cmd->getConfigOpt('seeds_storage'); foreach(glob($seedsDirectory . '/*' . '.php') as $file) { $seeders[] = $file; } return $seeders; }
Returns an array of seeder files. @access protected @return <Array>
https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Console/Command/Seed.php#L176-L185
ddvphp/wechat
org/old_version/snoopy.class.php
Snoopy.fetch
function fetch($URI) { //preg_match("|^([^:]+)://([^:/]+)(:[\d]+)*(.*)|",$URI,$URI_PARTS); $URI_PARTS = parse_url($URI); if (!empty($URI_PARTS["user"])) $this->user = $URI_PARTS["user"]; if (!empty($URI_PARTS["pass"])) $this->pass = $URI_PARTS["pass"]; if (empty($URI_PARTS["query"])) $URI_PARTS["query"] = ''; if (empty($URI_PARTS["path"])) $URI_PARTS["path"] = ''; switch(strtolower($URI_PARTS["scheme"])) { case "http": $this->host = $URI_PARTS["host"]; if(!empty($URI_PARTS["port"])) $this->port = $URI_PARTS["port"]; if($this->_connect($fp)) { if($this->_isproxy) { // using proxy, send entire URI $this->_httprequest($URI,$fp,$URI,$this->_httpmethod); } else { $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); // no proxy, send only the path $this->_httprequest($path, $fp, $URI, $this->_httpmethod); } $this->_disconnect($fp); if($this->_redirectaddr) { /* url was redirected, check if we've hit the max depth */ if($this->maxredirs > $this->_redirectdepth) { // only follow redirect if it's on this site, or offsiteok is true if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) { /* follow the redirect */ $this->_redirectdepth++; $this->lastredirectaddr=$this->_redirectaddr; $this->fetch($this->_redirectaddr); } } } if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) { $frameurls = $this->_frameurls; $this->_frameurls = array(); while(list(,$frameurl) = each($frameurls)) { if($this->_framedepth < $this->maxframes) { $this->fetch($frameurl); $this->_framedepth++; } else break; } } } else { return false; } return true; break; case "https": if (!function_exists('curl_init')) { if(!$this->curl_path) return false; if(function_exists("is_executable")) if (!is_executable($this->curl_path)) return false; } $this->host = $URI_PARTS["host"]; if(!empty($URI_PARTS["port"])) $this->port = $URI_PARTS["port"]; if($this->_isproxy) { // using proxy, send entire URI $this->_httpsrequest($URI,$URI,$this->_httpmethod); } else { $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); // no proxy, send only the path $this->_httpsrequest($path, $URI, $this->_httpmethod); } if($this->_redirectaddr) { /* url was redirected, check if we've hit the max depth */ if($this->maxredirs > $this->_redirectdepth) { // only follow redirect if it's on this site, or offsiteok is true if(preg_match("|^https://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) { /* follow the redirect */ $this->_redirectdepth++; $this->lastredirectaddr=$this->_redirectaddr; $this->fetch($this->_redirectaddr); } } } if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) { $frameurls = $this->_frameurls; $this->_frameurls = array(); while(list(,$frameurl) = each($frameurls)) { if($this->_framedepth < $this->maxframes) { $this->fetch($frameurl); $this->_framedepth++; } else break; } } return true; break; default: // not a valid protocol $this->error = 'Invalid protocol "'.$URI_PARTS["scheme"].'"\n'; return false; break; } return true; }
php
function fetch($URI) { //preg_match("|^([^:]+)://([^:/]+)(:[\d]+)*(.*)|",$URI,$URI_PARTS); $URI_PARTS = parse_url($URI); if (!empty($URI_PARTS["user"])) $this->user = $URI_PARTS["user"]; if (!empty($URI_PARTS["pass"])) $this->pass = $URI_PARTS["pass"]; if (empty($URI_PARTS["query"])) $URI_PARTS["query"] = ''; if (empty($URI_PARTS["path"])) $URI_PARTS["path"] = ''; switch(strtolower($URI_PARTS["scheme"])) { case "http": $this->host = $URI_PARTS["host"]; if(!empty($URI_PARTS["port"])) $this->port = $URI_PARTS["port"]; if($this->_connect($fp)) { if($this->_isproxy) { // using proxy, send entire URI $this->_httprequest($URI,$fp,$URI,$this->_httpmethod); } else { $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); // no proxy, send only the path $this->_httprequest($path, $fp, $URI, $this->_httpmethod); } $this->_disconnect($fp); if($this->_redirectaddr) { /* url was redirected, check if we've hit the max depth */ if($this->maxredirs > $this->_redirectdepth) { // only follow redirect if it's on this site, or offsiteok is true if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) { /* follow the redirect */ $this->_redirectdepth++; $this->lastredirectaddr=$this->_redirectaddr; $this->fetch($this->_redirectaddr); } } } if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) { $frameurls = $this->_frameurls; $this->_frameurls = array(); while(list(,$frameurl) = each($frameurls)) { if($this->_framedepth < $this->maxframes) { $this->fetch($frameurl); $this->_framedepth++; } else break; } } } else { return false; } return true; break; case "https": if (!function_exists('curl_init')) { if(!$this->curl_path) return false; if(function_exists("is_executable")) if (!is_executable($this->curl_path)) return false; } $this->host = $URI_PARTS["host"]; if(!empty($URI_PARTS["port"])) $this->port = $URI_PARTS["port"]; if($this->_isproxy) { // using proxy, send entire URI $this->_httpsrequest($URI,$URI,$this->_httpmethod); } else { $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); // no proxy, send only the path $this->_httpsrequest($path, $URI, $this->_httpmethod); } if($this->_redirectaddr) { /* url was redirected, check if we've hit the max depth */ if($this->maxredirs > $this->_redirectdepth) { // only follow redirect if it's on this site, or offsiteok is true if(preg_match("|^https://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) { /* follow the redirect */ $this->_redirectdepth++; $this->lastredirectaddr=$this->_redirectaddr; $this->fetch($this->_redirectaddr); } } } if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) { $frameurls = $this->_frameurls; $this->_frameurls = array(); while(list(,$frameurl) = each($frameurls)) { if($this->_framedepth < $this->maxframes) { $this->fetch($frameurl); $this->_framedepth++; } else break; } } return true; break; default: // not a valid protocol $this->error = 'Invalid protocol "'.$URI_PARTS["scheme"].'"\n'; return false; break; } return true; }
/*======================================================================*\ Function: fetch Purpose: fetch the contents of a web page (and possibly other protocols in the future like ftp, nntp, gopher, etc.) Input: $URI the location of the page to fetch Output: $this->results the output text from the fetch \*======================================================================
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/snoopy.class.php#L122-L261
ddvphp/wechat
org/old_version/snoopy.class.php
Snoopy.submit
function submit($URI, $formvars="", $formfiles="") { unset($postdata); $postdata = $this->_prepare_post_body($formvars, $formfiles); $URI_PARTS = parse_url($URI); if (!empty($URI_PARTS["user"])) $this->user = $URI_PARTS["user"]; if (!empty($URI_PARTS["pass"])) $this->pass = $URI_PARTS["pass"]; if (empty($URI_PARTS["query"])) $URI_PARTS["query"] = ''; if (empty($URI_PARTS["path"])) $URI_PARTS["path"] = ''; switch(strtolower($URI_PARTS["scheme"])) { case "http": $this->host = $URI_PARTS["host"]; if(!empty($URI_PARTS["port"])) $this->port = $URI_PARTS["port"]; if($this->_connect($fp)) { if($this->_isproxy) { // using proxy, send entire URI $this->_httprequest($URI,$fp,$URI,$this->_submit_method,$this->_submit_type,$postdata); } else { $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); // no proxy, send only the path $this->_httprequest($path, $fp, $URI, $this->_submit_method, $this->_submit_type, $postdata); } $this->_disconnect($fp); if($this->_redirectaddr) { /* url was redirected, check if we've hit the max depth */ if($this->maxredirs > $this->_redirectdepth) { if(!preg_match("|^".$URI_PARTS["scheme"]."://|", $this->_redirectaddr)) $this->_redirectaddr = $this->_expandlinks($this->_redirectaddr,$URI_PARTS["scheme"]."://".$URI_PARTS["host"]); // only follow redirect if it's on this site, or offsiteok is true if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) { /* follow the redirect */ $this->_redirectdepth++; $this->lastredirectaddr=$this->_redirectaddr; if( strpos( $this->_redirectaddr, "?" ) > 0 ) $this->fetch($this->_redirectaddr); // the redirect has changed the request method from post to get else $this->submit($this->_redirectaddr,$formvars, $formfiles); } } } if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) { $frameurls = $this->_frameurls; $this->_frameurls = array(); while(list(,$frameurl) = each($frameurls)) { if($this->_framedepth < $this->maxframes) { $this->fetch($frameurl); $this->_framedepth++; } else break; } } } else { return false; } return true; break; case "https": if (!function_exists('curl_init')) { if(!$this->curl_path) return false; if(function_exists("is_executable")) if (!is_executable($this->curl_path)) return false; } $this->host = $URI_PARTS["host"]; if(!empty($URI_PARTS["port"])) $this->port = $URI_PARTS["port"]; if($this->_isproxy) { // using proxy, send entire URI $this->_httpsrequest($URI, $URI, $this->_submit_method, $this->_submit_type, $postdata); } else { $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); // no proxy, send only the path $this->_httpsrequest($path, $URI, $this->_submit_method, $this->_submit_type, $postdata); } if($this->_redirectaddr) { /* url was redirected, check if we've hit the max depth */ if($this->maxredirs > $this->_redirectdepth) { if(!preg_match("|^".$URI_PARTS["scheme"]."://|", $this->_redirectaddr)) $this->_redirectaddr = $this->_expandlinks($this->_redirectaddr,$URI_PARTS["scheme"]."://".$URI_PARTS["host"]); // only follow redirect if it's on this site, or offsiteok is true if(preg_match("|^https://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) { /* follow the redirect */ $this->_redirectdepth++; $this->lastredirectaddr=$this->_redirectaddr; if( strpos( $this->_redirectaddr, "?" ) > 0 ) $this->fetch($this->_redirectaddr); // the redirect has changed the request method from post to get else $this->submit($this->_redirectaddr,$formvars, $formfiles); } } } if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) { $frameurls = $this->_frameurls; $this->_frameurls = array(); while(list(,$frameurl) = each($frameurls)) { if($this->_framedepth < $this->maxframes) { $this->fetch($frameurl); $this->_framedepth++; } else break; } } return true; break; default: // not a valid protocol $this->error = 'Invalid protocol "'.$URI_PARTS["scheme"].'"\n'; return false; break; } return true; }
php
function submit($URI, $formvars="", $formfiles="") { unset($postdata); $postdata = $this->_prepare_post_body($formvars, $formfiles); $URI_PARTS = parse_url($URI); if (!empty($URI_PARTS["user"])) $this->user = $URI_PARTS["user"]; if (!empty($URI_PARTS["pass"])) $this->pass = $URI_PARTS["pass"]; if (empty($URI_PARTS["query"])) $URI_PARTS["query"] = ''; if (empty($URI_PARTS["path"])) $URI_PARTS["path"] = ''; switch(strtolower($URI_PARTS["scheme"])) { case "http": $this->host = $URI_PARTS["host"]; if(!empty($URI_PARTS["port"])) $this->port = $URI_PARTS["port"]; if($this->_connect($fp)) { if($this->_isproxy) { // using proxy, send entire URI $this->_httprequest($URI,$fp,$URI,$this->_submit_method,$this->_submit_type,$postdata); } else { $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); // no proxy, send only the path $this->_httprequest($path, $fp, $URI, $this->_submit_method, $this->_submit_type, $postdata); } $this->_disconnect($fp); if($this->_redirectaddr) { /* url was redirected, check if we've hit the max depth */ if($this->maxredirs > $this->_redirectdepth) { if(!preg_match("|^".$URI_PARTS["scheme"]."://|", $this->_redirectaddr)) $this->_redirectaddr = $this->_expandlinks($this->_redirectaddr,$URI_PARTS["scheme"]."://".$URI_PARTS["host"]); // only follow redirect if it's on this site, or offsiteok is true if(preg_match("|^http://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) { /* follow the redirect */ $this->_redirectdepth++; $this->lastredirectaddr=$this->_redirectaddr; if( strpos( $this->_redirectaddr, "?" ) > 0 ) $this->fetch($this->_redirectaddr); // the redirect has changed the request method from post to get else $this->submit($this->_redirectaddr,$formvars, $formfiles); } } } if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) { $frameurls = $this->_frameurls; $this->_frameurls = array(); while(list(,$frameurl) = each($frameurls)) { if($this->_framedepth < $this->maxframes) { $this->fetch($frameurl); $this->_framedepth++; } else break; } } } else { return false; } return true; break; case "https": if (!function_exists('curl_init')) { if(!$this->curl_path) return false; if(function_exists("is_executable")) if (!is_executable($this->curl_path)) return false; } $this->host = $URI_PARTS["host"]; if(!empty($URI_PARTS["port"])) $this->port = $URI_PARTS["port"]; if($this->_isproxy) { // using proxy, send entire URI $this->_httpsrequest($URI, $URI, $this->_submit_method, $this->_submit_type, $postdata); } else { $path = $URI_PARTS["path"].($URI_PARTS["query"] ? "?".$URI_PARTS["query"] : ""); // no proxy, send only the path $this->_httpsrequest($path, $URI, $this->_submit_method, $this->_submit_type, $postdata); } if($this->_redirectaddr) { /* url was redirected, check if we've hit the max depth */ if($this->maxredirs > $this->_redirectdepth) { if(!preg_match("|^".$URI_PARTS["scheme"]."://|", $this->_redirectaddr)) $this->_redirectaddr = $this->_expandlinks($this->_redirectaddr,$URI_PARTS["scheme"]."://".$URI_PARTS["host"]); // only follow redirect if it's on this site, or offsiteok is true if(preg_match("|^https://".preg_quote($this->host)."|i",$this->_redirectaddr) || $this->offsiteok) { /* follow the redirect */ $this->_redirectdepth++; $this->lastredirectaddr=$this->_redirectaddr; if( strpos( $this->_redirectaddr, "?" ) > 0 ) $this->fetch($this->_redirectaddr); // the redirect has changed the request method from post to get else $this->submit($this->_redirectaddr,$formvars, $formfiles); } } } if($this->_framedepth < $this->maxframes && count($this->_frameurls) > 0) { $frameurls = $this->_frameurls; $this->_frameurls = array(); while(list(,$frameurl) = each($frameurls)) { if($this->_framedepth < $this->maxframes) { $this->fetch($frameurl); $this->_framedepth++; } else break; } } return true; break; default: // not a valid protocol $this->error = 'Invalid protocol "'.$URI_PARTS["scheme"].'"\n'; return false; break; } return true; }
/*======================================================================*\ Function: submit Purpose: submit an http form Input: $URI the location to post the data $formvars the formvars to use. format: $formvars["var"] = "val"; $formfiles an array of files to submit format: $formfiles["var"] = "/dir/filename.ext"; Output: $this->results the text output from the post \*======================================================================
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/snoopy.class.php#L274-L428
ddvphp/wechat
org/old_version/snoopy.class.php
Snoopy.fetchlinks
function fetchlinks($URI) { if ($this->fetch($URI)) { if($this->lastredirectaddr) $URI = $this->lastredirectaddr; if(is_array($this->results)) { for($x=0;$x<count($this->results);$x++) $this->results[$x] = $this->_striplinks($this->results[$x]); } else $this->results = $this->_striplinks($this->results); if($this->expandlinks) $this->results = $this->_expandlinks($this->results, $URI); return true; } else return false; }
php
function fetchlinks($URI) { if ($this->fetch($URI)) { if($this->lastredirectaddr) $URI = $this->lastredirectaddr; if(is_array($this->results)) { for($x=0;$x<count($this->results);$x++) $this->results[$x] = $this->_striplinks($this->results[$x]); } else $this->results = $this->_striplinks($this->results); if($this->expandlinks) $this->results = $this->_expandlinks($this->results, $URI); return true; } else return false; }
/*======================================================================*\ Function: fetchlinks Purpose: fetch the links from a web page Input: $URI where you are fetching from Output: $this->results an array of the URLs \*======================================================================
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/snoopy.class.php#L437-L457
ddvphp/wechat
org/old_version/snoopy.class.php
Snoopy.fetchform
function fetchform($URI) { if ($this->fetch($URI)) { if(is_array($this->results)) { for($x=0;$x<count($this->results);$x++) $this->results[$x] = $this->_stripform($this->results[$x]); } else $this->results = $this->_stripform($this->results); return true; } else return false; }
php
function fetchform($URI) { if ($this->fetch($URI)) { if(is_array($this->results)) { for($x=0;$x<count($this->results);$x++) $this->results[$x] = $this->_stripform($this->results[$x]); } else $this->results = $this->_stripform($this->results); return true; } else return false; }
/*======================================================================*\ Function: fetchform Purpose: fetch the form elements from a web page Input: $URI where you are fetching from Output: $this->results the resulting html form \*======================================================================
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/snoopy.class.php#L466-L484
ddvphp/wechat
org/old_version/snoopy.class.php
Snoopy.fetchtext
function fetchtext($URI) { if($this->fetch($URI)) { if(is_array($this->results)) { for($x=0;$x<count($this->results);$x++) $this->results[$x] = $this->_striptext($this->results[$x]); } else $this->results = $this->_striptext($this->results); return true; } else return false; }
php
function fetchtext($URI) { if($this->fetch($URI)) { if(is_array($this->results)) { for($x=0;$x<count($this->results);$x++) $this->results[$x] = $this->_striptext($this->results[$x]); } else $this->results = $this->_striptext($this->results); return true; } else return false; }
/*======================================================================*\ Function: fetchtext Purpose: fetch the text from a web page, stripping the links Input: $URI where you are fetching from Output: $this->results the text from the web page \*======================================================================
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/snoopy.class.php#L494-L509
ddvphp/wechat
org/old_version/snoopy.class.php
Snoopy._striptext
function _striptext($document) { // I didn't use preg eval (//e) since that is only available in PHP 4.0. // so, list your entities one by one here. I included some of the // more common ones. $search = array("'<script[^>]*?>.*?</script>'si", // strip out javascript "'<[\/\!]*?[^<>]*?>'si", // strip out html tags "'([\r\n])[\s]+'", // strip out white space "'&(quot|#34|#034|#x22);'i", // replace html entities "'&(amp|#38|#038|#x26);'i", // added hexadecimal values "'&(lt|#60|#060|#x3c);'i", "'&(gt|#62|#062|#x3e);'i", "'&(nbsp|#160|#xa0);'i", "'&(iexcl|#161);'i", "'&(cent|#162);'i", "'&(pound|#163);'i", "'&(copy|#169);'i", "'&(reg|#174);'i", "'&(deg|#176);'i", "'&(#39|#039|#x27);'", "'&(euro|#8364);'i", // europe "'&a(uml|UML);'", // german "'&o(uml|UML);'", "'&u(uml|UML);'", "'&A(uml|UML);'", "'&O(uml|UML);'", "'&U(uml|UML);'", "'&szlig;'i", ); $replace = array( "", "", "\\1", "\"", "&", "<", ">", " ", chr(161), chr(162), chr(163), chr(169), chr(174), chr(176), chr(39), chr(128), "�", "�", "�", "�", "�", "�", "�", ); $text = preg_replace($search,$replace,$document); return $text; }
php
function _striptext($document) { // I didn't use preg eval (//e) since that is only available in PHP 4.0. // so, list your entities one by one here. I included some of the // more common ones. $search = array("'<script[^>]*?>.*?</script>'si", // strip out javascript "'<[\/\!]*?[^<>]*?>'si", // strip out html tags "'([\r\n])[\s]+'", // strip out white space "'&(quot|#34|#034|#x22);'i", // replace html entities "'&(amp|#38|#038|#x26);'i", // added hexadecimal values "'&(lt|#60|#060|#x3c);'i", "'&(gt|#62|#062|#x3e);'i", "'&(nbsp|#160|#xa0);'i", "'&(iexcl|#161);'i", "'&(cent|#162);'i", "'&(pound|#163);'i", "'&(copy|#169);'i", "'&(reg|#174);'i", "'&(deg|#176);'i", "'&(#39|#039|#x27);'", "'&(euro|#8364);'i", // europe "'&a(uml|UML);'", // german "'&o(uml|UML);'", "'&u(uml|UML);'", "'&A(uml|UML);'", "'&O(uml|UML);'", "'&U(uml|UML);'", "'&szlig;'i", ); $replace = array( "", "", "\\1", "\"", "&", "<", ">", " ", chr(161), chr(162), chr(163), chr(169), chr(174), chr(176), chr(39), chr(128), "�", "�", "�", "�", "�", "�", "�", ); $text = preg_replace($search,$replace,$document); return $text; }
/*======================================================================*\ Function: _striptext Purpose: strip the text from an html document Input: $document document to strip. Output: $text the resulting text \*======================================================================
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/snoopy.class.php#L671-L730
ddvphp/wechat
org/old_version/snoopy.class.php
Snoopy._httpsrequest
function _httpsrequest($url,$URI,$http_method,$content_type="",$body="") { if($this->passcookies && $this->_redirectaddr) $this->setcookies(); $headers = array(); $URI_PARTS = parse_url($URI); if(empty($url)) $url = "/"; // GET ... header not needed for curl //$headers[] = $http_method." ".$url." ".$this->_httpversion; if(!empty($this->agent)) $headers[] = "User-Agent: ".$this->agent; if(!empty($this->host)) if(!empty($this->port) && $this->port!=80) $headers[] = "Host: ".$this->host.":".$this->port; else $headers[] = "Host: ".$this->host; if(!empty($this->accept)) $headers[] = "Accept: ".$this->accept; if(!empty($this->referer)) $headers[] = "Referer: ".$this->referer; if(!empty($this->cookies)) { if(!is_array($this->cookies)) $this->cookies = (array)$this->cookies; reset($this->cookies); if ( count($this->cookies) > 0 ) { $cookie_str = 'Cookie: '; foreach ( $this->cookies as $cookieKey => $cookieVal ) { $cookie_str .= $cookieKey."=".urlencode($cookieVal)."; "; } $headers[] = substr($cookie_str,0,-2); } } if(!empty($this->rawheaders)) { if(!is_array($this->rawheaders)) $this->rawheaders = (array)$this->rawheaders; while(list($headerKey,$headerVal) = each($this->rawheaders)) $headers[] = $headerKey.": ".$headerVal; } if(!empty($content_type)) { if ($content_type == "multipart/form-data") $headers[] = "Content-type: $content_type; boundary=".$this->_mime_boundary; else $headers[] = "Content-type: $content_type"; } if(!empty($body)) $headers[] = "Content-length: ".strlen($body); if(!empty($this->user) || !empty($this->pass)) $headers[] = "Authorization: BASIC ".base64_encode($this->user.":".$this->pass); if (function_exists('curl_init')) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $URI); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_SSLVERSION,3); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_TIMEOUT, $this->read_timeout); if(!empty($body)) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); } $data = curl_exec($ch); if ($data === false) { $this->error = "Error: Curl error ".curl_error($ch); return false; } $parts = explode("\r\n\r\n",$data,2); $result_headers = explode("\r\n",$parts[0]); $results = $parts[1]; unset($parts); } else { for($curr_header = 0; $curr_header < count($headers); $curr_header++) { $safer_header = strtr( $headers[$curr_header], "\"", " " ); $cmdline_params .= " -H \"".$safer_header."\""; } if(!empty($body)) $cmdline_params .= " -d \"$body\""; if($this->read_timeout > 0) $cmdline_params .= " -m ".$this->read_timeout; $headerfile = tempnam($temp_dir, "sno"); exec($this->curl_path." -k -D \"$headerfile\"".$cmdline_params." \"".escapeshellcmd($URI)."\"",$results,$return); if($return) { $this->error = "Error: cURL could not retrieve the document, error $return."; return false; } $results = implode("\r\n",$results); $result_headers = file("$headerfile"); } $this->_redirectaddr = false; unset($this->headers); for($currentHeader = 0; $currentHeader < count($result_headers); $currentHeader++) { // if a header begins with Location: or URI:, set the redirect if(preg_match("/^(Location: |URI: )/i",$result_headers[$currentHeader])) { // get URL portion of the redirect preg_match("/^(Location: |URI:)\s+(.*)/",chop($result_headers[$currentHeader]),$matches); // look for :// in the Location header to see if hostname is included if (!empty($matches)) { if(!preg_match("|\:\/\/|",$matches[2])) { // no host in the path, so prepend $this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host; // eliminate double slash if(!preg_match("|^/|",$matches[2])) $this->_redirectaddr .= "/".$matches[2]; else $this->_redirectaddr .= $matches[2]; } else $this->_redirectaddr = $matches[2]; } } if(preg_match("|^HTTP/|",$result_headers[$currentHeader])) $this->response_code = $result_headers[$currentHeader]; $this->headers[] = $result_headers[$currentHeader]; } // check if there is a a redirect meta tag if(preg_match("'<meta[\s]*http-equiv[^>]*?content[\s]*=[\s]*[\"\']?\d+;[\s]*URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match)) { $this->_redirectaddr = $this->_expandlinks($match[1],$URI); } // have we hit our frame depth and is there frame src to fetch? if(($this->_framedepth < $this->maxframes) && preg_match_all("'<frame\s+.*src[\s]*=[\'\"]?([^\'\"\>]+)'i",$results,$match)) { $this->results[] = $results; for($x=0; $x<count($match[1]); $x++) $this->_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host); } // have we already fetched framed content? elseif(is_array($this->results)) $this->results[] = $results; // no framed content else $this->results = $results; if (isset($headerfile) && file_exists($headerfile)) unlink($headerfile); return true; }
php
function _httpsrequest($url,$URI,$http_method,$content_type="",$body="") { if($this->passcookies && $this->_redirectaddr) $this->setcookies(); $headers = array(); $URI_PARTS = parse_url($URI); if(empty($url)) $url = "/"; // GET ... header not needed for curl //$headers[] = $http_method." ".$url." ".$this->_httpversion; if(!empty($this->agent)) $headers[] = "User-Agent: ".$this->agent; if(!empty($this->host)) if(!empty($this->port) && $this->port!=80) $headers[] = "Host: ".$this->host.":".$this->port; else $headers[] = "Host: ".$this->host; if(!empty($this->accept)) $headers[] = "Accept: ".$this->accept; if(!empty($this->referer)) $headers[] = "Referer: ".$this->referer; if(!empty($this->cookies)) { if(!is_array($this->cookies)) $this->cookies = (array)$this->cookies; reset($this->cookies); if ( count($this->cookies) > 0 ) { $cookie_str = 'Cookie: '; foreach ( $this->cookies as $cookieKey => $cookieVal ) { $cookie_str .= $cookieKey."=".urlencode($cookieVal)."; "; } $headers[] = substr($cookie_str,0,-2); } } if(!empty($this->rawheaders)) { if(!is_array($this->rawheaders)) $this->rawheaders = (array)$this->rawheaders; while(list($headerKey,$headerVal) = each($this->rawheaders)) $headers[] = $headerKey.": ".$headerVal; } if(!empty($content_type)) { if ($content_type == "multipart/form-data") $headers[] = "Content-type: $content_type; boundary=".$this->_mime_boundary; else $headers[] = "Content-type: $content_type"; } if(!empty($body)) $headers[] = "Content-length: ".strlen($body); if(!empty($this->user) || !empty($this->pass)) $headers[] = "Authorization: BASIC ".base64_encode($this->user.":".$this->pass); if (function_exists('curl_init')) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $URI); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_SSLVERSION,3); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_TIMEOUT, $this->read_timeout); if(!empty($body)) { curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); } $data = curl_exec($ch); if ($data === false) { $this->error = "Error: Curl error ".curl_error($ch); return false; } $parts = explode("\r\n\r\n",$data,2); $result_headers = explode("\r\n",$parts[0]); $results = $parts[1]; unset($parts); } else { for($curr_header = 0; $curr_header < count($headers); $curr_header++) { $safer_header = strtr( $headers[$curr_header], "\"", " " ); $cmdline_params .= " -H \"".$safer_header."\""; } if(!empty($body)) $cmdline_params .= " -d \"$body\""; if($this->read_timeout > 0) $cmdline_params .= " -m ".$this->read_timeout; $headerfile = tempnam($temp_dir, "sno"); exec($this->curl_path." -k -D \"$headerfile\"".$cmdline_params." \"".escapeshellcmd($URI)."\"",$results,$return); if($return) { $this->error = "Error: cURL could not retrieve the document, error $return."; return false; } $results = implode("\r\n",$results); $result_headers = file("$headerfile"); } $this->_redirectaddr = false; unset($this->headers); for($currentHeader = 0; $currentHeader < count($result_headers); $currentHeader++) { // if a header begins with Location: or URI:, set the redirect if(preg_match("/^(Location: |URI: )/i",$result_headers[$currentHeader])) { // get URL portion of the redirect preg_match("/^(Location: |URI:)\s+(.*)/",chop($result_headers[$currentHeader]),$matches); // look for :// in the Location header to see if hostname is included if (!empty($matches)) { if(!preg_match("|\:\/\/|",$matches[2])) { // no host in the path, so prepend $this->_redirectaddr = $URI_PARTS["scheme"]."://".$this->host; // eliminate double slash if(!preg_match("|^/|",$matches[2])) $this->_redirectaddr .= "/".$matches[2]; else $this->_redirectaddr .= $matches[2]; } else $this->_redirectaddr = $matches[2]; } } if(preg_match("|^HTTP/|",$result_headers[$currentHeader])) $this->response_code = $result_headers[$currentHeader]; $this->headers[] = $result_headers[$currentHeader]; } // check if there is a a redirect meta tag if(preg_match("'<meta[\s]*http-equiv[^>]*?content[\s]*=[\s]*[\"\']?\d+;[\s]*URL[\s]*=[\s]*([^\"\']*?)[\"\']?>'i",$results,$match)) { $this->_redirectaddr = $this->_expandlinks($match[1],$URI); } // have we hit our frame depth and is there frame src to fetch? if(($this->_framedepth < $this->maxframes) && preg_match_all("'<frame\s+.*src[\s]*=[\'\"]?([^\'\"\>]+)'i",$results,$match)) { $this->results[] = $results; for($x=0; $x<count($match[1]); $x++) $this->_frameurls[] = $this->_expandlinks($match[1][$x],$URI_PARTS["scheme"]."://".$this->host); } // have we already fetched framed content? elseif(is_array($this->results)) $this->results[] = $results; // no framed content else $this->results = $results; if (isset($headerfile) && file_exists($headerfile)) unlink($headerfile); return true; }
/*======================================================================*\ Function: _httpsrequest Purpose: go get the https data from the server using curl Input: $url the url to fetch $URI the full URI $body body contents to send if any (POST) Output: \*======================================================================
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/snoopy.class.php#L945-L1107
ddvphp/wechat
org/old_version/snoopy.class.php
Snoopy._connect
function _connect(&$fp) { if(!empty($this->proxy_host) && !empty($this->proxy_port)) { $this->_isproxy = true; $host = $this->proxy_host; $port = $this->proxy_port; } else { $host = $this->host; $port = $this->port; } $this->status = 0; if($fp = fsockopen( $host, $port, $errno, $errstr, $this->_fp_timeout )) { // socket connection succeeded return true; } else { // socket connection failed $this->status = $errno; switch($errno) { case -3: $this->error="socket creation failed (-3)"; case -4: $this->error="dns lookup failure (-4)"; case -5: $this->error="connection refused or timed out (-5)"; default: $this->error="connection failed (".$errno.")"; } return false; } }
php
function _connect(&$fp) { if(!empty($this->proxy_host) && !empty($this->proxy_port)) { $this->_isproxy = true; $host = $this->proxy_host; $port = $this->proxy_port; } else { $host = $this->host; $port = $this->port; } $this->status = 0; if($fp = fsockopen( $host, $port, $errno, $errstr, $this->_fp_timeout )) { // socket connection succeeded return true; } else { // socket connection failed $this->status = $errno; switch($errno) { case -3: $this->error="socket creation failed (-3)"; case -4: $this->error="dns lookup failure (-4)"; case -5: $this->error="connection refused or timed out (-5)"; default: $this->error="connection failed (".$errno.")"; } return false; } }
/*======================================================================*\ Function: _connect Purpose: make a socket connection Input: $fp file pointer \*======================================================================
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/snoopy.class.php#L1148-L1194
ddvphp/wechat
org/old_version/snoopy.class.php
Snoopy._prepare_post_body
function _prepare_post_body($formvars, $formfiles) { settype($formvars, "array"); settype($formfiles, "array"); $postdata = ''; if (count($formvars) == 0 && count($formfiles) == 0) return; if (is_string($formvars)) return $formvars; if((count($formvars) == 1) && isset($formvars[0])) return $formvars[0]; switch ($this->_submit_type) { case "application/x-www-form-urlencoded": reset($formvars); while(list($key,$val) = each($formvars)) { if (is_array($val) || is_object($val)) { while (list($cur_key, $cur_val) = each($val)) { $postdata .= urlencode($key)."[]=".urlencode($cur_val)."&"; } } else $postdata .= urlencode($key)."=".urlencode($val)."&"; } break; case "multipart/form-data": $this->_mime_boundary = "--------".md5(uniqid(microtime())); reset($formvars); while(list($key,$val) = each($formvars)) { if (is_array($val) || is_object($val)) { while (list($cur_key, $cur_val) = each($val)) { $postdata .= "--".$this->_mime_boundary."\r\n"; $postdata .= "Content-Disposition: form-data; name=\"$key\[\]\"\r\n\r\n"; $postdata .= "$cur_val\r\n"; } } else { $postdata .= "--".$this->_mime_boundary."\r\n"; $postdata .= "Content-Disposition: form-data; name=\"$key\"\r\n\r\n"; $postdata .= "$val\r\n"; } } reset($formfiles); while (list($field_name, $file_names) = each($formfiles)) { settype($file_names, "array"); while (list(, $file_name) = each($file_names)) { $file_content = file_get_contents($file_name); if (!$file_content) continue; $base_name = basename($file_name); $postdata .= "--".$this->_mime_boundary."\r\n"; $postdata .= "Content-Disposition: form-data; name=\"$field_name\"; filename=\"$base_name\"\r\nContent-Type: image/jpeg\r\n\r\n"; $postdata .= "$file_content\r\n"; } } $postdata .= "--".$this->_mime_boundary."--\r\n"; break; } return $postdata; }
php
function _prepare_post_body($formvars, $formfiles) { settype($formvars, "array"); settype($formfiles, "array"); $postdata = ''; if (count($formvars) == 0 && count($formfiles) == 0) return; if (is_string($formvars)) return $formvars; if((count($formvars) == 1) && isset($formvars[0])) return $formvars[0]; switch ($this->_submit_type) { case "application/x-www-form-urlencoded": reset($formvars); while(list($key,$val) = each($formvars)) { if (is_array($val) || is_object($val)) { while (list($cur_key, $cur_val) = each($val)) { $postdata .= urlencode($key)."[]=".urlencode($cur_val)."&"; } } else $postdata .= urlencode($key)."=".urlencode($val)."&"; } break; case "multipart/form-data": $this->_mime_boundary = "--------".md5(uniqid(microtime())); reset($formvars); while(list($key,$val) = each($formvars)) { if (is_array($val) || is_object($val)) { while (list($cur_key, $cur_val) = each($val)) { $postdata .= "--".$this->_mime_boundary."\r\n"; $postdata .= "Content-Disposition: form-data; name=\"$key\[\]\"\r\n\r\n"; $postdata .= "$cur_val\r\n"; } } else { $postdata .= "--".$this->_mime_boundary."\r\n"; $postdata .= "Content-Disposition: form-data; name=\"$key\"\r\n\r\n"; $postdata .= "$val\r\n"; } } reset($formfiles); while (list($field_name, $file_names) = each($formfiles)) { settype($file_names, "array"); while (list(, $file_name) = each($file_names)) { $file_content = file_get_contents($file_name); if (!$file_content) continue; $base_name = basename($file_name); $postdata .= "--".$this->_mime_boundary."\r\n"; $postdata .= "Content-Disposition: form-data; name=\"$field_name\"; filename=\"$base_name\"\r\nContent-Type: image/jpeg\r\n\r\n"; $postdata .= "$file_content\r\n"; } } $postdata .= "--".$this->_mime_boundary."--\r\n"; break; } return $postdata; }
/*======================================================================*\ Function: _prepare_post_body Purpose: Prepare post body according to encoding type Input: $formvars - form variables $formfiles - form upload files Output: post body \*======================================================================
https://github.com/ddvphp/wechat/blob/b5991526e7220c2bdc6b9e7a35651c11299aa69d/org/old_version/snoopy.class.php#L1215-L1275
skeeks-cms/cms-composer-update-plugin
src/Plugin.php
Plugin.activate
public function activate(Composer $composer, IOInterface $io) { $this->composer = $composer; $this->io = $io; if (!file_exists($this->getUpdateLockFile())) { $this->io->writeError('<info>Create update lock tmp file: ' . $this->getUpdateLockFile() . '</info>'); $fp = fopen($this->getUpdateLockFile(), "w"); fwrite($fp, time()); fclose($fp); } }
php
public function activate(Composer $composer, IOInterface $io) { $this->composer = $composer; $this->io = $io; if (!file_exists($this->getUpdateLockFile())) { $this->io->writeError('<info>Create update lock tmp file: ' . $this->getUpdateLockFile() . '</info>'); $fp = fopen($this->getUpdateLockFile(), "w"); fwrite($fp, time()); fclose($fp); } }
Initializes the plugin object with the passed $composer and $io. @param Composer $composer @param IOInterface $io
https://github.com/skeeks-cms/cms-composer-update-plugin/blob/6368e6c12968cc9fc3ae763b2b3a6752c9494738/src/Plugin.php#L57-L71
skeeks-cms/cms-composer-update-plugin
src/Plugin.php
Plugin.onPostAutoloadDump
public function onPostAutoloadDump(Event $event) { $this->io->writeError('<info>Remove update lock tmp file: ' . $this->getUpdateLockFile() . '</info>'); if (file_exists($this->getUpdateLockFile())) { if (!unlink($this->getUpdateLockFile())) { $this->io->writeError("<error>Not removed lock file: " . $this->getUpdateLockFile() . "</error>"); } } else { $this->io->writeError("<warning>Not found lock file: " . $this->getUpdateLockFile() . "</warning>"); } }
php
public function onPostAutoloadDump(Event $event) { $this->io->writeError('<info>Remove update lock tmp file: ' . $this->getUpdateLockFile() . '</info>'); if (file_exists($this->getUpdateLockFile())) { if (!unlink($this->getUpdateLockFile())) { $this->io->writeError("<error>Not removed lock file: " . $this->getUpdateLockFile() . "</error>"); } } else { $this->io->writeError("<warning>Not found lock file: " . $this->getUpdateLockFile() . "</warning>"); } }
This is the main function. @param Event $event
https://github.com/skeeks-cms/cms-composer-update-plugin/blob/6368e6c12968cc9fc3ae763b2b3a6752c9494738/src/Plugin.php#L99-L109
internetofvoice/libvoice
src/Alexa/Request/Request/Intent/ResolutionPerAuthority.php
ResolutionPerAuthority.getValuesAsArray
public function getValuesAsArray() { $values = []; foreach($this->getValues() as $value) { $values[$value->getId()] = $value->getName(); } return $values; }
php
public function getValuesAsArray() { $values = []; foreach($this->getValues() as $value) { $values[$value->getId()] = $value->getName(); } return $values; }
Get ResolutionValues as condensed array [id1 => value1, id2 => value2, ...] @return array
https://github.com/internetofvoice/libvoice/blob/15dc4420ddd52234c53902752dc0da16b9d4acdf/src/Alexa/Request/Request/Intent/ResolutionPerAuthority.php#L70-L77
7kgame/php-common
src/Security/Utils.php
Utils.getSalt
public static function getSalt($len, $level=111) { $chars = ""; if($level & 100) { $chars .= self::ALPHABETS; } if($level & 010) { $chars .= self::DIGITAL; } if($level & 001) { $chars .= self::SPECIALCHARS; } $charArr = array(); for($i = 0; $i < strlen($chars); $i++) { $charArr[] = $chars[$i]; } $charArr = str_split( $chars ); shuffle($charArr); return implode("", array_slice($charArr, 0, $len)); }
php
public static function getSalt($len, $level=111) { $chars = ""; if($level & 100) { $chars .= self::ALPHABETS; } if($level & 010) { $chars .= self::DIGITAL; } if($level & 001) { $chars .= self::SPECIALCHARS; } $charArr = array(); for($i = 0; $i < strlen($chars); $i++) { $charArr[] = $chars[$i]; } $charArr = str_split( $chars ); shuffle($charArr); return implode("", array_slice($charArr, 0, $len)); }
$len 生成的salt长度 $level 位运算: 100:字母, 010:数字, 001:特殊字符
https://github.com/7kgame/php-common/blob/1df84bc40b190c305d4d7628e6d2e0a82f9a4b57/src/Security/Utils.php#L14-L35
RobinDumontChaponet/TransitiveWeb
src/View.php
View.getHead
public function getHead(): Core\ViewResource { return new Core\ViewResource(array( 'metas' => $this->getMetasValue(), 'title' => $this->getTitleValue(), 'scripts' => $this->getScriptsValue(), 'styles' => $this->getStylesValue(), ), 'asArray'); }
php
public function getHead(): Core\ViewResource { return new Core\ViewResource(array( 'metas' => $this->getMetasValue(), 'title' => $this->getTitleValue(), 'scripts' => $this->getScriptsValue(), 'styles' => $this->getStylesValue(), ), 'asArray'); }
/* @return Core\ViewResource
https://github.com/RobinDumontChaponet/TransitiveWeb/blob/50f43bd6d5a84e10965e4f8f269b561d082d5774/src/View.php#L53-L61
RobinDumontChaponet/TransitiveWeb
src/View.php
View.getMetas
public function getMetas(): string { $str = ''; if(isset($this->metas)) foreach($this->metas as $meta) if(isset($meta['name'])) $str .= '<meta name="'.$meta['name'].'" content="'.$meta['content'].'">'; else $str .= $meta['raw']; return $str; }
php
public function getMetas(): string { $str = ''; if(isset($this->metas)) foreach($this->metas as $meta) if(isset($meta['name'])) $str .= '<meta name="'.$meta['name'].'" content="'.$meta['content'].'">'; else $str .= $meta['raw']; return $str; }
/* @return string
https://github.com/RobinDumontChaponet/TransitiveWeb/blob/50f43bd6d5a84e10965e4f8f269b561d082d5774/src/View.php#L118-L130
RobinDumontChaponet/TransitiveWeb
src/View.php
View.importStyleSheet
public function importStyleSheet(string $filepath, string $type = 'text/css', bool $cacheBust = false): bool { if(!is_file($filepath)) { trigger_error('file "'.$filepath.'" failed for import, ressource not found or not a file', E_USER_NOTICE); return false; } if(!is_readable($filepath)) { trigger_error('file "'.$filepath.'" failed for import, ressource is not readable', E_USER_NOTICE); return false; } if($cacheBust) $filepath = self::cacheBust($filepath); $this->addStyle(self::_getIncludeContents($filepath), $type); return true; }
php
public function importStyleSheet(string $filepath, string $type = 'text/css', bool $cacheBust = false): bool { if(!is_file($filepath)) { trigger_error('file "'.$filepath.'" failed for import, ressource not found or not a file', E_USER_NOTICE); return false; } if(!is_readable($filepath)) { trigger_error('file "'.$filepath.'" failed for import, ressource is not readable', E_USER_NOTICE); return false; } if($cacheBust) $filepath = self::cacheBust($filepath); $this->addStyle(self::_getIncludeContents($filepath), $type); return true; }
@param string $filepath @param string $type = 'text/css' @param bool $cacheBust = false @return bool
https://github.com/RobinDumontChaponet/TransitiveWeb/blob/50f43bd6d5a84e10965e4f8f269b561d082d5774/src/View.php#L219-L237
RobinDumontChaponet/TransitiveWeb
src/View.php
View.importScript
public function importScript(string $filepath, string $type = 'text/javascript', bool $cacheBust = false): bool { if(!is_file($filepath)) { trigger_error('file "'.$filepath.'" failed for import, ressource not found or not a file', E_USER_NOTICE); return false; } if(!is_readable($filepath)) { trigger_error('file "'.$filepath.'" failed for import, ressource is not readable', E_USER_NOTICE); return false; } if($cacheBust) $filepath = self::cacheBust($filepath); $this->addScript(self::_getIncludeContents($filepath), $type); return true; }
php
public function importScript(string $filepath, string $type = 'text/javascript', bool $cacheBust = false): bool { if(!is_file($filepath)) { trigger_error('file "'.$filepath.'" failed for import, ressource not found or not a file', E_USER_NOTICE); return false; } if(!is_readable($filepath)) { trigger_error('file "'.$filepath.'" failed for import, ressource is not readable', E_USER_NOTICE); return false; } if($cacheBust) $filepath = self::cacheBust($filepath); $this->addScript(self::_getIncludeContents($filepath), $type); return true; }
@param string $filepath @param string $type = 'text/javascript' @param bool $cacheBust = false @return bool
https://github.com/RobinDumontChaponet/TransitiveWeb/blob/50f43bd6d5a84e10965e4f8f269b561d082d5774/src/View.php#L246-L264
RobinDumontChaponet/TransitiveWeb
src/View.php
View.getStyles
public function getStyles(): string { $str = ''; if(isset($this->styles)) foreach($this->styles as $style) if(isset($style['content'])) $str .= '<style type="'.$style['type'].'">'.$style['content'].'</style>'; elseif(isset($style['href'])) $str .= '<link rel="'.$style['rel'].'" type="'.$style['type'].'" href="'.$style['href'].'"'.(($style['defer']) ? ' defer async' : '').' />'; elseif(isset($style['raw'])) $str .= $style['raw']; return $str; }
php
public function getStyles(): string { $str = ''; if(isset($this->styles)) foreach($this->styles as $style) if(isset($style['content'])) $str .= '<style type="'.$style['type'].'">'.$style['content'].'</style>'; elseif(isset($style['href'])) $str .= '<link rel="'.$style['rel'].'" type="'.$style['type'].'" href="'.$style['href'].'"'.(($style['defer']) ? ' defer async' : '').' />'; elseif(isset($style['raw'])) $str .= $style['raw']; return $str; }
/* @return string
https://github.com/RobinDumontChaponet/TransitiveWeb/blob/50f43bd6d5a84e10965e4f8f269b561d082d5774/src/View.php#L269-L283
RobinDumontChaponet/TransitiveWeb
src/View.php
View.getStylesContent
public function getStylesContent(): string { $content = ''; if(isset($this->styles)) foreach($this->styles as $style) if(isset($style['content'])) $content .= $style['content'].PHP_EOL; return $content; }
php
public function getStylesContent(): string { $content = ''; if(isset($this->styles)) foreach($this->styles as $style) if(isset($style['content'])) $content .= $style['content'].PHP_EOL; return $content; }
/* @return string
https://github.com/RobinDumontChaponet/TransitiveWeb/blob/50f43bd6d5a84e10965e4f8f269b561d082d5774/src/View.php#L288-L297
RobinDumontChaponet/TransitiveWeb
src/View.php
View.getScripts
public function getScripts(): string { $str = ''; if(isset($this->scripts)) foreach($this->scripts as $script) if(isset($script['content'])) $str .= '<script type="'.$script['type'].'">'.$script['content'].'</script>'; elseif(isset($script['href'])) $str .= '<script type="'.$script['type'].'" src="'.$script['href'].'"'.(($script['defer']) ? ' defer async' : '').'></script>'; elseif(isset($script['raw'])) $str .= $script['raw']; return $str; }
php
public function getScripts(): string { $str = ''; if(isset($this->scripts)) foreach($this->scripts as $script) if(isset($script['content'])) $str .= '<script type="'.$script['type'].'">'.$script['content'].'</script>'; elseif(isset($script['href'])) $str .= '<script type="'.$script['type'].'" src="'.$script['href'].'"'.(($script['defer']) ? ' defer async' : '').'></script>'; elseif(isset($script['raw'])) $str .= $script['raw']; return $str; }
/* @return string
https://github.com/RobinDumontChaponet/TransitiveWeb/blob/50f43bd6d5a84e10965e4f8f269b561d082d5774/src/View.php#L302-L316
RobinDumontChaponet/TransitiveWeb
src/View.php
View.getScriptsContent
public function getScriptsContent(): string { $content = ''; if(isset($this->scripts)) foreach($this->scripts as $script) if(isset($script['content'])) $content .= $script['content']; return $content; }
php
public function getScriptsContent(): string { $content = ''; if(isset($this->scripts)) foreach($this->scripts as $script) if(isset($script['content'])) $content .= $script['content']; return $content; }
/* @return string
https://github.com/RobinDumontChaponet/TransitiveWeb/blob/50f43bd6d5a84e10965e4f8f269b561d082d5774/src/View.php#L321-L330
RobinDumontChaponet/TransitiveWeb
src/View.php
View.redirect
public function redirect(string $url, int $delay = 0, int $code = 303): bool { $this->addRawMetaTag('<meta http-equiv="refresh" content="'.$delay.'; url='.$url.'">'); if(!headers_sent()) { http_response_code($code); $_SERVER['REDIRECT_STATUS'] = $code; if($delay <= 0) header('Location: '.$url, true, $code); else header('Refresh:'.$delay.'; url='.$url, true, $code); return true; } return false; }
php
public function redirect(string $url, int $delay = 0, int $code = 303): bool { $this->addRawMetaTag('<meta http-equiv="refresh" content="'.$delay.'; url='.$url.'">'); if(!headers_sent()) { http_response_code($code); $_SERVER['REDIRECT_STATUS'] = $code; if($delay <= 0) header('Location: '.$url, true, $code); else header('Refresh:'.$delay.'; url='.$url, true, $code); return true; } return false; }
/* @param string url @param int delay = 0 @param int code = 303 @return bool
https://github.com/RobinDumontChaponet/TransitiveWeb/blob/50f43bd6d5a84e10965e4f8f269b561d082d5774/src/View.php#L354-L370
slickframework/form
src/Renderer/Checkbox.php
Checkbox.getLabelAttributes
public function getLabelAttributes() { $result = []; $label = $this->element->getLabel(); foreach ($label->getAttributes() as $attribute => $value) { if (null === $value) { $result[] = $attribute; continue; } $result[] = "{$attribute}=\"{$value}\""; } return implode(' ', $result); }
php
public function getLabelAttributes() { $result = []; $label = $this->element->getLabel(); foreach ($label->getAttributes() as $attribute => $value) { if (null === $value) { $result[] = $attribute; continue; } $result[] = "{$attribute}=\"{$value}\""; } return implode(' ', $result); }
Returns the elements's label attributes as a string @return string
https://github.com/slickframework/form/blob/e7d536b3bad49194e246ff93587da2589e31a003/src/Renderer/Checkbox.php#L37-L50
phphacks/zend-mvc-di
src/Dependency/Reflection/DependencyReflector.php
DependencyReflector.isSolvable
private function isSolvable(\ReflectionParameter $parameter): bool { if ($parameter->getType() == null && !$parameter->isOptional()) { return false; } $reflection = new \ReflectionClass($parameter->getType()->getName()); if (!$reflection->isInstantiable()) { return false; } return true; }
php
private function isSolvable(\ReflectionParameter $parameter): bool { if ($parameter->getType() == null && !$parameter->isOptional()) { return false; } $reflection = new \ReflectionClass($parameter->getType()->getName()); if (!$reflection->isInstantiable()) { return false; } return true; }
isSolvable Verifica se o parâmetro informado pode ser resolvido e injetado automaticamente. @param \ReflectionParameter $parameter @return bool @throws \ReflectionException
https://github.com/phphacks/zend-mvc-di/blob/725507c386c49f1c9154c3d9306281764e38fc0b/src/Dependency/Reflection/DependencyReflector.php#L58-L71
tiagosampaio/data-object
src/DataObject.php
DataObject.setData
public function setData($key, $value = null) { if (is_array($key)) { $this->data = (array) $key; } if (!is_array($key)) { $this->data[$key] = $value; } return $this; }
php
public function setData($key, $value = null) { if (is_array($key)) { $this->data = (array) $key; } if (!is_array($key)) { $this->data[$key] = $value; } return $this; }
{@inheritdoc}
https://github.com/tiagosampaio/data-object/blob/8d0bf20af886222e06cc39264a9c2e5fa20712f7/src/DataObject.php#L79-L90
tiagosampaio/data-object
src/DataObject.php
DataObject.unsetData
public function unsetData($key = null) { if (null === $key) { $this->setData([]); } if (is_string($key)) { if (isset($this->data[$key]) || array_key_exists($key, $this->data)) { unset($this->data[$key]); } } if (is_array($key)) { foreach ($key as $element) { $this->unsetData($element); } } return $this; }
php
public function unsetData($key = null) { if (null === $key) { $this->setData([]); } if (is_string($key)) { if (isset($this->data[$key]) || array_key_exists($key, $this->data)) { unset($this->data[$key]); } } if (is_array($key)) { foreach ($key as $element) { $this->unsetData($element); } } return $this; }
{@inheritdoc}
https://github.com/tiagosampaio/data-object/blob/8d0bf20af886222e06cc39264a9c2e5fa20712f7/src/DataObject.php#L95-L114
tiagosampaio/data-object
src/DataObject.php
DataObject.export
public function export(array $keys = []) { if (empty($keys)) { return (array) $this->data; } $result = []; /** @var string $key */ foreach ($keys as $key) { $result[$key] = $this->getData($key); } return (array) $result; }
php
public function export(array $keys = []) { if (empty($keys)) { return (array) $this->data; } $result = []; /** @var string $key */ foreach ($keys as $key) { $result[$key] = $this->getData($key); } return (array) $result; }
{@inheritdoc}
https://github.com/tiagosampaio/data-object/blob/8d0bf20af886222e06cc39264a9c2e5fa20712f7/src/DataObject.php#L168-L182
tiagosampaio/data-object
src/DataObject.php
DataObject.underscore
private function underscore($name) { $result = preg_replace('/([A-Z]|[0-9]+)/', "_$1", $name); $result = trim($result, '_'); $result = strtolower($result); return $result; }
php
private function underscore($name) { $result = preg_replace('/([A-Z]|[0-9]+)/', "_$1", $name); $result = trim($result, '_'); $result = strtolower($result); return $result; }
@param string $name @return string|null
https://github.com/tiagosampaio/data-object/blob/8d0bf20af886222e06cc39264a9c2e5fa20712f7/src/DataObject.php#L236-L243
Anahkiasen/php-configuration
src/Dumpers/JsonReferenceDumper.php
JsonReferenceDumper.dumpNode
public function dumpNode(BaseNode $node) { $reference = parent::dumpNode($node); // Simply convert the PHP to JSON for simicity's sake $reference = str_replace('<?php', null, $reference); $reference = eval($reference); $reference = json_encode($reference, JSON_PRETTY_PRINT); return $reference.PHP_EOL; }
php
public function dumpNode(BaseNode $node) { $reference = parent::dumpNode($node); // Simply convert the PHP to JSON for simicity's sake $reference = str_replace('<?php', null, $reference); $reference = eval($reference); $reference = json_encode($reference, JSON_PRETTY_PRINT); return $reference.PHP_EOL; }
@param BaseNode $node @return string
https://github.com/Anahkiasen/php-configuration/blob/f67f1e045f3e2e3dc8bd88c66caf960095e69d97/src/Dumpers/JsonReferenceDumper.php#L14-L24
gisostallenberg/correct-horse-battery-staple
src/CorrectHorseBatteryStaple.php
CorrectHorseBatteryStaple.verifyCommand
private function verifyCommand() { $process = new Process('which cracklib-check'); $process->setTimeout(10); $process->run(); if ($process->isSuccessful()) { return trim($process->getOutput() ); } $process = new Process('whereis cracklib-check'); $process->setTimeout(10); $process->run(); if ($process->isSuccessful()) { return preg_replace('/cracklib-check: ([^ ]*) .*/', '$1', trim($process->getOutput() ) ); } throw new RuntimeException('Unable to find cracklib-check command, please install cracklib-check'); }
php
private function verifyCommand() { $process = new Process('which cracklib-check'); $process->setTimeout(10); $process->run(); if ($process->isSuccessful()) { return trim($process->getOutput() ); } $process = new Process('whereis cracklib-check'); $process->setTimeout(10); $process->run(); if ($process->isSuccessful()) { return preg_replace('/cracklib-check: ([^ ]*) .*/', '$1', trim($process->getOutput() ) ); } throw new RuntimeException('Unable to find cracklib-check command, please install cracklib-check'); }
Verify the command to be available @return string @throws RuntimeException
https://github.com/gisostallenberg/correct-horse-battery-staple/blob/5be41f0bcba23d25e173e49117e30a738b75a353/src/CorrectHorseBatteryStaple.php#L54-L72
gisostallenberg/correct-horse-battery-staple
src/CorrectHorseBatteryStaple.php
CorrectHorseBatteryStaple.check
public function check($password) { if (empty($password) ) { throw new InvalidArgumentException('The password cannot be empty'); } $process = new Process($this->command); $process->setInput($password); $process->mustRun(); return $this->verifyOutput($process->getOutput() ); }
php
public function check($password) { if (empty($password) ) { throw new InvalidArgumentException('The password cannot be empty'); } $process = new Process($this->command); $process->setInput($password); $process->mustRun(); return $this->verifyOutput($process->getOutput() ); }
Performs an obscure check with the given password @param string $password @throws ProcessFailedException
https://github.com/gisostallenberg/correct-horse-battery-staple/blob/5be41f0bcba23d25e173e49117e30a738b75a353/src/CorrectHorseBatteryStaple.php#L80-L89
gisostallenberg/correct-horse-battery-staple
src/CorrectHorseBatteryStaple.php
CorrectHorseBatteryStaple.verifyOutput
private function verifyOutput($output) { $output = trim($output); $result = 'unknown'; if (preg_match('/: ([^:]+)$/', $output, $matches) ) { $result = $matches[1]; } $this->message = $result; if (array_key_exists($result, $this->messageStatus) ) { $this->status = $this->messageStatus[$result]; } else { $this->status = $this->messageStatus['unknown']; } return ($this->status === 0); }
php
private function verifyOutput($output) { $output = trim($output); $result = 'unknown'; if (preg_match('/: ([^:]+)$/', $output, $matches) ) { $result = $matches[1]; } $this->message = $result; if (array_key_exists($result, $this->messageStatus) ) { $this->status = $this->messageStatus[$result]; } else { $this->status = $this->messageStatus['unknown']; } return ($this->status === 0); }
Checks the result of the password check @param string $output
https://github.com/gisostallenberg/correct-horse-battery-staple/blob/5be41f0bcba23d25e173e49117e30a738b75a353/src/CorrectHorseBatteryStaple.php#L96-L113
gregorybesson/PlaygroundFlow
src/Service/Object.php
Object.getObjectMapper
public function getObjectMapper() { if (null === $this->objectMapper) { $this->objectMapper = $this->serviceLocator->get('playgroundflow_object_mapper'); } return $this->objectMapper; }
php
public function getObjectMapper() { if (null === $this->objectMapper) { $this->objectMapper = $this->serviceLocator->get('playgroundflow_object_mapper'); } return $this->objectMapper; }
getObjectMapper @return ObjectMapperInterface
https://github.com/gregorybesson/PlaygroundFlow/blob/f97493f8527e425d46223ac7b5c41331ab8b3022/src/Service/Object.php#L123-L130
gregorybesson/PlaygroundFlow
src/Service/Object.php
Object.getObjectAttributeMapper
public function getObjectAttributeMapper() { if (null === $this->objectAttributeMapper) { $this->objectAttributeMapper = $this->serviceLocator->get('playgroundflow_objectattribute_mapper'); } return $this->objectAttributeMapper; }
php
public function getObjectAttributeMapper() { if (null === $this->objectAttributeMapper) { $this->objectAttributeMapper = $this->serviceLocator->get('playgroundflow_objectattribute_mapper'); } return $this->objectAttributeMapper; }
getObjectAttributeMapper @return ObjectAttributeMapperInterface
https://github.com/gregorybesson/PlaygroundFlow/blob/f97493f8527e425d46223ac7b5c41331ab8b3022/src/Service/Object.php#L150-L157
chilimatic/chilimatic-framework
lib/traits/View.php
View.__init_view
protected function __init_view($engine = '') { $view = (string)__NAMESPACE__ . (string)(empty($engine) ? "\\View_{$this->default_view_engine}" : "\\View_{$engine}"); if ($this->view instanceof $view) return true; try { $this->view = new $view(); } catch (ViewException $e) { throw $e; } return true; }
php
protected function __init_view($engine = '') { $view = (string)__NAMESPACE__ . (string)(empty($engine) ? "\\View_{$this->default_view_engine}" : "\\View_{$engine}"); if ($this->view instanceof $view) return true; try { $this->view = new $view(); } catch (ViewException $e) { throw $e; } return true; }
initializes the database Object if necessary @param string $engine @throws \chilimatic\lib\exception\ViewException|\Exception @return boolean
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/traits/View.php#L42-L56
bruno-barros/w.eloquent-framework
src/weloquent/Support/Navigation/BootstrapMenuWalker.php
BootstrapMenuWalker.start_lvl
public function start_lvl( &$output, $depth = 0, $args = array() ) { // depth dependent classes $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent $display_depth = ( $depth + 1); // because it counts the first submenu as 0 $classes = array( 'sub-menu', ( $display_depth == 0 ? 'dropdown' : '' ), ( $display_depth > 0 ? 'dropdown-menu' : '' ), ); $class_names = implode( ' ', $classes ); // build html $output .= "\n" . $indent . '<ul class="' . $class_names . '">' . "\n"; }
php
public function start_lvl( &$output, $depth = 0, $args = array() ) { // depth dependent classes $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent $display_depth = ( $depth + 1); // because it counts the first submenu as 0 $classes = array( 'sub-menu', ( $display_depth == 0 ? 'dropdown' : '' ), ( $display_depth > 0 ? 'dropdown-menu' : '' ), ); $class_names = implode( ' ', $classes ); // build html $output .= "\n" . $indent . '<ul class="' . $class_names . '">' . "\n"; }
Starts the list before the elements are added. add classes to ul sub-menus @param string $output @param int $depth @param array $args @return string
https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Support/Navigation/BootstrapMenuWalker.php#L20-L34
bruno-barros/w.eloquent-framework
src/weloquent/Support/Navigation/BootstrapMenuWalker.php
BootstrapMenuWalker.start_el
public function start_el( &$output, $item, $depth = 0, $args = array(), $current_object_id = 0 ) { global $wp_query, $wpdb; $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent // só faz pesquisa pelos filhos no primeiro nível $has_children = 0; if($depth == 0){ $has_children = $wpdb -> get_var( "SELECT COUNT(meta_id) FROM {$wpdb->prefix}postmeta WHERE meta_key='_menu_item_menu_item_parent' AND meta_value='" . $item->ID . "'" ); } // depth dependent classes $depth_classes = array( ( $depth == 0 ? 'dropdown' : 'sub-menu-item' ), $item->current ? 'active' : '', ); $depth_class_names = esc_attr( implode( ' ', $depth_classes ) ); // passed classes $classes = empty( $item->classes ) ? array() : (array) $item->classes; $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) ); // build html $output .= $indent . '<li id="nav-menu-item-'. $item->ID . '" class="' . $depth_class_names . ' ' . $class_names . '">'; // link attributes // <a href="#" class="dropdown-toggle" data-toggle="dropdown">biblioteca <b class="caret"></b></a> $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : ''; $attributes .= ' class="menu-link menu-depth-'.$depth . ( $depth > 0 ? '' : ' dropdown-toggle' ) . '"'; $attributes .= $has_children > 0 ? ' data-toggle="dropdown"' : ''; $caret = $has_children > 0 ? ' <b class="caret"></b>' : ''; $item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s', $args->before, $attributes, $args->link_before, apply_filters( 'the_title', $item->title, $item->ID ), $args->link_after . $caret, $args->after ); // build html $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); }
php
public function start_el( &$output, $item, $depth = 0, $args = array(), $current_object_id = 0 ) { global $wp_query, $wpdb; $indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent // só faz pesquisa pelos filhos no primeiro nível $has_children = 0; if($depth == 0){ $has_children = $wpdb -> get_var( "SELECT COUNT(meta_id) FROM {$wpdb->prefix}postmeta WHERE meta_key='_menu_item_menu_item_parent' AND meta_value='" . $item->ID . "'" ); } // depth dependent classes $depth_classes = array( ( $depth == 0 ? 'dropdown' : 'sub-menu-item' ), $item->current ? 'active' : '', ); $depth_class_names = esc_attr( implode( ' ', $depth_classes ) ); // passed classes $classes = empty( $item->classes ) ? array() : (array) $item->classes; $class_names = esc_attr( implode( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) ) ); // build html $output .= $indent . '<li id="nav-menu-item-'. $item->ID . '" class="' . $depth_class_names . ' ' . $class_names . '">'; // link attributes // <a href="#" class="dropdown-toggle" data-toggle="dropdown">biblioteca <b class="caret"></b></a> $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : ''; $attributes .= ' class="menu-link menu-depth-'.$depth . ( $depth > 0 ? '' : ' dropdown-toggle' ) . '"'; $attributes .= $has_children > 0 ? ' data-toggle="dropdown"' : ''; $caret = $has_children > 0 ? ' <b class="caret"></b>' : ''; $item_output = sprintf( '%1$s<a%2$s>%3$s%4$s%5$s</a>%6$s', $args->before, $attributes, $args->link_before, apply_filters( 'the_title', $item->title, $item->ID ), $args->link_after . $caret, $args->after ); // build html $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); }
Start the element output. add main/sub classes to li's and links @param string $output @param object $item @param int $depth @param array $args @param int $current_object_id @return string
https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Support/Navigation/BootstrapMenuWalker.php#L47-L97
Synapse-Cmf/synapse-cmf
src/Synapse/Cmf/Framework/Engine/Resolver/ThemeResolver.php
ThemeResolver.resolve
public function resolve($themeName = null) { switch (true) { // given theme name case $themeName: if (!$theme = $this->themeLoader->retrieveByName($themeName)) { throw new InvalidThemeException(sprintf( 'No themes registered under for "%s" theme name. Did you mean one of these themes : %s ?', $themeName, $this->themeLoader->retrieveAll()->display('name') )); } break; // // default theme - not yet implemented // case $theme = $this->themeLoader->retrieveOne(array( // 'default' => true // )): // break; // first theme defined if there is only one activated case ($themes = $this->themeLoader->retrieveAll()) && $themes->count() == 1: $theme = $themes->first(); break; default: throw new InvalidThemeException( 'Unavailable to determine which theme to use, if you are using more than one you have to call one explicitely. See online documentation at https://synapse-cmf.github.io/documentation/fr/3_book/1_decorator/2_themes.html for more informations.' ); } return $theme; }
php
public function resolve($themeName = null) { switch (true) { // given theme name case $themeName: if (!$theme = $this->themeLoader->retrieveByName($themeName)) { throw new InvalidThemeException(sprintf( 'No themes registered under for "%s" theme name. Did you mean one of these themes : %s ?', $themeName, $this->themeLoader->retrieveAll()->display('name') )); } break; // // default theme - not yet implemented // case $theme = $this->themeLoader->retrieveOne(array( // 'default' => true // )): // break; // first theme defined if there is only one activated case ($themes = $this->themeLoader->retrieveAll()) && $themes->count() == 1: $theme = $themes->first(); break; default: throw new InvalidThemeException( 'Unavailable to determine which theme to use, if you are using more than one you have to call one explicitely. See online documentation at https://synapse-cmf.github.io/documentation/fr/3_book/1_decorator/2_themes.html for more informations.' ); } return $theme; }
Select Theme to use from given parameters and return it. @param string $themeName optional theme name to use @return Theme @throws InvalidThemeException If no theme found for given theme name
https://github.com/Synapse-Cmf/synapse-cmf/blob/d8122a4150a83d5607289724425cf35c56a5e880/src/Synapse/Cmf/Framework/Engine/Resolver/ThemeResolver.php#L35-L69
kokspflanze/ZfcBBCode
src/Service/SBBCodeParser.php
SBBCodeParser.getParsedText
public function getParsedText(string $text): string { $parser = new Node_Container_Document(true, false); if ($this->configData['emoticons']['active']) { $parser->add_emoticons($this->configData['emoticons']['path']); } $result = $parser->parse($text) ->detect_links() ->detect_emails(); if ($this->configData['emoticons']['active']) { $result->detect_emoticons(); } return $result->get_html(); }
php
public function getParsedText(string $text): string { $parser = new Node_Container_Document(true, false); if ($this->configData['emoticons']['active']) { $parser->add_emoticons($this->configData['emoticons']['path']); } $result = $parser->parse($text) ->detect_links() ->detect_emails(); if ($this->configData['emoticons']['active']) { $result->detect_emoticons(); } return $result->get_html(); }
get parsed text @param string $text @return string
https://github.com/kokspflanze/ZfcBBCode/blob/9d60baa2132b1df8b1db3283c3034e275ed53355/src/Service/SBBCodeParser.php#L30-L47
kokspflanze/ZfcBBCode
src/Service/SBBCodeParser.php
SBBCodeParser.isTextValid
public function isTextValid(string $text): bool { $parser = new Node_Container_Document(); if ($this->configData['emoticons']['active']) { $parser->add_emoticons($this->configData['emoticons']['path']); } $this->errorText = ''; $result = true; try { $parser->parse($text) ->detect_links() ->detect_emails(); if ($this->configData['emoticons']['active']) { $parser->detect_emoticons(); } $parser->get_html(); } catch (\Exception $e) { $result = false; $this->errorText = $e->getMessage(); } catch (\Throwable $e) { $result = false; $this->errorText = $e->getMessage(); } return $result; }
php
public function isTextValid(string $text): bool { $parser = new Node_Container_Document(); if ($this->configData['emoticons']['active']) { $parser->add_emoticons($this->configData['emoticons']['path']); } $this->errorText = ''; $result = true; try { $parser->parse($text) ->detect_links() ->detect_emails(); if ($this->configData['emoticons']['active']) { $parser->detect_emoticons(); } $parser->get_html(); } catch (\Exception $e) { $result = false; $this->errorText = $e->getMessage(); } catch (\Throwable $e) { $result = false; $this->errorText = $e->getMessage(); } return $result; }
check if the text is correct @param string $text @return bool
https://github.com/kokspflanze/ZfcBBCode/blob/9d60baa2132b1df8b1db3283c3034e275ed53355/src/Service/SBBCodeParser.php#L55-L85
DimNS/MFLPHP
src/Helpers/NeedLogin.php
NeedLogin.getResponse
public static function getResponse($request, $response, $service, $di) { if ($request->headers()->get('X-Requested-With', '') === 'XMLHttpRequest') { $response->json([ 'error' => true, 'message' => 'Необходимо войти в систему.', ]); } else { $service->title = $di->auth->config->site_name; $service->external_page = true; $service->message_code = 'primary'; $service->message_text = 'Необходимо войти в систему.'; $service->render($service->app_root_path . '/Pages/User/view_auth.php'); } }
php
public static function getResponse($request, $response, $service, $di) { if ($request->headers()->get('X-Requested-With', '') === 'XMLHttpRequest') { $response->json([ 'error' => true, 'message' => 'Необходимо войти в систему.', ]); } else { $service->title = $di->auth->config->site_name; $service->external_page = true; $service->message_code = 'primary'; $service->message_text = 'Необходимо войти в систему.'; $service->render($service->app_root_path . '/Pages/User/view_auth.php'); } }
В зависимости от запроса вернуть ответ или показать страницу @param object $request Объект запроса @param object $response Объект ответа @param object $service Объект сервисов @param object $di Контейнер @version 22.04.2017 @author Дмитрий Щербаков <[email protected]>
https://github.com/DimNS/MFLPHP/blob/8da06f3f9aabf1da5796f9a3cea97425b30af201/src/Helpers/NeedLogin.php#L24-L39
noizu/fragmented-keys
src/NoizuLabs/FragmentedKeys/Tag.php
Tag.Increment
public function Increment() { if($this->version == null) { $this->_getVersion(); } $this->version += .1; $this->_StoreVersion(); }
php
public function Increment() { if($this->version == null) { $this->_getVersion(); } $this->version += .1; $this->_StoreVersion(); }
Increment version number.
https://github.com/noizu/fragmented-keys/blob/5eccc8553ba11920d6d84e20e89b50c28d941b45/src/NoizuLabs/FragmentedKeys/Tag.php#L144-L151
noizu/fragmented-keys
src/NoizuLabs/FragmentedKeys/Tag.php
Tag._getVersion
protected function _getVersion() { if(empty($this->version)) { $result = $this->cacheHandler->get($this->getTagName()); if(empty($result)) { $this->ResetTagVersion(); } else { $this->version = $result; } } return $this->version; }
php
protected function _getVersion() { if(empty($this->version)) { $result = $this->cacheHandler->get($this->getTagName()); if(empty($result)) { $this->ResetTagVersion(); } else { $this->version = $result; } } return $this->version; }
return current version number of tag-instance @return int
https://github.com/noizu/fragmented-keys/blob/5eccc8553ba11920d6d84e20e89b50c28d941b45/src/NoizuLabs/FragmentedKeys/Tag.php#L167-L179
phPoirot/Client-OAuth2
mod/Authenticate/IdentifierTokenAssertion.php
IdentifierTokenAssertion.getOwnerId
function getOwnerId() { if ($this->withIdentity() instanceof iIdentityOfUser) { /** @var IdentityOAuthToken|iIdentityOfUser $identity */ $identity = $this->withIdentity(); $userId = $identity->getOwnerId(); } else { $userInfo = $this->getAuthInfo(); $userId = $userInfo['user']['uid']; } return $userId; }
php
function getOwnerId() { if ($this->withIdentity() instanceof iIdentityOfUser) { /** @var IdentityOAuthToken|iIdentityOfUser $identity */ $identity = $this->withIdentity(); $userId = $identity->getOwnerId(); } else { $userInfo = $this->getAuthInfo(); $userId = $userInfo['user']['uid']; } return $userId; }
Get Owner Identifier @return mixed
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/mod/Authenticate/IdentifierTokenAssertion.php#L30-L46
phPoirot/Client-OAuth2
mod/Authenticate/IdentifierTokenAssertion.php
IdentifierTokenAssertion.getAuthInfo
function getAuthInfo($grants = false) { if ($this->_c_info) return $this->_c_info; $options = null; if ( $grants ) $options['include_grants'] = true; try { $info = $this->federation()->getMyAccountInfo($options); } catch (exOAuthAccessDenied $e) { throw new exAccessDenied($e->getMessage(), $e->getCode(), $e); } return $this->_c_info = $info; }
php
function getAuthInfo($grants = false) { if ($this->_c_info) return $this->_c_info; $options = null; if ( $grants ) $options['include_grants'] = true; try { $info = $this->federation()->getMyAccountInfo($options); } catch (exOAuthAccessDenied $e) { throw new exAccessDenied($e->getMessage(), $e->getCode(), $e); } return $this->_c_info = $info; }
Retrieve User Info From OAuth Server @param bool $grants @return array
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/mod/Authenticate/IdentifierTokenAssertion.php#L56-L74
phPoirot/Client-OAuth2
mod/Authenticate/IdentifierTokenAssertion.php
IdentifierTokenAssertion.federation
function federation() { if ($this->_c_federation) return $this->_c_federation; $federation = clone $this->federation; $federation->setTokenProvider( $this->insTokenProvider() ); return $this->_c_federation = $federation; }
php
function federation() { if ($this->_c_federation) return $this->_c_federation; $federation = clone $this->federation; $federation->setTokenProvider( $this->insTokenProvider() ); return $this->_c_federation = $federation; }
Access Federation Commands Of Identified User @return Federation
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/mod/Authenticate/IdentifierTokenAssertion.php#L82-L94
phPoirot/Client-OAuth2
mod/Authenticate/IdentifierTokenAssertion.php
IdentifierTokenAssertion.insTokenProvider
function insTokenProvider() { if ($this->_tokenProvider) return $this->_tokenProvider; /** @var IdentityOAuthToken|iIdentityAccTokenProvider $identity */ $identity = $this->withIdentity(); $tokenProvider = new TokenProviderSolid( $identity->getAccessToken() ); return $tokenProvider; }
php
function insTokenProvider() { if ($this->_tokenProvider) return $this->_tokenProvider; /** @var IdentityOAuthToken|iIdentityAccTokenProvider $identity */ $identity = $this->withIdentity(); $tokenProvider = new TokenProviderSolid( $identity->getAccessToken() ); return $tokenProvider; }
Token Provider Help Call API`s Behalf Of User with given token [code] $federation = clone \Module\OAuth2Client\Services::OAuthFederate(); $federation->setTokenProvider($tokenProvider); $info = $federation->getMyAccountInfo(); [/code] @return TokenProviderSolid
https://github.com/phPoirot/Client-OAuth2/blob/8745fd54afbbb185669b9e38b1241ecc8ffc7268/mod/Authenticate/IdentifierTokenAssertion.php#L111-L124
mlocati/concrete5-translation-library
src/Parser/BlockTemplates.php
BlockTemplates.parseDirectoryDo
protected function parseDirectoryDo(\Gettext\Translations $translations, $rootDirectory, $relativePath, $subParsersFilter, $exclude3rdParty) { $templateHandles = array(); $prefix = ($relativePath === '') ? '' : "$relativePath/"; $matches = null; foreach (array_merge(array(''), $this->getDirectoryStructure($rootDirectory, $exclude3rdParty)) as $child) { $shownChild = ($child === '') ? rtrim($prefix, '/') : ($prefix.$child); $fullpath = ($child === '') ? $rootDirectory : "$rootDirectory/$child"; if (preg_match('%(?:^|/)blocks/\w+/(?:templates|composer)/(\w+)$%', $fullpath, $matches)) { if (!isset($templateHandles[$matches[1]])) { $templateHandles[$matches[1]] = array(); } $templateHandles[$matches[1]][] = $shownChild; } elseif (preg_match('%(^|/)blocks/\w+/(?:templates|composer)$%', $fullpath)) { $contents = @scandir($fullpath); if ($contents === false) { throw new \Exception("Unable to parse directory $fullpath"); } foreach ($contents as $file) { if ($file[0] !== '.') { if (preg_match('/^(.*)\.php$/', $file, $matches) && is_file("$fullpath/$file")) { if (!isset($templateHandles[$matches[1]])) { $templateHandles[$matches[1]] = array(); } $templateHandles[$matches[1]][] = $shownChild."/$file"; } } } } } foreach ($templateHandles as $templateHandle => $references) { $translation = $translations->insert('TemplateFileName', ucwords(str_replace(array('_', '-', '/'), ' ', $templateHandle))); foreach ($references as $reference) { $translation->addReference($reference); } } }
php
protected function parseDirectoryDo(\Gettext\Translations $translations, $rootDirectory, $relativePath, $subParsersFilter, $exclude3rdParty) { $templateHandles = array(); $prefix = ($relativePath === '') ? '' : "$relativePath/"; $matches = null; foreach (array_merge(array(''), $this->getDirectoryStructure($rootDirectory, $exclude3rdParty)) as $child) { $shownChild = ($child === '') ? rtrim($prefix, '/') : ($prefix.$child); $fullpath = ($child === '') ? $rootDirectory : "$rootDirectory/$child"; if (preg_match('%(?:^|/)blocks/\w+/(?:templates|composer)/(\w+)$%', $fullpath, $matches)) { if (!isset($templateHandles[$matches[1]])) { $templateHandles[$matches[1]] = array(); } $templateHandles[$matches[1]][] = $shownChild; } elseif (preg_match('%(^|/)blocks/\w+/(?:templates|composer)$%', $fullpath)) { $contents = @scandir($fullpath); if ($contents === false) { throw new \Exception("Unable to parse directory $fullpath"); } foreach ($contents as $file) { if ($file[0] !== '.') { if (preg_match('/^(.*)\.php$/', $file, $matches) && is_file("$fullpath/$file")) { if (!isset($templateHandles[$matches[1]])) { $templateHandles[$matches[1]] = array(); } $templateHandles[$matches[1]][] = $shownChild."/$file"; } } } } } foreach ($templateHandles as $templateHandle => $references) { $translation = $translations->insert('TemplateFileName', ucwords(str_replace(array('_', '-', '/'), ' ', $templateHandle))); foreach ($references as $reference) { $translation->addReference($reference); } } }
{@inheritdoc} @see \C5TL\Parser::parseDirectoryDo()
https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser/BlockTemplates.php#L35-L71
soliantconsulting/SoliantEntityAudit
src/SoliantEntityAudit/Mapping/Driver/AuditDriver.php
AuditDriver.loadMetadataForClass
function loadMetadataForClass($className, ClassMetadata $metadata) { $moduleOptions = \SoliantEntityAudit\Module::getModuleOptions(); $entityManager = $moduleOptions->getEntityManager(); $metadataFactory = $entityManager->getMetadataFactory(); $builder = new ClassMetadataBuilder($metadata); if ($className == 'SoliantEntityAudit\\Entity\RevisionEntity') { $builder->createField('id', 'integer')->isPrimaryKey()->generatedValue()->build(); $builder->addManyToOne('revision', 'SoliantEntityAudit\\Entity\\Revision', 'revisionEntities'); $builder->addField('entityKeys', 'string'); $builder->addField('auditEntityClass', 'string'); $builder->addField('targetEntityClass', 'string'); $builder->addField('revisionType', 'string'); $builder->addField('title', 'string', array('nullable' => true)); $metadata->setTableName($moduleOptions->getRevisionEntityTableName()); return; } // Revision is managed here rather than a separate namespace and driver if ($className == 'SoliantEntityAudit\\Entity\\Revision') { $builder->createField('id', 'integer')->isPrimaryKey()->generatedValue()->build(); $builder->addField('comment', 'text', array('nullable' => true)); $builder->addField('timestamp', 'datetime'); // Add association between RevisionEntity and Revision $builder->addOneToMany('revisionEntities', 'SoliantEntityAudit\\Entity\\RevisionEntity', 'revision'); // Add assoication between User and Revision $userMetadata = $metadataFactory->getMetadataFor($moduleOptions->getUserEntityClassName()); $builder ->createManyToOne('user', $userMetadata->getName()) ->addJoinColumn('user_id', $userMetadata->getSingleIdentifierColumnName()) ->build(); $metadata->setTableName($moduleOptions->getRevisionTableName()); return; } # $builder->createField('audit_id', 'integer')->isPrimaryKey()->generatedValue()->build(); $identifiers = array(); # $metadata->setIdentifier(array('audit_id')); // Build a discovered many to many join class $joinClasses = $moduleOptions->getJoinClasses(); if (in_array($className, array_keys($joinClasses))) { $builder->createField('id', 'integer')->isPrimaryKey()->generatedValue()->build(); $builder->addManyToOne('targetRevisionEntity', 'SoliantEntityAudit\\Entity\\RevisionEntity'); $builder->addManyToOne('sourceRevisionEntity', 'SoliantEntityAudit\\Entity\\RevisionEntity'); $metadata->setTableName($moduleOptions->getTableNamePrefix() . $joinClasses[$className]['joinTable']['name'] . $moduleOptions->getTableNameSuffix()); // $metadata->setIdentifier($identifiers); return; } // Get the entity this entity audits $metadataClassName = $metadata->getName(); $metadataClass = new $metadataClassName(); $auditedClassMetadata = $metadataFactory->getMetadataFor($metadataClass->getAuditedEntityClass()); $builder->addManyToOne($moduleOptions->getRevisionEntityFieldName(), 'SoliantEntityAudit\\Entity\\RevisionEntity'); # Compound keys removed in favor of auditId (audit_id) $identifiers[] = $moduleOptions->getRevisionEntityFieldName(); // Add fields from target to audit entity foreach ($auditedClassMetadata->getFieldNames() as $fieldName) { $builder->addField($fieldName, $auditedClassMetadata->getTypeOfField($fieldName), array('nullable' => true, 'quoted' => true)); if ($auditedClassMetadata->isIdentifier($fieldName)) $identifiers[] = $fieldName; } foreach ($auditedClassMetadata->getAssociationMappings() as $mapping) { if (!$mapping['isOwningSide']) continue; if (isset($mapping['joinTable'])) { continue; } if (isset($mapping['joinTableColumns'])) { foreach ($mapping['joinTableColumns'] as $field) { $builder->addField($mapping['fieldName'], 'integer', array('nullable' => true, 'columnName' => $field)); } } elseif (isset($mapping['joinColumnFieldNames'])) { foreach ($mapping['joinColumnFieldNames'] as $field) { $builder->addField($mapping['fieldName'], 'integer', array('nullable' => true, 'columnName' => $field)); } } else { throw new \Exception('Unhandled association mapping'); } } $metadata->setTableName($moduleOptions->getTableNamePrefix() . $auditedClassMetadata->getTableName() . $moduleOptions->getTableNameSuffix()); $metadata->setIdentifier($identifiers); return; }
php
function loadMetadataForClass($className, ClassMetadata $metadata) { $moduleOptions = \SoliantEntityAudit\Module::getModuleOptions(); $entityManager = $moduleOptions->getEntityManager(); $metadataFactory = $entityManager->getMetadataFactory(); $builder = new ClassMetadataBuilder($metadata); if ($className == 'SoliantEntityAudit\\Entity\RevisionEntity') { $builder->createField('id', 'integer')->isPrimaryKey()->generatedValue()->build(); $builder->addManyToOne('revision', 'SoliantEntityAudit\\Entity\\Revision', 'revisionEntities'); $builder->addField('entityKeys', 'string'); $builder->addField('auditEntityClass', 'string'); $builder->addField('targetEntityClass', 'string'); $builder->addField('revisionType', 'string'); $builder->addField('title', 'string', array('nullable' => true)); $metadata->setTableName($moduleOptions->getRevisionEntityTableName()); return; } // Revision is managed here rather than a separate namespace and driver if ($className == 'SoliantEntityAudit\\Entity\\Revision') { $builder->createField('id', 'integer')->isPrimaryKey()->generatedValue()->build(); $builder->addField('comment', 'text', array('nullable' => true)); $builder->addField('timestamp', 'datetime'); // Add association between RevisionEntity and Revision $builder->addOneToMany('revisionEntities', 'SoliantEntityAudit\\Entity\\RevisionEntity', 'revision'); // Add assoication between User and Revision $userMetadata = $metadataFactory->getMetadataFor($moduleOptions->getUserEntityClassName()); $builder ->createManyToOne('user', $userMetadata->getName()) ->addJoinColumn('user_id', $userMetadata->getSingleIdentifierColumnName()) ->build(); $metadata->setTableName($moduleOptions->getRevisionTableName()); return; } # $builder->createField('audit_id', 'integer')->isPrimaryKey()->generatedValue()->build(); $identifiers = array(); # $metadata->setIdentifier(array('audit_id')); // Build a discovered many to many join class $joinClasses = $moduleOptions->getJoinClasses(); if (in_array($className, array_keys($joinClasses))) { $builder->createField('id', 'integer')->isPrimaryKey()->generatedValue()->build(); $builder->addManyToOne('targetRevisionEntity', 'SoliantEntityAudit\\Entity\\RevisionEntity'); $builder->addManyToOne('sourceRevisionEntity', 'SoliantEntityAudit\\Entity\\RevisionEntity'); $metadata->setTableName($moduleOptions->getTableNamePrefix() . $joinClasses[$className]['joinTable']['name'] . $moduleOptions->getTableNameSuffix()); // $metadata->setIdentifier($identifiers); return; } // Get the entity this entity audits $metadataClassName = $metadata->getName(); $metadataClass = new $metadataClassName(); $auditedClassMetadata = $metadataFactory->getMetadataFor($metadataClass->getAuditedEntityClass()); $builder->addManyToOne($moduleOptions->getRevisionEntityFieldName(), 'SoliantEntityAudit\\Entity\\RevisionEntity'); # Compound keys removed in favor of auditId (audit_id) $identifiers[] = $moduleOptions->getRevisionEntityFieldName(); // Add fields from target to audit entity foreach ($auditedClassMetadata->getFieldNames() as $fieldName) { $builder->addField($fieldName, $auditedClassMetadata->getTypeOfField($fieldName), array('nullable' => true, 'quoted' => true)); if ($auditedClassMetadata->isIdentifier($fieldName)) $identifiers[] = $fieldName; } foreach ($auditedClassMetadata->getAssociationMappings() as $mapping) { if (!$mapping['isOwningSide']) continue; if (isset($mapping['joinTable'])) { continue; } if (isset($mapping['joinTableColumns'])) { foreach ($mapping['joinTableColumns'] as $field) { $builder->addField($mapping['fieldName'], 'integer', array('nullable' => true, 'columnName' => $field)); } } elseif (isset($mapping['joinColumnFieldNames'])) { foreach ($mapping['joinColumnFieldNames'] as $field) { $builder->addField($mapping['fieldName'], 'integer', array('nullable' => true, 'columnName' => $field)); } } else { throw new \Exception('Unhandled association mapping'); } } $metadata->setTableName($moduleOptions->getTableNamePrefix() . $auditedClassMetadata->getTableName() . $moduleOptions->getTableNameSuffix()); $metadata->setIdentifier($identifiers); return; }
Loads the metadata for the specified class into the provided container. @param string $className @param ClassMetadata $metadata
https://github.com/soliantconsulting/SoliantEntityAudit/blob/9e77a39ca8399d43c2113c532f3cf2df5349d4a5/src/SoliantEntityAudit/Mapping/Driver/AuditDriver.php#L18-L118
soliantconsulting/SoliantEntityAudit
src/SoliantEntityAudit/Mapping/Driver/AuditDriver.php
AuditDriver.getAllClassNames
function getAllClassNames() { $moduleOptions = \SoliantEntityAudit\Module::getModuleOptions(); $entityManager = $moduleOptions->getEntityManager(); $metadataFactory = $entityManager->getMetadataFactory(); $auditEntities = array(); foreach ($moduleOptions->getAuditedClassNames() as $name => $targetClassOptions) { $auditClassName = "SoliantEntityAudit\\Entity\\" . str_replace('\\', '_', $name); $auditEntities[] = $auditClassName; $auditedClassMetadata = $metadataFactory->getMetadataFor($name); // FIXME: done in autoloader foreach ($auditedClassMetadata->getAssociationMappings() as $mapping) { if (isset($mapping['joinTable']['name'])) { $auditJoinTableClassName = "SoliantEntityAudit\\Entity\\" . str_replace('\\', '_', $mapping['joinTable']['name']); $auditEntities[] = $auditJoinTableClassName; $moduleOptions->addJoinClass($auditJoinTableClassName, $mapping); } } } // Add revision (manage here rather than separate namespace) $auditEntities[] = 'SoliantEntityAudit\\Entity\\Revision'; $auditEntities[] = 'SoliantEntityAudit\\Entity\\RevisionEntity'; return $auditEntities; }
php
function getAllClassNames() { $moduleOptions = \SoliantEntityAudit\Module::getModuleOptions(); $entityManager = $moduleOptions->getEntityManager(); $metadataFactory = $entityManager->getMetadataFactory(); $auditEntities = array(); foreach ($moduleOptions->getAuditedClassNames() as $name => $targetClassOptions) { $auditClassName = "SoliantEntityAudit\\Entity\\" . str_replace('\\', '_', $name); $auditEntities[] = $auditClassName; $auditedClassMetadata = $metadataFactory->getMetadataFor($name); // FIXME: done in autoloader foreach ($auditedClassMetadata->getAssociationMappings() as $mapping) { if (isset($mapping['joinTable']['name'])) { $auditJoinTableClassName = "SoliantEntityAudit\\Entity\\" . str_replace('\\', '_', $mapping['joinTable']['name']); $auditEntities[] = $auditJoinTableClassName; $moduleOptions->addJoinClass($auditJoinTableClassName, $mapping); } } } // Add revision (manage here rather than separate namespace) $auditEntities[] = 'SoliantEntityAudit\\Entity\\Revision'; $auditEntities[] = 'SoliantEntityAudit\\Entity\\RevisionEntity'; return $auditEntities; }
Gets the names of all mapped classes known to this driver. @return array The names of all mapped classes known to this driver.
https://github.com/soliantconsulting/SoliantEntityAudit/blob/9e77a39ca8399d43c2113c532f3cf2df5349d4a5/src/SoliantEntityAudit/Mapping/Driver/AuditDriver.php#L125-L152
jiyis/generator
src/Commands/Publish/GeneratorPublishCommand.php
GeneratorPublishCommand.publishAPIRoutes
public function publishAPIRoutes() { $routesPath = __DIR__.'/../../../templates/api/routes/api_routes.stub'; $apiRoutesPath = config('jiyis.laravel_generator.path.api_routes', app_path('Http/api_routes.php')); $this->publishFile($routesPath, $apiRoutesPath, 'api_routes.php'); }
php
public function publishAPIRoutes() { $routesPath = __DIR__.'/../../../templates/api/routes/api_routes.stub'; $apiRoutesPath = config('jiyis.laravel_generator.path.api_routes', app_path('Http/api_routes.php')); $this->publishFile($routesPath, $apiRoutesPath, 'api_routes.php'); }
Publishes api_routes.php.
https://github.com/jiyis/generator/blob/20984036878444d2b9af021e3e4e0585d313dfa7/src/Commands/Publish/GeneratorPublishCommand.php#L40-L47
jiyis/generator
src/Commands/Publish/GeneratorPublishCommand.php
GeneratorPublishCommand.initAPIRoutes
private function initAPIRoutes() { $path = config('jiyis.laravel_generator.path.routes', app_path('Http/routes.php')); $prompt = 'Existing routes.php file detected. Should we add an API group to the file? (y|N) :'; if (file_exists($path) && !$this->confirmOverwrite($path, $prompt)) { return; } $routeContents = file_get_contents($path); $template = 'api.routes.api_routes_group'; $templateData = TemplateUtil::getTemplate($template, 'laravel-generator'); $templateData = $this->fillTemplate($templateData); file_put_contents($path, $routeContents."\n\n".$templateData); $this->comment("\nAPI group added to routes.php"); }
php
private function initAPIRoutes() { $path = config('jiyis.laravel_generator.path.routes', app_path('Http/routes.php')); $prompt = 'Existing routes.php file detected. Should we add an API group to the file? (y|N) :'; if (file_exists($path) && !$this->confirmOverwrite($path, $prompt)) { return; } $routeContents = file_get_contents($path); $template = 'api.routes.api_routes_group'; $templateData = TemplateUtil::getTemplate($template, 'laravel-generator'); $templateData = $this->fillTemplate($templateData); file_put_contents($path, $routeContents."\n\n".$templateData); $this->comment("\nAPI group added to routes.php"); }
Initialize routes group based on route integration.
https://github.com/jiyis/generator/blob/20984036878444d2b9af021e3e4e0585d313dfa7/src/Commands/Publish/GeneratorPublishCommand.php#L52-L71
jiyis/generator
src/Commands/Publish/GeneratorPublishCommand.php
GeneratorPublishCommand.fillTemplate
private function fillTemplate($templateData) { $apiVersion = config('jiyis.laravel_generator.api_version', 'v1'); $apiPrefix = config('jiyis.laravel_generator.api_prefix', 'api'); $apiNamespace = config( 'jiyis.laravel_generator.namespace.api_controller', 'App\Http\Controllers\API' ); $templateData = str_replace('$API_VERSION$', $apiVersion, $templateData); $templateData = str_replace('$NAMESPACE_API_CONTROLLER$', $apiNamespace, $templateData); $templateData = str_replace('$API_PREFIX$', $apiPrefix, $templateData); $templateData = str_replace( '$NAMESPACE_CONTROLLER$', config('jiyis.laravel_generator.namespace.controller'), $templateData ); return $templateData; }
php
private function fillTemplate($templateData) { $apiVersion = config('jiyis.laravel_generator.api_version', 'v1'); $apiPrefix = config('jiyis.laravel_generator.api_prefix', 'api'); $apiNamespace = config( 'jiyis.laravel_generator.namespace.api_controller', 'App\Http\Controllers\API' ); $templateData = str_replace('$API_VERSION$', $apiVersion, $templateData); $templateData = str_replace('$NAMESPACE_API_CONTROLLER$', $apiNamespace, $templateData); $templateData = str_replace('$API_PREFIX$', $apiPrefix, $templateData); $templateData = str_replace( '$NAMESPACE_CONTROLLER$', config('jiyis.laravel_generator.namespace.controller'), $templateData ); return $templateData; }
Replaces dynamic variables of template. @param string $templateData @return string
https://github.com/jiyis/generator/blob/20984036878444d2b9af021e3e4e0585d313dfa7/src/Commands/Publish/GeneratorPublishCommand.php#L113-L131
praxisnetau/silverware-navigation
src/Components/BarNavigation.php
BarNavigation.getCMSFields
public function getCMSFields() { // Obtain Field Objects (from parent): $fields = parent::getCMSFields(); // Create Main Fields: $fields->addFieldsToTab( 'Root.Main', [ TextField::create( 'ButtonLabel', $this->fieldLabel('ButtonLabel') ) ] ); // Insert Brand Tab: $fields->insertAfter( Tab::create( 'Brand', $this->fieldLabel('Brand') ), 'Main' ); // Create Brand Fields: $fields->addFieldsToTab( 'Root.Brand', [ TextField::create( 'BrandText', $this->fieldLabel('BrandText') ), PageDropdownField::create( 'BrandPageID', $this->fieldLabel('BrandPageID') ), FieldSection::create( 'BrandLogo', $this->fieldLabel('BrandLogo'), [ $logo = UploadField::create( 'BrandLogo', $this->fieldLabel('BrandLogoFile') ), ViewportsField::create( 'BrandLogoWidth', $this->fieldLabel('BrandLogoWidth') )->setUseTextInput(true), ViewportsField::create( 'BrandLogoHeight', $this->fieldLabel('BrandLogoHeight') )->setUseTextInput(true) ] ) ] ); // Define Logo Field: $logo->setAllowedExtensions(['gif', 'jpg', 'jpeg', 'png', 'svg']); $logo->setFolderName($this->getAssetFolder()); // Define Placeholder: $placeholder = _t(__CLASS__ . '.DROPDOWNDEFAULT', '(default)'); // Create Style Fields: $fields->addFieldToTab( 'Root.Style', FieldSection::create( 'NavigationStyle', $this->fieldLabel('NavigationStyle'), [ DropdownField::create( 'Background', $this->fieldLabel('Background'), $this->getBackgroundOptions() )->setEmptyString(' ')->setAttribute('data-placeholder', $placeholder), DropdownField::create( 'Foreground', $this->fieldLabel('Foreground'), $this->getForegroundOptions() )->setEmptyString(' ')->setAttribute('data-placeholder', $placeholder), DropdownField::create( 'ButtonAlignment', $this->fieldLabel('ButtonAlignment'), $this->getButtonAlignmentOptions() )->setEmptyString(' ')->setAttribute('data-placeholder', $placeholder), DropdownField::create( 'ItemAlign', $this->fieldLabel('ItemAlign'), $this->getItemAlignOptions() )->setEmptyString(' ')->setAttribute('data-placeholder', $placeholder), DropdownField::create( 'ItemJustify', $this->fieldLabel('ItemJustify'), $this->getItemJustifyOptions() )->setEmptyString(' ')->setAttribute('data-placeholder', $placeholder), DropdownField::create( 'Position', $this->fieldLabel('Position'), $this->getPositionOptions() )->setEmptyString(' ')->setAttribute('data-placeholder', $placeholder) ] ) ); // Create Options Fields: $fields->addFieldToTab( 'Root.Options', FieldSection::create( 'NavigationOptions', $this->fieldLabel('NavigationOptions'), [ ViewportField::create( 'ExpandOn', $this->fieldLabel('ExpandOn') )->setRightTitle( _t( __CLASS__ . '.EXPANDONRIGHTTITLE', 'Specifies the viewport size to expand collapsed content.' ) ), CheckboxField::create( 'BrandLinkDisabled', $this->fieldLabel('BrandLinkDisabled') ) ] ) ); // Answer Field Objects: return $fields; }
php
public function getCMSFields() { // Obtain Field Objects (from parent): $fields = parent::getCMSFields(); // Create Main Fields: $fields->addFieldsToTab( 'Root.Main', [ TextField::create( 'ButtonLabel', $this->fieldLabel('ButtonLabel') ) ] ); // Insert Brand Tab: $fields->insertAfter( Tab::create( 'Brand', $this->fieldLabel('Brand') ), 'Main' ); // Create Brand Fields: $fields->addFieldsToTab( 'Root.Brand', [ TextField::create( 'BrandText', $this->fieldLabel('BrandText') ), PageDropdownField::create( 'BrandPageID', $this->fieldLabel('BrandPageID') ), FieldSection::create( 'BrandLogo', $this->fieldLabel('BrandLogo'), [ $logo = UploadField::create( 'BrandLogo', $this->fieldLabel('BrandLogoFile') ), ViewportsField::create( 'BrandLogoWidth', $this->fieldLabel('BrandLogoWidth') )->setUseTextInput(true), ViewportsField::create( 'BrandLogoHeight', $this->fieldLabel('BrandLogoHeight') )->setUseTextInput(true) ] ) ] ); // Define Logo Field: $logo->setAllowedExtensions(['gif', 'jpg', 'jpeg', 'png', 'svg']); $logo->setFolderName($this->getAssetFolder()); // Define Placeholder: $placeholder = _t(__CLASS__ . '.DROPDOWNDEFAULT', '(default)'); // Create Style Fields: $fields->addFieldToTab( 'Root.Style', FieldSection::create( 'NavigationStyle', $this->fieldLabel('NavigationStyle'), [ DropdownField::create( 'Background', $this->fieldLabel('Background'), $this->getBackgroundOptions() )->setEmptyString(' ')->setAttribute('data-placeholder', $placeholder), DropdownField::create( 'Foreground', $this->fieldLabel('Foreground'), $this->getForegroundOptions() )->setEmptyString(' ')->setAttribute('data-placeholder', $placeholder), DropdownField::create( 'ButtonAlignment', $this->fieldLabel('ButtonAlignment'), $this->getButtonAlignmentOptions() )->setEmptyString(' ')->setAttribute('data-placeholder', $placeholder), DropdownField::create( 'ItemAlign', $this->fieldLabel('ItemAlign'), $this->getItemAlignOptions() )->setEmptyString(' ')->setAttribute('data-placeholder', $placeholder), DropdownField::create( 'ItemJustify', $this->fieldLabel('ItemJustify'), $this->getItemJustifyOptions() )->setEmptyString(' ')->setAttribute('data-placeholder', $placeholder), DropdownField::create( 'Position', $this->fieldLabel('Position'), $this->getPositionOptions() )->setEmptyString(' ')->setAttribute('data-placeholder', $placeholder) ] ) ); // Create Options Fields: $fields->addFieldToTab( 'Root.Options', FieldSection::create( 'NavigationOptions', $this->fieldLabel('NavigationOptions'), [ ViewportField::create( 'ExpandOn', $this->fieldLabel('ExpandOn') )->setRightTitle( _t( __CLASS__ . '.EXPANDONRIGHTTITLE', 'Specifies the viewport size to expand collapsed content.' ) ), CheckboxField::create( 'BrandLinkDisabled', $this->fieldLabel('BrandLinkDisabled') ) ] ) ); // Answer Field Objects: return $fields; }
Answers a list of field objects for the CMS interface. @return FieldList
https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/BarNavigation.php#L225-L366
praxisnetau/silverware-navigation
src/Components/BarNavigation.php
BarNavigation.getWrapperClassNames
public function getWrapperClassNames() { $classes = $this->styles('navbar'); $classes[] = $this->style('navbar', sprintf('expand-%s', $this->ExpandOn)); if ($this->Background) { $classes[] = $this->style('background', $this->Background); } if ($this->Foreground) { $classes[] = $this->style('navbar', sprintf('fg-%s', $this->Foreground)); } if ($this->Position) { $classes[] = $this->style('position', $this->Position); } $this->extend('updateWrapperClassNames', $classes); return $classes; }
php
public function getWrapperClassNames() { $classes = $this->styles('navbar'); $classes[] = $this->style('navbar', sprintf('expand-%s', $this->ExpandOn)); if ($this->Background) { $classes[] = $this->style('background', $this->Background); } if ($this->Foreground) { $classes[] = $this->style('navbar', sprintf('fg-%s', $this->Foreground)); } if ($this->Position) { $classes[] = $this->style('position', $this->Position); } $this->extend('updateWrapperClassNames', $classes); return $classes; }
Answers an array of wrapper class names for the HTML template. @return array
https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/BarNavigation.php#L440-L461
praxisnetau/silverware-navigation
src/Components/BarNavigation.php
BarNavigation.getButtonAttributes
public function getButtonAttributes() { $attributes = [ 'type' => 'button', 'class' => $this->ButtonClass, 'title' => $this->ButtonLabel, 'aria-label' => $this->ButtonLabel, 'aria-expanded' => 'false', 'aria-controls' => $this->CollapseHTMLID, 'data-target' => $this->CollapseCSSID, 'data-toggle' => 'collapse' ]; $this->extend('updateButtonAttributes', $attributes); return $attributes; }
php
public function getButtonAttributes() { $attributes = [ 'type' => 'button', 'class' => $this->ButtonClass, 'title' => $this->ButtonLabel, 'aria-label' => $this->ButtonLabel, 'aria-expanded' => 'false', 'aria-controls' => $this->CollapseHTMLID, 'data-target' => $this->CollapseCSSID, 'data-toggle' => 'collapse' ]; $this->extend('updateButtonAttributes', $attributes); return $attributes; }
Answers an array of HTML tag attributes for the button. @return array
https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/BarNavigation.php#L482-L498
praxisnetau/silverware-navigation
src/Components/BarNavigation.php
BarNavigation.getCollapseClassNames
public function getCollapseClassNames() { $classes = $this->styles('navbar.collapse', 'collapse'); if ($this->hasRows()) { $classes[] = $this->style('navbar.column'); } if ($align = $this->ItemAlign) { $classes[] = $this->style(sprintf('navbar.item-align-%s', $align)); } if ($justify = $this->ItemJustify) { $classes[] = $this->style(sprintf('navbar.item-justify-%s', $justify)); } $this->extend('updateCollapseClassNames', $classes); return $classes; }
php
public function getCollapseClassNames() { $classes = $this->styles('navbar.collapse', 'collapse'); if ($this->hasRows()) { $classes[] = $this->style('navbar.column'); } if ($align = $this->ItemAlign) { $classes[] = $this->style(sprintf('navbar.item-align-%s', $align)); } if ($justify = $this->ItemJustify) { $classes[] = $this->style(sprintf('navbar.item-justify-%s', $justify)); } $this->extend('updateCollapseClassNames', $classes); return $classes; }
Answers an array of collapse class names for the HTML template. @return array
https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/BarNavigation.php#L589-L608
praxisnetau/silverware-navigation
src/Components/BarNavigation.php
BarNavigation.getLogoDimensions
public function getLogoDimensions() { // Initialise: $data = []; // Obtain Dimensions: $widths = $this->dbObject('BrandLogoWidth'); $heights = $this->dbObject('BrandLogoHeight'); // Iterate Width Viewports: foreach ($widths->getViewports() as $viewport) { if ($value = $widths->getField($viewport)) { $data[$viewport]['Width'] = $value; $data[$viewport]['Breakpoint'] = $widths->getBreakpoint($viewport); } } // Iterate Height Viewports: foreach ($heights->getViewports() as $viewport) { if ($value = $heights->getField($viewport)) { $data[$viewport]['Height'] = $value; $data[$viewport]['Breakpoint'] = $heights->getBreakpoint($viewport); } } // Create Items List: $items = ArrayList::create(); // Create Data Items: foreach ($data as $item) { $items->push(ArrayData::create($item)); } // Answer Items List: return $items; }
php
public function getLogoDimensions() { // Initialise: $data = []; // Obtain Dimensions: $widths = $this->dbObject('BrandLogoWidth'); $heights = $this->dbObject('BrandLogoHeight'); // Iterate Width Viewports: foreach ($widths->getViewports() as $viewport) { if ($value = $widths->getField($viewport)) { $data[$viewport]['Width'] = $value; $data[$viewport]['Breakpoint'] = $widths->getBreakpoint($viewport); } } // Iterate Height Viewports: foreach ($heights->getViewports() as $viewport) { if ($value = $heights->getField($viewport)) { $data[$viewport]['Height'] = $value; $data[$viewport]['Breakpoint'] = $heights->getBreakpoint($viewport); } } // Create Items List: $items = ArrayList::create(); // Create Data Items: foreach ($data as $item) { $items->push(ArrayData::create($item)); } // Answer Items List: return $items; }
Answers a list of logo dimensions for the custom CSS template. @return ArrayList
https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/BarNavigation.php#L709-L755
praxisnetau/silverware-navigation
src/Components/BarNavigation.php
BarNavigation.getBackgroundOptions
public function getBackgroundOptions() { return [ self::BG_PRIMARY => _t(__CLASS__ . '.PRIMARY', 'Primary'), self::BG_LIGHT => _t(__CLASS__ . '.LIGHT', 'Light'), self::BG_DARK => _t(__CLASS__ . '.DARK', 'Dark') ]; }
php
public function getBackgroundOptions() { return [ self::BG_PRIMARY => _t(__CLASS__ . '.PRIMARY', 'Primary'), self::BG_LIGHT => _t(__CLASS__ . '.LIGHT', 'Light'), self::BG_DARK => _t(__CLASS__ . '.DARK', 'Dark') ]; }
Answers an array of options for the background field. @return array
https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/BarNavigation.php#L762-L769
praxisnetau/silverware-navigation
src/Components/BarNavigation.php
BarNavigation.getItemAlignOptions
public function getItemAlignOptions() { return [ self::ITEM_ALIGN_START => _t(__CLASS__ . '.START', 'Start'), self::ITEM_ALIGN_CENTER => _t(__CLASS__ . '.CENTER', 'Center'), self::ITEM_ALIGN_END => _t(__CLASS__ . '.END', 'End'), self::ITEM_ALIGN_BETWEEN => _t(__CLASS__ . '.BETWEEN', 'Between'), self::ITEM_ALIGN_AROUND => _t(__CLASS__ . '.AROUND', 'Around') ]; }
php
public function getItemAlignOptions() { return [ self::ITEM_ALIGN_START => _t(__CLASS__ . '.START', 'Start'), self::ITEM_ALIGN_CENTER => _t(__CLASS__ . '.CENTER', 'Center'), self::ITEM_ALIGN_END => _t(__CLASS__ . '.END', 'End'), self::ITEM_ALIGN_BETWEEN => _t(__CLASS__ . '.BETWEEN', 'Between'), self::ITEM_ALIGN_AROUND => _t(__CLASS__ . '.AROUND', 'Around') ]; }
Answers an array of options for the item align field. @return array
https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/BarNavigation.php#L802-L811
praxisnetau/silverware-navigation
src/Components/BarNavigation.php
BarNavigation.getItemJustifyOptions
public function getItemJustifyOptions() { return [ self::ITEM_ALIGN_START => _t(__CLASS__ . '.START', 'Start'), self::ITEM_ALIGN_CENTER => _t(__CLASS__ . '.CENTER', 'Center'), self::ITEM_ALIGN_END => _t(__CLASS__ . '.END', 'End'), self::ITEM_ALIGN_BASELINE => _t(__CLASS__ . '.BASELINE', 'Baseline'), self::ITEM_ALIGN_STRETCH => _t(__CLASS__ . '.STRETCH', 'Stretch') ]; }
php
public function getItemJustifyOptions() { return [ self::ITEM_ALIGN_START => _t(__CLASS__ . '.START', 'Start'), self::ITEM_ALIGN_CENTER => _t(__CLASS__ . '.CENTER', 'Center'), self::ITEM_ALIGN_END => _t(__CLASS__ . '.END', 'End'), self::ITEM_ALIGN_BASELINE => _t(__CLASS__ . '.BASELINE', 'Baseline'), self::ITEM_ALIGN_STRETCH => _t(__CLASS__ . '.STRETCH', 'Stretch') ]; }
Answers an array of options for the item justify field. @return array
https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/BarNavigation.php#L818-L827
kokspflanze/ZfcTicketSystem
src/Mapper/HydratorTicketEntry.php
HydratorTicketEntry.extract
public function extract($object) { if (!$object instanceof TicketEntry) { throw new \InvalidArgumentException('$object must be an instance of TicketEntry'); } /* @var $object TicketEntry */ $data = parent::extract($object); return $data; }
php
public function extract($object) { if (!$object instanceof TicketEntry) { throw new \InvalidArgumentException('$object must be an instance of TicketEntry'); } /* @var $object TicketEntry */ $data = parent::extract($object); return $data; }
Extract values from an object @param object $object @return array @throws \InvalidArgumentException
https://github.com/kokspflanze/ZfcTicketSystem/blob/d7cdbf48b12a5e5cf6a2bd3ca545b2fe65fc57e0/src/Mapper/HydratorTicketEntry.php#L17-L26
kokspflanze/ZfcTicketSystem
src/Mapper/HydratorTicketEntry.php
HydratorTicketEntry.hydrate
public function hydrate(array $data, $object) { if (!$object instanceof TicketEntry) { throw new \InvalidArgumentException('$object must be an instance of TicketEntry'); } return parent::hydrate($data, $object); }
php
public function hydrate(array $data, $object) { if (!$object instanceof TicketEntry) { throw new \InvalidArgumentException('$object must be an instance of TicketEntry'); } return parent::hydrate($data, $object); }
Hydrate $object with the provided $data. @param array $data @param object $object @return TicketEntry @throws \InvalidArgumentException
https://github.com/kokspflanze/ZfcTicketSystem/blob/d7cdbf48b12a5e5cf6a2bd3ca545b2fe65fc57e0/src/Mapper/HydratorTicketEntry.php#L35-L42
rujiali/acquia-site-factory-cli
src/AppBundle/Commands/WaitBackupCommand.php
WaitBackupCommand.execute
protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Start to wait for the backup'); if ($this->connectorSites->waitBackup($input->getArgument('label'))) { $output->writeln('Backup finished!'); } }
php
protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Start to wait for the backup'); if ($this->connectorSites->waitBackup($input->getArgument('label'))) { $output->writeln('Backup finished!'); } }
{@inheritdoc}
https://github.com/rujiali/acquia-site-factory-cli/blob/c9dbb9dfd71408adff0ea26db94678a61c584df6/src/AppBundle/Commands/WaitBackupCommand.php#L46-L53
amneale/dns-updater
src/Console/Question/AdapterQuestionProvider.php
AdapterQuestionProvider.getQuestionsFor
public function getQuestionsFor(string $adapter): array { Assert::that($adapter)->choice(AdapterChoice::AVAILABLE_ADAPTERS); switch ($adapter) { case DigitalOceanAdapter::NAME: return [new AccessTokenQuestion()]; case CloudFlareAdapter::NAME: return [ new EmailQuestion(), new ApiKeyQuestion(), ]; default: return []; } }
php
public function getQuestionsFor(string $adapter): array { Assert::that($adapter)->choice(AdapterChoice::AVAILABLE_ADAPTERS); switch ($adapter) { case DigitalOceanAdapter::NAME: return [new AccessTokenQuestion()]; case CloudFlareAdapter::NAME: return [ new EmailQuestion(), new ApiKeyQuestion(), ]; default: return []; } }
@param string $adapter @return Question[]
https://github.com/amneale/dns-updater/blob/e29ff2f3a5bf13084afd3858eccf7f499854fa32/src/Console/Question/AdapterQuestionProvider.php#L20-L35
4devs/serializer
Mapping/Loader/XmlFilesLoader.php
XmlFilesLoader.loadClassMetadata
public function loadClassMetadata(ClassMetadataInterface $classMetadata) { $name = $classMetadata->getName(); if (!isset($this->classes[$name])) { $this->classes[$name] = $this->parseFile($this->files[$name]); } $this->loadClassMetadataFromXml($classMetadata, $this->classes[$name]->class[0]); return true; }
php
public function loadClassMetadata(ClassMetadataInterface $classMetadata) { $name = $classMetadata->getName(); if (!isset($this->classes[$name])) { $this->classes[$name] = $this->parseFile($this->files[$name]); } $this->loadClassMetadataFromXml($classMetadata, $this->classes[$name]->class[0]); return true; }
{@inheritdoc}
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Mapping/Loader/XmlFilesLoader.php#L34-L45
4devs/serializer
Mapping/Loader/XmlFilesLoader.php
XmlFilesLoader.parseMetadataType
private function parseMetadataType(\SimpleXMLElement $node, $type) { $options = $this->parseOptions($node); return $this->getMetadataType((string) $node['name'], $type, $options); }
php
private function parseMetadataType(\SimpleXMLElement $node, $type) { $options = $this->parseOptions($node); return $this->getMetadataType((string) $node['name'], $type, $options); }
@param \SimpleXMLElement $node @param string $type @return MetadataInterface
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Mapping/Loader/XmlFilesLoader.php#L118-L123
4devs/serializer
Mapping/Loader/XmlFilesLoader.php
XmlFilesLoader.parseValues
protected function parseValues(\SimpleXMLElement $node) { $values = []; foreach ($node->value as $item) { if ($item->count() > 0) { $value = $this->parseValues($item); } else { $value = trim($item); } if (isset($item['key'])) { $values[(string) $item['key']] = $value; } else { $values[] = $value; } } return $values; }
php
protected function parseValues(\SimpleXMLElement $node) { $values = []; foreach ($node->value as $item) { if ($item->count() > 0) { $value = $this->parseValues($item); } else { $value = trim($item); } if (isset($item['key'])) { $values[(string) $item['key']] = $value; } else { $values[] = $value; } } return $values; }
Parses a collection of "value" XML nodes. @param \SimpleXMLElement $nodes The XML nodes @return array The values
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Mapping/Loader/XmlFilesLoader.php#L132-L151
4devs/serializer
Mapping/Loader/XmlFilesLoader.php
XmlFilesLoader.parseOptions
protected function parseOptions(\SimpleXMLElement $node) { $options = []; /** @var \SimpleXMLElement $option */ foreach ($node->option as $option) { if ($option->count() > 0) { if (count($option->value) > 0) { $value = $this->parseValues($option); } else { $value = []; } } else { $value = XmlUtils::phpize($option); if (is_string($value)) { $value = trim($value); } } $options[(string) $option['name']] = $value; } return $options; }
php
protected function parseOptions(\SimpleXMLElement $node) { $options = []; /** @var \SimpleXMLElement $option */ foreach ($node->option as $option) { if ($option->count() > 0) { if (count($option->value) > 0) { $value = $this->parseValues($option); } else { $value = []; } } else { $value = XmlUtils::phpize($option); if (is_string($value)) { $value = trim($value); } } $options[(string) $option['name']] = $value; } return $options; }
Parses a collection of "option" XML nodes. @param \SimpleXMLElement $nodes The XML nodes @return array The options
https://github.com/4devs/serializer/blob/c2a9bf81ed59dd123c9877ef3f75c1a9673b236e/Mapping/Loader/XmlFilesLoader.php#L160-L182
selikhovleonid/nadir
src/core/WebCtrlResolver.php
WebCtrlResolver.createCtrl
protected function createCtrl() { $oView = ViewFactory::createView( $this->ctrlName, str_replace('action', '', $this->actionName) ); $aComponentsRootMap = AppHelper::getInstance()->getConfig('componentsRootMap'); if (!isset($aComponentsRootMap['controllers'])) { throw new Exception("The field 'componentsRootMap.controllers' must be " ."presented in the main configuration file."); } $sCtrlNamespace = str_replace( \DIRECTORY_SEPARATOR, '\\', $aComponentsRootMap['controllers'] ); $sCtrlNameFull = $sCtrlNamespace.'\\'.$this->ctrlName; if (!is_null($oView)) { $sLayoutName = AppHelper::getInstance()->getConfig('defaultLayout'); if (!is_null($sLayoutName)) { $oLayout = ViewFactory::createLayout($sLayoutName, $oView); $oCtrl = new $sCtrlNameFull($this->request, $oLayout); } else { $oCtrl = new $sCtrlNameFull($this->request, $oView); } } else { $oCtrl = new $sCtrlNameFull($this->request); } return $oCtrl; }
php
protected function createCtrl() { $oView = ViewFactory::createView( $this->ctrlName, str_replace('action', '', $this->actionName) ); $aComponentsRootMap = AppHelper::getInstance()->getConfig('componentsRootMap'); if (!isset($aComponentsRootMap['controllers'])) { throw new Exception("The field 'componentsRootMap.controllers' must be " ."presented in the main configuration file."); } $sCtrlNamespace = str_replace( \DIRECTORY_SEPARATOR, '\\', $aComponentsRootMap['controllers'] ); $sCtrlNameFull = $sCtrlNamespace.'\\'.$this->ctrlName; if (!is_null($oView)) { $sLayoutName = AppHelper::getInstance()->getConfig('defaultLayout'); if (!is_null($sLayoutName)) { $oLayout = ViewFactory::createLayout($sLayoutName, $oView); $oCtrl = new $sCtrlNameFull($this->request, $oLayout); } else { $oCtrl = new $sCtrlNameFull($this->request, $oView); } } else { $oCtrl = new $sCtrlNameFull($this->request); } return $oCtrl; }
It creates the controller object, assignes it with default view and layout objects. @return \nadir\core\AWebController.
https://github.com/selikhovleonid/nadir/blob/47545fccd8516c8f0a20c02ba62f68269c7199da/src/core/WebCtrlResolver.php#L30-L59
selikhovleonid/nadir
src/core/WebCtrlResolver.php
WebCtrlResolver.tryAssignController
protected function tryAssignController() { $sMethod = strtolower($this->request->getMethod()); if (isset($this->routeMap[$sMethod])) { foreach ($this->routeMap[$sMethod] as $sRoute => $aRouteConfig) { if (preg_match( '#^'.$sRoute.'/?$#u', urldecode($this->request->getUrlPath()), $aParam ) ) { AppHelper::getInstance()->setRouteConfig($aRouteConfig); $this->ctrlName = $aRouteConfig['ctrl'][0]; $this->actionName = $aRouteConfig['ctrl'][1]; unset($aParam[0]); $this->actionArgs = array_values($aParam); break; } } } }
php
protected function tryAssignController() { $sMethod = strtolower($this->request->getMethod()); if (isset($this->routeMap[$sMethod])) { foreach ($this->routeMap[$sMethod] as $sRoute => $aRouteConfig) { if (preg_match( '#^'.$sRoute.'/?$#u', urldecode($this->request->getUrlPath()), $aParam ) ) { AppHelper::getInstance()->setRouteConfig($aRouteConfig); $this->ctrlName = $aRouteConfig['ctrl'][0]; $this->actionName = $aRouteConfig['ctrl'][1]; unset($aParam[0]); $this->actionArgs = array_values($aParam); break; } } } }
{@inheritdoc}
https://github.com/selikhovleonid/nadir/blob/47545fccd8516c8f0a20c02ba62f68269c7199da/src/core/WebCtrlResolver.php#L64-L84
RowlandOti/ooglee-blogmodule
src/OoGlee/Domain/Entities/Post/Commands/GetPostPathCommand.php
GetPostPathCommand.handle
public function handle() { $data = [ 'year' => $this->post->created_at->format('Y'), 'month' => $this->post->created_at->format('m'), 'day' => $this->post->created_at->format('d'), 'post' => $this->post->getSlug() ]; return URL::route('post', $data); }
php
public function handle() { $data = [ 'year' => $this->post->created_at->format('Y'), 'month' => $this->post->created_at->format('m'), 'day' => $this->post->created_at->format('d'), 'post' => $this->post->getSlug() ]; return URL::route('post', $data); }
Handle the command. @return string
https://github.com/RowlandOti/ooglee-blogmodule/blob/d9c0fe4745bb09f8b94047b0cda4fd7438cde16a/src/OoGlee/Domain/Entities/Post/Commands/GetPostPathCommand.php#L42-L52
pmdevelopment/tool-bundle
Form/ConfigFormType.php
ConfigFormType.buildForm
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('value', $options['value_type'], [ 'label' => 'label.value', 'constraints' => new NotBlank(), ]); if (true === $options['show_submit_button']) { $builder ->add('submit', SubmitType::class, [ 'label' => 'button.save', ]); } }
php
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('value', $options['value_type'], [ 'label' => 'label.value', 'constraints' => new NotBlank(), ]); if (true === $options['show_submit_button']) { $builder ->add('submit', SubmitType::class, [ 'label' => 'button.save', ]); } }
{@inheritdoc}
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Form/ConfigFormType.php#L29-L43
octris/sqlbuilder
libs/Sqlbuilder/Template.php
Template.resolveSql
public function resolveSql(array $parameters = array()) { // sql statement from template $sql = preg_replace_callback('|/\*\*(.+?)\*\*/|', function($match) use (&$parameters) { $name = trim($match[1]); $snippet = $this->builder->resolveSnippet($name, $parameters); return $snippet; }, $this->sql); // resolve parameters $types = ''; $values = []; $sql = preg_replace_callback('/@(?P<type>.):(?P<name>.+?)@/', function($match) use (&$types, &$values, $parameters) { $types .= $match['type']; $values[] = $parameters[$match['name']]; return $this->builder->resolveParameter(count($values), $match['type'], $match['name']); }, $sql); return (object)['sql' => $sql, 'types' => $types, 'parameters' => $values]; }
php
public function resolveSql(array $parameters = array()) { // sql statement from template $sql = preg_replace_callback('|/\*\*(.+?)\*\*/|', function($match) use (&$parameters) { $name = trim($match[1]); $snippet = $this->builder->resolveSnippet($name, $parameters); return $snippet; }, $this->sql); // resolve parameters $types = ''; $values = []; $sql = preg_replace_callback('/@(?P<type>.):(?P<name>.+?)@/', function($match) use (&$types, &$values, $parameters) { $types .= $match['type']; $values[] = $parameters[$match['name']]; return $this->builder->resolveParameter(count($values), $match['type'], $match['name']); }, $sql); return (object)['sql' => $sql, 'types' => $types, 'parameters' => $values]; }
Resolve SQL statement. @param array $parameters Optional parameters for forming SQL statement. @return string Resolved SQL statement.
https://github.com/octris/sqlbuilder/blob/d22a494fd4814b3245fce20b4076eec1b382ffd3/libs/Sqlbuilder/Template.php#L54-L77
ben-gibson/foursquare-venue-client
src/Factory/ContactFactory.php
ContactFactory.create
public function create(Description $description) { return new ContactEntity( $description->getOptionalProperty('phone'), $description->getOptionalProperty('twitter'), $description->getOptionalProperty('facebook') ); }
php
public function create(Description $description) { return new ContactEntity( $description->getOptionalProperty('phone'), $description->getOptionalProperty('twitter'), $description->getOptionalProperty('facebook') ); }
Create contact information from a description. @param Description $description The contact description. @return ContactEntity
https://github.com/ben-gibson/foursquare-venue-client/blob/ce5e7c308f87d5ccc28ab8d27a9cb51bd106d969/src/Factory/ContactFactory.php#L19-L26
alphacomm/alpharpc
src/AlphaRPC/Manager/WorkerHandler/Action.php
Action.addWorker
public function addWorker($worker) { if (!$worker instanceof Worker) { throw new \Exception('$worker is not an instance of Worker'); } $this->workerList[$worker->getId()] = $worker; return $this; }
php
public function addWorker($worker) { if (!$worker instanceof Worker) { throw new \Exception('$worker is not an instance of Worker'); } $this->workerList[$worker->getId()] = $worker; return $this; }
Adds a worker to the action. @param Worker $worker @return Action @throws \Exception
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/WorkerHandler/Action.php#L76-L84
alphacomm/alpharpc
src/AlphaRPC/Manager/WorkerHandler/Action.php
Action.removeWorker
public function removeWorker($id) { if ($id instanceof Worker) { $id = $id->getId(); } if (isset($this->waitingList[$id])) { unset($this->waitingList[$id]); } if (isset($this->workerList[$id])) { unset($this->workerList[$id]); } return $this; }
php
public function removeWorker($id) { if ($id instanceof Worker) { $id = $id->getId(); } if (isset($this->waitingList[$id])) { unset($this->waitingList[$id]); } if (isset($this->workerList[$id])) { unset($this->workerList[$id]); } return $this; }
Removes the worker from the action. @param Worker $id @return Action
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/WorkerHandler/Action.php#L93-L107
alphacomm/alpharpc
src/AlphaRPC/Manager/WorkerHandler/Action.php
Action.addWaitingWorker
public function addWaitingWorker($id) { if ($id instanceof Worker) { $id = $id->getId(); } if (!isset($this->workerList[$id])) { throw new \Exception('Trying to add non existent worker to the queue.'); } $worker = $this->workerList[$id]; $this->ready = true; /* * Only add the worker to the end of the wait list if it is not * already there. */ if (!isset($this->waitingList[$id])) { $this->waitingList[$id] = $worker; } return $this; }
php
public function addWaitingWorker($id) { if ($id instanceof Worker) { $id = $id->getId(); } if (!isset($this->workerList[$id])) { throw new \Exception('Trying to add non existent worker to the queue.'); } $worker = $this->workerList[$id]; $this->ready = true; /* * Only add the worker to the end of the wait list if it is not * already there. */ if (!isset($this->waitingList[$id])) { $this->waitingList[$id] = $worker; } return $this; }
Adds the worker to the waiting list if it is not already in there. @param string|Worker $id @return Action @throws \Exception
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/WorkerHandler/Action.php#L117-L139
alphacomm/alpharpc
src/AlphaRPC/Manager/WorkerHandler/Action.php
Action.fetchWaitingWorker
public function fetchWaitingWorker() { $count = count($this->waitingList); for ($i = 0; $i < $count; $i++) { $worker = array_shift($this->waitingList); if ($worker->isValid() && $worker->isReady()) { return $worker; } } $this->ready = false; return null; }
php
public function fetchWaitingWorker() { $count = count($this->waitingList); for ($i = 0; $i < $count; $i++) { $worker = array_shift($this->waitingList); if ($worker->isValid() && $worker->isReady()) { return $worker; } } $this->ready = false; return null; }
Gets the first available worker in the waiting list. @return Worker|null
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/WorkerHandler/Action.php#L146-L159
alphacomm/alpharpc
src/AlphaRPC/Manager/WorkerHandler/Action.php
Action.cleanup
public function cleanup() { foreach ($this->workerList as $worker) { if (!$worker->isValid()) { $this->removeWorker($worker); } } return $this; }
php
public function cleanup() { foreach ($this->workerList as $worker) { if (!$worker->isValid()) { $this->removeWorker($worker); } } return $this; }
Removes all invalid workers. @return Action
https://github.com/alphacomm/alpharpc/blob/cf162854500554c4ba8d39f2675de35a49c30ed0/src/AlphaRPC/Manager/WorkerHandler/Action.php#L187-L196
acacha/forge-publish
src/Console/Commands/PublishInit.php
PublishInit.handle
public function handle() { $this->info('Hello! Together we are going to config Acacha Laravel Forge publish ...'); if (! ForgePublishRCFile::exists()) { $this->call('publish:rc'); }; $this->confirmAnUserIsCreatedInAcachaLaravelForge(); $this->call('publish:url'); $this->call('publish:email'); $this->login(); $this->call('publish:check_token'); $this->call('publish:server'); $this->call('publish:domain'); $this->call('publish:project_type'); $this->call('publish:site_directory'); $this->call('publish:site'); $this->call('publish:github'); $this->finish(); }
php
public function handle() { $this->info('Hello! Together we are going to config Acacha Laravel Forge publish ...'); if (! ForgePublishRCFile::exists()) { $this->call('publish:rc'); }; $this->confirmAnUserIsCreatedInAcachaLaravelForge(); $this->call('publish:url'); $this->call('publish:email'); $this->login(); $this->call('publish:check_token'); $this->call('publish:server'); $this->call('publish:domain'); $this->call('publish:project_type'); $this->call('publish:site_directory'); $this->call('publish:site'); $this->call('publish:github'); $this->finish(); }
Execute the console command.
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishInit.php#L33-L64
acacha/forge-publish
src/Console/Commands/PublishInit.php
PublishInit.confirmAnUserIsCreatedInAcachaLaravelForge
protected function confirmAnUserIsCreatedInAcachaLaravelForge() { $this->info(''); $this->info('Please visit and login on http://forge.acacha.org'); $this->info(''); $this->error('Please use Github Social Login for login!!!'); while (! $this->confirm('Do you have an user created at http:://forge.acacha.com?')) { } }
php
protected function confirmAnUserIsCreatedInAcachaLaravelForge() { $this->info(''); $this->info('Please visit and login on http://forge.acacha.org'); $this->info(''); $this->error('Please use Github Social Login for login!!!'); while (! $this->confirm('Do you have an user created at http:://forge.acacha.com?')) { } }
Confirm an user is created in Acacha Laravel Forge.
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishInit.php#L69-L78
acacha/forge-publish
src/Console/Commands/PublishInit.php
PublishInit.login
protected function login() { if (fp_env('ACACHA_FORGE_ACCESS_TOKEN')) { $this->info('You have a token already configured in your environment.'); if (! $this->confirm('Do you want to relogin?')) { return; } } $this->info('I need permissions to operate in Acacha Forge in your name...'); $this->info('So we need to obtain a valid token. Two options here:'); $this->info('1) Login: You provide your user credentials and I obtain the token from Laravel Forge'); $this->info('2) Personal Access Token: You provide a Personal Access token'); $option = $this->choice('Which one you prefer?', ['Login', 'Personal Access Token'], 0); if ($option == 'Login') { $this->call('publish:login', [ 'email' => fp_env('ACACHA_FORGE_EMAIL') ]); } else { $this->call('publish:token'); } }
php
protected function login() { if (fp_env('ACACHA_FORGE_ACCESS_TOKEN')) { $this->info('You have a token already configured in your environment.'); if (! $this->confirm('Do you want to relogin?')) { return; } } $this->info('I need permissions to operate in Acacha Forge in your name...'); $this->info('So we need to obtain a valid token. Two options here:'); $this->info('1) Login: You provide your user credentials and I obtain the token from Laravel Forge'); $this->info('2) Personal Access Token: You provide a Personal Access token'); $option = $this->choice('Which one you prefer?', ['Login', 'Personal Access Token'], 0); if ($option == 'Login') { $this->call('publish:login', [ 'email' => fp_env('ACACHA_FORGE_EMAIL') ]); } else { $this->call('publish:token'); } }
Login
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishInit.php#L83-L106
acacha/forge-publish
src/Console/Commands/PublishInit.php
PublishInit.finish
protected function finish() { $this->info(''); $this->info('Ok! let me resume: '); $this->call('publish:info'); $this->info(''); $this->info('Perfect! All info is saved to your environment (.env file).'); $this->info(''); $this->error('If needed, remember to rerun your server to apply changes in .env file!!!'); $this->info(''); $this->info("I have finished! Congratulations and enjoy Acha Laravel Forge!"); $this->info("You are now ready to publish your awesome project to Laravel Forge using:"); $this->info("**** php artisan publish ***"); }
php
protected function finish() { $this->info(''); $this->info('Ok! let me resume: '); $this->call('publish:info'); $this->info(''); $this->info('Perfect! All info is saved to your environment (.env file).'); $this->info(''); $this->error('If needed, remember to rerun your server to apply changes in .env file!!!'); $this->info(''); $this->info("I have finished! Congratulations and enjoy Acha Laravel Forge!"); $this->info("You are now ready to publish your awesome project to Laravel Forge using:"); $this->info("**** php artisan publish ***"); }
Finish command.
https://github.com/acacha/forge-publish/blob/010779e3d2297c763b82dc3fbde992edffb3a6c6/src/Console/Commands/PublishInit.php#L111-L128
pedra/phtml
Lib/Html.php
Html.assets
private function assets() { $s = ''; foreach($this->styles as $id=>$f){ $s .= '<link id="stylesheet_'.$id.'" rel="stylesheet" href="'.$this->url.'css/'.$f.'.css">'."\n\t"; } $this->val('style', $s); $s = '<script id="javascript_base">var URL=\''.$this->url.'\''; foreach ($this->jsvalues as $n=>$v) { $s .= ','.$n.'='.(is_string($v) ? '\''.str_replace("'", '"', $v).'\'' : $v); } $s .= ';</script>'; foreach($this->scripts as $id=>$f){ $s .= "\n\t".'<script id="javascript_'.$id.'" src="'.$this->url.'js/'.$f.'.js"></script>'; } $this->val('script', $s); //e($this); }
php
private function assets() { $s = ''; foreach($this->styles as $id=>$f){ $s .= '<link id="stylesheet_'.$id.'" rel="stylesheet" href="'.$this->url.'css/'.$f.'.css">'."\n\t"; } $this->val('style', $s); $s = '<script id="javascript_base">var URL=\''.$this->url.'\''; foreach ($this->jsvalues as $n=>$v) { $s .= ','.$n.'='.(is_string($v) ? '\''.str_replace("'", '"', $v).'\'' : $v); } $s .= ';</script>'; foreach($this->scripts as $id=>$f){ $s .= "\n\t".'<script id="javascript_'.$id.'" src="'.$this->url.'js/'.$f.'.js"></script>'; } $this->val('script', $s); //e($this); }
/* Produção dos links ou arquivos compactados. para Style e Javascript Em modo 'dev' gera somente os links; Em modo 'pro' compacta e obfusca os arquivos e insere diretamente no HTML.
https://github.com/pedra/phtml/blob/9c9237c1d5a8e2017cc912d732c6810de931bb7b/Lib/Html.php#L310-L329
pedra/phtml
Lib/Html.php
Html.sTag
private function sTag(&$arquivo, $ponteiro = -1, $tag = null) { if($tag == null) $tag = $this->tag; $inicio = strpos($arquivo, '<'.$tag, $ponteiro + 1); if($inicio !== false){ //get the type (<s:tipo ... ) $x = substr($arquivo, $inicio, 25); preg_match('/(?<tag>\w+):(?<type>\w+|[\:]\w+)/', $x, $m); if(!isset($m[0])) return false; $ntag = $m[0]; //the final ... $ftag = strpos($arquivo, '</' . $ntag . '>', $inicio); $fnTag = strpos($arquivo, '/>', $inicio); $fn = strpos($arquivo, '>', $inicio); //not /> or </s:xxx> = error if($fnTag === false && $ftag === false) return false; if($ftag !== false ) { if($fn !== false && $fn < $ftag){ $a['-content-'] = substr($arquivo, $fn+1, ($ftag - $fn)-1); $finTag = $fn; $a['-final-'] = $ftag + strlen('</'.$ntag.'>'); } else return false; } elseif($fnTag !== false) { $a['-content-'] = ''; $finTag = $fnTag; $a['-final-'] = $fnTag + 2; } else return false; //catching attributes preg_match_all('/(?<att>\w+)="(?<val>.*?)"/', substr($arquivo, $inicio, $finTag - $inicio), $atb); if(isset($atb['att'])){ foreach ($atb['att'] as $k=>$v){ $a[$v] = $atb['val'][$k]; } } //block data $a['-inicio-'] = $inicio; $a['-tamanho-'] = ($a['-final-'] - $inicio); $a['-tipo-'] = 'var'; if(strpos($m['type'], ':') !== false) $a['-tipo-'] = str_replace (':', '', $m['type']); else $a['var'] = $m['type']; return $a; } return false; }
php
private function sTag(&$arquivo, $ponteiro = -1, $tag = null) { if($tag == null) $tag = $this->tag; $inicio = strpos($arquivo, '<'.$tag, $ponteiro + 1); if($inicio !== false){ //get the type (<s:tipo ... ) $x = substr($arquivo, $inicio, 25); preg_match('/(?<tag>\w+):(?<type>\w+|[\:]\w+)/', $x, $m); if(!isset($m[0])) return false; $ntag = $m[0]; //the final ... $ftag = strpos($arquivo, '</' . $ntag . '>', $inicio); $fnTag = strpos($arquivo, '/>', $inicio); $fn = strpos($arquivo, '>', $inicio); //not /> or </s:xxx> = error if($fnTag === false && $ftag === false) return false; if($ftag !== false ) { if($fn !== false && $fn < $ftag){ $a['-content-'] = substr($arquivo, $fn+1, ($ftag - $fn)-1); $finTag = $fn; $a['-final-'] = $ftag + strlen('</'.$ntag.'>'); } else return false; } elseif($fnTag !== false) { $a['-content-'] = ''; $finTag = $fnTag; $a['-final-'] = $fnTag + 2; } else return false; //catching attributes preg_match_all('/(?<att>\w+)="(?<val>.*?)"/', substr($arquivo, $inicio, $finTag - $inicio), $atb); if(isset($atb['att'])){ foreach ($atb['att'] as $k=>$v){ $a[$v] = $atb['val'][$k]; } } //block data $a['-inicio-'] = $inicio; $a['-tamanho-'] = ($a['-final-'] - $inicio); $a['-tipo-'] = 'var'; if(strpos($m['type'], ':') !== false) $a['-tipo-'] = str_replace (':', '', $m['type']); else $a['var'] = $m['type']; return $a; } return false; }
Scaner for ©NeosTag Scans the file to find a ©NeosTag - returns an array with the data found ©NeosTag @param string $arquivo file content @param string $ponteiro file pointer @param string $tag ©NeosTag to scan @return array|false array with the data found ©NeosTag or false (not ©NeosTag)
https://github.com/pedra/phtml/blob/9c9237c1d5a8e2017cc912d732c6810de931bb7b/Lib/Html.php#L466-L517
pedra/phtml
Lib/Html.php
Html.blade
private function blade() { $arquivo = $this->getContent(); $t = strlen($arquivo) - 1; $ini = ''; $o = ''; for($i =0; $i <= $t; $i++){ if($ini != '' && $ini < $i){ if($arquivo[$i] == '@' && ($i - $ini) < 2) { $o .= '@'; $ini = ''; continue; } if(!preg_match("/[a-zA-Z0-9\.:\[\]\-_()\/'$+,\\\]/",$arquivo[$i])){ $out1 = substr($arquivo, $ini+1, $i-$ini-1); $out = rtrim($out1, ',.:'); $i += (strlen($out) - strlen($out1)); if($this->getVar($out)) $out = $this->getVar($out); else { restore_error_handler(); ob_start(); $ret = eval('return '.$out.';'); if(ob_get_clean() === '') $out = $ret; else $out = ''; } $o .= $out; //exit($o); $ini = ''; if($arquivo[$i] != ' ') $i --;//retirando espaço em branco... } } elseif($ini == '' && $arquivo[$i] == '@') $ini = $i; else $o .= $arquivo[$i]; }//end FOR return $this->setContent($o); }
php
private function blade() { $arquivo = $this->getContent(); $t = strlen($arquivo) - 1; $ini = ''; $o = ''; for($i =0; $i <= $t; $i++){ if($ini != '' && $ini < $i){ if($arquivo[$i] == '@' && ($i - $ini) < 2) { $o .= '@'; $ini = ''; continue; } if(!preg_match("/[a-zA-Z0-9\.:\[\]\-_()\/'$+,\\\]/",$arquivo[$i])){ $out1 = substr($arquivo, $ini+1, $i-$ini-1); $out = rtrim($out1, ',.:'); $i += (strlen($out) - strlen($out1)); if($this->getVar($out)) $out = $this->getVar($out); else { restore_error_handler(); ob_start(); $ret = eval('return '.$out.';'); if(ob_get_clean() === '') $out = $ret; else $out = ''; } $o .= $out; //exit($o); $ini = ''; if($arquivo[$i] != ' ') $i --;//retirando espaço em branco... } } elseif($ini == '' && $arquivo[$i] == '@') $ini = $i; else $o .= $arquivo[$i]; }//end FOR return $this->setContent($o); }
Scaner para Blade. Retorna o conteúdo substituindo variáveis BLADE (@var_name). @return void O mesmo conteudo com variáveis BLADE substituídas
https://github.com/pedra/phtml/blob/9c9237c1d5a8e2017cc912d732c6810de931bb7b/Lib/Html.php#L525-L561
pedra/phtml
Lib/Html.php
Html._var
private function _var($ret) { $v = $this->getVar($ret['var']); if(!$v) return ''; //$ret['-content-'] .= $v; $ret['-content-'] .= '<?php echo Lib\Html::get("'.trim($ret['var']).'")?>'; //List type if(is_array($v)) return $this->_list($ret); return $this->setAttributes($ret); }
php
private function _var($ret) { $v = $this->getVar($ret['var']); if(!$v) return ''; //$ret['-content-'] .= $v; $ret['-content-'] .= '<?php echo Lib\Html::get("'.trim($ret['var']).'")?>'; //List type if(is_array($v)) return $this->_list($ret); return $this->setAttributes($ret); }
_var Insert variable data assigned in view Parameter "tag" is the tag type indicator (ex.: <s:variable . . . tag="span" />) @param array $ret ©NeosTag data array @return string Renderized Html
https://github.com/pedra/phtml/blob/9c9237c1d5a8e2017cc912d732c6810de931bb7b/Lib/Html.php#L571-L582
pedra/phtml
Lib/Html.php
Html._list
private function _list($ret) { if(!isset($ret['var'])) return ''; $v = $this->getVar($ret['var']); if(!$v || !is_array($v)) return ''; $tag = isset($ret['tag']) ? $ret['tag'] : 'li'; $ret = $this->clearData($ret); //Tag UL and params. (class, id, etc) $o = '<ul'; foreach($ret as $k=>$val){ $o .= ' '.trim($k).'="'.trim($val).'"'; } $o .= '>'; //create list foreach ($v as $k=>$val){ $o .= '<'.$tag.'>'.$val.'</'.$tag.'>'; } return $o . '</ul>'; }
php
private function _list($ret) { if(!isset($ret['var'])) return ''; $v = $this->getVar($ret['var']); if(!$v || !is_array($v)) return ''; $tag = isset($ret['tag']) ? $ret['tag'] : 'li'; $ret = $this->clearData($ret); //Tag UL and params. (class, id, etc) $o = '<ul'; foreach($ret as $k=>$val){ $o .= ' '.trim($k).'="'.trim($val).'"'; } $o .= '>'; //create list foreach ($v as $k=>$val){ $o .= '<'.$tag.'>'.$val.'</'.$tag.'>'; } return $o . '</ul>'; }
_list :: Create ul html tag Parameter "tag" is the list type indicator (ex.: <s:_list . . . tag="li" />) @param array $ret ©NeosTag data array @return string|html
https://github.com/pedra/phtml/blob/9c9237c1d5a8e2017cc912d732c6810de931bb7b/Lib/Html.php#L591-L611
pedra/phtml
Lib/Html.php
Html._block
private function _block($ret) { if(!isset($ret['name'])) return ''; $ret['-content-'] .= $this->getBlock(trim($ret['name'])); if($ret['-content-'] == false) return ''; unset($ret['name']); return $this->setAttributes($ret); }
php
private function _block($ret) { if(!isset($ret['name'])) return ''; $ret['-content-'] .= $this->getBlock(trim($ret['name'])); if($ret['-content-'] == false) return ''; unset($ret['name']); return $this->setAttributes($ret); }
_block :: insert content block Parameter "name" is the name of block; @param array $ret ©NeosTag data array @return string|html
https://github.com/pedra/phtml/blob/9c9237c1d5a8e2017cc912d732c6810de931bb7b/Lib/Html.php#L620-L628
pedra/phtml
Lib/Html.php
Html._select
private function _select($ret) { $var = $this->getVar($ret['data']); if(!$var) return false; $o = ''; foreach($var['data'] as $k => $v) { $o .= '<option value="'.$k.'"'.($var['default'] == $k ? ' selected':'').'>'.$v.'</option>'; } $ret['-content-'] = $o; $ret['tag'] = 'select'; return $this->setAttributes($ret); }
php
private function _select($ret) { $var = $this->getVar($ret['data']); if(!$var) return false; $o = ''; foreach($var['data'] as $k => $v) { $o .= '<option value="'.$k.'"'.($var['default'] == $k ? ' selected':'').'>'.$v.'</option>'; } $ret['-content-'] = $o; $ret['tag'] = 'select'; return $this->setAttributes($ret); }
Create <select> HTML tag configuration: $select['data'] = ['value'=>'display', 'val....]; $select['default'] = '..value...'; $LibDocHtml->val('varName',$select); ---- in HTML file <x::select data="varName" ...some attributes /> @param array $ret ©NeosTag data array @return string|html
https://github.com/pedra/phtml/blob/9c9237c1d5a8e2017cc912d732c6810de931bb7b/Lib/Html.php#L643-L655
YiMAproject/yimaWidgetator
src/yimaWidgetator/Widget/AbstractWidgetMvc.php
AbstractWidgetMvc.getLayout
function getLayout() { $layoutName = ($this->layout) ? $this->layout : $this->getDefaultLayoutName(); if (strstr($layoutName, '/') === false) { // we have just layout name // the directory prefix assigned to it $DS = (defined('DS')) ? constant('DS') : DIRECTORY_SEPARATOR; // derive default layout pathname $pathname = self::$PATH_PREFIX # widgets .$DS .$this->deriveLayoutPathPrefix() # namespace_widget\widget_name\ .$DS .$layoutName; $this->layout = $pathname; } return $this->layout; }
php
function getLayout() { $layoutName = ($this->layout) ? $this->layout : $this->getDefaultLayoutName(); if (strstr($layoutName, '/') === false) { // we have just layout name // the directory prefix assigned to it $DS = (defined('DS')) ? constant('DS') : DIRECTORY_SEPARATOR; // derive default layout pathname $pathname = self::$PATH_PREFIX # widgets .$DS .$this->deriveLayoutPathPrefix() # namespace_widget\widget_name\ .$DS .$layoutName; $this->layout = $pathname; } return $this->layout; }
Get view script layout @return string|ModelInterface
https://github.com/YiMAproject/yimaWidgetator/blob/332bc9318e6ceaec918147b30317da2f5b3d2636/src/yimaWidgetator/Widget/AbstractWidgetMvc.php#L69-L90
YiMAproject/yimaWidgetator
src/yimaWidgetator/Widget/AbstractWidgetMvc.php
AbstractWidgetMvc.deriveLayoutPathPrefix
final function deriveLayoutPathPrefix() { $moduleNamespace = $this->deriveModuleNamespace(); $path = ($moduleNamespace) ? $moduleNamespace .'/' : ''; $path .= $this->deriveWidgetName(); // in some cases widget name contains \ from class namespace $path = str_replace('\\', '/', $this->inflectName($path)); return $path; }
php
final function deriveLayoutPathPrefix() { $moduleNamespace = $this->deriveModuleNamespace(); $path = ($moduleNamespace) ? $moduleNamespace .'/' : ''; $path .= $this->deriveWidgetName(); // in some cases widget name contains \ from class namespace $path = str_replace('\\', '/', $this->inflectName($path)); return $path; }
Get layout path prefixed to module layout name note: WidgetNamespace\WidgetName inflected: widget_namespace\widget_name @return string
https://github.com/YiMAproject/yimaWidgetator/blob/332bc9318e6ceaec918147b30317da2f5b3d2636/src/yimaWidgetator/Widget/AbstractWidgetMvc.php#L138-L148
IftekherSunny/Planet-Framework
src/Sun/Console/Commands/MakeCommand.php
MakeCommand.handle
public function handle() { // generate command class $commandName = $this->input->getArgument('name'); $commandNamespace = $this->getNamespace('Commands', $commandName); $commandStubs = $this->filesystem->get(__DIR__.'/../stubs/MakeCommand.txt'); $commandStubs = str_replace([ 'dummyCommandName', 'dummyNamespace', '\\\\' ], [ basename($commandName), $commandNamespace, '\\' ], $commandStubs); if(!file_exists($filename = app_path() ."/Commands/{$commandName}Command.php")) { $this->filesystem->create($filename, $commandStubs); $this->info("{$commandName} command has been created successfully."); } else { $this->info("{$commandName} command already exists."); } // generate command handler class $commandHandlerNamespace = $this->getNamespace('Handlers', $commandName); $commandClassName = basename($commandName); $commandHandlerUse = "{$commandNamespace}\\{$commandClassName}"; $commandHandlerStubs = $this->filesystem->get(__DIR__.'/../stubs/MakeCommand-handler.txt'); $commandHandlerStubs = str_replace( [ 'dummyCommandName', 'dummyNamespace', 'dummyUse', '\\\\' ], [ basename($commandName), $commandHandlerNamespace, $commandHandlerUse, '\\' ], $commandHandlerStubs ); if(!file_exists($filename = app_path() ."/Handlers/{$commandName}CommandHandler.php")) { $this->filesystem->create($filename, $commandHandlerStubs); $this->info("{$commandName} handler has been created successfully."); } else { $this->info("{$commandName} handler already exists."); } }
php
public function handle() { // generate command class $commandName = $this->input->getArgument('name'); $commandNamespace = $this->getNamespace('Commands', $commandName); $commandStubs = $this->filesystem->get(__DIR__.'/../stubs/MakeCommand.txt'); $commandStubs = str_replace([ 'dummyCommandName', 'dummyNamespace', '\\\\' ], [ basename($commandName), $commandNamespace, '\\' ], $commandStubs); if(!file_exists($filename = app_path() ."/Commands/{$commandName}Command.php")) { $this->filesystem->create($filename, $commandStubs); $this->info("{$commandName} command has been created successfully."); } else { $this->info("{$commandName} command already exists."); } // generate command handler class $commandHandlerNamespace = $this->getNamespace('Handlers', $commandName); $commandClassName = basename($commandName); $commandHandlerUse = "{$commandNamespace}\\{$commandClassName}"; $commandHandlerStubs = $this->filesystem->get(__DIR__.'/../stubs/MakeCommand-handler.txt'); $commandHandlerStubs = str_replace( [ 'dummyCommandName', 'dummyNamespace', 'dummyUse', '\\\\' ], [ basename($commandName), $commandHandlerNamespace, $commandHandlerUse, '\\' ], $commandHandlerStubs ); if(!file_exists($filename = app_path() ."/Handlers/{$commandName}CommandHandler.php")) { $this->filesystem->create($filename, $commandHandlerStubs); $this->info("{$commandName} handler has been created successfully."); } else { $this->info("{$commandName} handler already exists."); } }
To handle console command
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Commands/MakeCommand.php#L43-L77
air-php/database
src/Connection.php
Connection.getConnection
private function getConnection() { if (!isset($this->connection)) { $config = new Configuration(); $this->connection = DriverManager::getConnection($this->connectionParams, $config); } return $this->connection; }
php
private function getConnection() { if (!isset($this->connection)) { $config = new Configuration(); $this->connection = DriverManager::getConnection($this->connectionParams, $config); } return $this->connection; }
Returns the connection object. @return Connection
https://github.com/air-php/database/blob/74bdd485b36f3f353b51ab146d2130dd9fc714bd/src/Connection.php#L70-L79
air-php/database
src/Connection.php
Connection.setTimezone
public function setTimezone($timezone) { $smt = $this->getConnection()->prepare('SET time_zone = ?'); $smt->bindValue(1, $timezone); $smt->execute(); }
php
public function setTimezone($timezone) { $smt = $this->getConnection()->prepare('SET time_zone = ?'); $smt->bindValue(1, $timezone); $smt->execute(); }
Sets a timezone. @param string $timezone The timezone you wish to set.
https://github.com/air-php/database/blob/74bdd485b36f3f353b51ab146d2130dd9fc714bd/src/Connection.php#L87-L92
hal-platform/hal-core
src/Crypto/Encryption.php
Encryption.encrypt
public function encrypt($data) { if (!$data || !is_scalar($data)) { return null; } $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); $cipher = sodium_crypto_secretbox($data, $nonce, $this->key); return base64_encode($nonce . $cipher); }
php
public function encrypt($data) { if (!$data || !is_scalar($data)) { return null; } $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); $cipher = sodium_crypto_secretbox($data, $nonce, $this->key); return base64_encode($nonce . $cipher); }
Encrypt a string. @param string $data @return string|null
https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Crypto/Encryption.php#L52-L62
hal-platform/hal-core
src/Crypto/Encryption.php
Encryption.decrypt
public function decrypt($data) { if (!$data || !is_scalar($data)) { return null; } $decoded = base64_decode($data, true); if ($decoded === false) { return null; } if (strlen($decoded) < SODIUM_CRYPTO_SECRETBOX_NONCEBYTES) { return null; } $nonce = substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); $cipher = substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); $decrypted = sodium_crypto_secretbox_open($cipher, $nonce, $this->key); if ($decrypted === false) { return null; } return $decrypted; }
php
public function decrypt($data) { if (!$data || !is_scalar($data)) { return null; } $decoded = base64_decode($data, true); if ($decoded === false) { return null; } if (strlen($decoded) < SODIUM_CRYPTO_SECRETBOX_NONCEBYTES) { return null; } $nonce = substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); $cipher = substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); $decrypted = sodium_crypto_secretbox_open($cipher, $nonce, $this->key); if ($decrypted === false) { return null; } return $decrypted; }
Decrypt a string. @param string $data @return string|null
https://github.com/hal-platform/hal-core/blob/30d456f8392fc873301ad4217d2ae90436c67090/src/Crypto/Encryption.php#L71-L96