repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
schpill/thin
src/Html/Sizer.php
Sizer.getCropPoints
private function getCropPoints($optimalWidth, $optimalHeight, $newWidth, $newHeight) { $cropPoints = array(); $vertical_start = arrayGet($this->config, 'crop_vertical_start_point'); $horizontal_start = arrayGet($this->config, 'crop_horizontal_start_point'); // Where is our vertical starting crop point? switch ($vertical_start) { case 'top': $cropPoints['y'] = 0; break; case 'center': $cropPoints['y'] = ($optimalHeight / 2) - ($newHeight / 2); break; case 'bottom': $cropPoints['y'] = $optimalHeight - $newHeight; break; default: throw new Exception('Unknown value for crop_vertical_start_point: '. $vertical_start .'. Please check config file in the Resizer bundle.'); break; } // Where is our horizontal starting crop point? switch ($horizontal_start) { case 'left': $cropPoints['x'] = 0; break; case 'center': $cropPoints['x'] = ($optimalWidth / 2) - ($newWidth / 2); break; case 'right': $cropPoints['x'] = $optimalWidth - $newWidth; break; default: throw new Exception('Unknown value for crop_horizontal_start_point: '. $horizontal_start .'. Please check config file in the Resizer bundle.'); break; } return $cropPoints; }
php
private function getCropPoints($optimalWidth, $optimalHeight, $newWidth, $newHeight) { $cropPoints = array(); $vertical_start = arrayGet($this->config, 'crop_vertical_start_point'); $horizontal_start = arrayGet($this->config, 'crop_horizontal_start_point'); // Where is our vertical starting crop point? switch ($vertical_start) { case 'top': $cropPoints['y'] = 0; break; case 'center': $cropPoints['y'] = ($optimalHeight / 2) - ($newHeight / 2); break; case 'bottom': $cropPoints['y'] = $optimalHeight - $newHeight; break; default: throw new Exception('Unknown value for crop_vertical_start_point: '. $vertical_start .'. Please check config file in the Resizer bundle.'); break; } // Where is our horizontal starting crop point? switch ($horizontal_start) { case 'left': $cropPoints['x'] = 0; break; case 'center': $cropPoints['x'] = ($optimalWidth / 2) - ($newWidth / 2); break; case 'right': $cropPoints['x'] = $optimalWidth - $newWidth; break; default: throw new Exception('Unknown value for crop_horizontal_start_point: '. $horizontal_start .'. Please check config file in the Resizer bundle.'); break; } return $cropPoints; }
[ "private", "function", "getCropPoints", "(", "$", "optimalWidth", ",", "$", "optimalHeight", ",", "$", "newWidth", ",", "$", "newHeight", ")", "{", "$", "cropPoints", "=", "array", "(", ")", ";", "$", "vertical_start", "=", "arrayGet", "(", "$", "this", "->", "config", ",", "'crop_vertical_start_point'", ")", ";", "$", "horizontal_start", "=", "arrayGet", "(", "$", "this", "->", "config", ",", "'crop_horizontal_start_point'", ")", ";", "// Where is our vertical starting crop point?", "switch", "(", "$", "vertical_start", ")", "{", "case", "'top'", ":", "$", "cropPoints", "[", "'y'", "]", "=", "0", ";", "break", ";", "case", "'center'", ":", "$", "cropPoints", "[", "'y'", "]", "=", "(", "$", "optimalHeight", "/", "2", ")", "-", "(", "$", "newHeight", "/", "2", ")", ";", "break", ";", "case", "'bottom'", ":", "$", "cropPoints", "[", "'y'", "]", "=", "$", "optimalHeight", "-", "$", "newHeight", ";", "break", ";", "default", ":", "throw", "new", "Exception", "(", "'Unknown value for crop_vertical_start_point: '", ".", "$", "vertical_start", ".", "'. Please check config file in the Resizer bundle.'", ")", ";", "break", ";", "}", "// Where is our horizontal starting crop point?", "switch", "(", "$", "horizontal_start", ")", "{", "case", "'left'", ":", "$", "cropPoints", "[", "'x'", "]", "=", "0", ";", "break", ";", "case", "'center'", ":", "$", "cropPoints", "[", "'x'", "]", "=", "(", "$", "optimalWidth", "/", "2", ")", "-", "(", "$", "newWidth", "/", "2", ")", ";", "break", ";", "case", "'right'", ":", "$", "cropPoints", "[", "'x'", "]", "=", "$", "optimalWidth", "-", "$", "newWidth", ";", "break", ";", "default", ":", "throw", "new", "Exception", "(", "'Unknown value for crop_horizontal_start_point: '", ".", "$", "horizontal_start", ".", "'. Please check config file in the Resizer bundle.'", ")", ";", "break", ";", "}", "return", "$", "cropPoints", ";", "}" ]
Gets the crop points based on the configuration either set in the file or overridden by user in their own config file, or on the fly. @param int $optimalWidth The width of the image @param int $optimalHeight The height of the image @param int $newWidth The new width @param int $newHeight The new height @return array Array containing the crop x and y points.
[ "Gets", "the", "crop", "points", "based", "on", "the", "configuration", "either", "set", "in", "the", "file", "or", "overridden", "by", "user", "in", "their", "own", "config", "file", "or", "on", "the", "fly", "." ]
a9102d9d6f70e8b0f6be93153f70849f46489ee1
https://github.com/schpill/thin/blob/a9102d9d6f70e8b0f6be93153f70849f46489ee1/src/Html/Sizer.php#L430-L472
train
theloopyewe/ravelry-api.php
src/RavelryApi/TypeConversion.php
TypeConversion.toRavelryPostFile
public static function toRavelryPostFile($value, Parameter $parameter) { if (is_string($value)) { $value = fopen($value, 'r'); } if (!($value instanceof StreamInterface)) { $value = \GuzzleHttp\Stream\create($value); } if ($value instanceof MetadataStreamInterface) { $filename = $value->getMetadata('uri'); } if (!$filename || substr($filename, 0, 6) === 'php://') { $filename = $parameter->getWireName(); } return new PostFile( $parameter->getWireName(), $value, $filename, [ 'Content-Disposition' => sprintf( 'form-data; name="%s"; filename="%s"', $parameter->getWireName(), basename($filename) ), ] ); }
php
public static function toRavelryPostFile($value, Parameter $parameter) { if (is_string($value)) { $value = fopen($value, 'r'); } if (!($value instanceof StreamInterface)) { $value = \GuzzleHttp\Stream\create($value); } if ($value instanceof MetadataStreamInterface) { $filename = $value->getMetadata('uri'); } if (!$filename || substr($filename, 0, 6) === 'php://') { $filename = $parameter->getWireName(); } return new PostFile( $parameter->getWireName(), $value, $filename, [ 'Content-Disposition' => sprintf( 'form-data; name="%s"; filename="%s"', $parameter->getWireName(), basename($filename) ), ] ); }
[ "public", "static", "function", "toRavelryPostFile", "(", "$", "value", ",", "Parameter", "$", "parameter", ")", "{", "if", "(", "is_string", "(", "$", "value", ")", ")", "{", "$", "value", "=", "fopen", "(", "$", "value", ",", "'r'", ")", ";", "}", "if", "(", "!", "(", "$", "value", "instanceof", "StreamInterface", ")", ")", "{", "$", "value", "=", "\\", "GuzzleHttp", "\\", "Stream", "\\", "create", "(", "$", "value", ")", ";", "}", "if", "(", "$", "value", "instanceof", "MetadataStreamInterface", ")", "{", "$", "filename", "=", "$", "value", "->", "getMetadata", "(", "'uri'", ")", ";", "}", "if", "(", "!", "$", "filename", "||", "substr", "(", "$", "filename", ",", "0", ",", "6", ")", "===", "'php://'", ")", "{", "$", "filename", "=", "$", "parameter", "->", "getWireName", "(", ")", ";", "}", "return", "new", "PostFile", "(", "$", "parameter", "->", "getWireName", "(", ")", ",", "$", "value", ",", "$", "filename", ",", "[", "'Content-Disposition'", "=>", "sprintf", "(", "'form-data; name=\"%s\"; filename=\"%s\"'", ",", "$", "parameter", "->", "getWireName", "(", ")", ",", "basename", "(", "$", "filename", ")", ")", ",", "]", ")", ";", "}" ]
This is duplicating logic from `GuzzleHttp\Post\PostFile` in order to patch odd API server behavior. It also makes sure the value is a proper stream reference. See http://www.ravelry.com/discuss/ravelry-api/2936052/1-25#5
[ "This", "is", "duplicating", "logic", "from", "GuzzleHttp", "\\", "Post", "\\", "PostFile", "in", "order", "to", "patch", "odd", "API", "server", "behavior", ".", "It", "also", "makes", "sure", "the", "value", "is", "a", "proper", "stream", "reference", "." ]
4dacae056e15cf5fd4e236b79843d0736db1e885
https://github.com/theloopyewe/ravelry-api.php/blob/4dacae056e15cf5fd4e236b79843d0736db1e885/src/RavelryApi/TypeConversion.php#L108-L138
train
bruno-barros/w.eloquent-framework
src/weloquent/Support/TaxonomyTrait.php
TaxonomyTrait.getPostType
public function getPostType() { global $wp_query; if(isset($wp_query->post) && $wp_query->post->post_type) { return $wp_query->post->post_type; } if (isset($wp_query->query) && isset($wp_query->query['post_type'])) { return $wp_query->query['post_type']; } else if(isset($wp_query->query_vars) && isset($wp_query->query_vars['post_type'])) { return $wp_query->query_vars['post_type']; } return false; }
php
public function getPostType() { global $wp_query; if(isset($wp_query->post) && $wp_query->post->post_type) { return $wp_query->post->post_type; } if (isset($wp_query->query) && isset($wp_query->query['post_type'])) { return $wp_query->query['post_type']; } else if(isset($wp_query->query_vars) && isset($wp_query->query_vars['post_type'])) { return $wp_query->query_vars['post_type']; } return false; }
[ "public", "function", "getPostType", "(", ")", "{", "global", "$", "wp_query", ";", "if", "(", "isset", "(", "$", "wp_query", "->", "post", ")", "&&", "$", "wp_query", "->", "post", "->", "post_type", ")", "{", "return", "$", "wp_query", "->", "post", "->", "post_type", ";", "}", "if", "(", "isset", "(", "$", "wp_query", "->", "query", ")", "&&", "isset", "(", "$", "wp_query", "->", "query", "[", "'post_type'", "]", ")", ")", "{", "return", "$", "wp_query", "->", "query", "[", "'post_type'", "]", ";", "}", "else", "if", "(", "isset", "(", "$", "wp_query", "->", "query_vars", ")", "&&", "isset", "(", "$", "wp_query", "->", "query_vars", "[", "'post_type'", "]", ")", ")", "{", "return", "$", "wp_query", "->", "query_vars", "[", "'post_type'", "]", ";", "}", "return", "false", ";", "}" ]
Return the post type slug if available @return bool|string
[ "Return", "the", "post", "type", "slug", "if", "available" ]
d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd
https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Support/TaxonomyTrait.php#L17-L35
train
bruno-barros/w.eloquent-framework
src/weloquent/Support/TaxonomyTrait.php
TaxonomyTrait.getTax
public function getTax() { global $wp_query; if (isset($wp_query->tax_query) && !empty($wp_query->tax_query)) { return reset($wp_query->tax_query->queries)['taxonomy']; } return false; }
php
public function getTax() { global $wp_query; if (isset($wp_query->tax_query) && !empty($wp_query->tax_query)) { return reset($wp_query->tax_query->queries)['taxonomy']; } return false; }
[ "public", "function", "getTax", "(", ")", "{", "global", "$", "wp_query", ";", "if", "(", "isset", "(", "$", "wp_query", "->", "tax_query", ")", "&&", "!", "empty", "(", "$", "wp_query", "->", "tax_query", ")", ")", "{", "return", "reset", "(", "$", "wp_query", "->", "tax_query", "->", "queries", ")", "[", "'taxonomy'", "]", ";", "}", "return", "false", ";", "}" ]
Return the taxonomy slug if available @return bool|mixed
[ "Return", "the", "taxonomy", "slug", "if", "available" ]
d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd
https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Support/TaxonomyTrait.php#L42-L52
train
bruno-barros/w.eloquent-framework
src/weloquent/Support/TaxonomyTrait.php
TaxonomyTrait.getTerm
public function getTerm() { global $wp_query; if (isset($wp_query->tax_query) && !empty($wp_query->tax_query)) { $first = reset($wp_query->tax_query->queries); return is_array($first) ? reset($first['terms']) : false; } return false; }
php
public function getTerm() { global $wp_query; if (isset($wp_query->tax_query) && !empty($wp_query->tax_query)) { $first = reset($wp_query->tax_query->queries); return is_array($first) ? reset($first['terms']) : false; } return false; }
[ "public", "function", "getTerm", "(", ")", "{", "global", "$", "wp_query", ";", "if", "(", "isset", "(", "$", "wp_query", "->", "tax_query", ")", "&&", "!", "empty", "(", "$", "wp_query", "->", "tax_query", ")", ")", "{", "$", "first", "=", "reset", "(", "$", "wp_query", "->", "tax_query", "->", "queries", ")", ";", "return", "is_array", "(", "$", "first", ")", "?", "reset", "(", "$", "first", "[", "'terms'", "]", ")", ":", "false", ";", "}", "return", "false", ";", "}" ]
Return the taxonomy term if available @return bool|mixed
[ "Return", "the", "taxonomy", "term", "if", "available" ]
d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd
https://github.com/bruno-barros/w.eloquent-framework/blob/d252dcb1ba1b6b1cecf67877d7d6d3ba57ebedbd/src/weloquent/Support/TaxonomyTrait.php#L59-L70
train
inhere/php-library-plus
libs/Network/Telnet.php
Telnet.watch
public function watch($command, $interval = 500) { $count = 0; $activeTime = time(); $maxTime = (int)$this->config['max_watch_time']; $intervalUs = $interval * 1000; //echo "watch command: $command, refresh interval: {$interval}ms\n"; while (true) { $count++; $result = $this->command($command); if (0 === strpos($result, 'ERR')) { echo "$result\n"; echo "error command: $command. "; break; } // clear screen before output echo "\033[2JThe {$count} times watch {$command} result(refresh interval: {$interval}ms):\n{$result}\n"; if ($maxTime > 0 && time() - $activeTime >= $maxTime) { echo 'watch time end. '; break; } usleep($intervalUs); } echo "Quit\n"; }
php
public function watch($command, $interval = 500) { $count = 0; $activeTime = time(); $maxTime = (int)$this->config['max_watch_time']; $intervalUs = $interval * 1000; //echo "watch command: $command, refresh interval: {$interval}ms\n"; while (true) { $count++; $result = $this->command($command); if (0 === strpos($result, 'ERR')) { echo "$result\n"; echo "error command: $command. "; break; } // clear screen before output echo "\033[2JThe {$count} times watch {$command} result(refresh interval: {$interval}ms):\n{$result}\n"; if ($maxTime > 0 && time() - $activeTime >= $maxTime) { echo 'watch time end. '; break; } usleep($intervalUs); } echo "Quit\n"; }
[ "public", "function", "watch", "(", "$", "command", ",", "$", "interval", "=", "500", ")", "{", "$", "count", "=", "0", ";", "$", "activeTime", "=", "time", "(", ")", ";", "$", "maxTime", "=", "(", "int", ")", "$", "this", "->", "config", "[", "'max_watch_time'", "]", ";", "$", "intervalUs", "=", "$", "interval", "*", "1000", ";", "//echo \"watch command: $command, refresh interval: {$interval}ms\\n\";", "while", "(", "true", ")", "{", "$", "count", "++", ";", "$", "result", "=", "$", "this", "->", "command", "(", "$", "command", ")", ";", "if", "(", "0", "===", "strpos", "(", "$", "result", ",", "'ERR'", ")", ")", "{", "echo", "\"$result\\n\"", ";", "echo", "\"error command: $command. \"", ";", "break", ";", "}", "// clear screen before output", "echo", "\"\\033[2JThe {$count} times watch {$command} result(refresh interval: {$interval}ms):\\n{$result}\\n\"", ";", "if", "(", "$", "maxTime", ">", "0", "&&", "time", "(", ")", "-", "$", "activeTime", ">=", "$", "maxTime", ")", "{", "echo", "'watch time end. '", ";", "break", ";", "}", "usleep", "(", "$", "intervalUs", ")", ";", "}", "echo", "\"Quit\\n\"", ";", "}" ]
watch a command @param string $command @param integer $interval (ms)
[ "watch", "a", "command" ]
8604e037937d31fa2338d79aaf9d0910cb48f559
https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Network/Telnet.php#L179-L210
train
inhere/php-library-plus
libs/Network/Telnet.php
Telnet.interactive
public function interactive() { echo "welcome! please input command('quit' or 'exit' to Quit).\n "; while (true) { echo '> '; if ($cmd = trim(fgets(\STDIN))) { // echo "input command: $cmd\n"; if ($cmd === 'quit' || $cmd === 'exit') { echo "Quit. Bye\n"; break; } echo $this->command($cmd) . PHP_EOL; } usleep(50000); } $this->close(); }
php
public function interactive() { echo "welcome! please input command('quit' or 'exit' to Quit).\n "; while (true) { echo '> '; if ($cmd = trim(fgets(\STDIN))) { // echo "input command: $cmd\n"; if ($cmd === 'quit' || $cmd === 'exit') { echo "Quit. Bye\n"; break; } echo $this->command($cmd) . PHP_EOL; } usleep(50000); } $this->close(); }
[ "public", "function", "interactive", "(", ")", "{", "echo", "\"welcome! please input command('quit' or 'exit' to Quit).\\n \"", ";", "while", "(", "true", ")", "{", "echo", "'> '", ";", "if", "(", "$", "cmd", "=", "trim", "(", "fgets", "(", "\\", "STDIN", ")", ")", ")", "{", "// echo \"input command: $cmd\\n\";", "if", "(", "$", "cmd", "===", "'quit'", "||", "$", "cmd", "===", "'exit'", ")", "{", "echo", "\"Quit. Bye\\n\"", ";", "break", ";", "}", "echo", "$", "this", "->", "command", "(", "$", "cmd", ")", ".", "PHP_EOL", ";", "}", "usleep", "(", "50000", ")", ";", "}", "$", "this", "->", "close", "(", ")", ";", "}" ]
into interactive environment
[ "into", "interactive", "environment" ]
8604e037937d31fa2338d79aaf9d0910cb48f559
https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Network/Telnet.php#L215-L235
train
thelia-modules/SmartyFilter
Model/Base/SmartyFilterI18n.php
SmartyFilterI18n.setSmartyFilter
public function setSmartyFilter(ChildSmartyFilter $v = null) { if ($v === null) { $this->setId(null); } else { $this->setId($v->getId()); } $this->aSmartyFilter = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the ChildSmartyFilter object, it will not be re-added. if ($v !== null) { $v->addSmartyFilterI18n($this); } return $this; }
php
public function setSmartyFilter(ChildSmartyFilter $v = null) { if ($v === null) { $this->setId(null); } else { $this->setId($v->getId()); } $this->aSmartyFilter = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the ChildSmartyFilter object, it will not be re-added. if ($v !== null) { $v->addSmartyFilterI18n($this); } return $this; }
[ "public", "function", "setSmartyFilter", "(", "ChildSmartyFilter", "$", "v", "=", "null", ")", "{", "if", "(", "$", "v", "===", "null", ")", "{", "$", "this", "->", "setId", "(", "null", ")", ";", "}", "else", "{", "$", "this", "->", "setId", "(", "$", "v", "->", "getId", "(", ")", ")", ";", "}", "$", "this", "->", "aSmartyFilter", "=", "$", "v", ";", "// Add binding for other direction of this n:n relationship.", "// If this object has already been added to the ChildSmartyFilter object, it will not be re-added.", "if", "(", "$", "v", "!==", "null", ")", "{", "$", "v", "->", "addSmartyFilterI18n", "(", "$", "this", ")", ";", "}", "return", "$", "this", ";", "}" ]
Declares an association between this object and a ChildSmartyFilter object. @param ChildSmartyFilter $v @return \SmartyFilter\Model\SmartyFilterI18n The current object (for fluent API support) @throws PropelException
[ "Declares", "an", "association", "between", "this", "object", "and", "a", "ChildSmartyFilter", "object", "." ]
e510d281f51ddc4344e563d0f6aaa192fa7171e9
https://github.com/thelia-modules/SmartyFilter/blob/e510d281f51ddc4344e563d0f6aaa192fa7171e9/Model/Base/SmartyFilterI18n.php#L1127-L1145
train
thelia-modules/SmartyFilter
Model/Base/SmartyFilterI18n.php
SmartyFilterI18n.getSmartyFilter
public function getSmartyFilter(ConnectionInterface $con = null) { if ($this->aSmartyFilter === null && ($this->id !== null)) { $this->aSmartyFilter = ChildSmartyFilterQuery::create()->findPk($this->id, $con); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->aSmartyFilter->addSmartyFilterI18ns($this); */ } return $this->aSmartyFilter; }
php
public function getSmartyFilter(ConnectionInterface $con = null) { if ($this->aSmartyFilter === null && ($this->id !== null)) { $this->aSmartyFilter = ChildSmartyFilterQuery::create()->findPk($this->id, $con); /* The following can be used additionally to guarantee the related object contains a reference to this object. This level of coupling may, however, be undesirable since it could result in an only partially populated collection in the referenced object. $this->aSmartyFilter->addSmartyFilterI18ns($this); */ } return $this->aSmartyFilter; }
[ "public", "function", "getSmartyFilter", "(", "ConnectionInterface", "$", "con", "=", "null", ")", "{", "if", "(", "$", "this", "->", "aSmartyFilter", "===", "null", "&&", "(", "$", "this", "->", "id", "!==", "null", ")", ")", "{", "$", "this", "->", "aSmartyFilter", "=", "ChildSmartyFilterQuery", "::", "create", "(", ")", "->", "findPk", "(", "$", "this", "->", "id", ",", "$", "con", ")", ";", "/* The following can be used additionally to\n guarantee the related object contains a reference\n to this object. This level of coupling may, however, be\n undesirable since it could result in an only partially populated collection\n in the referenced object.\n $this->aSmartyFilter->addSmartyFilterI18ns($this);\n */", "}", "return", "$", "this", "->", "aSmartyFilter", ";", "}" ]
Get the associated ChildSmartyFilter object @param ConnectionInterface $con Optional Connection object. @return ChildSmartyFilter The associated ChildSmartyFilter object. @throws PropelException
[ "Get", "the", "associated", "ChildSmartyFilter", "object" ]
e510d281f51ddc4344e563d0f6aaa192fa7171e9
https://github.com/thelia-modules/SmartyFilter/blob/e510d281f51ddc4344e563d0f6aaa192fa7171e9/Model/Base/SmartyFilterI18n.php#L1155-L1169
train
cityware/city-format
src/Date.php
Date.getMonthsRange
public static function getMonthsRange($startData, $endDate) { $time1 = strtotime($startData); //absolute date comparison needs to be done here, because PHP doesn't do date comparisons $time2 = strtotime($endDate); //$my1 = date('mY', $time1); //need these to compare dates at 'month' granularity //$my2 = date('mY', $time2); $year1 = date('Y', $time1); $year2 = date('Y', $time2); $years = range($year1, $year2); $months = Array(); foreach ($years as $year) { $months[$year] = array(); while ($time1 < $time2) { if (date('Y', $time1) == $year) { $months[$year][] = date('m', $time1); $time1 = strtotime(date('Y-m-d', $time1) . ' +1 month'); } else { break; } } continue; } return $months; }
php
public static function getMonthsRange($startData, $endDate) { $time1 = strtotime($startData); //absolute date comparison needs to be done here, because PHP doesn't do date comparisons $time2 = strtotime($endDate); //$my1 = date('mY', $time1); //need these to compare dates at 'month' granularity //$my2 = date('mY', $time2); $year1 = date('Y', $time1); $year2 = date('Y', $time2); $years = range($year1, $year2); $months = Array(); foreach ($years as $year) { $months[$year] = array(); while ($time1 < $time2) { if (date('Y', $time1) == $year) { $months[$year][] = date('m', $time1); $time1 = strtotime(date('Y-m-d', $time1) . ' +1 month'); } else { break; } } continue; } return $months; }
[ "public", "static", "function", "getMonthsRange", "(", "$", "startData", ",", "$", "endDate", ")", "{", "$", "time1", "=", "strtotime", "(", "$", "startData", ")", ";", "//absolute date comparison needs to be done here, because PHP doesn't do date comparisons", "$", "time2", "=", "strtotime", "(", "$", "endDate", ")", ";", "//$my1 = date('mY', $time1); //need these to compare dates at 'month' granularity", "//$my2 = date('mY', $time2);", "$", "year1", "=", "date", "(", "'Y'", ",", "$", "time1", ")", ";", "$", "year2", "=", "date", "(", "'Y'", ",", "$", "time2", ")", ";", "$", "years", "=", "range", "(", "$", "year1", ",", "$", "year2", ")", ";", "$", "months", "=", "Array", "(", ")", ";", "foreach", "(", "$", "years", "as", "$", "year", ")", "{", "$", "months", "[", "$", "year", "]", "=", "array", "(", ")", ";", "while", "(", "$", "time1", "<", "$", "time2", ")", "{", "if", "(", "date", "(", "'Y'", ",", "$", "time1", ")", "==", "$", "year", ")", "{", "$", "months", "[", "$", "year", "]", "[", "]", "=", "date", "(", "'m'", ",", "$", "time1", ")", ";", "$", "time1", "=", "strtotime", "(", "date", "(", "'Y-m-d'", ",", "$", "time1", ")", ".", "' +1 month'", ")", ";", "}", "else", "{", "break", ";", "}", "}", "continue", ";", "}", "return", "$", "months", ";", "}" ]
Cria um intervalo de Meses de acordo com a data inicial e final @param date $startData @param date $endDate @return array
[ "Cria", "um", "intervalo", "de", "Meses", "de", "acordo", "com", "a", "data", "inicial", "e", "final" ]
1e292670639a950ecf561b545462427512950c74
https://github.com/cityware/city-format/blob/1e292670639a950ecf561b545462427512950c74/src/Date.php#L217-L240
train
WolfMicrosystems/ldap
src/WMS/Library/Ldap/Collection/AccountNodeCollection.php
AccountNodeCollection.createEntry
protected function createEntry(array $data) { return Entity\AccountNode::fromNode(parent::createEntry($data), $this->getConnection()->getConfiguration()); }
php
protected function createEntry(array $data) { return Entity\AccountNode::fromNode(parent::createEntry($data), $this->getConnection()->getConfiguration()); }
[ "protected", "function", "createEntry", "(", "array", "$", "data", ")", "{", "return", "Entity", "\\", "AccountNode", "::", "fromNode", "(", "parent", "::", "createEntry", "(", "$", "data", ")", ",", "$", "this", "->", "getConnection", "(", ")", "->", "getConfiguration", "(", ")", ")", ";", "}" ]
Creates the data structure for the given entry data @param array $data @return Entity\AccountNode
[ "Creates", "the", "data", "structure", "for", "the", "given", "entry", "data" ]
872bbdc6127a41f0c51f2aa73425b8063a5c8148
https://github.com/WolfMicrosystems/ldap/blob/872bbdc6127a41f0c51f2aa73425b8063a5c8148/src/WMS/Library/Ldap/Collection/AccountNodeCollection.php#L22-L25
train
xiewulong/yii2-wechat
Manager.php
Manager.sendTemplateMessageByType
public function sendTemplateMessageByType($touser, $type, $data, $url = null) { return isset($this->templates[$type]) && $this->sendTemplateMessage($touser, $this->templates[$type], $data, $url); }
php
public function sendTemplateMessageByType($touser, $type, $data, $url = null) { return isset($this->templates[$type]) && $this->sendTemplateMessage($touser, $this->templates[$type], $data, $url); }
[ "public", "function", "sendTemplateMessageByType", "(", "$", "touser", ",", "$", "type", ",", "$", "data", ",", "$", "url", "=", "null", ")", "{", "return", "isset", "(", "$", "this", "->", "templates", "[", "$", "type", "]", ")", "&&", "$", "this", "->", "sendTemplateMessage", "(", "$", "touser", ",", "$", "this", "->", "templates", "[", "$", "type", "]", ",", "$", "data", ",", "$", "url", ")", ";", "}" ]
Send template by type @since 0.0.1 @param {string} $touser openid @param {string} $type @param {array} $data @param {string} [$url] @return {boolean} @example \Yii::$app->wechat->sendTemplateMessageByType($touser, $type, $data, $url);
[ "Send", "template", "by", "type" ]
e7a209072c9d16bd6ec8d51808439f806c3e56a2
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L93-L95
train
xiewulong/yii2-wechat
Manager.php
Manager.setTemplateIndustry
public function setTemplateIndustry($industry_id1, $industry_id2) { $data = $this->getData('/cgi-bin/template/api_set_industry', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'industry_id1' => $industry_id1, 'industry_id2' => $industry_id2, ])); return $this->errcode == 0; }
php
public function setTemplateIndustry($industry_id1, $industry_id2) { $data = $this->getData('/cgi-bin/template/api_set_industry', [ 'access_token' => $this->getAccessToken(), ], Json::encode([ 'industry_id1' => $industry_id1, 'industry_id2' => $industry_id2, ])); return $this->errcode == 0; }
[ "public", "function", "setTemplateIndustry", "(", "$", "industry_id1", ",", "$", "industry_id2", ")", "{", "$", "data", "=", "$", "this", "->", "getData", "(", "'/cgi-bin/template/api_set_industry'", ",", "[", "'access_token'", "=>", "$", "this", "->", "getAccessToken", "(", ")", ",", "]", ",", "Json", "::", "encode", "(", "[", "'industry_id1'", "=>", "$", "industry_id1", ",", "'industry_id2'", "=>", "$", "industry_id2", ",", "]", ")", ")", ";", "return", "$", "this", "->", "errcode", "==", "0", ";", "}" ]
Set template industry @since 0.0.1 @param {integer} $industry_id1 primary @param {integer} $industry_id2 secondary @return {boolean} @example \Yii::$app->wechat->setTemplateIndustry($industry_id1, $industry_id2);
[ "Set", "template", "industry" ]
e7a209072c9d16bd6ec8d51808439f806c3e56a2
https://github.com/xiewulong/yii2-wechat/blob/e7a209072c9d16bd6ec8d51808439f806c3e56a2/Manager.php#L208-L217
train
oscarpalmer/shelf
src/oscarpalmer/Shelf/Blob.php
Blob.delete
public function delete($key) : Blob { if ($this->offsetExists($key)) { $this->offsetUnset($key); } return $this; }
php
public function delete($key) : Blob { if ($this->offsetExists($key)) { $this->offsetUnset($key); } return $this; }
[ "public", "function", "delete", "(", "$", "key", ")", ":", "Blob", "{", "if", "(", "$", "this", "->", "offsetExists", "(", "$", "key", ")", ")", "{", "$", "this", "->", "offsetUnset", "(", "$", "key", ")", ";", "}", "return", "$", "this", ";", "}" ]
Delete value for key in Blob. @param mixed $key Key to delete. @return Blob Blob object for optional chaining.
[ "Delete", "value", "for", "key", "in", "Blob", "." ]
47bccf7fd8f1750defe1f2805480a6721f1a0e79
https://github.com/oscarpalmer/shelf/blob/47bccf7fd8f1750defe1f2805480a6721f1a0e79/src/oscarpalmer/Shelf/Blob.php#L28-L35
train
as3io/symfony-data-importer
src/Console/Import.php
Import.doCommandImportSetUp
final protected function doCommandImportSetUp() { $this->writeln('Executing <info>setup</info> tasks', true); // $this->updateSchema(); $this->importManager->setUp(); $this->writeln('Startup tasks complete.', true, true); }
php
final protected function doCommandImportSetUp() { $this->writeln('Executing <info>setup</info> tasks', true); // $this->updateSchema(); $this->importManager->setUp(); $this->writeln('Startup tasks complete.', true, true); }
[ "final", "protected", "function", "doCommandImportSetUp", "(", ")", "{", "$", "this", "->", "writeln", "(", "'Executing <info>setup</info> tasks'", ",", "true", ")", ";", "// $this->updateSchema();", "$", "this", "->", "importManager", "->", "setUp", "(", ")", ";", "$", "this", "->", "writeln", "(", "'Startup tasks complete.'", ",", "true", ",", "true", ")", ";", "}" ]
Performs startup tasks
[ "Performs", "startup", "tasks" ]
33383e38f20f6b7a4b83da619bd028ac84ced579
https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Console/Import.php#L247-L255
train
as3io/symfony-data-importer
src/Console/Import.php
Import.doCommandImport
final protected function doCommandImport() { $this->writeln('Starting Import', true, true); $this->indent(); foreach ($this->importManager->getConfiguration()->getSegments() as $segment) { $this->importSegment($segment); } $this->outdent(); $this->writeln('<info>Import complete!</info>', true, true); }
php
final protected function doCommandImport() { $this->writeln('Starting Import', true, true); $this->indent(); foreach ($this->importManager->getConfiguration()->getSegments() as $segment) { $this->importSegment($segment); } $this->outdent(); $this->writeln('<info>Import complete!</info>', true, true); }
[ "final", "protected", "function", "doCommandImport", "(", ")", "{", "$", "this", "->", "writeln", "(", "'Starting Import'", ",", "true", ",", "true", ")", ";", "$", "this", "->", "indent", "(", ")", ";", "foreach", "(", "$", "this", "->", "importManager", "->", "getConfiguration", "(", ")", "->", "getSegments", "(", ")", "as", "$", "segment", ")", "{", "$", "this", "->", "importSegment", "(", "$", "segment", ")", ";", "}", "$", "this", "->", "outdent", "(", ")", ";", "$", "this", "->", "writeln", "(", "'<info>Import complete!</info>'", ",", "true", ",", "true", ")", ";", "}" ]
The main import loop
[ "The", "main", "import", "loop" ]
33383e38f20f6b7a4b83da619bd028ac84ced579
https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Console/Import.php#L260-L271
train
as3io/symfony-data-importer
src/Console/Import.php
Import.doCommandImportTearDown
final protected function doCommandImportTearDown() { $this->writeln('Executing <info>teardown</info> tasks', false, true); $this->indent(); $this->subscriberPass(); $this->outdent(); $this->writeln('Teardown tasks complete.', false, true); }
php
final protected function doCommandImportTearDown() { $this->writeln('Executing <info>teardown</info> tasks', false, true); $this->indent(); $this->subscriberPass(); $this->outdent(); $this->writeln('Teardown tasks complete.', false, true); }
[ "final", "protected", "function", "doCommandImportTearDown", "(", ")", "{", "$", "this", "->", "writeln", "(", "'Executing <info>teardown</info> tasks'", ",", "false", ",", "true", ")", ";", "$", "this", "->", "indent", "(", ")", ";", "$", "this", "->", "subscriberPass", "(", ")", ";", "$", "this", "->", "outdent", "(", ")", ";", "$", "this", "->", "writeln", "(", "'Teardown tasks complete.'", ",", "false", ",", "true", ")", ";", "}" ]
Performs teardown tasks
[ "Performs", "teardown", "tasks" ]
33383e38f20f6b7a4b83da619bd028ac84ced579
https://github.com/as3io/symfony-data-importer/blob/33383e38f20f6b7a4b83da619bd028ac84ced579/src/Console/Import.php#L276-L285
train
iron-bound-designs/wp-notifications
src/Template/Manager.php
Manager.listen
public function listen( Listener $listener ) { if ( isset( $this->listeners[ $listener->get_tag() ] ) ) { return false; } $this->listeners[ $listener->get_tag() ] = $listener; return true; }
php
public function listen( Listener $listener ) { if ( isset( $this->listeners[ $listener->get_tag() ] ) ) { return false; } $this->listeners[ $listener->get_tag() ] = $listener; return true; }
[ "public", "function", "listen", "(", "Listener", "$", "listener", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "listeners", "[", "$", "listener", "->", "get_tag", "(", ")", "]", ")", ")", "{", "return", "false", ";", "}", "$", "this", "->", "listeners", "[", "$", "listener", "->", "get_tag", "(", ")", "]", "=", "$", "listener", ";", "return", "true", ";", "}" ]
Listen for a template tag. @since 1.0 @param Listener $listener @return bool
[ "Listen", "for", "a", "template", "tag", "." ]
4fdf67d28d194576d35f86245b2f539c4815cde2
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Template/Manager.php#L50-L59
train
iron-bound-designs/wp-notifications
src/Template/Manager.php
Manager.get_listener
public function get_listener( $tag ) { return isset( $this->listeners[ $tag ] ) ? $this->listeners[ $tag ] : new Null_Listener(); }
php
public function get_listener( $tag ) { return isset( $this->listeners[ $tag ] ) ? $this->listeners[ $tag ] : new Null_Listener(); }
[ "public", "function", "get_listener", "(", "$", "tag", ")", "{", "return", "isset", "(", "$", "this", "->", "listeners", "[", "$", "tag", "]", ")", "?", "$", "this", "->", "listeners", "[", "$", "tag", "]", ":", "new", "Null_Listener", "(", ")", ";", "}" ]
Get a listener for a certain tag. @param string $tag @return Listener|Null_Listener Null Listener is returned if listener for given tag does not exist.
[ "Get", "a", "listener", "for", "a", "certain", "tag", "." ]
4fdf67d28d194576d35f86245b2f539c4815cde2
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Template/Manager.php#L68-L70
train
iron-bound-designs/wp-notifications
src/Template/Manager.php
Manager.render_tags
public function render_tags( array $data_sources ) { $replaced = array(); foreach ( $this->get_listeners() as $tag => $listener ) { $params = $listener->get_callback_reflection()->getParameters(); $args = array(); foreach ( $params as $param ) { $found = false; foreach ( $data_sources as $name => $data_source ) { if ( is_object( $data_source ) && ( $class = $param->getClass() ) !== null && $class->isInstance( $data_source ) ) { $args[] = $data_source; $found = true; } elseif ( $param->getName() === $name ) { if ( isset( $class ) ) { throw new \BadMethodCallException( "Data source '$name' does not match type of required parameter '{$param->getName()}'. Required type: '{$class->getName()}''", 1 ); } $args[] = $data_source; $found = true; } if ( $found ) { break; } } if ( $found ) { continue; } if ( $param->isDefaultValueAvailable() ) { $args[] = $param->getDefaultValue(); } else { throw new \BadMethodCallException( "Not all required parameters were provided. Required: '{$param->getName()}'.'", 2 ); } } $replaced[ $tag ] = $listener->render( $args ); } return $replaced; }
php
public function render_tags( array $data_sources ) { $replaced = array(); foreach ( $this->get_listeners() as $tag => $listener ) { $params = $listener->get_callback_reflection()->getParameters(); $args = array(); foreach ( $params as $param ) { $found = false; foreach ( $data_sources as $name => $data_source ) { if ( is_object( $data_source ) && ( $class = $param->getClass() ) !== null && $class->isInstance( $data_source ) ) { $args[] = $data_source; $found = true; } elseif ( $param->getName() === $name ) { if ( isset( $class ) ) { throw new \BadMethodCallException( "Data source '$name' does not match type of required parameter '{$param->getName()}'. Required type: '{$class->getName()}''", 1 ); } $args[] = $data_source; $found = true; } if ( $found ) { break; } } if ( $found ) { continue; } if ( $param->isDefaultValueAvailable() ) { $args[] = $param->getDefaultValue(); } else { throw new \BadMethodCallException( "Not all required parameters were provided. Required: '{$param->getName()}'.'", 2 ); } } $replaced[ $tag ] = $listener->render( $args ); } return $replaced; }
[ "public", "function", "render_tags", "(", "array", "$", "data_sources", ")", "{", "$", "replaced", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "get_listeners", "(", ")", "as", "$", "tag", "=>", "$", "listener", ")", "{", "$", "params", "=", "$", "listener", "->", "get_callback_reflection", "(", ")", "->", "getParameters", "(", ")", ";", "$", "args", "=", "array", "(", ")", ";", "foreach", "(", "$", "params", "as", "$", "param", ")", "{", "$", "found", "=", "false", ";", "foreach", "(", "$", "data_sources", "as", "$", "name", "=>", "$", "data_source", ")", "{", "if", "(", "is_object", "(", "$", "data_source", ")", "&&", "(", "$", "class", "=", "$", "param", "->", "getClass", "(", ")", ")", "!==", "null", "&&", "$", "class", "->", "isInstance", "(", "$", "data_source", ")", ")", "{", "$", "args", "[", "]", "=", "$", "data_source", ";", "$", "found", "=", "true", ";", "}", "elseif", "(", "$", "param", "->", "getName", "(", ")", "===", "$", "name", ")", "{", "if", "(", "isset", "(", "$", "class", ")", ")", "{", "throw", "new", "\\", "BadMethodCallException", "(", "\"Data source '$name' does not match type of required parameter '{$param->getName()}'. Required type: '{$class->getName()}''\"", ",", "1", ")", ";", "}", "$", "args", "[", "]", "=", "$", "data_source", ";", "$", "found", "=", "true", ";", "}", "if", "(", "$", "found", ")", "{", "break", ";", "}", "}", "if", "(", "$", "found", ")", "{", "continue", ";", "}", "if", "(", "$", "param", "->", "isDefaultValueAvailable", "(", ")", ")", "{", "$", "args", "[", "]", "=", "$", "param", "->", "getDefaultValue", "(", ")", ";", "}", "else", "{", "throw", "new", "\\", "BadMethodCallException", "(", "\"Not all required parameters were provided. Required: '{$param->getName()}'.'\"", ",", "2", ")", ";", "}", "}", "$", "replaced", "[", "$", "tag", "]", "=", "$", "listener", "->", "render", "(", "$", "args", ")", ";", "}", "return", "$", "replaced", ";", "}" ]
Return an array of the rendered tags. @since 1.0 @param array $data_sources @return array @throws \BadMethodCallException
[ "Return", "an", "array", "of", "the", "rendered", "tags", "." ]
4fdf67d28d194576d35f86245b2f539c4815cde2
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Template/Manager.php#L107-L159
train
jelix/file-utilities
lib/Directory.php
Directory.create
public static function create($dir, $chmod = null) { if (!file_exists($dir)) { if ($chmod === null) { $chmod = self::$defaultChmod; } mkdir($dir, $chmod, true); // php mkdir apply umask on the given mode, so we must to // do a chmod manually. chmod($dir, $chmod); return true; } return false; }
php
public static function create($dir, $chmod = null) { if (!file_exists($dir)) { if ($chmod === null) { $chmod = self::$defaultChmod; } mkdir($dir, $chmod, true); // php mkdir apply umask on the given mode, so we must to // do a chmod manually. chmod($dir, $chmod); return true; } return false; }
[ "public", "static", "function", "create", "(", "$", "dir", ",", "$", "chmod", "=", "null", ")", "{", "if", "(", "!", "file_exists", "(", "$", "dir", ")", ")", "{", "if", "(", "$", "chmod", "===", "null", ")", "{", "$", "chmod", "=", "self", "::", "$", "defaultChmod", ";", "}", "mkdir", "(", "$", "dir", ",", "$", "chmod", ",", "true", ")", ";", "// php mkdir apply umask on the given mode, so we must to", "// do a chmod manually.", "chmod", "(", "$", "dir", ",", "$", "chmod", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
create a directory. @return bool false if the directory did already exist
[ "create", "a", "directory", "." ]
05fd364860ed147e6367de9db3dc544f58c5a05c
https://github.com/jelix/file-utilities/blob/05fd364860ed147e6367de9db3dc544f58c5a05c/lib/Directory.php#L26-L40
train
jelix/file-utilities
lib/Directory.php
Directory.remove
public static function remove($path, $deleteDir = true) { // minimum security check if ($path == '' || $path == '/' || $path == DIRECTORY_SEPARATOR) { throw new \InvalidArgumentException('The root cannot be removed !!'); } if (!file_exists($path)) { return true; } $dir = new \DirectoryIterator($path); foreach ($dir as $dirContent) { // file deletion if ($dirContent->isFile() || $dirContent->isLink()) { unlink($dirContent->getPathName()); } else { // recursive directory deletion if (!$dirContent->isDot() && $dirContent->isDir()) { self::remove($dirContent->getPathName()); } } } unset($dir); unset($dirContent); // removes the parent directory if ($deleteDir) { rmdir($path); } }
php
public static function remove($path, $deleteDir = true) { // minimum security check if ($path == '' || $path == '/' || $path == DIRECTORY_SEPARATOR) { throw new \InvalidArgumentException('The root cannot be removed !!'); } if (!file_exists($path)) { return true; } $dir = new \DirectoryIterator($path); foreach ($dir as $dirContent) { // file deletion if ($dirContent->isFile() || $dirContent->isLink()) { unlink($dirContent->getPathName()); } else { // recursive directory deletion if (!$dirContent->isDot() && $dirContent->isDir()) { self::remove($dirContent->getPathName()); } } } unset($dir); unset($dirContent); // removes the parent directory if ($deleteDir) { rmdir($path); } }
[ "public", "static", "function", "remove", "(", "$", "path", ",", "$", "deleteDir", "=", "true", ")", "{", "// minimum security check", "if", "(", "$", "path", "==", "''", "||", "$", "path", "==", "'/'", "||", "$", "path", "==", "DIRECTORY_SEPARATOR", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The root cannot be removed !!'", ")", ";", "}", "if", "(", "!", "file_exists", "(", "$", "path", ")", ")", "{", "return", "true", ";", "}", "$", "dir", "=", "new", "\\", "DirectoryIterator", "(", "$", "path", ")", ";", "foreach", "(", "$", "dir", "as", "$", "dirContent", ")", "{", "// file deletion", "if", "(", "$", "dirContent", "->", "isFile", "(", ")", "||", "$", "dirContent", "->", "isLink", "(", ")", ")", "{", "unlink", "(", "$", "dirContent", "->", "getPathName", "(", ")", ")", ";", "}", "else", "{", "// recursive directory deletion", "if", "(", "!", "$", "dirContent", "->", "isDot", "(", ")", "&&", "$", "dirContent", "->", "isDir", "(", ")", ")", "{", "self", "::", "remove", "(", "$", "dirContent", "->", "getPathName", "(", ")", ")", ";", "}", "}", "}", "unset", "(", "$", "dir", ")", ";", "unset", "(", "$", "dirContent", ")", ";", "// removes the parent directory", "if", "(", "$", "deleteDir", ")", "{", "rmdir", "(", "$", "path", ")", ";", "}", "}" ]
Recursive function deleting a directory. @param string $path The path of the directory to remove recursively @param bool $deleteDir If the path must be deleted too @author Loic Mathaud
[ "Recursive", "function", "deleting", "a", "directory", "." ]
05fd364860ed147e6367de9db3dc544f58c5a05c
https://github.com/jelix/file-utilities/blob/05fd364860ed147e6367de9db3dc544f58c5a05c/lib/Directory.php#L50-L80
train
jelix/file-utilities
lib/Directory.php
Directory.removeExcept
public static function removeExcept($path, $except, $deleteDir = true) { if (!is_array($except) || !count($except)) { throw new \InvalidArgumentException('list of exception is not an array or is empty'); } if ($path == '' || $path == '/' || $path == DIRECTORY_SEPARATOR) { throw new \InvalidArgumentException('The root cannot be removed !!'); } if (!file_exists($path)) { return true; } $allIsDeleted = true; $dir = new \DirectoryIterator($path); foreach ($dir as $dirContent) { // test if the basename matches one of patterns $exception = false; foreach ($except as $pattern) { if ($pattern[0] == '*') { // for pattern like *.foo if ($dirContent->getBasename() != $dirContent->getBasename(substr($pattern, 1))) { $allIsDeleted = false; $exception = true; break; } } elseif ($pattern == $dirContent->getBasename()) { $allIsDeleted = false; $exception = true; break; } } if ($exception) { continue; } // file deletion if ($dirContent->isFile() || $dirContent->isLink()) { unlink($dirContent->getPathName()); } else { // recursive directory deletion if (!$dirContent->isDot() && $dirContent->isDir()) { $removed = self::removeExcept($dirContent->getPathName(), $except, true); if (!$removed) { $allIsDeleted = false; } } } } unset($dir); unset($dirContent); // removes the parent directory if ($deleteDir && $allIsDeleted) { rmdir($path); } return $allIsDeleted; }
php
public static function removeExcept($path, $except, $deleteDir = true) { if (!is_array($except) || !count($except)) { throw new \InvalidArgumentException('list of exception is not an array or is empty'); } if ($path == '' || $path == '/' || $path == DIRECTORY_SEPARATOR) { throw new \InvalidArgumentException('The root cannot be removed !!'); } if (!file_exists($path)) { return true; } $allIsDeleted = true; $dir = new \DirectoryIterator($path); foreach ($dir as $dirContent) { // test if the basename matches one of patterns $exception = false; foreach ($except as $pattern) { if ($pattern[0] == '*') { // for pattern like *.foo if ($dirContent->getBasename() != $dirContent->getBasename(substr($pattern, 1))) { $allIsDeleted = false; $exception = true; break; } } elseif ($pattern == $dirContent->getBasename()) { $allIsDeleted = false; $exception = true; break; } } if ($exception) { continue; } // file deletion if ($dirContent->isFile() || $dirContent->isLink()) { unlink($dirContent->getPathName()); } else { // recursive directory deletion if (!$dirContent->isDot() && $dirContent->isDir()) { $removed = self::removeExcept($dirContent->getPathName(), $except, true); if (!$removed) { $allIsDeleted = false; } } } } unset($dir); unset($dirContent); // removes the parent directory if ($deleteDir && $allIsDeleted) { rmdir($path); } return $allIsDeleted; }
[ "public", "static", "function", "removeExcept", "(", "$", "path", ",", "$", "except", ",", "$", "deleteDir", "=", "true", ")", "{", "if", "(", "!", "is_array", "(", "$", "except", ")", "||", "!", "count", "(", "$", "except", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'list of exception is not an array or is empty'", ")", ";", "}", "if", "(", "$", "path", "==", "''", "||", "$", "path", "==", "'/'", "||", "$", "path", "==", "DIRECTORY_SEPARATOR", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'The root cannot be removed !!'", ")", ";", "}", "if", "(", "!", "file_exists", "(", "$", "path", ")", ")", "{", "return", "true", ";", "}", "$", "allIsDeleted", "=", "true", ";", "$", "dir", "=", "new", "\\", "DirectoryIterator", "(", "$", "path", ")", ";", "foreach", "(", "$", "dir", "as", "$", "dirContent", ")", "{", "// test if the basename matches one of patterns", "$", "exception", "=", "false", ";", "foreach", "(", "$", "except", "as", "$", "pattern", ")", "{", "if", "(", "$", "pattern", "[", "0", "]", "==", "'*'", ")", "{", "// for pattern like *.foo", "if", "(", "$", "dirContent", "->", "getBasename", "(", ")", "!=", "$", "dirContent", "->", "getBasename", "(", "substr", "(", "$", "pattern", ",", "1", ")", ")", ")", "{", "$", "allIsDeleted", "=", "false", ";", "$", "exception", "=", "true", ";", "break", ";", "}", "}", "elseif", "(", "$", "pattern", "==", "$", "dirContent", "->", "getBasename", "(", ")", ")", "{", "$", "allIsDeleted", "=", "false", ";", "$", "exception", "=", "true", ";", "break", ";", "}", "}", "if", "(", "$", "exception", ")", "{", "continue", ";", "}", "// file deletion", "if", "(", "$", "dirContent", "->", "isFile", "(", ")", "||", "$", "dirContent", "->", "isLink", "(", ")", ")", "{", "unlink", "(", "$", "dirContent", "->", "getPathName", "(", ")", ")", ";", "}", "else", "{", "// recursive directory deletion", "if", "(", "!", "$", "dirContent", "->", "isDot", "(", ")", "&&", "$", "dirContent", "->", "isDir", "(", ")", ")", "{", "$", "removed", "=", "self", "::", "removeExcept", "(", "$", "dirContent", "->", "getPathName", "(", ")", ",", "$", "except", ",", "true", ")", ";", "if", "(", "!", "$", "removed", ")", "{", "$", "allIsDeleted", "=", "false", ";", "}", "}", "}", "}", "unset", "(", "$", "dir", ")", ";", "unset", "(", "$", "dirContent", ")", ";", "// removes the parent directory", "if", "(", "$", "deleteDir", "&&", "$", "allIsDeleted", ")", "{", "rmdir", "(", "$", "path", ")", ";", "}", "return", "$", "allIsDeleted", ";", "}" ]
Recursive function deleting all files into a directory except those indicated. @param string $path The path of the directory to remove recursively @param array $except filenames and suffix of filename, for files to NOT delete @param bool $deleteDir If the path must be deleted too @return bool true if all the content has been removed @author Loic Mathaud
[ "Recursive", "function", "deleting", "all", "files", "into", "a", "directory", "except", "those", "indicated", "." ]
05fd364860ed147e6367de9db3dc544f58c5a05c
https://github.com/jelix/file-utilities/blob/05fd364860ed147e6367de9db3dc544f58c5a05c/lib/Directory.php#L93-L150
train
jelix/file-utilities
lib/Directory.php
Directory.copy
static function copy($srcDir, $destDir, $overwrite = true) { Directory::create($destDir); $dir = new \DirectoryIterator($srcDir); foreach ($dir as $dirContent) { if ($dirContent->isFile() || $dirContent->isLink()) { $target = $destDir.'/'.$dirContent->getFilename(); if ($overwrite || !file_exists($target)) { copy($dirContent->getPathName(), $target); } } else if (!$dirContent->isDot() && $dirContent->isDir()) { self::copy($dirContent->getPathName(), $destDir.'/'.$dirContent->getFilename(), $overwrite); } } }
php
static function copy($srcDir, $destDir, $overwrite = true) { Directory::create($destDir); $dir = new \DirectoryIterator($srcDir); foreach ($dir as $dirContent) { if ($dirContent->isFile() || $dirContent->isLink()) { $target = $destDir.'/'.$dirContent->getFilename(); if ($overwrite || !file_exists($target)) { copy($dirContent->getPathName(), $target); } } else if (!$dirContent->isDot() && $dirContent->isDir()) { self::copy($dirContent->getPathName(), $destDir.'/'.$dirContent->getFilename(), $overwrite); } } }
[ "static", "function", "copy", "(", "$", "srcDir", ",", "$", "destDir", ",", "$", "overwrite", "=", "true", ")", "{", "Directory", "::", "create", "(", "$", "destDir", ")", ";", "$", "dir", "=", "new", "\\", "DirectoryIterator", "(", "$", "srcDir", ")", ";", "foreach", "(", "$", "dir", "as", "$", "dirContent", ")", "{", "if", "(", "$", "dirContent", "->", "isFile", "(", ")", "||", "$", "dirContent", "->", "isLink", "(", ")", ")", "{", "$", "target", "=", "$", "destDir", ".", "'/'", ".", "$", "dirContent", "->", "getFilename", "(", ")", ";", "if", "(", "$", "overwrite", "||", "!", "file_exists", "(", "$", "target", ")", ")", "{", "copy", "(", "$", "dirContent", "->", "getPathName", "(", ")", ",", "$", "target", ")", ";", "}", "}", "else", "if", "(", "!", "$", "dirContent", "->", "isDot", "(", ")", "&&", "$", "dirContent", "->", "isDir", "(", ")", ")", "{", "self", "::", "copy", "(", "$", "dirContent", "->", "getPathName", "(", ")", ",", "$", "destDir", ".", "'/'", ".", "$", "dirContent", "->", "getFilename", "(", ")", ",", "$", "overwrite", ")", ";", "}", "}", "}" ]
Copy a content directory into an other @param string $srcDir the directory from which content will be copied @param string $destDir the directory in which content will be copied @param boolean $overwrite set to false to not overwrite existing files in the target directory
[ "Copy", "a", "content", "directory", "into", "an", "other" ]
05fd364860ed147e6367de9db3dc544f58c5a05c
https://github.com/jelix/file-utilities/blob/05fd364860ed147e6367de9db3dc544f58c5a05c/lib/Directory.php#L159-L173
train
ellipsephp/container-reflection
src/AbstractReflectionContainer.php
AbstractReflectionContainer.isAutoWirable
private function isAutoWirable($id): bool { if (is_string($id) && class_exists($id)) { if (count($this->interfaces) > 0) { return (bool) array_intersect($this->interfaces, class_implements($id)); } return true; } return false; }
php
private function isAutoWirable($id): bool { if (is_string($id) && class_exists($id)) { if (count($this->interfaces) > 0) { return (bool) array_intersect($this->interfaces, class_implements($id)); } return true; } return false; }
[ "private", "function", "isAutoWirable", "(", "$", "id", ")", ":", "bool", "{", "if", "(", "is_string", "(", "$", "id", ")", "&&", "class_exists", "(", "$", "id", ")", ")", "{", "if", "(", "count", "(", "$", "this", "->", "interfaces", ")", ">", "0", ")", "{", "return", "(", "bool", ")", "array_intersect", "(", "$", "this", "->", "interfaces", ",", "class_implements", "(", "$", "id", ")", ")", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Return whether the given id is an auto wirable class. @param $id @return bool
[ "Return", "whether", "the", "given", "id", "is", "an", "auto", "wirable", "class", "." ]
bd35a26e0fc924788f54b560d4a2d72ecf9a2be9
https://github.com/ellipsephp/container-reflection/blob/bd35a26e0fc924788f54b560d4a2d72ecf9a2be9/src/AbstractReflectionContainer.php#L99-L114
train
ellipsephp/container-reflection
src/AbstractReflectionContainer.php
AbstractReflectionContainer.make
private function make(string $class) { if (! array_key_exists($class, $this->instances)) { try { return $this->instances[$class] = ($this->factory)($class)->value($this); } catch (ResolvingExceptionInterface $e) { throw new ReflectionContainerException($class, $e); } } return $this->instances[$class]; }
php
private function make(string $class) { if (! array_key_exists($class, $this->instances)) { try { return $this->instances[$class] = ($this->factory)($class)->value($this); } catch (ResolvingExceptionInterface $e) { throw new ReflectionContainerException($class, $e); } } return $this->instances[$class]; }
[ "private", "function", "make", "(", "string", "$", "class", ")", "{", "if", "(", "!", "array_key_exists", "(", "$", "class", ",", "$", "this", "->", "instances", ")", ")", "{", "try", "{", "return", "$", "this", "->", "instances", "[", "$", "class", "]", "=", "(", "$", "this", "->", "factory", ")", "(", "$", "class", ")", "->", "value", "(", "$", "this", ")", ";", "}", "catch", "(", "ResolvingExceptionInterface", "$", "e", ")", "{", "throw", "new", "ReflectionContainerException", "(", "$", "class", ",", "$", "e", ")", ";", "}", "}", "return", "$", "this", "->", "instances", "[", "$", "class", "]", ";", "}" ]
Return an instance of the given class name. Cache the created instance so the same one is returned on multiple calls. @param string $class @return mixed @throws \Ellipse\Container\Exceptions\ReflectionContainerException
[ "Return", "an", "instance", "of", "the", "given", "class", "name", ".", "Cache", "the", "created", "instance", "so", "the", "same", "one", "is", "returned", "on", "multiple", "calls", "." ]
bd35a26e0fc924788f54b560d4a2d72ecf9a2be9
https://github.com/ellipsephp/container-reflection/blob/bd35a26e0fc924788f54b560d4a2d72ecf9a2be9/src/AbstractReflectionContainer.php#L124-L143
train
pmdevelopment/tool-bundle
Framework/Model/ChartJs/DataObject.php
DataObject.exportDataSets
public function exportDataSets($dataSetConfig = null) { $response = []; foreach ($this->getDataSets() as $set) { if ($set instanceof DataSet) { $response[] = $set->export($dataSetConfig); } else { $response[] = $set; } } return $response; }
php
public function exportDataSets($dataSetConfig = null) { $response = []; foreach ($this->getDataSets() as $set) { if ($set instanceof DataSet) { $response[] = $set->export($dataSetConfig); } else { $response[] = $set; } } return $response; }
[ "public", "function", "exportDataSets", "(", "$", "dataSetConfig", "=", "null", ")", "{", "$", "response", "=", "[", "]", ";", "foreach", "(", "$", "this", "->", "getDataSets", "(", ")", "as", "$", "set", ")", "{", "if", "(", "$", "set", "instanceof", "DataSet", ")", "{", "$", "response", "[", "]", "=", "$", "set", "->", "export", "(", "$", "dataSetConfig", ")", ";", "}", "else", "{", "$", "response", "[", "]", "=", "$", "set", ";", "}", "}", "return", "$", "response", ";", "}" ]
Export Data Sets @param DataSetConfig|null $dataSetConfig @return array
[ "Export", "Data", "Sets" ]
2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129
https://github.com/pmdevelopment/tool-bundle/blob/2cbc9f82c5b33fd7a9d389edd3676e9f70ea8129/Framework/Model/ChartJs/DataObject.php#L64-L77
train
crisu83/yii-consoletools
commands/PermissionsCommand.php
PermissionsCommand.changeOwner
protected function changeOwner($path, $newOwner) { $ownerUid = fileowner($path); $ownerData = posix_getpwuid($ownerUid); $oldOwner = $ownerData['name']; if ($oldOwner !== $this->user) { if(!@chown($path, $newOwner)) { throw new CException(sprintf('Unable to change owner for %s, permission denied', $path)); } echo sprintf("Changing owner for %s (%s => %s)... ", $path, $oldOwner, $newOwner); echo "done\n"; } }
php
protected function changeOwner($path, $newOwner) { $ownerUid = fileowner($path); $ownerData = posix_getpwuid($ownerUid); $oldOwner = $ownerData['name']; if ($oldOwner !== $this->user) { if(!@chown($path, $newOwner)) { throw new CException(sprintf('Unable to change owner for %s, permission denied', $path)); } echo sprintf("Changing owner for %s (%s => %s)... ", $path, $oldOwner, $newOwner); echo "done\n"; } }
[ "protected", "function", "changeOwner", "(", "$", "path", ",", "$", "newOwner", ")", "{", "$", "ownerUid", "=", "fileowner", "(", "$", "path", ")", ";", "$", "ownerData", "=", "posix_getpwuid", "(", "$", "ownerUid", ")", ";", "$", "oldOwner", "=", "$", "ownerData", "[", "'name'", "]", ";", "if", "(", "$", "oldOwner", "!==", "$", "this", "->", "user", ")", "{", "if", "(", "!", "@", "chown", "(", "$", "path", ",", "$", "newOwner", ")", ")", "{", "throw", "new", "CException", "(", "sprintf", "(", "'Unable to change owner for %s, permission denied'", ",", "$", "path", ")", ")", ";", "}", "echo", "sprintf", "(", "\"Changing owner for %s (%s => %s)... \"", ",", "$", "path", ",", "$", "oldOwner", ",", "$", "newOwner", ")", ";", "echo", "\"done\\n\"", ";", "}", "}" ]
Changes the owner for a directory. @param string $path the directory path. @param string $newOwner the name of the new owner.
[ "Changes", "the", "owner", "for", "a", "directory", "." ]
53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/PermissionsCommand.php#L94-L106
train
crisu83/yii-consoletools
commands/PermissionsCommand.php
PermissionsCommand.changeGroup
protected function changeGroup($path, $newGroup) { $groupGid = filegroup($path); $groupData = posix_getgrgid($groupGid); $oldGroup = $groupData['name']; if ($oldGroup !== $newGroup) { if(!@chgrp($path, $newGroup)) { throw new CException(sprintf('Unable to change group for %s, permission denied', $path)); } echo sprintf("Changing group for %s (%s => %s)... ", $path, $oldGroup, $newGroup); echo "done\n"; } }
php
protected function changeGroup($path, $newGroup) { $groupGid = filegroup($path); $groupData = posix_getgrgid($groupGid); $oldGroup = $groupData['name']; if ($oldGroup !== $newGroup) { if(!@chgrp($path, $newGroup)) { throw new CException(sprintf('Unable to change group for %s, permission denied', $path)); } echo sprintf("Changing group for %s (%s => %s)... ", $path, $oldGroup, $newGroup); echo "done\n"; } }
[ "protected", "function", "changeGroup", "(", "$", "path", ",", "$", "newGroup", ")", "{", "$", "groupGid", "=", "filegroup", "(", "$", "path", ")", ";", "$", "groupData", "=", "posix_getgrgid", "(", "$", "groupGid", ")", ";", "$", "oldGroup", "=", "$", "groupData", "[", "'name'", "]", ";", "if", "(", "$", "oldGroup", "!==", "$", "newGroup", ")", "{", "if", "(", "!", "@", "chgrp", "(", "$", "path", ",", "$", "newGroup", ")", ")", "{", "throw", "new", "CException", "(", "sprintf", "(", "'Unable to change group for %s, permission denied'", ",", "$", "path", ")", ")", ";", "}", "echo", "sprintf", "(", "\"Changing group for %s (%s => %s)... \"", ",", "$", "path", ",", "$", "oldGroup", ",", "$", "newGroup", ")", ";", "echo", "\"done\\n\"", ";", "}", "}" ]
Changes the group for a directory. @param string $path the directory path. @param string $newGroup the name of the new group.
[ "Changes", "the", "group", "for", "a", "directory", "." ]
53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/PermissionsCommand.php#L113-L125
train
crisu83/yii-consoletools
commands/PermissionsCommand.php
PermissionsCommand.changeMode
protected function changeMode($path, $mode) { $oldPermission = substr(sprintf('%o', fileperms($path)), -4); $newPermission = sprintf('%04o', $mode); if ($oldPermission !== $newPermission) { if(!@chmod($path, $mode)) { throw new CException (sprintf("Unable to change mode for %s, permission denied", $path)); } echo sprintf("Changing mode for %s (%s => %s)... ", $path, $oldPermission, $newPermission); echo "done\n"; } }
php
protected function changeMode($path, $mode) { $oldPermission = substr(sprintf('%o', fileperms($path)), -4); $newPermission = sprintf('%04o', $mode); if ($oldPermission !== $newPermission) { if(!@chmod($path, $mode)) { throw new CException (sprintf("Unable to change mode for %s, permission denied", $path)); } echo sprintf("Changing mode for %s (%s => %s)... ", $path, $oldPermission, $newPermission); echo "done\n"; } }
[ "protected", "function", "changeMode", "(", "$", "path", ",", "$", "mode", ")", "{", "$", "oldPermission", "=", "substr", "(", "sprintf", "(", "'%o'", ",", "fileperms", "(", "$", "path", ")", ")", ",", "-", "4", ")", ";", "$", "newPermission", "=", "sprintf", "(", "'%04o'", ",", "$", "mode", ")", ";", "if", "(", "$", "oldPermission", "!==", "$", "newPermission", ")", "{", "if", "(", "!", "@", "chmod", "(", "$", "path", ",", "$", "mode", ")", ")", "{", "throw", "new", "CException", "(", "sprintf", "(", "\"Unable to change mode for %s, permission denied\"", ",", "$", "path", ")", ")", ";", "}", "echo", "sprintf", "(", "\"Changing mode for %s (%s => %s)... \"", ",", "$", "path", ",", "$", "oldPermission", ",", "$", "newPermission", ")", ";", "echo", "\"done\\n\"", ";", "}", "}" ]
Changes the mode for a directory. @param string $path the directory path. @param integer $mode the mode.
[ "Changes", "the", "mode", "for", "a", "directory", "." ]
53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc
https://github.com/crisu83/yii-consoletools/blob/53bcb1bcdd33b9ef79034ff9c0d5bbfb3f971afc/commands/PermissionsCommand.php#L132-L143
train
IftekherSunny/Planet-Framework
src/Sun/Http/Redirect.php
Redirect.with
public function with($key, $value) { $this->hasData = true; $this->session->create($key, $value); return $this; }
php
public function with($key, $value) { $this->hasData = true; $this->session->create($key, $value); return $this; }
[ "public", "function", "with", "(", "$", "key", ",", "$", "value", ")", "{", "$", "this", "->", "hasData", "=", "true", ";", "$", "this", "->", "session", "->", "create", "(", "$", "key", ",", "$", "value", ")", ";", "return", "$", "this", ";", "}" ]
To store data in a session @param string $key @param mixed $value @return $this
[ "To", "store", "data", "in", "a", "session" ]
530e772fb97695c1c4e1af73f81675f189474d9f
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Http/Redirect.php#L72-L79
train
IftekherSunny/Planet-Framework
src/Sun/Http/Redirect.php
Redirect.backWith
public function backWith($key, $value) { $this->with($key, $value); $url = $this->session->get('previous_uri'); header('location: ' . $url); exit(); }
php
public function backWith($key, $value) { $this->with($key, $value); $url = $this->session->get('previous_uri'); header('location: ' . $url); exit(); }
[ "public", "function", "backWith", "(", "$", "key", ",", "$", "value", ")", "{", "$", "this", "->", "with", "(", "$", "key", ",", "$", "value", ")", ";", "$", "url", "=", "$", "this", "->", "session", "->", "get", "(", "'previous_uri'", ")", ";", "header", "(", "'location: '", ".", "$", "url", ")", ";", "exit", "(", ")", ";", "}" ]
To redirect back with value @param string $key @param mixed $value
[ "To", "redirect", "back", "with", "value" ]
530e772fb97695c1c4e1af73f81675f189474d9f
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Http/Redirect.php#L97-L105
train
akumar2-velsof/guzzlehttp
src/RingBridge.php
RingBridge.createRingRequest
public static function createRingRequest(RequestInterface $request) { $options = $request->getConfig()->toArray(); $url = $request->getUrl(); // No need to calculate the query string twice (in URL and query). $qs = ($pos = strpos($url, '?')) ? substr($url, $pos + 1) : null; return [ 'scheme' => $request->getScheme(), 'http_method' => $request->getMethod(), 'url' => $url, 'uri' => $request->getPath(), 'headers' => $request->getHeaders(), 'body' => $request->getBody(), 'version' => $request->getProtocolVersion(), 'client' => $options, 'query_string' => $qs, 'future' => isset($options['future']) ? $options['future'] : false ]; }
php
public static function createRingRequest(RequestInterface $request) { $options = $request->getConfig()->toArray(); $url = $request->getUrl(); // No need to calculate the query string twice (in URL and query). $qs = ($pos = strpos($url, '?')) ? substr($url, $pos + 1) : null; return [ 'scheme' => $request->getScheme(), 'http_method' => $request->getMethod(), 'url' => $url, 'uri' => $request->getPath(), 'headers' => $request->getHeaders(), 'body' => $request->getBody(), 'version' => $request->getProtocolVersion(), 'client' => $options, 'query_string' => $qs, 'future' => isset($options['future']) ? $options['future'] : false ]; }
[ "public", "static", "function", "createRingRequest", "(", "RequestInterface", "$", "request", ")", "{", "$", "options", "=", "$", "request", "->", "getConfig", "(", ")", "->", "toArray", "(", ")", ";", "$", "url", "=", "$", "request", "->", "getUrl", "(", ")", ";", "// No need to calculate the query string twice (in URL and query).", "$", "qs", "=", "(", "$", "pos", "=", "strpos", "(", "$", "url", ",", "'?'", ")", ")", "?", "substr", "(", "$", "url", ",", "$", "pos", "+", "1", ")", ":", "null", ";", "return", "[", "'scheme'", "=>", "$", "request", "->", "getScheme", "(", ")", ",", "'http_method'", "=>", "$", "request", "->", "getMethod", "(", ")", ",", "'url'", "=>", "$", "url", ",", "'uri'", "=>", "$", "request", "->", "getPath", "(", ")", ",", "'headers'", "=>", "$", "request", "->", "getHeaders", "(", ")", ",", "'body'", "=>", "$", "request", "->", "getBody", "(", ")", ",", "'version'", "=>", "$", "request", "->", "getProtocolVersion", "(", ")", ",", "'client'", "=>", "$", "options", ",", "'query_string'", "=>", "$", "qs", ",", "'future'", "=>", "isset", "(", "$", "options", "[", "'future'", "]", ")", "?", "$", "options", "[", "'future'", "]", ":", "false", "]", ";", "}" ]
Creates a Ring request from a request object. This function does not hook up the "then" and "progress" events that would be required for actually sending a Guzzle request through a RingPHP handler. @param RequestInterface $request Request to convert. @return array Converted Guzzle Ring request.
[ "Creates", "a", "Ring", "request", "from", "a", "request", "object", "." ]
9588a489c52b27e2d4047f146ddacffc3e111b7e
https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/RingBridge.php#L28-L47
train
akumar2-velsof/guzzlehttp
src/RingBridge.php
RingBridge.prepareRingRequest
public static function prepareRingRequest(Transaction $trans) { // Clear out the transaction state when initiating. $trans->exception = null; $request = self::createRingRequest($trans->request); // Emit progress events if any progress listeners are registered. if ($trans->request->getEmitter()->hasListeners('progress')) { $emitter = $trans->request->getEmitter(); $request['client']['progress'] = function ($a, $b, $c, $d) use ($trans, $emitter) { $emitter->emit('progress', new ProgressEvent($trans, $a, $b, $c, $d)); }; } return $request; }
php
public static function prepareRingRequest(Transaction $trans) { // Clear out the transaction state when initiating. $trans->exception = null; $request = self::createRingRequest($trans->request); // Emit progress events if any progress listeners are registered. if ($trans->request->getEmitter()->hasListeners('progress')) { $emitter = $trans->request->getEmitter(); $request['client']['progress'] = function ($a, $b, $c, $d) use ($trans, $emitter) { $emitter->emit('progress', new ProgressEvent($trans, $a, $b, $c, $d)); }; } return $request; }
[ "public", "static", "function", "prepareRingRequest", "(", "Transaction", "$", "trans", ")", "{", "// Clear out the transaction state when initiating.", "$", "trans", "->", "exception", "=", "null", ";", "$", "request", "=", "self", "::", "createRingRequest", "(", "$", "trans", "->", "request", ")", ";", "// Emit progress events if any progress listeners are registered.", "if", "(", "$", "trans", "->", "request", "->", "getEmitter", "(", ")", "->", "hasListeners", "(", "'progress'", ")", ")", "{", "$", "emitter", "=", "$", "trans", "->", "request", "->", "getEmitter", "(", ")", ";", "$", "request", "[", "'client'", "]", "[", "'progress'", "]", "=", "function", "(", "$", "a", ",", "$", "b", ",", "$", "c", ",", "$", "d", ")", "use", "(", "$", "trans", ",", "$", "emitter", ")", "{", "$", "emitter", "->", "emit", "(", "'progress'", ",", "new", "ProgressEvent", "(", "$", "trans", ",", "$", "a", ",", "$", "b", ",", "$", "c", ",", "$", "d", ")", ")", ";", "}", ";", "}", "return", "$", "request", ";", "}" ]
Creates a Ring request from a request object AND prepares the callbacks. @param Transaction $trans Transaction to update. @return array Converted Guzzle Ring request.
[ "Creates", "a", "Ring", "request", "from", "a", "request", "object", "AND", "prepares", "the", "callbacks", "." ]
9588a489c52b27e2d4047f146ddacffc3e111b7e
https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/RingBridge.php#L56-L71
train
akumar2-velsof/guzzlehttp
src/RingBridge.php
RingBridge.completeRingResponse
public static function completeRingResponse( Transaction $trans, array $response, MessageFactoryInterface $messageFactory ) { $trans->state = 'complete'; $trans->transferInfo = isset($response['transfer_stats']) ? $response['transfer_stats'] : []; if (!empty($response['status'])) { $options = []; if (isset($response['version'])) { $options['protocol_version'] = $response['version']; } if (isset($response['reason'])) { $options['reason_phrase'] = $response['reason']; } $trans->response = $messageFactory->createResponse( $response['status'], isset($response['headers']) ? $response['headers'] : [], isset($response['body']) ? $response['body'] : null, $options ); if (isset($response['effective_url'])) { $trans->response->setEffectiveUrl($response['effective_url']); } } elseif (empty($response['error'])) { // When nothing was returned, then we need to add an error. $response['error'] = self::getNoRingResponseException($trans->request); } if (isset($response['error'])) { $trans->state = 'error'; $trans->exception = $response['error']; } }
php
public static function completeRingResponse( Transaction $trans, array $response, MessageFactoryInterface $messageFactory ) { $trans->state = 'complete'; $trans->transferInfo = isset($response['transfer_stats']) ? $response['transfer_stats'] : []; if (!empty($response['status'])) { $options = []; if (isset($response['version'])) { $options['protocol_version'] = $response['version']; } if (isset($response['reason'])) { $options['reason_phrase'] = $response['reason']; } $trans->response = $messageFactory->createResponse( $response['status'], isset($response['headers']) ? $response['headers'] : [], isset($response['body']) ? $response['body'] : null, $options ); if (isset($response['effective_url'])) { $trans->response->setEffectiveUrl($response['effective_url']); } } elseif (empty($response['error'])) { // When nothing was returned, then we need to add an error. $response['error'] = self::getNoRingResponseException($trans->request); } if (isset($response['error'])) { $trans->state = 'error'; $trans->exception = $response['error']; } }
[ "public", "static", "function", "completeRingResponse", "(", "Transaction", "$", "trans", ",", "array", "$", "response", ",", "MessageFactoryInterface", "$", "messageFactory", ")", "{", "$", "trans", "->", "state", "=", "'complete'", ";", "$", "trans", "->", "transferInfo", "=", "isset", "(", "$", "response", "[", "'transfer_stats'", "]", ")", "?", "$", "response", "[", "'transfer_stats'", "]", ":", "[", "]", ";", "if", "(", "!", "empty", "(", "$", "response", "[", "'status'", "]", ")", ")", "{", "$", "options", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "response", "[", "'version'", "]", ")", ")", "{", "$", "options", "[", "'protocol_version'", "]", "=", "$", "response", "[", "'version'", "]", ";", "}", "if", "(", "isset", "(", "$", "response", "[", "'reason'", "]", ")", ")", "{", "$", "options", "[", "'reason_phrase'", "]", "=", "$", "response", "[", "'reason'", "]", ";", "}", "$", "trans", "->", "response", "=", "$", "messageFactory", "->", "createResponse", "(", "$", "response", "[", "'status'", "]", ",", "isset", "(", "$", "response", "[", "'headers'", "]", ")", "?", "$", "response", "[", "'headers'", "]", ":", "[", "]", ",", "isset", "(", "$", "response", "[", "'body'", "]", ")", "?", "$", "response", "[", "'body'", "]", ":", "null", ",", "$", "options", ")", ";", "if", "(", "isset", "(", "$", "response", "[", "'effective_url'", "]", ")", ")", "{", "$", "trans", "->", "response", "->", "setEffectiveUrl", "(", "$", "response", "[", "'effective_url'", "]", ")", ";", "}", "}", "elseif", "(", "empty", "(", "$", "response", "[", "'error'", "]", ")", ")", "{", "// When nothing was returned, then we need to add an error.", "$", "response", "[", "'error'", "]", "=", "self", "::", "getNoRingResponseException", "(", "$", "trans", "->", "request", ")", ";", "}", "if", "(", "isset", "(", "$", "response", "[", "'error'", "]", ")", ")", "{", "$", "trans", "->", "state", "=", "'error'", ";", "$", "trans", "->", "exception", "=", "$", "response", "[", "'error'", "]", ";", "}", "}" ]
Handles the process of processing a response received from a ring handler. The created response is added to the transaction, and the transaction stat is set appropriately. @param Transaction $trans Owns request and response. @param array $response Ring response array @param MessageFactoryInterface $messageFactory Creates response objects.
[ "Handles", "the", "process", "of", "processing", "a", "response", "received", "from", "a", "ring", "handler", ".", "The", "created", "response", "is", "added", "to", "the", "transaction", "and", "the", "transaction", "stat", "is", "set", "appropriately", "." ]
9588a489c52b27e2d4047f146ddacffc3e111b7e
https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/RingBridge.php#L82-L117
train
akumar2-velsof/guzzlehttp
src/RingBridge.php
RingBridge.fromRingRequest
public static function fromRingRequest(array $request) { $options = []; if (isset($request['version'])) { $options['protocol_version'] = $request['version']; } if (!isset($request['http_method'])) { throw new \InvalidArgumentException('No http_method'); } return new Request( $request['http_method'], Core::url($request), isset($request['headers']) ? $request['headers'] : [], isset($request['body']) ? Stream::factory($request['body']) : null, $options ); }
php
public static function fromRingRequest(array $request) { $options = []; if (isset($request['version'])) { $options['protocol_version'] = $request['version']; } if (!isset($request['http_method'])) { throw new \InvalidArgumentException('No http_method'); } return new Request( $request['http_method'], Core::url($request), isset($request['headers']) ? $request['headers'] : [], isset($request['body']) ? Stream::factory($request['body']) : null, $options ); }
[ "public", "static", "function", "fromRingRequest", "(", "array", "$", "request", ")", "{", "$", "options", "=", "[", "]", ";", "if", "(", "isset", "(", "$", "request", "[", "'version'", "]", ")", ")", "{", "$", "options", "[", "'protocol_version'", "]", "=", "$", "request", "[", "'version'", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "request", "[", "'http_method'", "]", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'No http_method'", ")", ";", "}", "return", "new", "Request", "(", "$", "request", "[", "'http_method'", "]", ",", "Core", "::", "url", "(", "$", "request", ")", ",", "isset", "(", "$", "request", "[", "'headers'", "]", ")", "?", "$", "request", "[", "'headers'", "]", ":", "[", "]", ",", "isset", "(", "$", "request", "[", "'body'", "]", ")", "?", "Stream", "::", "factory", "(", "$", "request", "[", "'body'", "]", ")", ":", "null", ",", "$", "options", ")", ";", "}" ]
Creates a Guzzle request object using a ring request array. @param array $request Ring request @return Request @throws \InvalidArgumentException for incomplete requests.
[ "Creates", "a", "Guzzle", "request", "object", "using", "a", "ring", "request", "array", "." ]
9588a489c52b27e2d4047f146ddacffc3e111b7e
https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/RingBridge.php#L127-L145
train
loevgaard/dandomain-api
src/Api.php
Api.objectToArray
protected function objectToArray($obj) : array { if ($obj instanceof \stdClass) { $obj = json_decode(json_encode($obj), true); } return (array)$obj; }
php
protected function objectToArray($obj) : array { if ($obj instanceof \stdClass) { $obj = json_decode(json_encode($obj), true); } return (array)$obj; }
[ "protected", "function", "objectToArray", "(", "$", "obj", ")", ":", "array", "{", "if", "(", "$", "obj", "instanceof", "\\", "stdClass", ")", "{", "$", "obj", "=", "json_decode", "(", "json_encode", "(", "$", "obj", ")", ",", "true", ")", ";", "}", "return", "(", "array", ")", "$", "obj", ";", "}" ]
Helper method to convert a \stdClass into an array @param $obj @return array
[ "Helper", "method", "to", "convert", "a", "\\", "stdClass", "into", "an", "array" ]
cd420d5f92a78eece4201ab57a5f6356537ed371
https://github.com/loevgaard/dandomain-api/blob/cd420d5f92a78eece4201ab57a5f6356537ed371/src/Api.php#L307-L314
train
selikhovleonid/nadir
src/core/ViewFactory.php
ViewFactory.createView
public static function createView($sCtrlName = null, $sActionName) { $sViewsRoot = AppHelper::getInstance()->getComponentRoot('views'); $sAddPath = ''; if (!empty($sCtrlName)) { $sAddPath .= DIRECTORY_SEPARATOR.strtolower($sCtrlName); } $sViewFile = $sViewsRoot.$sAddPath.DIRECTORY_SEPARATOR .strtolower($sActionName).'.php'; if (is_readable($sViewFile)) { return new View($sViewFile); } return null; }
php
public static function createView($sCtrlName = null, $sActionName) { $sViewsRoot = AppHelper::getInstance()->getComponentRoot('views'); $sAddPath = ''; if (!empty($sCtrlName)) { $sAddPath .= DIRECTORY_SEPARATOR.strtolower($sCtrlName); } $sViewFile = $sViewsRoot.$sAddPath.DIRECTORY_SEPARATOR .strtolower($sActionName).'.php'; if (is_readable($sViewFile)) { return new View($sViewFile); } return null; }
[ "public", "static", "function", "createView", "(", "$", "sCtrlName", "=", "null", ",", "$", "sActionName", ")", "{", "$", "sViewsRoot", "=", "AppHelper", "::", "getInstance", "(", ")", "->", "getComponentRoot", "(", "'views'", ")", ";", "$", "sAddPath", "=", "''", ";", "if", "(", "!", "empty", "(", "$", "sCtrlName", ")", ")", "{", "$", "sAddPath", ".=", "DIRECTORY_SEPARATOR", ".", "strtolower", "(", "$", "sCtrlName", ")", ";", "}", "$", "sViewFile", "=", "$", "sViewsRoot", ".", "$", "sAddPath", ".", "DIRECTORY_SEPARATOR", ".", "strtolower", "(", "$", "sActionName", ")", ".", "'.php'", ";", "if", "(", "is_readable", "(", "$", "sViewFile", ")", ")", "{", "return", "new", "View", "(", "$", "sViewFile", ")", ";", "}", "return", "null", ";", "}" ]
The method creates a view object assigned with the specific controller and action in it. If controller name is empty it means a markup file determined only with action name. It doesn't physically consist into the direcory named as controller, it's in the root of the view directory. @param string $sCtrlName|null The controller name (as optional) @param string $sActionName The action name. @return \nadir\core\View|null It returns null if view file isn't readable.
[ "The", "method", "creates", "a", "view", "object", "assigned", "with", "the", "specific", "controller", "and", "action", "in", "it", ".", "If", "controller", "name", "is", "empty", "it", "means", "a", "markup", "file", "determined", "only", "with", "action", "name", ".", "It", "doesn", "t", "physically", "consist", "into", "the", "direcory", "named", "as", "controller", "it", "s", "in", "the", "root", "of", "the", "view", "directory", "." ]
47545fccd8516c8f0a20c02ba62f68269c7199da
https://github.com/selikhovleonid/nadir/blob/47545fccd8516c8f0a20c02ba62f68269c7199da/src/core/ViewFactory.php#L29-L42
train
selikhovleonid/nadir
src/core/ViewFactory.php
ViewFactory.createLayout
public static function createLayout($sLayoutName, View $oView) { $sLayoutsRoot = AppHelper::getInstance()->getComponentRoot('layouts'); $sLayoutFile = $sLayoutsRoot.DIRECTORY_SEPARATOR .strtolower($sLayoutName).'.php'; if (is_readable($sLayoutFile)) { return new Layout($sLayoutFile, $oView); } return null; }
php
public static function createLayout($sLayoutName, View $oView) { $sLayoutsRoot = AppHelper::getInstance()->getComponentRoot('layouts'); $sLayoutFile = $sLayoutsRoot.DIRECTORY_SEPARATOR .strtolower($sLayoutName).'.php'; if (is_readable($sLayoutFile)) { return new Layout($sLayoutFile, $oView); } return null; }
[ "public", "static", "function", "createLayout", "(", "$", "sLayoutName", ",", "View", "$", "oView", ")", "{", "$", "sLayoutsRoot", "=", "AppHelper", "::", "getInstance", "(", ")", "->", "getComponentRoot", "(", "'layouts'", ")", ";", "$", "sLayoutFile", "=", "$", "sLayoutsRoot", ".", "DIRECTORY_SEPARATOR", ".", "strtolower", "(", "$", "sLayoutName", ")", ".", "'.php'", ";", "if", "(", "is_readable", "(", "$", "sLayoutFile", ")", ")", "{", "return", "new", "Layout", "(", "$", "sLayoutFile", ",", "$", "oView", ")", ";", "}", "return", "null", ";", "}" ]
It creates a layout object. @param type $sLayoutName The layout name. @param \nadir\core\View $oView The object of view. @return \nadir\core\Layout|null
[ "It", "creates", "a", "layout", "object", "." ]
47545fccd8516c8f0a20c02ba62f68269c7199da
https://github.com/selikhovleonid/nadir/blob/47545fccd8516c8f0a20c02ba62f68269c7199da/src/core/ViewFactory.php#L50-L59
train
selikhovleonid/nadir
src/core/ViewFactory.php
ViewFactory.createSnippet
public static function createSnippet($sSnptName) { $sSnptRoot = AppHelper::getInstance()->getComponentRoot('snippets'); $SnptFile = $sSnptRoot.DIRECTORY_SEPARATOR .strtolower($sSnptName).'.php'; if (is_readable($SnptFile)) { return new Snippet($SnptFile); } return null; }
php
public static function createSnippet($sSnptName) { $sSnptRoot = AppHelper::getInstance()->getComponentRoot('snippets'); $SnptFile = $sSnptRoot.DIRECTORY_SEPARATOR .strtolower($sSnptName).'.php'; if (is_readable($SnptFile)) { return new Snippet($SnptFile); } return null; }
[ "public", "static", "function", "createSnippet", "(", "$", "sSnptName", ")", "{", "$", "sSnptRoot", "=", "AppHelper", "::", "getInstance", "(", ")", "->", "getComponentRoot", "(", "'snippets'", ")", ";", "$", "SnptFile", "=", "$", "sSnptRoot", ".", "DIRECTORY_SEPARATOR", ".", "strtolower", "(", "$", "sSnptName", ")", ".", "'.php'", ";", "if", "(", "is_readable", "(", "$", "SnptFile", ")", ")", "{", "return", "new", "Snippet", "(", "$", "SnptFile", ")", ";", "}", "return", "null", ";", "}" ]
The method creates a snippet-object. @param type $sSnptName The snippet name. @return \nadir\core\Snippet|null.
[ "The", "method", "creates", "a", "snippet", "-", "object", "." ]
47545fccd8516c8f0a20c02ba62f68269c7199da
https://github.com/selikhovleonid/nadir/blob/47545fccd8516c8f0a20c02ba62f68269c7199da/src/core/ViewFactory.php#L66-L75
train
fxpio/fxp-gluon
Twig/Extension/GoogleFontsExtension.php
GoogleFontsExtension.addStylesheetGoogleFonts
public function addStylesheetGoogleFonts() { $str = ''; foreach ($this->fonts as $url) { $str .= sprintf('<link href="%s" rel="stylesheet">', $url); } return $str; }
php
public function addStylesheetGoogleFonts() { $str = ''; foreach ($this->fonts as $url) { $str .= sprintf('<link href="%s" rel="stylesheet">', $url); } return $str; }
[ "public", "function", "addStylesheetGoogleFonts", "(", ")", "{", "$", "str", "=", "''", ";", "foreach", "(", "$", "this", "->", "fonts", "as", "$", "url", ")", "{", "$", "str", ".=", "sprintf", "(", "'<link href=\"%s\" rel=\"stylesheet\">'", ",", "$", "url", ")", ";", "}", "return", "$", "str", ";", "}" ]
Build the stylesheet links of google fonts. @return string
[ "Build", "the", "stylesheet", "links", "of", "google", "fonts", "." ]
0548b7d598ef4b0785b5df3b849a10f439b2dc65
https://github.com/fxpio/fxp-gluon/blob/0548b7d598ef4b0785b5df3b849a10f439b2dc65/Twig/Extension/GoogleFontsExtension.php#L51-L60
train
IftekherSunny/Planet-Framework
src/Sun/Console/Commands/AppName.php
AppName.setAppNamespace
private function setAppNamespace($oldNamespace, $newNamespace) { $files = $this->filesystem->files(app_path()); foreach ($files as $file) { $content = $this->filesystem->get($file); $this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content)); } }
php
private function setAppNamespace($oldNamespace, $newNamespace) { $files = $this->filesystem->files(app_path()); foreach ($files as $file) { $content = $this->filesystem->get($file); $this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content)); } }
[ "private", "function", "setAppNamespace", "(", "$", "oldNamespace", ",", "$", "newNamespace", ")", "{", "$", "files", "=", "$", "this", "->", "filesystem", "->", "files", "(", "app_path", "(", ")", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "content", "=", "$", "this", "->", "filesystem", "->", "get", "(", "$", "file", ")", ";", "$", "this", "->", "filesystem", "->", "create", "(", "$", "file", ",", "preg_replace", "(", "\"/\\\\b\"", ".", "$", "oldNamespace", ".", "\"\\\\b/\"", ",", "$", "newNamespace", ",", "$", "content", ")", ")", ";", "}", "}" ]
To set app directory files namespace @param $oldNamespace @param $newNamespace
[ "To", "set", "app", "directory", "files", "namespace" ]
530e772fb97695c1c4e1af73f81675f189474d9f
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Commands/AppName.php#L88-L96
train
IftekherSunny/Planet-Framework
src/Sun/Console/Commands/AppName.php
AppName.setBootstrapNamespace
private function setBootstrapNamespace($oldNamespace, $newNamespace) { $files = $this->filesystem->files(base_path() . '/bootstrap'); foreach ($files as $file) { $content = $this->filesystem->get($file); $this->filesystem->create($file, str_replace($oldNamespace . '\Controllers', $newNamespace . '\Controllers', $content)); } }
php
private function setBootstrapNamespace($oldNamespace, $newNamespace) { $files = $this->filesystem->files(base_path() . '/bootstrap'); foreach ($files as $file) { $content = $this->filesystem->get($file); $this->filesystem->create($file, str_replace($oldNamespace . '\Controllers', $newNamespace . '\Controllers', $content)); } }
[ "private", "function", "setBootstrapNamespace", "(", "$", "oldNamespace", ",", "$", "newNamespace", ")", "{", "$", "files", "=", "$", "this", "->", "filesystem", "->", "files", "(", "base_path", "(", ")", ".", "'/bootstrap'", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "content", "=", "$", "this", "->", "filesystem", "->", "get", "(", "$", "file", ")", ";", "$", "this", "->", "filesystem", "->", "create", "(", "$", "file", ",", "str_replace", "(", "$", "oldNamespace", ".", "'\\Controllers'", ",", "$", "newNamespace", ".", "'\\Controllers'", ",", "$", "content", ")", ")", ";", "}", "}" ]
To set bootstrap file namespace @param $oldNamespace @param $newNamespace @return array
[ "To", "set", "bootstrap", "file", "namespace" ]
530e772fb97695c1c4e1af73f81675f189474d9f
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Commands/AppName.php#L106-L114
train
IftekherSunny/Planet-Framework
src/Sun/Console/Commands/AppName.php
AppName.setConfigNamespace
private function setConfigNamespace($oldNamespace, $newNamespace) { $files = $this->filesystem->files(base_path() . '/config'); foreach ($files as $file) { $content = $this->filesystem->get($file); $this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content)); } }
php
private function setConfigNamespace($oldNamespace, $newNamespace) { $files = $this->filesystem->files(base_path() . '/config'); foreach ($files as $file) { $content = $this->filesystem->get($file); $this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content)); } }
[ "private", "function", "setConfigNamespace", "(", "$", "oldNamespace", ",", "$", "newNamespace", ")", "{", "$", "files", "=", "$", "this", "->", "filesystem", "->", "files", "(", "base_path", "(", ")", ".", "'/config'", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "content", "=", "$", "this", "->", "filesystem", "->", "get", "(", "$", "file", ")", ";", "$", "this", "->", "filesystem", "->", "create", "(", "$", "file", ",", "preg_replace", "(", "\"/\\\\b\"", ".", "$", "oldNamespace", ".", "\"\\\\b/\"", ",", "$", "newNamespace", ",", "$", "content", ")", ")", ";", "}", "}" ]
To set config directory files namespace @param $oldNamespace @param $newNamespace @return array
[ "To", "set", "config", "directory", "files", "namespace" ]
530e772fb97695c1c4e1af73f81675f189474d9f
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Commands/AppName.php#L124-L132
train
IftekherSunny/Planet-Framework
src/Sun/Console/Commands/AppName.php
AppName.setComposerNamespace
private function setComposerNamespace($oldNamespace, $newNamespace) { $files = $this->filesystem->files(base_path() . '/vendor/composer'); foreach ($files as $file) { $content = $this->filesystem->get($file); $this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content)); } $file = base_path() . '/composer.json'; $content = $this->filesystem->get($file); $this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content)); }
php
private function setComposerNamespace($oldNamespace, $newNamespace) { $files = $this->filesystem->files(base_path() . '/vendor/composer'); foreach ($files as $file) { $content = $this->filesystem->get($file); $this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content)); } $file = base_path() . '/composer.json'; $content = $this->filesystem->get($file); $this->filesystem->create($file, preg_replace("/\\b" . $oldNamespace . "\\b/", $newNamespace, $content)); }
[ "private", "function", "setComposerNamespace", "(", "$", "oldNamespace", ",", "$", "newNamespace", ")", "{", "$", "files", "=", "$", "this", "->", "filesystem", "->", "files", "(", "base_path", "(", ")", ".", "'/vendor/composer'", ")", ";", "foreach", "(", "$", "files", "as", "$", "file", ")", "{", "$", "content", "=", "$", "this", "->", "filesystem", "->", "get", "(", "$", "file", ")", ";", "$", "this", "->", "filesystem", "->", "create", "(", "$", "file", ",", "preg_replace", "(", "\"/\\\\b\"", ".", "$", "oldNamespace", ".", "\"\\\\b/\"", ",", "$", "newNamespace", ",", "$", "content", ")", ")", ";", "}", "$", "file", "=", "base_path", "(", ")", ".", "'/composer.json'", ";", "$", "content", "=", "$", "this", "->", "filesystem", "->", "get", "(", "$", "file", ")", ";", "$", "this", "->", "filesystem", "->", "create", "(", "$", "file", ",", "preg_replace", "(", "\"/\\\\b\"", ".", "$", "oldNamespace", ".", "\"\\\\b/\"", ",", "$", "newNamespace", ",", "$", "content", ")", ")", ";", "}" ]
To set composer namespace @param $oldNamespace @param $newNamespace
[ "To", "set", "composer", "namespace" ]
530e772fb97695c1c4e1af73f81675f189474d9f
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Console/Commands/AppName.php#L140-L152
train
inhere/php-library-plus
libs/Task/Worker/OptionAndConfigTrait.php
OptionAndConfigTrait.loadCliOptions
protected function loadCliOptions(array $opts) { $map = [ 'c' => 'conf_file', // config file 's' => 'servers', // server address 'n' => 'workerNum', // worker number do all tasks 'u' => 'user', 'g' => 'group', 'l' => 'logFile', 'p' => 'pidFile', 'r' => 'maxRunTasks', // max run tasks for a worker 'x' => 'maxLifetime',// max lifetime for a worker 't' => 'timeout', ]; // show help if (isset($opts['h']) || isset($opts['help'])) { $this->showHelp(); } // show version if (isset($opts['V']) || isset($opts['version'])) { $this->showVersion(); } // load opts values to config foreach ($map as $k => $v) { if (isset($opts[$k]) && $opts[$k]) { $this->config[$v] = $opts[$k]; } } // load Custom Config File if ($file = $this->config['conf_file']) { if (!file_exists($file)) { $this->showHelp("Custom config file {$file} not found."); } $config = require $file; $this->setConfig($config); } // watch modify if (isset($opts['w']) || isset($opts['watch'])) { $this->config['watch_modify'] = $opts['w']; } // run as daemon if (isset($opts['d']) || isset($opts['daemon'])) { $this->config['daemon'] = true; } // no test if (isset($opts['no-test'])) { $this->config['no_test'] = true; } // only added tasks if (isset($opts['tasks']) && ($added = trim($opts['tasks'], ','))) { $this->config['added_tasks'] = strpos($added, ',') ? explode(',', $added) : [$added]; } if (isset($opts['v'])) { $opts['v'] = $opts['v'] === true ? '' : $opts['v']; switch ($opts['v']) { case '': $this->config['logLevel'] = self::LOG_INFO; break; case 'v': $this->config['logLevel'] = self::LOG_PROC_INFO; break; case 'vv': $this->config['logLevel'] = self::LOG_WORKER_INFO; break; case 'vvv': $this->config['logLevel'] = self::LOG_DEBUG; break; case 'vvvv': $this->config['logLevel'] = self::LOG_CRAZY; break; default: // $this->config['logLevel'] = self::LOG_INFO; break; } } }
php
protected function loadCliOptions(array $opts) { $map = [ 'c' => 'conf_file', // config file 's' => 'servers', // server address 'n' => 'workerNum', // worker number do all tasks 'u' => 'user', 'g' => 'group', 'l' => 'logFile', 'p' => 'pidFile', 'r' => 'maxRunTasks', // max run tasks for a worker 'x' => 'maxLifetime',// max lifetime for a worker 't' => 'timeout', ]; // show help if (isset($opts['h']) || isset($opts['help'])) { $this->showHelp(); } // show version if (isset($opts['V']) || isset($opts['version'])) { $this->showVersion(); } // load opts values to config foreach ($map as $k => $v) { if (isset($opts[$k]) && $opts[$k]) { $this->config[$v] = $opts[$k]; } } // load Custom Config File if ($file = $this->config['conf_file']) { if (!file_exists($file)) { $this->showHelp("Custom config file {$file} not found."); } $config = require $file; $this->setConfig($config); } // watch modify if (isset($opts['w']) || isset($opts['watch'])) { $this->config['watch_modify'] = $opts['w']; } // run as daemon if (isset($opts['d']) || isset($opts['daemon'])) { $this->config['daemon'] = true; } // no test if (isset($opts['no-test'])) { $this->config['no_test'] = true; } // only added tasks if (isset($opts['tasks']) && ($added = trim($opts['tasks'], ','))) { $this->config['added_tasks'] = strpos($added, ',') ? explode(',', $added) : [$added]; } if (isset($opts['v'])) { $opts['v'] = $opts['v'] === true ? '' : $opts['v']; switch ($opts['v']) { case '': $this->config['logLevel'] = self::LOG_INFO; break; case 'v': $this->config['logLevel'] = self::LOG_PROC_INFO; break; case 'vv': $this->config['logLevel'] = self::LOG_WORKER_INFO; break; case 'vvv': $this->config['logLevel'] = self::LOG_DEBUG; break; case 'vvvv': $this->config['logLevel'] = self::LOG_CRAZY; break; default: // $this->config['logLevel'] = self::LOG_INFO; break; } } }
[ "protected", "function", "loadCliOptions", "(", "array", "$", "opts", ")", "{", "$", "map", "=", "[", "'c'", "=>", "'conf_file'", ",", "// config file", "'s'", "=>", "'servers'", ",", "// server address", "'n'", "=>", "'workerNum'", ",", "// worker number do all tasks", "'u'", "=>", "'user'", ",", "'g'", "=>", "'group'", ",", "'l'", "=>", "'logFile'", ",", "'p'", "=>", "'pidFile'", ",", "'r'", "=>", "'maxRunTasks'", ",", "// max run tasks for a worker", "'x'", "=>", "'maxLifetime'", ",", "// max lifetime for a worker", "'t'", "=>", "'timeout'", ",", "]", ";", "// show help", "if", "(", "isset", "(", "$", "opts", "[", "'h'", "]", ")", "||", "isset", "(", "$", "opts", "[", "'help'", "]", ")", ")", "{", "$", "this", "->", "showHelp", "(", ")", ";", "}", "// show version", "if", "(", "isset", "(", "$", "opts", "[", "'V'", "]", ")", "||", "isset", "(", "$", "opts", "[", "'version'", "]", ")", ")", "{", "$", "this", "->", "showVersion", "(", ")", ";", "}", "// load opts values to config", "foreach", "(", "$", "map", "as", "$", "k", "=>", "$", "v", ")", "{", "if", "(", "isset", "(", "$", "opts", "[", "$", "k", "]", ")", "&&", "$", "opts", "[", "$", "k", "]", ")", "{", "$", "this", "->", "config", "[", "$", "v", "]", "=", "$", "opts", "[", "$", "k", "]", ";", "}", "}", "// load Custom Config File", "if", "(", "$", "file", "=", "$", "this", "->", "config", "[", "'conf_file'", "]", ")", "{", "if", "(", "!", "file_exists", "(", "$", "file", ")", ")", "{", "$", "this", "->", "showHelp", "(", "\"Custom config file {$file} not found.\"", ")", ";", "}", "$", "config", "=", "require", "$", "file", ";", "$", "this", "->", "setConfig", "(", "$", "config", ")", ";", "}", "// watch modify", "if", "(", "isset", "(", "$", "opts", "[", "'w'", "]", ")", "||", "isset", "(", "$", "opts", "[", "'watch'", "]", ")", ")", "{", "$", "this", "->", "config", "[", "'watch_modify'", "]", "=", "$", "opts", "[", "'w'", "]", ";", "}", "// run as daemon", "if", "(", "isset", "(", "$", "opts", "[", "'d'", "]", ")", "||", "isset", "(", "$", "opts", "[", "'daemon'", "]", ")", ")", "{", "$", "this", "->", "config", "[", "'daemon'", "]", "=", "true", ";", "}", "// no test", "if", "(", "isset", "(", "$", "opts", "[", "'no-test'", "]", ")", ")", "{", "$", "this", "->", "config", "[", "'no_test'", "]", "=", "true", ";", "}", "// only added tasks", "if", "(", "isset", "(", "$", "opts", "[", "'tasks'", "]", ")", "&&", "(", "$", "added", "=", "trim", "(", "$", "opts", "[", "'tasks'", "]", ",", "','", ")", ")", ")", "{", "$", "this", "->", "config", "[", "'added_tasks'", "]", "=", "strpos", "(", "$", "added", ",", "','", ")", "?", "explode", "(", "','", ",", "$", "added", ")", ":", "[", "$", "added", "]", ";", "}", "if", "(", "isset", "(", "$", "opts", "[", "'v'", "]", ")", ")", "{", "$", "opts", "[", "'v'", "]", "=", "$", "opts", "[", "'v'", "]", "===", "true", "?", "''", ":", "$", "opts", "[", "'v'", "]", ";", "switch", "(", "$", "opts", "[", "'v'", "]", ")", "{", "case", "''", ":", "$", "this", "->", "config", "[", "'logLevel'", "]", "=", "self", "::", "LOG_INFO", ";", "break", ";", "case", "'v'", ":", "$", "this", "->", "config", "[", "'logLevel'", "]", "=", "self", "::", "LOG_PROC_INFO", ";", "break", ";", "case", "'vv'", ":", "$", "this", "->", "config", "[", "'logLevel'", "]", "=", "self", "::", "LOG_WORKER_INFO", ";", "break", ";", "case", "'vvv'", ":", "$", "this", "->", "config", "[", "'logLevel'", "]", "=", "self", "::", "LOG_DEBUG", ";", "break", ";", "case", "'vvvv'", ":", "$", "this", "->", "config", "[", "'logLevel'", "]", "=", "self", "::", "LOG_CRAZY", ";", "break", ";", "default", ":", "// $this->config['logLevel'] = self::LOG_INFO;", "break", ";", "}", "}", "}" ]
load the command line options @param array $opts
[ "load", "the", "command", "line", "options" ]
8604e037937d31fa2338d79aaf9d0910cb48f559
https://github.com/inhere/php-library-plus/blob/8604e037937d31fa2338d79aaf9d0910cb48f559/libs/Task/Worker/OptionAndConfigTrait.php#L134-L222
train
chilimatic/chilimatic-framework
lib/request/CLI.php
CLI._transform
public function _transform(array $array = null) { if (empty($array)) return; foreach ($array as $param) { if (strpos($param, '=') > 0) { $tmp = explode(Generic::ASSIGNMENT_OPERATOR, $param); $this->$tmp[0] = $tmp[1]; } } return; }
php
public function _transform(array $array = null) { if (empty($array)) return; foreach ($array as $param) { if (strpos($param, '=') > 0) { $tmp = explode(Generic::ASSIGNMENT_OPERATOR, $param); $this->$tmp[0] = $tmp[1]; } } return; }
[ "public", "function", "_transform", "(", "array", "$", "array", "=", "null", ")", "{", "if", "(", "empty", "(", "$", "array", ")", ")", "return", ";", "foreach", "(", "$", "array", "as", "$", "param", ")", "{", "if", "(", "strpos", "(", "$", "param", ",", "'='", ")", ">", "0", ")", "{", "$", "tmp", "=", "explode", "(", "Generic", "::", "ASSIGNMENT_OPERATOR", ",", "$", "param", ")", ";", "$", "this", "->", "$", "tmp", "[", "0", "]", "=", "$", "tmp", "[", "1", "]", ";", "}", "}", "return", ";", "}" ]
adapted "transform" method for the argv we need a different approach ofc @param array $array @return void
[ "adapted", "transform", "method", "for", "the", "argv", "we", "need", "a", "different", "approach", "ofc" ]
8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12
https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/request/CLI.php#L72-L85
train
danhanly/signalert
src/Signalert/Renderer/FoundationRenderer.php
FoundationRenderer.render
public function render(array $notifications, $type = 'info') { // Ensure Type is Supported if (in_array($type, $this->supportedTypes) === false) { // If not, fall back to default $type = 'info'; } // If there aren't any notifications, then return an empty string if (empty($notifications) === true) { return ''; } $html = $this->createHtmlByType($notifications, $type); return $html; }
php
public function render(array $notifications, $type = 'info') { // Ensure Type is Supported if (in_array($type, $this->supportedTypes) === false) { // If not, fall back to default $type = 'info'; } // If there aren't any notifications, then return an empty string if (empty($notifications) === true) { return ''; } $html = $this->createHtmlByType($notifications, $type); return $html; }
[ "public", "function", "render", "(", "array", "$", "notifications", ",", "$", "type", "=", "'info'", ")", "{", "// Ensure Type is Supported", "if", "(", "in_array", "(", "$", "type", ",", "$", "this", "->", "supportedTypes", ")", "===", "false", ")", "{", "// If not, fall back to default", "$", "type", "=", "'info'", ";", "}", "// If there aren't any notifications, then return an empty string", "if", "(", "empty", "(", "$", "notifications", ")", "===", "true", ")", "{", "return", "''", ";", "}", "$", "html", "=", "$", "this", "->", "createHtmlByType", "(", "$", "notifications", ",", "$", "type", ")", ";", "return", "$", "html", ";", "}" ]
Renders all messages as part of the notification stack, beneath the defined identifier, as HTML @param array $notifications @param string $type @return string|void
[ "Renders", "all", "messages", "as", "part", "of", "the", "notification", "stack", "beneath", "the", "defined", "identifier", "as", "HTML" ]
21ee50e3fc0352306a2966b555984b5c9eada582
https://github.com/danhanly/signalert/blob/21ee50e3fc0352306a2966b555984b5c9eada582/src/Signalert/Renderer/FoundationRenderer.php#L23-L38
train
danhanly/signalert
src/Signalert/Renderer/FoundationRenderer.php
FoundationRenderer.createHtmlByType
private function createHtmlByType(array $notifications, $type) { $html = "<div class='alert-box {$type} radius' data-alert>"; foreach ($notifications as $notification) { $html .= "{$notification}"; // If it's not the last notification, add a line break for the next one if (end($notifications) !== $notification) { $html .= "<br />"; } } $html .= "<a href='#' class='close'>&times;</a>"; $html .= "</div>"; return $html; }
php
private function createHtmlByType(array $notifications, $type) { $html = "<div class='alert-box {$type} radius' data-alert>"; foreach ($notifications as $notification) { $html .= "{$notification}"; // If it's not the last notification, add a line break for the next one if (end($notifications) !== $notification) { $html .= "<br />"; } } $html .= "<a href='#' class='close'>&times;</a>"; $html .= "</div>"; return $html; }
[ "private", "function", "createHtmlByType", "(", "array", "$", "notifications", ",", "$", "type", ")", "{", "$", "html", "=", "\"<div class='alert-box {$type} radius' data-alert>\"", ";", "foreach", "(", "$", "notifications", "as", "$", "notification", ")", "{", "$", "html", ".=", "\"{$notification}\"", ";", "// If it's not the last notification, add a line break for the next one", "if", "(", "end", "(", "$", "notifications", ")", "!==", "$", "notification", ")", "{", "$", "html", ".=", "\"<br />\"", ";", "}", "}", "$", "html", ".=", "\"<a href='#' class='close'>&times;</a>\"", ";", "$", "html", ".=", "\"</div>\"", ";", "return", "$", "html", ";", "}" ]
Create and return html string. @param array $notifications @param string $type @return string
[ "Create", "and", "return", "html", "string", "." ]
21ee50e3fc0352306a2966b555984b5c9eada582
https://github.com/danhanly/signalert/blob/21ee50e3fc0352306a2966b555984b5c9eada582/src/Signalert/Renderer/FoundationRenderer.php#L47-L61
train
IftekherSunny/Planet-Framework
src/Sun/Support/Str.php
Str.random
public static function random($size = 32) { $bytes = openssl_random_pseudo_bytes($size, $strong); if ($bytes !== false && $strong !== false) { $string = ''; while (($len = strlen($string)) < $size) { $length = $size - $len; $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $length); } return $string; } }
php
public static function random($size = 32) { $bytes = openssl_random_pseudo_bytes($size, $strong); if ($bytes !== false && $strong !== false) { $string = ''; while (($len = strlen($string)) < $size) { $length = $size - $len; $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $length); } return $string; } }
[ "public", "static", "function", "random", "(", "$", "size", "=", "32", ")", "{", "$", "bytes", "=", "openssl_random_pseudo_bytes", "(", "$", "size", ",", "$", "strong", ")", ";", "if", "(", "$", "bytes", "!==", "false", "&&", "$", "strong", "!==", "false", ")", "{", "$", "string", "=", "''", ";", "while", "(", "(", "$", "len", "=", "strlen", "(", "$", "string", ")", ")", "<", "$", "size", ")", "{", "$", "length", "=", "$", "size", "-", "$", "len", ";", "$", "string", ".=", "substr", "(", "str_replace", "(", "[", "'/'", ",", "'+'", ",", "'='", "]", ",", "''", ",", "base64_encode", "(", "$", "bytes", ")", ")", ",", "0", ",", "$", "length", ")", ";", "}", "return", "$", "string", ";", "}", "}" ]
To generate random string @param int $size @return string
[ "To", "generate", "random", "string" ]
530e772fb97695c1c4e1af73f81675f189474d9f
https://github.com/IftekherSunny/Planet-Framework/blob/530e772fb97695c1c4e1af73f81675f189474d9f/src/Sun/Support/Str.php#L14-L28
train
nekudo/shiny_gears
src/Worker.php
Worker.getJobInfo
public function getJobInfo($Job) : void { $uptimeSeconds = time() - $this->startupTime; $uptimeSeconds = ($uptimeSeconds === 0) ? 1 : $uptimeSeconds; $avgJobsMin = $this->jobsTotal / ($uptimeSeconds / 60); $avgJobsMin = round($avgJobsMin, 2); $response = [ 'jobs_total' => $this->jobsTotal, 'avg_jobs_min' => $avgJobsMin, 'uptime_seconds' => $uptimeSeconds, ]; $Job->sendData(json_encode($response)); }
php
public function getJobInfo($Job) : void { $uptimeSeconds = time() - $this->startupTime; $uptimeSeconds = ($uptimeSeconds === 0) ? 1 : $uptimeSeconds; $avgJobsMin = $this->jobsTotal / ($uptimeSeconds / 60); $avgJobsMin = round($avgJobsMin, 2); $response = [ 'jobs_total' => $this->jobsTotal, 'avg_jobs_min' => $avgJobsMin, 'uptime_seconds' => $uptimeSeconds, ]; $Job->sendData(json_encode($response)); }
[ "public", "function", "getJobInfo", "(", "$", "Job", ")", ":", "void", "{", "$", "uptimeSeconds", "=", "time", "(", ")", "-", "$", "this", "->", "startupTime", ";", "$", "uptimeSeconds", "=", "(", "$", "uptimeSeconds", "===", "0", ")", "?", "1", ":", "$", "uptimeSeconds", ";", "$", "avgJobsMin", "=", "$", "this", "->", "jobsTotal", "/", "(", "$", "uptimeSeconds", "/", "60", ")", ";", "$", "avgJobsMin", "=", "round", "(", "$", "avgJobsMin", ",", "2", ")", ";", "$", "response", "=", "[", "'jobs_total'", "=>", "$", "this", "->", "jobsTotal", ",", "'avg_jobs_min'", "=>", "$", "avgJobsMin", ",", "'uptime_seconds'", "=>", "$", "uptimeSeconds", ",", "]", ";", "$", "Job", "->", "sendData", "(", "json_encode", "(", "$", "response", ")", ")", ";", "}" ]
Returns information about jobs handled. @param \GearmanJob $Job @return void
[ "Returns", "information", "about", "jobs", "handled", "." ]
5cb72e1efc7df1c9d97c8bf14ef1d8ba6d44df9a
https://github.com/nekudo/shiny_gears/blob/5cb72e1efc7df1c9d97c8bf14ef1d8ba6d44df9a/src/Worker.php#L154-L166
train
nekudo/shiny_gears
src/Worker.php
Worker.updatePidFile
public function updatePidFile() : void { $pidFolder = $this->getRunPath($this->poolName); if (!file_exists($pidFolder)) { mkdir($pidFolder, 0755, true); } $pidFile = $pidFolder . '/' . $this->workerName . '.pid'; $pid = getmypid(); if (file_put_contents($pidFile, $pid) === false) { throw new WorkerException('Could not create PID file.'); } }
php
public function updatePidFile() : void { $pidFolder = $this->getRunPath($this->poolName); if (!file_exists($pidFolder)) { mkdir($pidFolder, 0755, true); } $pidFile = $pidFolder . '/' . $this->workerName . '.pid'; $pid = getmypid(); if (file_put_contents($pidFile, $pid) === false) { throw new WorkerException('Could not create PID file.'); } }
[ "public", "function", "updatePidFile", "(", ")", ":", "void", "{", "$", "pidFolder", "=", "$", "this", "->", "getRunPath", "(", "$", "this", "->", "poolName", ")", ";", "if", "(", "!", "file_exists", "(", "$", "pidFolder", ")", ")", "{", "mkdir", "(", "$", "pidFolder", ",", "0755", ",", "true", ")", ";", "}", "$", "pidFile", "=", "$", "pidFolder", ".", "'/'", ".", "$", "this", "->", "workerName", ".", "'.pid'", ";", "$", "pid", "=", "getmypid", "(", ")", ";", "if", "(", "file_put_contents", "(", "$", "pidFile", ",", "$", "pid", ")", "===", "false", ")", "{", "throw", "new", "WorkerException", "(", "'Could not create PID file.'", ")", ";", "}", "}" ]
Updates PID file for the worker. @return void @throws WorkerException
[ "Updates", "PID", "file", "for", "the", "worker", "." ]
5cb72e1efc7df1c9d97c8bf14ef1d8ba6d44df9a
https://github.com/nekudo/shiny_gears/blob/5cb72e1efc7df1c9d97c8bf14ef1d8ba6d44df9a/src/Worker.php#L174-L185
train
mlocati/concrete5-translation-library
src/Parser/Dynamic.php
Dynamic.getSubParsers
public function getSubParsers() { $result = array(); $dir = __DIR__.'/DynamicItem'; if (is_dir($dir) && is_readable($dir)) { $matches = null; foreach (scandir($dir) as $item) { if (($item[0] !== '.') && preg_match('/^(.+)\.php$/i', $item, $matches) && ($matches[1] !== 'DynamicItem')) { $fqClassName = '\\'.__NAMESPACE__.'\\DynamicItem\\'.$matches[1]; $instance = new $fqClassName(); /* @var $instance \C5TL\Parser\DynamicItem\DynamicItem */ $result[$instance->getDynamicItemsParserHandler()] = $instance; } } } return $result; }
php
public function getSubParsers() { $result = array(); $dir = __DIR__.'/DynamicItem'; if (is_dir($dir) && is_readable($dir)) { $matches = null; foreach (scandir($dir) as $item) { if (($item[0] !== '.') && preg_match('/^(.+)\.php$/i', $item, $matches) && ($matches[1] !== 'DynamicItem')) { $fqClassName = '\\'.__NAMESPACE__.'\\DynamicItem\\'.$matches[1]; $instance = new $fqClassName(); /* @var $instance \C5TL\Parser\DynamicItem\DynamicItem */ $result[$instance->getDynamicItemsParserHandler()] = $instance; } } } return $result; }
[ "public", "function", "getSubParsers", "(", ")", "{", "$", "result", "=", "array", "(", ")", ";", "$", "dir", "=", "__DIR__", ".", "'/DynamicItem'", ";", "if", "(", "is_dir", "(", "$", "dir", ")", "&&", "is_readable", "(", "$", "dir", ")", ")", "{", "$", "matches", "=", "null", ";", "foreach", "(", "scandir", "(", "$", "dir", ")", "as", "$", "item", ")", "{", "if", "(", "(", "$", "item", "[", "0", "]", "!==", "'.'", ")", "&&", "preg_match", "(", "'/^(.+)\\.php$/i'", ",", "$", "item", ",", "$", "matches", ")", "&&", "(", "$", "matches", "[", "1", "]", "!==", "'DynamicItem'", ")", ")", "{", "$", "fqClassName", "=", "'\\\\'", ".", "__NAMESPACE__", ".", "'\\\\DynamicItem\\\\'", ".", "$", "matches", "[", "1", "]", ";", "$", "instance", "=", "new", "$", "fqClassName", "(", ")", ";", "/* @var $instance \\C5TL\\Parser\\DynamicItem\\DynamicItem */", "$", "result", "[", "$", "instance", "->", "getDynamicItemsParserHandler", "(", ")", "]", "=", "$", "instance", ";", "}", "}", "}", "return", "$", "result", ";", "}" ]
Returns the fully-qualified class names of all the sub-parsers. @return array[\C5TL\Parser\DynamicItem\DynamicItem]
[ "Returns", "the", "fully", "-", "qualified", "class", "names", "of", "all", "the", "sub", "-", "parsers", "." ]
26f806c8c1ecb6ce63115a4058ab396303622e00
https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser/Dynamic.php#L49-L66
train
hummer2k/ConLayout
src/Listener/ActionHandlesListener.php
ActionHandlesListener.injectActionHandles
public function injectActionHandles(EventInterface $event) { $handles = $this->getActionHandles($event); foreach ($handles as $handle) { $this->updater->addHandle($handle); } }
php
public function injectActionHandles(EventInterface $event) { $handles = $this->getActionHandles($event); foreach ($handles as $handle) { $this->updater->addHandle($handle); } }
[ "public", "function", "injectActionHandles", "(", "EventInterface", "$", "event", ")", "{", "$", "handles", "=", "$", "this", "->", "getActionHandles", "(", "$", "event", ")", ";", "foreach", "(", "$", "handles", "as", "$", "handle", ")", "{", "$", "this", "->", "updater", "->", "addHandle", "(", "$", "handle", ")", ";", "}", "}" ]
Callback handler invoked when the dispatch event is triggered. @param EventInterface $event @return void
[ "Callback", "handler", "invoked", "when", "the", "dispatch", "event", "is", "triggered", "." ]
15e472eaabc9b23ec6a5547524874e30d95e8d3e
https://github.com/hummer2k/ConLayout/blob/15e472eaabc9b23ec6a5547524874e30d95e8d3e/src/Listener/ActionHandlesListener.php#L102-L108
train
hummer2k/ConLayout
src/Listener/ActionHandlesListener.php
ActionHandlesListener.getActionHandles
protected function getActionHandles(EventInterface $event) { /* @var $routeMatch MvcEvent */ $routeMatch = $event->getRouteMatch(); $controller = $event->getTarget(); if (is_object($controller)) { $controller = get_class($controller); } $routeMatchController = $routeMatch->getParam('controller', ''); if (!$controller || ($this->preferRouteMatchController && $routeMatchController)) { $controller = $routeMatchController; } $template = $this->mapController($controller); if (!$template) { $module = $this->deriveModuleNamespace($controller); if ($namespace = $routeMatch->getParam(ModuleRouteListener::MODULE_NAMESPACE)) { $controllerSubNs = $this->deriveControllerSubNamespace($namespace); if (!empty($controllerSubNs)) { if (!empty($module)) { $module .= self::TEMPLATE_SEPARATOR . $controllerSubNs; } else { $module = $controllerSubNs; } } } $controller = $this->deriveControllerClass($controller); $template = $this->inflectName($module); if (!empty($template)) { $template .= self::TEMPLATE_SEPARATOR; } $template .= $this->inflectName($controller); } $action = $routeMatch->getParam('action'); if (null !== $action) { $template .= self::TEMPLATE_SEPARATOR . $this->inflectName($action); } $priority = 0; $actionHandles = []; $previousHandle = ''; $templateParts = explode(self::TEMPLATE_SEPARATOR, $template); foreach ($templateParts as $name) { $priority += 10; $actionHandles[] = new Handle($previousHandle.$name, $priority); $previousHandle .= $name.self::TEMPLATE_SEPARATOR; } return $actionHandles; }
php
protected function getActionHandles(EventInterface $event) { /* @var $routeMatch MvcEvent */ $routeMatch = $event->getRouteMatch(); $controller = $event->getTarget(); if (is_object($controller)) { $controller = get_class($controller); } $routeMatchController = $routeMatch->getParam('controller', ''); if (!$controller || ($this->preferRouteMatchController && $routeMatchController)) { $controller = $routeMatchController; } $template = $this->mapController($controller); if (!$template) { $module = $this->deriveModuleNamespace($controller); if ($namespace = $routeMatch->getParam(ModuleRouteListener::MODULE_NAMESPACE)) { $controllerSubNs = $this->deriveControllerSubNamespace($namespace); if (!empty($controllerSubNs)) { if (!empty($module)) { $module .= self::TEMPLATE_SEPARATOR . $controllerSubNs; } else { $module = $controllerSubNs; } } } $controller = $this->deriveControllerClass($controller); $template = $this->inflectName($module); if (!empty($template)) { $template .= self::TEMPLATE_SEPARATOR; } $template .= $this->inflectName($controller); } $action = $routeMatch->getParam('action'); if (null !== $action) { $template .= self::TEMPLATE_SEPARATOR . $this->inflectName($action); } $priority = 0; $actionHandles = []; $previousHandle = ''; $templateParts = explode(self::TEMPLATE_SEPARATOR, $template); foreach ($templateParts as $name) { $priority += 10; $actionHandles[] = new Handle($previousHandle.$name, $priority); $previousHandle .= $name.self::TEMPLATE_SEPARATOR; } return $actionHandles; }
[ "protected", "function", "getActionHandles", "(", "EventInterface", "$", "event", ")", "{", "/* @var $routeMatch MvcEvent */", "$", "routeMatch", "=", "$", "event", "->", "getRouteMatch", "(", ")", ";", "$", "controller", "=", "$", "event", "->", "getTarget", "(", ")", ";", "if", "(", "is_object", "(", "$", "controller", ")", ")", "{", "$", "controller", "=", "get_class", "(", "$", "controller", ")", ";", "}", "$", "routeMatchController", "=", "$", "routeMatch", "->", "getParam", "(", "'controller'", ",", "''", ")", ";", "if", "(", "!", "$", "controller", "||", "(", "$", "this", "->", "preferRouteMatchController", "&&", "$", "routeMatchController", ")", ")", "{", "$", "controller", "=", "$", "routeMatchController", ";", "}", "$", "template", "=", "$", "this", "->", "mapController", "(", "$", "controller", ")", ";", "if", "(", "!", "$", "template", ")", "{", "$", "module", "=", "$", "this", "->", "deriveModuleNamespace", "(", "$", "controller", ")", ";", "if", "(", "$", "namespace", "=", "$", "routeMatch", "->", "getParam", "(", "ModuleRouteListener", "::", "MODULE_NAMESPACE", ")", ")", "{", "$", "controllerSubNs", "=", "$", "this", "->", "deriveControllerSubNamespace", "(", "$", "namespace", ")", ";", "if", "(", "!", "empty", "(", "$", "controllerSubNs", ")", ")", "{", "if", "(", "!", "empty", "(", "$", "module", ")", ")", "{", "$", "module", ".=", "self", "::", "TEMPLATE_SEPARATOR", ".", "$", "controllerSubNs", ";", "}", "else", "{", "$", "module", "=", "$", "controllerSubNs", ";", "}", "}", "}", "$", "controller", "=", "$", "this", "->", "deriveControllerClass", "(", "$", "controller", ")", ";", "$", "template", "=", "$", "this", "->", "inflectName", "(", "$", "module", ")", ";", "if", "(", "!", "empty", "(", "$", "template", ")", ")", "{", "$", "template", ".=", "self", "::", "TEMPLATE_SEPARATOR", ";", "}", "$", "template", ".=", "$", "this", "->", "inflectName", "(", "$", "controller", ")", ";", "}", "$", "action", "=", "$", "routeMatch", "->", "getParam", "(", "'action'", ")", ";", "if", "(", "null", "!==", "$", "action", ")", "{", "$", "template", ".=", "self", "::", "TEMPLATE_SEPARATOR", ".", "$", "this", "->", "inflectName", "(", "$", "action", ")", ";", "}", "$", "priority", "=", "0", ";", "$", "actionHandles", "=", "[", "]", ";", "$", "previousHandle", "=", "''", ";", "$", "templateParts", "=", "explode", "(", "self", "::", "TEMPLATE_SEPARATOR", ",", "$", "template", ")", ";", "foreach", "(", "$", "templateParts", "as", "$", "name", ")", "{", "$", "priority", "+=", "10", ";", "$", "actionHandles", "[", "]", "=", "new", "Handle", "(", "$", "previousHandle", ".", "$", "name", ",", "$", "priority", ")", ";", "$", "previousHandle", ".=", "$", "name", ".", "self", "::", "TEMPLATE_SEPARATOR", ";", "}", "return", "$", "actionHandles", ";", "}" ]
Retrieve the action handles from the matched route. @param EventInterface $event @return array
[ "Retrieve", "the", "action", "handles", "from", "the", "matched", "route", "." ]
15e472eaabc9b23ec6a5547524874e30d95e8d3e
https://github.com/hummer2k/ConLayout/blob/15e472eaabc9b23ec6a5547524874e30d95e8d3e/src/Listener/ActionHandlesListener.php#L127-L183
train
mover-io/belt
lib/Trace.php
Trace._generateLine
public function _generateLine($string, $start=5) { if($this->options['trace']['enabled']) { $trace = $this->_stackString($this->options['trace']['depth'], $start+$this->options['trace']['offset'], $this->options['separator']); } else { $trace = ""; } $result = ""; if($this->options['timestamp']['enabled']) { $result .= date('c').' '; } $result .= implode($this->options['separator'],array_filter(array($trace,$string))); if($this->options['banner']['enabled']) { $result = $this->_generateBanner($result); } return $result; }
php
public function _generateLine($string, $start=5) { if($this->options['trace']['enabled']) { $trace = $this->_stackString($this->options['trace']['depth'], $start+$this->options['trace']['offset'], $this->options['separator']); } else { $trace = ""; } $result = ""; if($this->options['timestamp']['enabled']) { $result .= date('c').' '; } $result .= implode($this->options['separator'],array_filter(array($trace,$string))); if($this->options['banner']['enabled']) { $result = $this->_generateBanner($result); } return $result; }
[ "public", "function", "_generateLine", "(", "$", "string", ",", "$", "start", "=", "5", ")", "{", "if", "(", "$", "this", "->", "options", "[", "'trace'", "]", "[", "'enabled'", "]", ")", "{", "$", "trace", "=", "$", "this", "->", "_stackString", "(", "$", "this", "->", "options", "[", "'trace'", "]", "[", "'depth'", "]", ",", "$", "start", "+", "$", "this", "->", "options", "[", "'trace'", "]", "[", "'offset'", "]", ",", "$", "this", "->", "options", "[", "'separator'", "]", ")", ";", "}", "else", "{", "$", "trace", "=", "\"\"", ";", "}", "$", "result", "=", "\"\"", ";", "if", "(", "$", "this", "->", "options", "[", "'timestamp'", "]", "[", "'enabled'", "]", ")", "{", "$", "result", ".=", "date", "(", "'c'", ")", ".", "' '", ";", "}", "$", "result", ".=", "implode", "(", "$", "this", "->", "options", "[", "'separator'", "]", ",", "array_filter", "(", "array", "(", "$", "trace", ",", "$", "string", ")", ")", ")", ";", "if", "(", "$", "this", "->", "options", "[", "'banner'", "]", "[", "'enabled'", "]", ")", "{", "$", "result", "=", "$", "this", "->", "_generateBanner", "(", "$", "result", ")", ";", "}", "return", "$", "result", ";", "}" ]
Common method for generating the main logging line.
[ "Common", "method", "for", "generating", "the", "main", "logging", "line", "." ]
c966a70aa0f4eb51be55bbb86c89b1e85b773d68
https://github.com/mover-io/belt/blob/c966a70aa0f4eb51be55bbb86c89b1e85b773d68/lib/Trace.php#L149-L169
train
mover-io/belt
lib/Trace.php
Trace._toFile
public function _toFile($file = null) { $file = $file ?: sys_get_temp_dir() . '/belt_trace.log'; $this->options['printer'] = 'file://'.$file; return $this; }
php
public function _toFile($file = null) { $file = $file ?: sys_get_temp_dir() . '/belt_trace.log'; $this->options['printer'] = 'file://'.$file; return $this; }
[ "public", "function", "_toFile", "(", "$", "file", "=", "null", ")", "{", "$", "file", "=", "$", "file", "?", ":", "sys_get_temp_dir", "(", ")", ".", "'/belt_trace.log'", ";", "$", "this", "->", "options", "[", "'printer'", "]", "=", "'file://'", ".", "$", "file", ";", "return", "$", "this", ";", "}" ]
Use file based output. Useful to work around nginx's log swallowing annoyingness. @fluent
[ "Use", "file", "based", "output", ".", "Useful", "to", "work", "around", "nginx", "s", "log", "swallowing", "annoyingness", "." ]
c966a70aa0f4eb51be55bbb86c89b1e85b773d68
https://github.com/mover-io/belt/blob/c966a70aa0f4eb51be55bbb86c89b1e85b773d68/lib/Trace.php#L190-L194
train
phpcq/autoload-validation
src/ClassMapGenerator.php
ClassMapGenerator.dump
public static function dump($dirs, $file, $blackList = null) { $maps = array(); foreach ($dirs as $dir) { $maps = array_merge($maps, static::createMap($dir, null, null, $blackList)); } file_put_contents($file, sprintf('<?php return %s;', var_export($maps, true))); }
php
public static function dump($dirs, $file, $blackList = null) { $maps = array(); foreach ($dirs as $dir) { $maps = array_merge($maps, static::createMap($dir, null, null, $blackList)); } file_put_contents($file, sprintf('<?php return %s;', var_export($maps, true))); }
[ "public", "static", "function", "dump", "(", "$", "dirs", ",", "$", "file", ",", "$", "blackList", "=", "null", ")", "{", "$", "maps", "=", "array", "(", ")", ";", "foreach", "(", "$", "dirs", "as", "$", "dir", ")", "{", "$", "maps", "=", "array_merge", "(", "$", "maps", ",", "static", "::", "createMap", "(", "$", "dir", ",", "null", ",", "null", ",", "$", "blackList", ")", ")", ";", "}", "file_put_contents", "(", "$", "file", ",", "sprintf", "(", "'<?php return %s;'", ",", "var_export", "(", "$", "maps", ",", "true", ")", ")", ")", ";", "}" ]
Generate a class map file. @param \Traversable $dirs Directories or a single path to search in. @param string $file The name of the class map file. @param string[] $blackList Optional list of blacklist regex for files to exclude. @return void
[ "Generate", "a", "class", "map", "file", "." ]
c24d331f16034c2096ce0e55492993befbaa687a
https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/ClassMapGenerator.php#L82-L91
train
phpcq/autoload-validation
src/ClassMapGenerator.php
ClassMapGenerator.pathMatchesRegex
private static function pathMatchesRegex($path, $blackList) { foreach ($blackList as $item) { $match = '#' . strtr($item, '#', '\#') . '#'; if (preg_match($match, $path)) { return true; } } return false; }
php
private static function pathMatchesRegex($path, $blackList) { foreach ($blackList as $item) { $match = '#' . strtr($item, '#', '\#') . '#'; if (preg_match($match, $path)) { return true; } } return false; }
[ "private", "static", "function", "pathMatchesRegex", "(", "$", "path", ",", "$", "blackList", ")", "{", "foreach", "(", "$", "blackList", "as", "$", "item", ")", "{", "$", "match", "=", "'#'", ".", "strtr", "(", "$", "item", ",", "'#'", ",", "'\\#'", ")", ".", "'#'", ";", "if", "(", "preg_match", "(", "$", "match", ",", "$", "path", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Test path against blacklist regex list. @param string $path The path to check. @param string[] $blackList List of blacklist regexes. @return bool
[ "Test", "path", "against", "blacklist", "regex", "list", "." ]
c24d331f16034c2096ce0e55492993befbaa687a
https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/ClassMapGenerator.php#L177-L187
train
phpcq/autoload-validation
src/ClassMapGenerator.php
ClassMapGenerator.extractClasses
private static function extractClasses($contents, $extraTypes) { // strip heredocs/nowdocs $contents = preg_replace( '{<<<\s*(\'?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)\\2(?=\r\n|\n|\r|;)}s', 'null', $contents ); // strip strings $contents = preg_replace( '{"[^"\\\\]*+(\\\\.[^"\\\\]*+)*+"|\'[^\'\\\\]*+(\\\\.[^\'\\\\]*+)*+\'}s', 'null', $contents ); // strip leading non-php code if needed if (substr($contents, 0, 2) !== '<?') { $contents = preg_replace('{^.+?<\?}s', '<?', $contents, 1, $replacements); if ($replacements === 0) { return array(); } } // strip non-php blocks in the file $contents = preg_replace('{\?>.+<\?}s', '?><?', $contents); // strip trailing non-php code if needed $pos = strrpos($contents, '?>'); if (false !== $pos && false === strpos(substr($contents, $pos), '<?')) { $contents = substr($contents, 0, $pos); } preg_match_all( '{ (?: \b(?<![\$:>])(?P<type>class|interface' . $extraTypes . ') \s+ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*) | \b(?<![\$:>])(?P<ns>namespace) (?P<nsname>\s+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*' . '(?:\s*\\\\\s*[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*)? \s*[\{;] ) }ix', $contents, $matches ); return $matches; }
php
private static function extractClasses($contents, $extraTypes) { // strip heredocs/nowdocs $contents = preg_replace( '{<<<\s*(\'?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)\\2(?=\r\n|\n|\r|;)}s', 'null', $contents ); // strip strings $contents = preg_replace( '{"[^"\\\\]*+(\\\\.[^"\\\\]*+)*+"|\'[^\'\\\\]*+(\\\\.[^\'\\\\]*+)*+\'}s', 'null', $contents ); // strip leading non-php code if needed if (substr($contents, 0, 2) !== '<?') { $contents = preg_replace('{^.+?<\?}s', '<?', $contents, 1, $replacements); if ($replacements === 0) { return array(); } } // strip non-php blocks in the file $contents = preg_replace('{\?>.+<\?}s', '?><?', $contents); // strip trailing non-php code if needed $pos = strrpos($contents, '?>'); if (false !== $pos && false === strpos(substr($contents, $pos), '<?')) { $contents = substr($contents, 0, $pos); } preg_match_all( '{ (?: \b(?<![\$:>])(?P<type>class|interface' . $extraTypes . ') \s+ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*) | \b(?<![\$:>])(?P<ns>namespace) (?P<nsname>\s+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*' . '(?:\s*\\\\\s*[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*)? \s*[\{;] ) }ix', $contents, $matches ); return $matches; }
[ "private", "static", "function", "extractClasses", "(", "$", "contents", ",", "$", "extraTypes", ")", "{", "// strip heredocs/nowdocs", "$", "contents", "=", "preg_replace", "(", "'{<<<\\s*(\\'?)(\\w+)\\\\1(?:\\r\\n|\\n|\\r)(?:.*?)(?:\\r\\n|\\n|\\r)\\\\2(?=\\r\\n|\\n|\\r|;)}s'", ",", "'null'", ",", "$", "contents", ")", ";", "// strip strings", "$", "contents", "=", "preg_replace", "(", "'{\"[^\"\\\\\\\\]*+(\\\\\\\\.[^\"\\\\\\\\]*+)*+\"|\\'[^\\'\\\\\\\\]*+(\\\\\\\\.[^\\'\\\\\\\\]*+)*+\\'}s'", ",", "'null'", ",", "$", "contents", ")", ";", "// strip leading non-php code if needed", "if", "(", "substr", "(", "$", "contents", ",", "0", ",", "2", ")", "!==", "'<?'", ")", "{", "$", "contents", "=", "preg_replace", "(", "'{^.+?<\\?}s'", ",", "'<?'", ",", "$", "contents", ",", "1", ",", "$", "replacements", ")", ";", "if", "(", "$", "replacements", "===", "0", ")", "{", "return", "array", "(", ")", ";", "}", "}", "// strip non-php blocks in the file", "$", "contents", "=", "preg_replace", "(", "'{\\?>.+<\\?}s'", ",", "'?><?'", ",", "$", "contents", ")", ";", "// strip trailing non-php code if needed", "$", "pos", "=", "strrpos", "(", "$", "contents", ",", "'?>'", ")", ";", "if", "(", "false", "!==", "$", "pos", "&&", "false", "===", "strpos", "(", "substr", "(", "$", "contents", ",", "$", "pos", ")", ",", "'<?'", ")", ")", "{", "$", "contents", "=", "substr", "(", "$", "contents", ",", "0", ",", "$", "pos", ")", ";", "}", "preg_match_all", "(", "'{\n (?:\n \\b(?<![\\$:>])(?P<type>class|interface'", ".", "$", "extraTypes", ".", "') \\s+ (?P<name>[a-zA-Z_\\x7f-\\xff:][a-zA-Z0-9_\\x7f-\\xff:\\-]*)\n | \\b(?<![\\$:>])(?P<ns>namespace) (?P<nsname>\\s+[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*'", ".", "'(?:\\s*\\\\\\\\\\s*[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*)*)? \\s*[\\{;]\n )\n }ix'", ",", "$", "contents", ",", "$", "matches", ")", ";", "return", "$", "matches", ";", "}" ]
Prepare the file contents. @param string $contents The file contents. @param string $extraTypes The extra types to match. @return array
[ "Prepare", "the", "file", "contents", "." ]
c24d331f16034c2096ce0e55492993befbaa687a
https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/ClassMapGenerator.php#L260-L303
train
phpcq/autoload-validation
src/ClassMapGenerator.php
ClassMapGenerator.buildClassList
private static function buildClassList($matches) { if (array() === $matches) { return array(); } $classes = array(); $namespace = ''; for ($i = 0, $len = count($matches['type']); $i < $len; $i++) { if (!empty($matches['ns'][$i])) { $namespace = str_replace(array(' ', "\t", "\r", "\n"), '', $matches['nsname'][$i]) . '\\'; } else { $name = $matches['name'][$i]; // skip anon classes extending/implementing if ($name === 'extends' || $name === 'implements') { continue; } if ($name[0] === ':') { // This is an XHP class, https://github.com/facebook/xhp $name = 'xhp' . substr(str_replace(array('-', ':'), array('_', '__'), $name), 1); } elseif ($matches['type'][$i] === 'enum') { // In Hack, something like: // enum Foo: int { HERP = '123'; } // The regex above captures the colon, which isn't part of // the class name. $name = rtrim($name, ':'); } $classes[] = ltrim($namespace . $name, '\\'); } } return $classes; }
php
private static function buildClassList($matches) { if (array() === $matches) { return array(); } $classes = array(); $namespace = ''; for ($i = 0, $len = count($matches['type']); $i < $len; $i++) { if (!empty($matches['ns'][$i])) { $namespace = str_replace(array(' ', "\t", "\r", "\n"), '', $matches['nsname'][$i]) . '\\'; } else { $name = $matches['name'][$i]; // skip anon classes extending/implementing if ($name === 'extends' || $name === 'implements') { continue; } if ($name[0] === ':') { // This is an XHP class, https://github.com/facebook/xhp $name = 'xhp' . substr(str_replace(array('-', ':'), array('_', '__'), $name), 1); } elseif ($matches['type'][$i] === 'enum') { // In Hack, something like: // enum Foo: int { HERP = '123'; } // The regex above captures the colon, which isn't part of // the class name. $name = rtrim($name, ':'); } $classes[] = ltrim($namespace . $name, '\\'); } } return $classes; }
[ "private", "static", "function", "buildClassList", "(", "$", "matches", ")", "{", "if", "(", "array", "(", ")", "===", "$", "matches", ")", "{", "return", "array", "(", ")", ";", "}", "$", "classes", "=", "array", "(", ")", ";", "$", "namespace", "=", "''", ";", "for", "(", "$", "i", "=", "0", ",", "$", "len", "=", "count", "(", "$", "matches", "[", "'type'", "]", ")", ";", "$", "i", "<", "$", "len", ";", "$", "i", "++", ")", "{", "if", "(", "!", "empty", "(", "$", "matches", "[", "'ns'", "]", "[", "$", "i", "]", ")", ")", "{", "$", "namespace", "=", "str_replace", "(", "array", "(", "' '", ",", "\"\\t\"", ",", "\"\\r\"", ",", "\"\\n\"", ")", ",", "''", ",", "$", "matches", "[", "'nsname'", "]", "[", "$", "i", "]", ")", ".", "'\\\\'", ";", "}", "else", "{", "$", "name", "=", "$", "matches", "[", "'name'", "]", "[", "$", "i", "]", ";", "// skip anon classes extending/implementing", "if", "(", "$", "name", "===", "'extends'", "||", "$", "name", "===", "'implements'", ")", "{", "continue", ";", "}", "if", "(", "$", "name", "[", "0", "]", "===", "':'", ")", "{", "// This is an XHP class, https://github.com/facebook/xhp", "$", "name", "=", "'xhp'", ".", "substr", "(", "str_replace", "(", "array", "(", "'-'", ",", "':'", ")", ",", "array", "(", "'_'", ",", "'__'", ")", ",", "$", "name", ")", ",", "1", ")", ";", "}", "elseif", "(", "$", "matches", "[", "'type'", "]", "[", "$", "i", "]", "===", "'enum'", ")", "{", "// In Hack, something like:", "// enum Foo: int { HERP = '123'; }", "// The regex above captures the colon, which isn't part of", "// the class name.", "$", "name", "=", "rtrim", "(", "$", "name", ",", "':'", ")", ";", "}", "$", "classes", "[", "]", "=", "ltrim", "(", "$", "namespace", ".", "$", "name", ",", "'\\\\'", ")", ";", "}", "}", "return", "$", "classes", ";", "}" ]
Build the class list from the passed matches. @param array $matches The matches from extractClasses(). @return array
[ "Build", "the", "class", "list", "from", "the", "passed", "matches", "." ]
c24d331f16034c2096ce0e55492993befbaa687a
https://github.com/phpcq/autoload-validation/blob/c24d331f16034c2096ce0e55492993befbaa687a/src/ClassMapGenerator.php#L312-L345
train
interactivesolutions/honeycomb-scripts
src/app/commands/service/HCServiceModels.php
HCServiceModels.optimize
public function optimize (stdClass $data) { $data->modelDirectory = str_replace ('/http/controllers', '/models', $data->controllerDestination); $data->modelNamespace = str_replace ('\\http\\controllers', '\\models', $data->controllerNamespace); foreach ($data->database as $dbItem) { $dbItem->columns = $this->getTableColumns ($dbItem->tableName); $dbItem->modelLocation = $data->modelDirectory . '/' . $dbItem->modelName . '.php'; if (isset($dbItem->default) && $dbItem->default) if (isset($dbItem->multiLanguage)) { $dbItem->multiLanguage->columns = $this->getTableColumns ($dbItem->multiLanguage->tableName); $dbItem->multiLanguage->modelName = $dbItem->modelName . 'Translations'; $dbItem->multiLanguage->modelLocation = $data->modelDirectory . '/' . $dbItem->modelName . 'Translations.php'; } } //TODO get default model, there can be only one $data->mainModel = $data->database[0]; return $data; }
php
public function optimize (stdClass $data) { $data->modelDirectory = str_replace ('/http/controllers', '/models', $data->controllerDestination); $data->modelNamespace = str_replace ('\\http\\controllers', '\\models', $data->controllerNamespace); foreach ($data->database as $dbItem) { $dbItem->columns = $this->getTableColumns ($dbItem->tableName); $dbItem->modelLocation = $data->modelDirectory . '/' . $dbItem->modelName . '.php'; if (isset($dbItem->default) && $dbItem->default) if (isset($dbItem->multiLanguage)) { $dbItem->multiLanguage->columns = $this->getTableColumns ($dbItem->multiLanguage->tableName); $dbItem->multiLanguage->modelName = $dbItem->modelName . 'Translations'; $dbItem->multiLanguage->modelLocation = $data->modelDirectory . '/' . $dbItem->modelName . 'Translations.php'; } } //TODO get default model, there can be only one $data->mainModel = $data->database[0]; return $data; }
[ "public", "function", "optimize", "(", "stdClass", "$", "data", ")", "{", "$", "data", "->", "modelDirectory", "=", "str_replace", "(", "'/http/controllers'", ",", "'/models'", ",", "$", "data", "->", "controllerDestination", ")", ";", "$", "data", "->", "modelNamespace", "=", "str_replace", "(", "'\\\\http\\\\controllers'", ",", "'\\\\models'", ",", "$", "data", "->", "controllerNamespace", ")", ";", "foreach", "(", "$", "data", "->", "database", "as", "$", "dbItem", ")", "{", "$", "dbItem", "->", "columns", "=", "$", "this", "->", "getTableColumns", "(", "$", "dbItem", "->", "tableName", ")", ";", "$", "dbItem", "->", "modelLocation", "=", "$", "data", "->", "modelDirectory", ".", "'/'", ".", "$", "dbItem", "->", "modelName", ".", "'.php'", ";", "if", "(", "isset", "(", "$", "dbItem", "->", "default", ")", "&&", "$", "dbItem", "->", "default", ")", "if", "(", "isset", "(", "$", "dbItem", "->", "multiLanguage", ")", ")", "{", "$", "dbItem", "->", "multiLanguage", "->", "columns", "=", "$", "this", "->", "getTableColumns", "(", "$", "dbItem", "->", "multiLanguage", "->", "tableName", ")", ";", "$", "dbItem", "->", "multiLanguage", "->", "modelName", "=", "$", "dbItem", "->", "modelName", ".", "'Translations'", ";", "$", "dbItem", "->", "multiLanguage", "->", "modelLocation", "=", "$", "data", "->", "modelDirectory", ".", "'/'", ".", "$", "dbItem", "->", "modelName", ".", "'Translations.php'", ";", "}", "}", "//TODO get default model, there can be only one", "$", "data", "->", "mainModel", "=", "$", "data", "->", "database", "[", "0", "]", ";", "return", "$", "data", ";", "}" ]
Optimizing configuration for models @param $data @internal param $item @internal param $modelData @return stdClass
[ "Optimizing", "configuration", "for", "models" ]
be2428ded5219dc612ecc51f43aa4dedff3d034d
https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceModels.php#L25-L46
train
interactivesolutions/honeycomb-scripts
src/app/commands/service/HCServiceModels.php
HCServiceModels.getTableColumns
private function getTableColumns (string $tableName) { $columns = DB::getSchemaBuilder ()->getColumnListing ($tableName); if (!count ($columns)) $this->abort ("Table not found: " . $tableName); else $columns = DB::select (DB::raw ('SHOW COLUMNS FROM ' . $tableName)); return $columns; }
php
private function getTableColumns (string $tableName) { $columns = DB::getSchemaBuilder ()->getColumnListing ($tableName); if (!count ($columns)) $this->abort ("Table not found: " . $tableName); else $columns = DB::select (DB::raw ('SHOW COLUMNS FROM ' . $tableName)); return $columns; }
[ "private", "function", "getTableColumns", "(", "string", "$", "tableName", ")", "{", "$", "columns", "=", "DB", "::", "getSchemaBuilder", "(", ")", "->", "getColumnListing", "(", "$", "tableName", ")", ";", "if", "(", "!", "count", "(", "$", "columns", ")", ")", "$", "this", "->", "abort", "(", "\"Table not found: \"", ".", "$", "tableName", ")", ";", "else", "$", "columns", "=", "DB", "::", "select", "(", "DB", "::", "raw", "(", "'SHOW COLUMNS FROM '", ".", "$", "tableName", ")", ")", ";", "return", "$", "columns", ";", "}" ]
Getting table columns @param $tableName @return mixed
[ "Getting", "table", "columns" ]
be2428ded5219dc612ecc51f43aa4dedff3d034d
https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceModels.php#L54-L65
train
interactivesolutions/honeycomb-scripts
src/app/commands/service/HCServiceModels.php
HCServiceModels.getColumnsFillable
private function getColumnsFillable (array $columns, bool $translations = false) { $names = []; foreach ($columns as $column) { if ($translations) { if (!in_array ($column->Field, $this->getTranslationsAutoFill ())) array_push ($names, $column->Field); } else if (!in_array ($column->Field, $this->getAutoFill ())) array_push ($names, $column->Field); } return '[\'' . implode ('\', \'', $names) . '\']'; }
php
private function getColumnsFillable (array $columns, bool $translations = false) { $names = []; foreach ($columns as $column) { if ($translations) { if (!in_array ($column->Field, $this->getTranslationsAutoFill ())) array_push ($names, $column->Field); } else if (!in_array ($column->Field, $this->getAutoFill ())) array_push ($names, $column->Field); } return '[\'' . implode ('\', \'', $names) . '\']'; }
[ "private", "function", "getColumnsFillable", "(", "array", "$", "columns", ",", "bool", "$", "translations", "=", "false", ")", "{", "$", "names", "=", "[", "]", ";", "foreach", "(", "$", "columns", "as", "$", "column", ")", "{", "if", "(", "$", "translations", ")", "{", "if", "(", "!", "in_array", "(", "$", "column", "->", "Field", ",", "$", "this", "->", "getTranslationsAutoFill", "(", ")", ")", ")", "array_push", "(", "$", "names", ",", "$", "column", "->", "Field", ")", ";", "}", "else", "if", "(", "!", "in_array", "(", "$", "column", "->", "Field", ",", "$", "this", "->", "getAutoFill", "(", ")", ")", ")", "array_push", "(", "$", "names", ",", "$", "column", "->", "Field", ")", ";", "}", "return", "'[\\''", ".", "implode", "(", "'\\', \\''", ",", "$", "names", ")", ".", "'\\']'", ";", "}" ]
Get models fillable fields @param array $columns @param bool $translations @return string
[ "Get", "models", "fillable", "fields" ]
be2428ded5219dc612ecc51f43aa4dedff3d034d
https://github.com/interactivesolutions/honeycomb-scripts/blob/be2428ded5219dc612ecc51f43aa4dedff3d034d/src/app/commands/service/HCServiceModels.php#L130-L144
train
newup/core
src/Templates/BasePackageTemplate.php
BasePackageTemplate.shareData
public function shareData($key, $value= null) { if (is_array($key)) { foreach ($key as $variableName => $variableValue) { $this->templateRenderer->setData($variableName, $variableValue); } return $this; } $this->templateRenderer->setData($key, $value); return $this; }
php
public function shareData($key, $value= null) { if (is_array($key)) { foreach ($key as $variableName => $variableValue) { $this->templateRenderer->setData($variableName, $variableValue); } return $this; } $this->templateRenderer->setData($key, $value); return $this; }
[ "public", "function", "shareData", "(", "$", "key", ",", "$", "value", "=", "null", ")", "{", "if", "(", "is_array", "(", "$", "key", ")", ")", "{", "foreach", "(", "$", "key", "as", "$", "variableName", "=>", "$", "variableValue", ")", "{", "$", "this", "->", "templateRenderer", "->", "setData", "(", "$", "variableName", ",", "$", "variableValue", ")", ";", "}", "return", "$", "this", ";", "}", "$", "this", "->", "templateRenderer", "->", "setData", "(", "$", "key", ",", "$", "value", ")", ";", "return", "$", "this", ";", "}" ]
Shares data with package template files. @param $key The name of the variable to share. @param null $value The value of the variable to share. @return $this
[ "Shares", "data", "with", "package", "template", "files", "." ]
54128903e7775e67d63284d958b46862c8df71f9
https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Templates/BasePackageTemplate.php#L225-L236
train
newup/core
src/Templates/BasePackageTemplate.php
BasePackageTemplate.ignorePath
public function ignorePath($path) { if (is_array($path)) { foreach ($path as $pathToIgnore) { $this->ignorePath($pathToIgnore); } return $this; } $this->ignoredPaths[] = $path; return $this; }
php
public function ignorePath($path) { if (is_array($path)) { foreach ($path as $pathToIgnore) { $this->ignorePath($pathToIgnore); } return $this; } $this->ignoredPaths[] = $path; return $this; }
[ "public", "function", "ignorePath", "(", "$", "path", ")", "{", "if", "(", "is_array", "(", "$", "path", ")", ")", "{", "foreach", "(", "$", "path", "as", "$", "pathToIgnore", ")", "{", "$", "this", "->", "ignorePath", "(", "$", "pathToIgnore", ")", ";", "}", "return", "$", "this", ";", "}", "$", "this", "->", "ignoredPaths", "[", "]", "=", "$", "path", ";", "return", "$", "this", ";", "}" ]
Adds a path to the ignore list. @param $path @return $this
[ "Adds", "a", "path", "to", "the", "ignore", "list", "." ]
54128903e7775e67d63284d958b46862c8df71f9
https://github.com/newup/core/blob/54128903e7775e67d63284d958b46862c8df71f9/src/Templates/BasePackageTemplate.php#L256-L268
train
mover-io/belt
lib/Stack.php
Stack.filtered
public static function filtered($classes = array(), $files = array(), &$stack = null) { $skip_self_trace = 0; if ($stack === null) { $stack = debug_backtrace(); } $classes = array_merge((array) $classes, array(__CLASS__)); // Note: in a php backtrace, the class refers to the target of // invocation, whereas the file and line indicate where the invocation // happened. // E.g. // [file] => /mover/backend/test/Belt/Support/TracePrinter.php // [line] => 18 // [function] => debug // [class] => Belt\Trace // Here, one might expect class to be 'Belt\Trace' $files = array_merge((array) $files, array(__FILE__)); $filtered_stack = array(); foreach ($stack as $index => $item) { $file = Arrays::get($item, 'file', null); // So given the long comment above, we cheat by looking // at our caller's class. $class = Arrays::get($stack, ($index).'.class', null); if ( (in_array($file, $files)) // || // ($index != 0 && in_array($class, $classes)) ) { $skip_self_trace++; continue; } else { $filtered_stack[] = $item; } } return $filtered_stack; }
php
public static function filtered($classes = array(), $files = array(), &$stack = null) { $skip_self_trace = 0; if ($stack === null) { $stack = debug_backtrace(); } $classes = array_merge((array) $classes, array(__CLASS__)); // Note: in a php backtrace, the class refers to the target of // invocation, whereas the file and line indicate where the invocation // happened. // E.g. // [file] => /mover/backend/test/Belt/Support/TracePrinter.php // [line] => 18 // [function] => debug // [class] => Belt\Trace // Here, one might expect class to be 'Belt\Trace' $files = array_merge((array) $files, array(__FILE__)); $filtered_stack = array(); foreach ($stack as $index => $item) { $file = Arrays::get($item, 'file', null); // So given the long comment above, we cheat by looking // at our caller's class. $class = Arrays::get($stack, ($index).'.class', null); if ( (in_array($file, $files)) // || // ($index != 0 && in_array($class, $classes)) ) { $skip_self_trace++; continue; } else { $filtered_stack[] = $item; } } return $filtered_stack; }
[ "public", "static", "function", "filtered", "(", "$", "classes", "=", "array", "(", ")", ",", "$", "files", "=", "array", "(", ")", ",", "&", "$", "stack", "=", "null", ")", "{", "$", "skip_self_trace", "=", "0", ";", "if", "(", "$", "stack", "===", "null", ")", "{", "$", "stack", "=", "debug_backtrace", "(", ")", ";", "}", "$", "classes", "=", "array_merge", "(", "(", "array", ")", "$", "classes", ",", "array", "(", "__CLASS__", ")", ")", ";", "// Note: in a php backtrace, the class refers to the target of", "// invocation, whereas the file and line indicate where the invocation", "// happened.", "// E.g.", "// [file] => /mover/backend/test/Belt/Support/TracePrinter.php", "// [line] => 18", "// [function] => debug", "// [class] => Belt\\Trace", "// Here, one might expect class to be 'Belt\\Trace'", "$", "files", "=", "array_merge", "(", "(", "array", ")", "$", "files", ",", "array", "(", "__FILE__", ")", ")", ";", "$", "filtered_stack", "=", "array", "(", ")", ";", "foreach", "(", "$", "stack", "as", "$", "index", "=>", "$", "item", ")", "{", "$", "file", "=", "Arrays", "::", "get", "(", "$", "item", ",", "'file'", ",", "null", ")", ";", "// So given the long comment above, we cheat by looking", "// at our caller's class.", "$", "class", "=", "Arrays", "::", "get", "(", "$", "stack", ",", "(", "$", "index", ")", ".", "'.class'", ",", "null", ")", ";", "if", "(", "(", "in_array", "(", "$", "file", ",", "$", "files", ")", ")", "// ||", "// ($index != 0 && in_array($class, $classes))", ")", "{", "$", "skip_self_trace", "++", ";", "continue", ";", "}", "else", "{", "$", "filtered_stack", "[", "]", "=", "$", "item", ";", "}", "}", "return", "$", "filtered_stack", ";", "}" ]
Generates a stack trace while skipping internal and self calls. @return array
[ "Generates", "a", "stack", "trace", "while", "skipping", "internal", "and", "self", "calls", "." ]
c966a70aa0f4eb51be55bbb86c89b1e85b773d68
https://github.com/mover-io/belt/blob/c966a70aa0f4eb51be55bbb86c89b1e85b773d68/lib/Stack.php#L11-L48
train
praxisnetau/silverware-navigation
src/Components/LevelNavigation.php
LevelNavigation.getLevel
public function getLevel() { if ($page = $this->getCurrentPage(Page::class)) { if (!$page->Children()->exists()) { $parent = $page->getParent(); while ($parent && !$parent->Children()->exists()) { $parent = $parent->getParent(); } return $parent; } return $page; } }
php
public function getLevel() { if ($page = $this->getCurrentPage(Page::class)) { if (!$page->Children()->exists()) { $parent = $page->getParent(); while ($parent && !$parent->Children()->exists()) { $parent = $parent->getParent(); } return $parent; } return $page; } }
[ "public", "function", "getLevel", "(", ")", "{", "if", "(", "$", "page", "=", "$", "this", "->", "getCurrentPage", "(", "Page", "::", "class", ")", ")", "{", "if", "(", "!", "$", "page", "->", "Children", "(", ")", "->", "exists", "(", ")", ")", "{", "$", "parent", "=", "$", "page", "->", "getParent", "(", ")", ";", "while", "(", "$", "parent", "&&", "!", "$", "parent", "->", "Children", "(", ")", "->", "exists", "(", ")", ")", "{", "$", "parent", "=", "$", "parent", "->", "getParent", "(", ")", ";", "}", "return", "$", "parent", ";", "}", "return", "$", "page", ";", "}", "}" ]
Answers the page object at the current level. @return SiteTree
[ "Answers", "the", "page", "object", "at", "the", "current", "level", "." ]
04e6f3003c2871348d5bba7869d4fc273641627e
https://github.com/praxisnetau/silverware-navigation/blob/04e6f3003c2871348d5bba7869d4fc273641627e/src/Components/LevelNavigation.php#L264-L283
train
Etenil/assegai
src/assegai/modules/ModuleContainer.php
ModuleContainer.batchRun
public function batchRun($is_hook, $method_name, array $params = NULL) { // Prevents annoying notices. if($params == NULL) { $params = array(); } // We collect the results into an array. $results = array(); if(!$this->modules) $this->modules = array(); foreach($this->modules as $name => $module) { if(method_exists($module, $method_name)) { $result = call_user_func_array(array($module, $method_name), $params); if($is_hook) { // Hooks are pre-emptive if they return something. if($result) { return $result; } } else { // Collecting $results[$name] = $result; } } } return $is_hook? false : $results; }
php
public function batchRun($is_hook, $method_name, array $params = NULL) { // Prevents annoying notices. if($params == NULL) { $params = array(); } // We collect the results into an array. $results = array(); if(!$this->modules) $this->modules = array(); foreach($this->modules as $name => $module) { if(method_exists($module, $method_name)) { $result = call_user_func_array(array($module, $method_name), $params); if($is_hook) { // Hooks are pre-emptive if they return something. if($result) { return $result; } } else { // Collecting $results[$name] = $result; } } } return $is_hook? false : $results; }
[ "public", "function", "batchRun", "(", "$", "is_hook", ",", "$", "method_name", ",", "array", "$", "params", "=", "NULL", ")", "{", "// Prevents annoying notices.", "if", "(", "$", "params", "==", "NULL", ")", "{", "$", "params", "=", "array", "(", ")", ";", "}", "// We collect the results into an array.", "$", "results", "=", "array", "(", ")", ";", "if", "(", "!", "$", "this", "->", "modules", ")", "$", "this", "->", "modules", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "modules", "as", "$", "name", "=>", "$", "module", ")", "{", "if", "(", "method_exists", "(", "$", "module", ",", "$", "method_name", ")", ")", "{", "$", "result", "=", "call_user_func_array", "(", "array", "(", "$", "module", ",", "$", "method_name", ")", ",", "$", "params", ")", ";", "if", "(", "$", "is_hook", ")", "{", "// Hooks are pre-emptive if they return something.", "if", "(", "$", "result", ")", "{", "return", "$", "result", ";", "}", "}", "else", "{", "// Collecting", "$", "results", "[", "$", "name", "]", "=", "$", "result", ";", "}", "}", "}", "return", "$", "is_hook", "?", "false", ":", "$", "results", ";", "}" ]
Batch runs a method on all modules. @param bool $is_hook specifies that this is a hook call. @param string $method_name is the method to be used on all modules. @param array $params is an array of parameters to pass to all methods.
[ "Batch", "runs", "a", "method", "on", "all", "modules", "." ]
d43cce1a88f1c332f60dd0a4374b17764852af9e
https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/ModuleContainer.php#L149-L173
train
RadialCorp/magento-core
src/lib/Radial/RiskService/Sdk/Payload.php
Radial_RiskService_Sdk_Payload.deserialize
public function deserialize($serializedPayload) { $xpath = $this->_helper->getPayloadAsXPath($serializedPayload, $this->_getXmlNamespace()); $this->_deserializeExtractionPaths($xpath) ->_deserializeOptionalExtractionPaths($xpath) ->_deserializeBooleanExtractionPaths($xpath) ->_deserializeLineItems($serializedPayload) ->_deserializeSubpayloadExtractionPaths($xpath) ->_deserializeDateTimeExtractionPaths($xpath) ->_deserializeExtra($serializedPayload); return $this; }
php
public function deserialize($serializedPayload) { $xpath = $this->_helper->getPayloadAsXPath($serializedPayload, $this->_getXmlNamespace()); $this->_deserializeExtractionPaths($xpath) ->_deserializeOptionalExtractionPaths($xpath) ->_deserializeBooleanExtractionPaths($xpath) ->_deserializeLineItems($serializedPayload) ->_deserializeSubpayloadExtractionPaths($xpath) ->_deserializeDateTimeExtractionPaths($xpath) ->_deserializeExtra($serializedPayload); return $this; }
[ "public", "function", "deserialize", "(", "$", "serializedPayload", ")", "{", "$", "xpath", "=", "$", "this", "->", "_helper", "->", "getPayloadAsXPath", "(", "$", "serializedPayload", ",", "$", "this", "->", "_getXmlNamespace", "(", ")", ")", ";", "$", "this", "->", "_deserializeExtractionPaths", "(", "$", "xpath", ")", "->", "_deserializeOptionalExtractionPaths", "(", "$", "xpath", ")", "->", "_deserializeBooleanExtractionPaths", "(", "$", "xpath", ")", "->", "_deserializeLineItems", "(", "$", "serializedPayload", ")", "->", "_deserializeSubpayloadExtractionPaths", "(", "$", "xpath", ")", "->", "_deserializeDateTimeExtractionPaths", "(", "$", "xpath", ")", "->", "_deserializeExtra", "(", "$", "serializedPayload", ")", ";", "return", "$", "this", ";", "}" ]
Fill out this payload object with data from the supplied string. @throws Radial_RiskService_Sdk_Exception_Invalid_Payload_Exception @param string @return $this
[ "Fill", "out", "this", "payload", "object", "with", "data", "from", "the", "supplied", "string", "." ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L93-L104
train
RadialCorp/magento-core
src/lib/Radial/RiskService/Sdk/Payload.php
Radial_RiskService_Sdk_Payload._deserializeOptionalExtractionPaths
protected function _deserializeOptionalExtractionPaths(DOMXPath $xpath) { foreach ($this->_optionalExtractionPaths as $setter => $path) { $foundNode = $xpath->query($path)->item(0); if ($foundNode) { $this->$setter($foundNode->nodeValue); } } return $this; }
php
protected function _deserializeOptionalExtractionPaths(DOMXPath $xpath) { foreach ($this->_optionalExtractionPaths as $setter => $path) { $foundNode = $xpath->query($path)->item(0); if ($foundNode) { $this->$setter($foundNode->nodeValue); } } return $this; }
[ "protected", "function", "_deserializeOptionalExtractionPaths", "(", "DOMXPath", "$", "xpath", ")", "{", "foreach", "(", "$", "this", "->", "_optionalExtractionPaths", "as", "$", "setter", "=>", "$", "path", ")", "{", "$", "foundNode", "=", "$", "xpath", "->", "query", "(", "$", "path", ")", "->", "item", "(", "0", ")", ";", "if", "(", "$", "foundNode", ")", "{", "$", "this", "->", "$", "setter", "(", "$", "foundNode", "->", "nodeValue", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
When optional nodes are not included in the serialized data, they should not be set in the payload. Fortunately, these are all string values so no additional type conversion is necessary. @param DOMXPath @return self
[ "When", "optional", "nodes", "are", "not", "included", "in", "the", "serialized", "data", "they", "should", "not", "be", "set", "in", "the", "payload", ".", "Fortunately", "these", "are", "all", "string", "values", "so", "no", "additional", "type", "conversion", "is", "necessary", "." ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L126-L135
train
RadialCorp/magento-core
src/lib/Radial/RiskService/Sdk/Payload.php
Radial_RiskService_Sdk_Payload._deserializeBooleanExtractionPaths
protected function _deserializeBooleanExtractionPaths(DOMXPath $xpath) { foreach ($this->_booleanExtractionPaths as $setter => $path) { $value = $xpath->evaluate($path); $this->$setter($this->_helper->convertStringToBoolean($value)); } return $this; }
php
protected function _deserializeBooleanExtractionPaths(DOMXPath $xpath) { foreach ($this->_booleanExtractionPaths as $setter => $path) { $value = $xpath->evaluate($path); $this->$setter($this->_helper->convertStringToBoolean($value)); } return $this; }
[ "protected", "function", "_deserializeBooleanExtractionPaths", "(", "DOMXPath", "$", "xpath", ")", "{", "foreach", "(", "$", "this", "->", "_booleanExtractionPaths", "as", "$", "setter", "=>", "$", "path", ")", "{", "$", "value", "=", "$", "xpath", "->", "evaluate", "(", "$", "path", ")", ";", "$", "this", "->", "$", "setter", "(", "$", "this", "->", "_helper", "->", "convertStringToBoolean", "(", "$", "value", ")", ")", ";", "}", "return", "$", "this", ";", "}" ]
boolean values have to be handled specially @param DOMXPath @return self
[ "boolean", "values", "have", "to", "be", "handled", "specially" ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L143-L150
train
RadialCorp/magento-core
src/lib/Radial/RiskService/Sdk/Payload.php
Radial_RiskService_Sdk_Payload._deserializeDateTimeExtractionPaths
protected function _deserializeDateTimeExtractionPaths(DOMXPath $xpath) { foreach ($this->_dateTimeExtractionPaths as $setter => $path) { $value = $xpath->evaluate($path); if ($value) { $this->$setter(new DateTime($value)); } } return $this; }
php
protected function _deserializeDateTimeExtractionPaths(DOMXPath $xpath) { foreach ($this->_dateTimeExtractionPaths as $setter => $path) { $value = $xpath->evaluate($path); if ($value) { $this->$setter(new DateTime($value)); } } return $this; }
[ "protected", "function", "_deserializeDateTimeExtractionPaths", "(", "DOMXPath", "$", "xpath", ")", "{", "foreach", "(", "$", "this", "->", "_dateTimeExtractionPaths", "as", "$", "setter", "=>", "$", "path", ")", "{", "$", "value", "=", "$", "xpath", "->", "evaluate", "(", "$", "path", ")", ";", "if", "(", "$", "value", ")", "{", "$", "this", "->", "$", "setter", "(", "new", "DateTime", "(", "$", "value", ")", ")", ";", "}", "}", "return", "$", "this", ";", "}" ]
Ensure any date time string is instantiate @param DOMXPath @return self
[ "Ensure", "any", "date", "time", "string", "is", "instantiate" ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L174-L183
train
RadialCorp/magento-core
src/lib/Radial/RiskService/Sdk/Payload.php
Radial_RiskService_Sdk_Payload._serializeRootAttributes
protected function _serializeRootAttributes() { $rootAttributes = $this->_getRootAttributes(); $qualifyAttributes = function ($name) use ($rootAttributes) { return sprintf('%s="%s"', $name, $rootAttributes[$name]); }; $qualifiedAttributes = array_map($qualifyAttributes, array_keys($rootAttributes)); return implode(' ', $qualifiedAttributes); }
php
protected function _serializeRootAttributes() { $rootAttributes = $this->_getRootAttributes(); $qualifyAttributes = function ($name) use ($rootAttributes) { return sprintf('%s="%s"', $name, $rootAttributes[$name]); }; $qualifiedAttributes = array_map($qualifyAttributes, array_keys($rootAttributes)); return implode(' ', $qualifiedAttributes); }
[ "protected", "function", "_serializeRootAttributes", "(", ")", "{", "$", "rootAttributes", "=", "$", "this", "->", "_getRootAttributes", "(", ")", ";", "$", "qualifyAttributes", "=", "function", "(", "$", "name", ")", "use", "(", "$", "rootAttributes", ")", "{", "return", "sprintf", "(", "'%s=\"%s\"'", ",", "$", "name", ",", "$", "rootAttributes", "[", "$", "name", "]", ")", ";", "}", ";", "$", "qualifiedAttributes", "=", "array_map", "(", "$", "qualifyAttributes", ",", "array_keys", "(", "$", "rootAttributes", ")", ")", ";", "return", "implode", "(", "' '", ",", "$", "qualifiedAttributes", ")", ";", "}" ]
Serialize Root Attributes @return string
[ "Serialize", "Root", "Attributes" ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L277-L285
train
RadialCorp/magento-core
src/lib/Radial/RiskService/Sdk/Payload.php
Radial_RiskService_Sdk_Payload._serializeNode
protected function _serializeNode($nodeName, $value) { return sprintf('<%s>%s</%1$s>', $nodeName, $this->xmlEncode($this->_helper->escapeHtml($value))); }
php
protected function _serializeNode($nodeName, $value) { return sprintf('<%s>%s</%1$s>', $nodeName, $this->xmlEncode($this->_helper->escapeHtml($value))); }
[ "protected", "function", "_serializeNode", "(", "$", "nodeName", ",", "$", "value", ")", "{", "return", "sprintf", "(", "'<%s>%s</%1$s>'", ",", "$", "nodeName", ",", "$", "this", "->", "xmlEncode", "(", "$", "this", "->", "_helper", "->", "escapeHtml", "(", "$", "value", ")", ")", ")", ";", "}" ]
Serialize the value as an xml element with the given node name. @param string @param mixed @return string
[ "Serialize", "the", "value", "as", "an", "xml", "element", "with", "the", "given", "node", "name", "." ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L318-L321
train
RadialCorp/magento-core
src/lib/Radial/RiskService/Sdk/Payload.php
Radial_RiskService_Sdk_Payload._serializeBooleanNode
protected function _serializeBooleanNode($nodeName, $value) { if(!$this->_helper->convertStringToBoolean($value)) { return sprintf('<%s>0</%1$s>', $nodeName); } else { return sprintf('<%s>%s</%1$s>', $nodeName, $this->_helper->convertStringToBoolean($value)); } }
php
protected function _serializeBooleanNode($nodeName, $value) { if(!$this->_helper->convertStringToBoolean($value)) { return sprintf('<%s>0</%1$s>', $nodeName); } else { return sprintf('<%s>%s</%1$s>', $nodeName, $this->_helper->convertStringToBoolean($value)); } }
[ "protected", "function", "_serializeBooleanNode", "(", "$", "nodeName", ",", "$", "value", ")", "{", "if", "(", "!", "$", "this", "->", "_helper", "->", "convertStringToBoolean", "(", "$", "value", ")", ")", "{", "return", "sprintf", "(", "'<%s>0</%1$s>'", ",", "$", "nodeName", ")", ";", "}", "else", "{", "return", "sprintf", "(", "'<%s>%s</%1$s>'", ",", "$", "nodeName", ",", "$", "this", "->", "_helper", "->", "convertStringToBoolean", "(", "$", "value", ")", ")", ";", "}", "}" ]
Serialize the boolean value as an xml element with the given node name. @param string @param mixed @return string
[ "Serialize", "the", "boolean", "value", "as", "an", "xml", "element", "with", "the", "given", "node", "name", "." ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L330-L338
train
RadialCorp/magento-core
src/lib/Radial/RiskService/Sdk/Payload.php
Radial_RiskService_Sdk_Payload._serializeOptionalValue
protected function _serializeOptionalValue($nodeName, $value) { return (!is_null($value) && $value !== '') ? $this->_serializeNode($nodeName, $value) : ''; }
php
protected function _serializeOptionalValue($nodeName, $value) { return (!is_null($value) && $value !== '') ? $this->_serializeNode($nodeName, $value) : ''; }
[ "protected", "function", "_serializeOptionalValue", "(", "$", "nodeName", ",", "$", "value", ")", "{", "return", "(", "!", "is_null", "(", "$", "value", ")", "&&", "$", "value", "!==", "''", ")", "?", "$", "this", "->", "_serializeNode", "(", "$", "nodeName", ",", "$", "value", ")", ":", "''", ";", "}" ]
Serialize the value as an xml element with the given node name. When given an empty value, returns an empty string instead of an empty element. @param string @param mixed @return string
[ "Serialize", "the", "value", "as", "an", "xml", "element", "with", "the", "given", "node", "name", ".", "When", "given", "an", "empty", "value", "returns", "an", "empty", "string", "instead", "of", "an", "empty", "element", "." ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L359-L362
train
RadialCorp/magento-core
src/lib/Radial/RiskService/Sdk/Payload.php
Radial_RiskService_Sdk_Payload._serializeOptionalAmount
protected function _serializeOptionalAmount($nodeName, $amount, $currencyCode=null) { if( $currencyCode) { return (!is_null($amount) && !is_nan($amount)) ? "<$nodeName currencyCode=\"$currencyCode\">{$this->_helper->formatAmount($amount)}</$nodeName>" : ''; } else { return (!is_null($amount) && !is_nan($amount)) ? "<$nodeName>{$this->_helper->formatAmount($amount)}</$nodeName>" : ''; } }
php
protected function _serializeOptionalAmount($nodeName, $amount, $currencyCode=null) { if( $currencyCode) { return (!is_null($amount) && !is_nan($amount)) ? "<$nodeName currencyCode=\"$currencyCode\">{$this->_helper->formatAmount($amount)}</$nodeName>" : ''; } else { return (!is_null($amount) && !is_nan($amount)) ? "<$nodeName>{$this->_helper->formatAmount($amount)}</$nodeName>" : ''; } }
[ "protected", "function", "_serializeOptionalAmount", "(", "$", "nodeName", ",", "$", "amount", ",", "$", "currencyCode", "=", "null", ")", "{", "if", "(", "$", "currencyCode", ")", "{", "return", "(", "!", "is_null", "(", "$", "amount", ")", "&&", "!", "is_nan", "(", "$", "amount", ")", ")", "?", "\"<$nodeName currencyCode=\\\"$currencyCode\\\">{$this->_helper->formatAmount($amount)}</$nodeName>\"", ":", "''", ";", "}", "else", "{", "return", "(", "!", "is_null", "(", "$", "amount", ")", "&&", "!", "is_nan", "(", "$", "amount", ")", ")", "?", "\"<$nodeName>{$this->_helper->formatAmount($amount)}</$nodeName>\"", ":", "''", ";", "}", "}" ]
Serialize the currency amount as an XML node with the provided name. When the amount is not set, returns an empty string. @param string @param float @param string @return string
[ "Serialize", "the", "currency", "amount", "as", "an", "XML", "node", "with", "the", "provided", "name", ".", "When", "the", "amount", "is", "not", "set", "returns", "an", "empty", "string", "." ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/lib/Radial/RiskService/Sdk/Payload.php#L373-L381
train
iron-bound-designs/wp-notifications
src/Queue/Storage/Options.php
Options.store_notifications
public function store_notifications( $queue_id, array $notifications, Strategy $strategy = null ) { $all = get_option( $this->bucket, array() ); $found = empty( $all ) ? false : true; if ( empty( $notifications ) ) { return $this->clear_notifications( $queue_id ); } $all[ $queue_id ] = array( 'notifications' => $notifications ); if ( isset( $strategy ) ) { $all[ $queue_id ]['strategy'] = $strategy; } if ( $found ) { return update_option( $this->bucket, $all ); } else { return add_option( $this->bucket, $all, '', 'no' ); } }
php
public function store_notifications( $queue_id, array $notifications, Strategy $strategy = null ) { $all = get_option( $this->bucket, array() ); $found = empty( $all ) ? false : true; if ( empty( $notifications ) ) { return $this->clear_notifications( $queue_id ); } $all[ $queue_id ] = array( 'notifications' => $notifications ); if ( isset( $strategy ) ) { $all[ $queue_id ]['strategy'] = $strategy; } if ( $found ) { return update_option( $this->bucket, $all ); } else { return add_option( $this->bucket, $all, '', 'no' ); } }
[ "public", "function", "store_notifications", "(", "$", "queue_id", ",", "array", "$", "notifications", ",", "Strategy", "$", "strategy", "=", "null", ")", "{", "$", "all", "=", "get_option", "(", "$", "this", "->", "bucket", ",", "array", "(", ")", ")", ";", "$", "found", "=", "empty", "(", "$", "all", ")", "?", "false", ":", "true", ";", "if", "(", "empty", "(", "$", "notifications", ")", ")", "{", "return", "$", "this", "->", "clear_notifications", "(", "$", "queue_id", ")", ";", "}", "$", "all", "[", "$", "queue_id", "]", "=", "array", "(", "'notifications'", "=>", "$", "notifications", ")", ";", "if", "(", "isset", "(", "$", "strategy", ")", ")", "{", "$", "all", "[", "$", "queue_id", "]", "[", "'strategy'", "]", "=", "$", "strategy", ";", "}", "if", "(", "$", "found", ")", "{", "return", "update_option", "(", "$", "this", "->", "bucket", ",", "$", "all", ")", ";", "}", "else", "{", "return", "add_option", "(", "$", "this", "->", "bucket", ",", "$", "all", ",", "''", ",", "'no'", ")", ";", "}", "}" ]
Store a set of notifications. If notifications is empty, it will clear the set. @since 1.0 @param string $queue_id @param Notification[] $notifications @param Strategy $strategy If null, previously set strategy will be used. @return bool
[ "Store", "a", "set", "of", "notifications", "." ]
4fdf67d28d194576d35f86245b2f539c4815cde2
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Queue/Storage/Options.php#L49-L72
train
iron-bound-designs/wp-notifications
src/Queue/Storage/Options.php
Options.get_notifications
public function get_notifications( $queue_id ) { $all = get_option( $this->bucket, array() ); if ( isset( $all[ $queue_id ]['notifications'] ) ) { return $all[ $queue_id ]['notifications']; } else { return null; } }
php
public function get_notifications( $queue_id ) { $all = get_option( $this->bucket, array() ); if ( isset( $all[ $queue_id ]['notifications'] ) ) { return $all[ $queue_id ]['notifications']; } else { return null; } }
[ "public", "function", "get_notifications", "(", "$", "queue_id", ")", "{", "$", "all", "=", "get_option", "(", "$", "this", "->", "bucket", ",", "array", "(", ")", ")", ";", "if", "(", "isset", "(", "$", "all", "[", "$", "queue_id", "]", "[", "'notifications'", "]", ")", ")", "{", "return", "$", "all", "[", "$", "queue_id", "]", "[", "'notifications'", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Get a set of notifications. @since 1.0 @param string $queue_id @return Notification[]|null
[ "Get", "a", "set", "of", "notifications", "." ]
4fdf67d28d194576d35f86245b2f539c4815cde2
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Queue/Storage/Options.php#L83-L92
train
iron-bound-designs/wp-notifications
src/Queue/Storage/Options.php
Options.get_notifications_strategy
public function get_notifications_strategy( $queue_id ) { $all = get_option( $this->bucket, array() ); if ( isset( $all[ $queue_id ]['strategy'] ) ) { return $all[ $queue_id ]['strategy']; } else { return null; } }
php
public function get_notifications_strategy( $queue_id ) { $all = get_option( $this->bucket, array() ); if ( isset( $all[ $queue_id ]['strategy'] ) ) { return $all[ $queue_id ]['strategy']; } else { return null; } }
[ "public", "function", "get_notifications_strategy", "(", "$", "queue_id", ")", "{", "$", "all", "=", "get_option", "(", "$", "this", "->", "bucket", ",", "array", "(", ")", ")", ";", "if", "(", "isset", "(", "$", "all", "[", "$", "queue_id", "]", "[", "'strategy'", "]", ")", ")", "{", "return", "$", "all", "[", "$", "queue_id", "]", "[", "'strategy'", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Get the strategy for a set of notifications. @since 1.0 @param string $queue_id @return Strategy|null
[ "Get", "the", "strategy", "for", "a", "set", "of", "notifications", "." ]
4fdf67d28d194576d35f86245b2f539c4815cde2
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Queue/Storage/Options.php#L103-L112
train
iron-bound-designs/wp-notifications
src/Queue/Storage/Options.php
Options.clear_notifications
public function clear_notifications( $queue_id ) { $all = get_option( $this->bucket, array() ); if ( ! isset( $all[ $queue_id ] ) ) { return false; } unset( $all[ $queue_id ] ); if ( empty( $all ) ) { delete_option( $this->bucket ); } else { update_option( $this->bucket, $all ); } return true; }
php
public function clear_notifications( $queue_id ) { $all = get_option( $this->bucket, array() ); if ( ! isset( $all[ $queue_id ] ) ) { return false; } unset( $all[ $queue_id ] ); if ( empty( $all ) ) { delete_option( $this->bucket ); } else { update_option( $this->bucket, $all ); } return true; }
[ "public", "function", "clear_notifications", "(", "$", "queue_id", ")", "{", "$", "all", "=", "get_option", "(", "$", "this", "->", "bucket", ",", "array", "(", ")", ")", ";", "if", "(", "!", "isset", "(", "$", "all", "[", "$", "queue_id", "]", ")", ")", "{", "return", "false", ";", "}", "unset", "(", "$", "all", "[", "$", "queue_id", "]", ")", ";", "if", "(", "empty", "(", "$", "all", ")", ")", "{", "delete_option", "(", "$", "this", "->", "bucket", ")", ";", "}", "else", "{", "update_option", "(", "$", "this", "->", "bucket", ",", "$", "all", ")", ";", "}", "return", "true", ";", "}" ]
Clear a set of notifications. @since 1.0 @param string $queue_id @return bool
[ "Clear", "a", "set", "of", "notifications", "." ]
4fdf67d28d194576d35f86245b2f539c4815cde2
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Queue/Storage/Options.php#L123-L140
train
iron-bound-designs/wp-notifications
src/Queue/Storage/Options.php
Options.clear_notification
public function clear_notification( $queue_id, Notification $notification ) { $notifications = $this->get_notifications( $queue_id ); $notification = array_search( $notification, $notifications ); if ( false === $notification ) { return false; } unset( $notifications[ $notification ] ); return $this->store_notifications( $queue_id, $notifications ); }
php
public function clear_notification( $queue_id, Notification $notification ) { $notifications = $this->get_notifications( $queue_id ); $notification = array_search( $notification, $notifications ); if ( false === $notification ) { return false; } unset( $notifications[ $notification ] ); return $this->store_notifications( $queue_id, $notifications ); }
[ "public", "function", "clear_notification", "(", "$", "queue_id", ",", "Notification", "$", "notification", ")", "{", "$", "notifications", "=", "$", "this", "->", "get_notifications", "(", "$", "queue_id", ")", ";", "$", "notification", "=", "array_search", "(", "$", "notification", ",", "$", "notifications", ")", ";", "if", "(", "false", "===", "$", "notification", ")", "{", "return", "false", ";", "}", "unset", "(", "$", "notifications", "[", "$", "notification", "]", ")", ";", "return", "$", "this", "->", "store_notifications", "(", "$", "queue_id", ",", "$", "notifications", ")", ";", "}" ]
Clear a single notification from storage. @since 1.0 @param string $queue_id @param Notification $notification @return bool
[ "Clear", "a", "single", "notification", "from", "storage", "." ]
4fdf67d28d194576d35f86245b2f539c4815cde2
https://github.com/iron-bound-designs/wp-notifications/blob/4fdf67d28d194576d35f86245b2f539c4815cde2/src/Queue/Storage/Options.php#L152-L165
train
mlocati/concrete5-translation-library
src/Gettext.php
Gettext.commandIsAvailable
public static function commandIsAvailable($command) { static $cache = array(); if (!isset($cache[$command])) { $cache[$command] = false; $safeMode = @ini_get('safe_mode'); if (empty($safeMode)) { if (function_exists('exec')) { if (!in_array('exec', array_map('trim', explode(',', strtolower(@ini_get('disable_functions')))), true)) { $rc = 1; $output = array(); @exec($command.' --version 2>&1', $output, $rc); if ($rc === 0) { $cache[$command] = true; } } } } } return $cache[$command]; }
php
public static function commandIsAvailable($command) { static $cache = array(); if (!isset($cache[$command])) { $cache[$command] = false; $safeMode = @ini_get('safe_mode'); if (empty($safeMode)) { if (function_exists('exec')) { if (!in_array('exec', array_map('trim', explode(',', strtolower(@ini_get('disable_functions')))), true)) { $rc = 1; $output = array(); @exec($command.' --version 2>&1', $output, $rc); if ($rc === 0) { $cache[$command] = true; } } } } } return $cache[$command]; }
[ "public", "static", "function", "commandIsAvailable", "(", "$", "command", ")", "{", "static", "$", "cache", "=", "array", "(", ")", ";", "if", "(", "!", "isset", "(", "$", "cache", "[", "$", "command", "]", ")", ")", "{", "$", "cache", "[", "$", "command", "]", "=", "false", ";", "$", "safeMode", "=", "@", "ini_get", "(", "'safe_mode'", ")", ";", "if", "(", "empty", "(", "$", "safeMode", ")", ")", "{", "if", "(", "function_exists", "(", "'exec'", ")", ")", "{", "if", "(", "!", "in_array", "(", "'exec'", ",", "array_map", "(", "'trim'", ",", "explode", "(", "','", ",", "strtolower", "(", "@", "ini_get", "(", "'disable_functions'", ")", ")", ")", ")", ",", "true", ")", ")", "{", "$", "rc", "=", "1", ";", "$", "output", "=", "array", "(", ")", ";", "@", "exec", "(", "$", "command", ".", "' --version 2>&1'", ",", "$", "output", ",", "$", "rc", ")", ";", "if", "(", "$", "rc", "===", "0", ")", "{", "$", "cache", "[", "$", "command", "]", "=", "true", ";", "}", "}", "}", "}", "}", "return", "$", "cache", "[", "$", "command", "]", ";", "}" ]
Checks if a gettext command is available. @param string $command One of the gettext commands @return bool
[ "Checks", "if", "a", "gettext", "command", "is", "available", "." ]
26f806c8c1ecb6ce63115a4058ab396303622e00
https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Gettext.php#L17-L38
train
pilipinews/common
src/Scraper.php
Scraper.html
protected function html(Crawler $crawler, $removables = array()) { $converter = new Converter; $html = trim($converter->convert($crawler->html())); foreach ((array) $removables as $keyword) { $html = str_replace($keyword, '', $html); } $html = str_replace(' ', ' ', (string) $html); return trim(preg_replace('/\s\s+/', "\n\n", $html)); }
php
protected function html(Crawler $crawler, $removables = array()) { $converter = new Converter; $html = trim($converter->convert($crawler->html())); foreach ((array) $removables as $keyword) { $html = str_replace($keyword, '', $html); } $html = str_replace(' ', ' ', (string) $html); return trim(preg_replace('/\s\s+/', "\n\n", $html)); }
[ "protected", "function", "html", "(", "Crawler", "$", "crawler", ",", "$", "removables", "=", "array", "(", ")", ")", "{", "$", "converter", "=", "new", "Converter", ";", "$", "html", "=", "trim", "(", "$", "converter", "->", "convert", "(", "$", "crawler", "->", "html", "(", ")", ")", ")", ";", "foreach", "(", "(", "array", ")", "$", "removables", "as", "$", "keyword", ")", "{", "$", "html", "=", "str_replace", "(", "$", "keyword", ",", "''", ",", "$", "html", ")", ";", "}", "$", "html", "=", "str_replace", "(", "' '", ",", "' '", ",", "(", "string", ")", "$", "html", ")", ";", "return", "trim", "(", "preg_replace", "(", "'/\\s\\s+/'", ",", "\"\\n\\n\"", ",", "$", "html", ")", ")", ";", "}" ]
Returns the HTML format of the body from the crawler. @param \Pilipinews\Common\Crawler $crawler @param string[] $removables @return string
[ "Returns", "the", "HTML", "format", "of", "the", "body", "from", "the", "crawler", "." ]
a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0
https://github.com/pilipinews/common/blob/a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0/src/Scraper.php#L40-L54
train
pilipinews/common
src/Scraper.php
Scraper.prepare
protected function prepare($link) { $response = Client::request((string) $link); $response = str_replace('<strong> </strong>', ' ', $response); $this->crawler = new Crawler($response); }
php
protected function prepare($link) { $response = Client::request((string) $link); $response = str_replace('<strong> </strong>', ' ', $response); $this->crawler = new Crawler($response); }
[ "protected", "function", "prepare", "(", "$", "link", ")", "{", "$", "response", "=", "Client", "::", "request", "(", "(", "string", ")", "$", "link", ")", ";", "$", "response", "=", "str_replace", "(", "'<strong> </strong>'", ",", "' '", ",", "$", "response", ")", ";", "$", "this", "->", "crawler", "=", "new", "Crawler", "(", "$", "response", ")", ";", "}" ]
Initializes the crawler instance. @param string $link @return void
[ "Initializes", "the", "crawler", "instance", "." ]
a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0
https://github.com/pilipinews/common/blob/a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0/src/Scraper.php#L62-L69
train
pilipinews/common
src/Scraper.php
Scraper.remove
protected function remove($elements) { $callback = function ($crawler) { $node = $crawler->getNode((integer) 0); $node->parentNode->removeChild($node); }; foreach ((array) $elements as $removable) { $this->crawler->filter($removable)->each($callback); } }
php
protected function remove($elements) { $callback = function ($crawler) { $node = $crawler->getNode((integer) 0); $node->parentNode->removeChild($node); }; foreach ((array) $elements as $removable) { $this->crawler->filter($removable)->each($callback); } }
[ "protected", "function", "remove", "(", "$", "elements", ")", "{", "$", "callback", "=", "function", "(", "$", "crawler", ")", "{", "$", "node", "=", "$", "crawler", "->", "getNode", "(", "(", "integer", ")", "0", ")", ";", "$", "node", "->", "parentNode", "->", "removeChild", "(", "$", "node", ")", ";", "}", ";", "foreach", "(", "(", "array", ")", "$", "elements", "as", "$", "removable", ")", "{", "$", "this", "->", "crawler", "->", "filter", "(", "$", "removable", ")", "->", "each", "(", "$", "callback", ")", ";", "}", "}" ]
Removes specified HTML tags from body. @param string[] $elements @return void
[ "Removes", "specified", "HTML", "tags", "from", "body", "." ]
a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0
https://github.com/pilipinews/common/blob/a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0/src/Scraper.php#L77-L90
train
pilipinews/common
src/Scraper.php
Scraper.replace
protected function replace(Crawler $crawler, $element, $callback) { $function = function (Crawler $crawler) use ($callback) { $node = $crawler->getNode(0); $html = $node->ownerDocument->saveHtml($node); $text = $callback($crawler, (string) $html); return array((string) $html, (string) $text); }; $items = $crawler->filter($element)->each($function); $html = (string) $crawler->html(); foreach ((array) $items as $item) { $html = str_replace($item[0], $item[1], $html); } return new Crawler((string) $html); }
php
protected function replace(Crawler $crawler, $element, $callback) { $function = function (Crawler $crawler) use ($callback) { $node = $crawler->getNode(0); $html = $node->ownerDocument->saveHtml($node); $text = $callback($crawler, (string) $html); return array((string) $html, (string) $text); }; $items = $crawler->filter($element)->each($function); $html = (string) $crawler->html(); foreach ((array) $items as $item) { $html = str_replace($item[0], $item[1], $html); } return new Crawler((string) $html); }
[ "protected", "function", "replace", "(", "Crawler", "$", "crawler", ",", "$", "element", ",", "$", "callback", ")", "{", "$", "function", "=", "function", "(", "Crawler", "$", "crawler", ")", "use", "(", "$", "callback", ")", "{", "$", "node", "=", "$", "crawler", "->", "getNode", "(", "0", ")", ";", "$", "html", "=", "$", "node", "->", "ownerDocument", "->", "saveHtml", "(", "$", "node", ")", ";", "$", "text", "=", "$", "callback", "(", "$", "crawler", ",", "(", "string", ")", "$", "html", ")", ";", "return", "array", "(", "(", "string", ")", "$", "html", ",", "(", "string", ")", "$", "text", ")", ";", "}", ";", "$", "items", "=", "$", "crawler", "->", "filter", "(", "$", "element", ")", "->", "each", "(", "$", "function", ")", ";", "$", "html", "=", "(", "string", ")", "$", "crawler", "->", "html", "(", ")", ";", "foreach", "(", "(", "array", ")", "$", "items", "as", "$", "item", ")", "{", "$", "html", "=", "str_replace", "(", "$", "item", "[", "0", "]", ",", "$", "item", "[", "1", "]", ",", "$", "html", ")", ";", "}", "return", "new", "Crawler", "(", "(", "string", ")", "$", "html", ")", ";", "}" ]
Replaces a specified HTML tag based from the given callback. @param \Pilipinews\Common\Crawler $crawler @param string $element @param callable $callback @return \Pilipinews\Common\Crawler
[ "Replaces", "a", "specified", "HTML", "tag", "based", "from", "the", "given", "callback", "." ]
a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0
https://github.com/pilipinews/common/blob/a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0/src/Scraper.php#L100-L123
train
pilipinews/common
src/Scraper.php
Scraper.title
protected function title($element, $removable = '') { $converter = new Converter; $crawler = $this->crawler->filter($element); $html = $crawler->first()->html(); $html = str_replace($removable, '', $html); return $converter->convert((string) $html); }
php
protected function title($element, $removable = '') { $converter = new Converter; $crawler = $this->crawler->filter($element); $html = $crawler->first()->html(); $html = str_replace($removable, '', $html); return $converter->convert((string) $html); }
[ "protected", "function", "title", "(", "$", "element", ",", "$", "removable", "=", "''", ")", "{", "$", "converter", "=", "new", "Converter", ";", "$", "crawler", "=", "$", "this", "->", "crawler", "->", "filter", "(", "$", "element", ")", ";", "$", "html", "=", "$", "crawler", "->", "first", "(", ")", "->", "html", "(", ")", ";", "$", "html", "=", "str_replace", "(", "$", "removable", ",", "''", ",", "$", "html", ")", ";", "return", "$", "converter", "->", "convert", "(", "(", "string", ")", "$", "html", ")", ";", "}" ]
Returns the title text based from given HTML tag. @param string $element @param string $removable @return string
[ "Returns", "the", "title", "text", "based", "from", "given", "HTML", "tag", "." ]
a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0
https://github.com/pilipinews/common/blob/a39f16e935b3b8e97b54b6e9348a1deab2d0a2a0/src/Scraper.php#L132-L143
train
digipolisgent/robo-digipolis-deploy
src/Ssh.php
Ssh.remoteDirectory
public function remoteDirectory($directory, $physical = false) { $this->remoteDir = $directory; $this->physicalRemoteDir = $physical; return $this; }
php
public function remoteDirectory($directory, $physical = false) { $this->remoteDir = $directory; $this->physicalRemoteDir = $physical; return $this; }
[ "public", "function", "remoteDirectory", "(", "$", "directory", ",", "$", "physical", "=", "false", ")", "{", "$", "this", "->", "remoteDir", "=", "$", "directory", ";", "$", "this", "->", "physicalRemoteDir", "=", "$", "physical", ";", "return", "$", "this", ";", "}" ]
Sets the remote directory. @param string $directory The remote directory. @param bool $physical Use the physical directory structure without following symbolic links (-P argument for cd). @return $this
[ "Sets", "the", "remote", "directory", "." ]
fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab
https://github.com/digipolisgent/robo-digipolis-deploy/blob/fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab/src/Ssh.php#L165-L171
train
digipolisgent/robo-digipolis-deploy
src/Ssh.php
Ssh.commandCallback
protected function commandCallback($callback) { return ( function ($output) use ($callback) { $this->output .= $output; if (is_callable($callback)) { return call_user_func($callback, $output); } } ); }
php
protected function commandCallback($callback) { return ( function ($output) use ($callback) { $this->output .= $output; if (is_callable($callback)) { return call_user_func($callback, $output); } } ); }
[ "protected", "function", "commandCallback", "(", "$", "callback", ")", "{", "return", "(", "function", "(", "$", "output", ")", "use", "(", "$", "callback", ")", "{", "$", "this", "->", "output", ".=", "$", "output", ";", "if", "(", "is_callable", "(", "$", "callback", ")", ")", "{", "return", "call_user_func", "(", "$", "callback", ",", "$", "output", ")", ";", "}", "}", ")", ";", "}" ]
Wrap the callback so we can print the output. @param callable $callback The callback to wrap.
[ "Wrap", "the", "callback", "so", "we", "can", "print", "the", "output", "." ]
fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab
https://github.com/digipolisgent/robo-digipolis-deploy/blob/fafa8967d98ed4d3f2265b17f4b1abe53bf0b5ab/src/Ssh.php#L306-L316
train
thelia-modules/SmartyFilter
Handler/ConfigurationFileHandler.php
ConfigurationFileHandler.parseXml
protected function parseXml(SplFileInfo $file) { $dom = XmlUtils::loadFile($file, realpath(dirname(__DIR__) . DS . 'Schema' . DS . 'smarty_filter.xsd')); /** @var \Symfony\Component\DependencyInjection\SimpleXMLElement $xml */ $xml = simplexml_import_dom($dom, '\\Symfony\\Component\\DependencyInjection\\SimpleXMLElement'); $parsedConfig = []; /** @var \Symfony\Component\DependencyInjection\SimpleXMLElement $smartyFilterDefinition */ foreach ($xml->smartyfilter as $smartyFilterDefinition) { $descriptive = []; /** @var \Symfony\Component\DependencyInjection\SimpleXMLElement $descriptiveDefinition */ foreach ($smartyFilterDefinition->descriptive as $descriptiveDefinition) { $descriptive[] = [ 'locale' => $descriptiveDefinition->getAttributeAsPhp('locale'), 'title' => (string)$descriptiveDefinition->title, 'description' => (string)$descriptiveDefinition->description, 'type' => (string)$descriptiveDefinition->type ]; } $parsedConfig['smarty_filter'][] = [ 'code' => $smartyFilterDefinition->getAttributeAsPhp('code'), 'descriptive' => $descriptive ]; } return $parsedConfig; }
php
protected function parseXml(SplFileInfo $file) { $dom = XmlUtils::loadFile($file, realpath(dirname(__DIR__) . DS . 'Schema' . DS . 'smarty_filter.xsd')); /** @var \Symfony\Component\DependencyInjection\SimpleXMLElement $xml */ $xml = simplexml_import_dom($dom, '\\Symfony\\Component\\DependencyInjection\\SimpleXMLElement'); $parsedConfig = []; /** @var \Symfony\Component\DependencyInjection\SimpleXMLElement $smartyFilterDefinition */ foreach ($xml->smartyfilter as $smartyFilterDefinition) { $descriptive = []; /** @var \Symfony\Component\DependencyInjection\SimpleXMLElement $descriptiveDefinition */ foreach ($smartyFilterDefinition->descriptive as $descriptiveDefinition) { $descriptive[] = [ 'locale' => $descriptiveDefinition->getAttributeAsPhp('locale'), 'title' => (string)$descriptiveDefinition->title, 'description' => (string)$descriptiveDefinition->description, 'type' => (string)$descriptiveDefinition->type ]; } $parsedConfig['smarty_filter'][] = [ 'code' => $smartyFilterDefinition->getAttributeAsPhp('code'), 'descriptive' => $descriptive ]; } return $parsedConfig; }
[ "protected", "function", "parseXml", "(", "SplFileInfo", "$", "file", ")", "{", "$", "dom", "=", "XmlUtils", "::", "loadFile", "(", "$", "file", ",", "realpath", "(", "dirname", "(", "__DIR__", ")", ".", "DS", ".", "'Schema'", ".", "DS", ".", "'smarty_filter.xsd'", ")", ")", ";", "/** @var \\Symfony\\Component\\DependencyInjection\\SimpleXMLElement $xml */", "$", "xml", "=", "simplexml_import_dom", "(", "$", "dom", ",", "'\\\\Symfony\\\\Component\\\\DependencyInjection\\\\SimpleXMLElement'", ")", ";", "$", "parsedConfig", "=", "[", "]", ";", "/** @var \\Symfony\\Component\\DependencyInjection\\SimpleXMLElement $smartyFilterDefinition */", "foreach", "(", "$", "xml", "->", "smartyfilter", "as", "$", "smartyFilterDefinition", ")", "{", "$", "descriptive", "=", "[", "]", ";", "/** @var \\Symfony\\Component\\DependencyInjection\\SimpleXMLElement $descriptiveDefinition */", "foreach", "(", "$", "smartyFilterDefinition", "->", "descriptive", "as", "$", "descriptiveDefinition", ")", "{", "$", "descriptive", "[", "]", "=", "[", "'locale'", "=>", "$", "descriptiveDefinition", "->", "getAttributeAsPhp", "(", "'locale'", ")", ",", "'title'", "=>", "(", "string", ")", "$", "descriptiveDefinition", "->", "title", ",", "'description'", "=>", "(", "string", ")", "$", "descriptiveDefinition", "->", "description", ",", "'type'", "=>", "(", "string", ")", "$", "descriptiveDefinition", "->", "type", "]", ";", "}", "$", "parsedConfig", "[", "'smarty_filter'", "]", "[", "]", "=", "[", "'code'", "=>", "$", "smartyFilterDefinition", "->", "getAttributeAsPhp", "(", "'code'", ")", ",", "'descriptive'", "=>", "$", "descriptive", "]", ";", "}", "return", "$", "parsedConfig", ";", "}" ]
Get config from xml file @param SplFileInfo $file XML file @return array Smarty Filter module configuration
[ "Get", "config", "from", "xml", "file" ]
e510d281f51ddc4344e563d0f6aaa192fa7171e9
https://github.com/thelia-modules/SmartyFilter/blob/e510d281f51ddc4344e563d0f6aaa192fa7171e9/Handler/ConfigurationFileHandler.php#L68-L96
train
thelia-modules/SmartyFilter
Handler/ConfigurationFileHandler.php
ConfigurationFileHandler.applyConfig
protected function applyConfig(array $moduleConfiguration) { foreach ($moduleConfiguration['smarty_filter'] as $smartyFilterData) { if (SmartyFilterQuery::create()->findOneByCode($smartyFilterData['code']) === null) { $smartyFilter = (new SmartyFilter()) ->setCode($smartyFilterData['code']); foreach ($smartyFilterData['descriptive'] as $descriptiveData) { $smartyFilter ->setLocale($descriptiveData['locale']) ->setTitle($descriptiveData['title']) ->setDescription($descriptiveData['description']) ->setFiltertype($descriptiveData['type']); } $smartyFilter->save(); } } }
php
protected function applyConfig(array $moduleConfiguration) { foreach ($moduleConfiguration['smarty_filter'] as $smartyFilterData) { if (SmartyFilterQuery::create()->findOneByCode($smartyFilterData['code']) === null) { $smartyFilter = (new SmartyFilter()) ->setCode($smartyFilterData['code']); foreach ($smartyFilterData['descriptive'] as $descriptiveData) { $smartyFilter ->setLocale($descriptiveData['locale']) ->setTitle($descriptiveData['title']) ->setDescription($descriptiveData['description']) ->setFiltertype($descriptiveData['type']); } $smartyFilter->save(); } } }
[ "protected", "function", "applyConfig", "(", "array", "$", "moduleConfiguration", ")", "{", "foreach", "(", "$", "moduleConfiguration", "[", "'smarty_filter'", "]", "as", "$", "smartyFilterData", ")", "{", "if", "(", "SmartyFilterQuery", "::", "create", "(", ")", "->", "findOneByCode", "(", "$", "smartyFilterData", "[", "'code'", "]", ")", "===", "null", ")", "{", "$", "smartyFilter", "=", "(", "new", "SmartyFilter", "(", ")", ")", "->", "setCode", "(", "$", "smartyFilterData", "[", "'code'", "]", ")", ";", "foreach", "(", "$", "smartyFilterData", "[", "'descriptive'", "]", "as", "$", "descriptiveData", ")", "{", "$", "smartyFilter", "->", "setLocale", "(", "$", "descriptiveData", "[", "'locale'", "]", ")", "->", "setTitle", "(", "$", "descriptiveData", "[", "'title'", "]", ")", "->", "setDescription", "(", "$", "descriptiveData", "[", "'description'", "]", ")", "->", "setFiltertype", "(", "$", "descriptiveData", "[", "'type'", "]", ")", ";", "}", "$", "smartyFilter", "->", "save", "(", ")", ";", "}", "}", "}" ]
Save new smarty filter to database @param array $moduleConfiguration Smarty Filter module configuration
[ "Save", "new", "smarty", "filter", "to", "database" ]
e510d281f51ddc4344e563d0f6aaa192fa7171e9
https://github.com/thelia-modules/SmartyFilter/blob/e510d281f51ddc4344e563d0f6aaa192fa7171e9/Handler/ConfigurationFileHandler.php#L117-L135
train
antaresproject/search
src/Response/QueryResponse.php
QueryResponse.isValid
protected function isValid() { if (!$this->request->ajax()) { return false; } $search = $this->request->input('search'); if (!is_string($search) or strlen($this->request->input('search')) <= 0) { return false; } $token = $this->request->header('search-protection'); if (!$this->validateToken($token)) { return false; } return true; }
php
protected function isValid() { if (!$this->request->ajax()) { return false; } $search = $this->request->input('search'); if (!is_string($search) or strlen($this->request->input('search')) <= 0) { return false; } $token = $this->request->header('search-protection'); if (!$this->validateToken($token)) { return false; } return true; }
[ "protected", "function", "isValid", "(", ")", "{", "if", "(", "!", "$", "this", "->", "request", "->", "ajax", "(", ")", ")", "{", "return", "false", ";", "}", "$", "search", "=", "$", "this", "->", "request", "->", "input", "(", "'search'", ")", ";", "if", "(", "!", "is_string", "(", "$", "search", ")", "or", "strlen", "(", "$", "this", "->", "request", "->", "input", "(", "'search'", ")", ")", "<=", "0", ")", "{", "return", "false", ";", "}", "$", "token", "=", "$", "this", "->", "request", "->", "header", "(", "'search-protection'", ")", ";", "if", "(", "!", "$", "this", "->", "validateToken", "(", "$", "token", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
validates submitted data from search form @return boolean
[ "validates", "submitted", "data", "from", "search", "form" ]
3bcb994e69c03792d20dfa688a3281f80cd8dde8
https://github.com/antaresproject/search/blob/3bcb994e69c03792d20dfa688a3281f80cd8dde8/src/Response/QueryResponse.php#L54-L68
train
antaresproject/search
src/Response/QueryResponse.php
QueryResponse.validateToken
private function validateToken($token = null) { if (is_null($token)) { return false; } $decrypted = Crypt::decrypt($token); $args = unserialize($decrypted); if (!isset($args['protection_string']) or $args['protection_string'] !== config('antares/search::protection_string')) { return false; } if (!isset($args['app_key']) or $args['app_key'] !== env('APP_KEY')) { return false; } return true; }
php
private function validateToken($token = null) { if (is_null($token)) { return false; } $decrypted = Crypt::decrypt($token); $args = unserialize($decrypted); if (!isset($args['protection_string']) or $args['protection_string'] !== config('antares/search::protection_string')) { return false; } if (!isset($args['app_key']) or $args['app_key'] !== env('APP_KEY')) { return false; } return true; }
[ "private", "function", "validateToken", "(", "$", "token", "=", "null", ")", "{", "if", "(", "is_null", "(", "$", "token", ")", ")", "{", "return", "false", ";", "}", "$", "decrypted", "=", "Crypt", "::", "decrypt", "(", "$", "token", ")", ";", "$", "args", "=", "unserialize", "(", "$", "decrypted", ")", ";", "if", "(", "!", "isset", "(", "$", "args", "[", "'protection_string'", "]", ")", "or", "$", "args", "[", "'protection_string'", "]", "!==", "config", "(", "'antares/search::protection_string'", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "isset", "(", "$", "args", "[", "'app_key'", "]", ")", "or", "$", "args", "[", "'app_key'", "]", "!==", "env", "(", "'APP_KEY'", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
validates protection token @param String $token @return boolean
[ "validates", "protection", "token" ]
3bcb994e69c03792d20dfa688a3281f80cd8dde8
https://github.com/antaresproject/search/blob/3bcb994e69c03792d20dfa688a3281f80cd8dde8/src/Response/QueryResponse.php#L76-L91
train
antaresproject/search
src/Response/QueryResponse.php
QueryResponse.boot
public function boot() { if (!$this->isValid()) { return false; } $serviceProvider = new \Antares\Customfields\CustomFieldsServiceProvider(app()); $serviceProvider->register(); $serviceProvider->boot(); $query = e($this->request->input('search')); $cacheKey = 'search_' . snake_case($query); $formated = []; try { //$formated = Cache::remember($cacheKey, 5, function() use($query) { $datatables = config('search.datatables', []); foreach ($datatables as $classname) { $datatable = $this->getDatatableInstance($classname); if (!$datatable) { continue; } request()->merge(['inline_search' => ['value' => $query, 'regex' => false]]); $formated = array_merge($formated, app('antares-search-row-decorator')->setDatatable($datatable)->getRows()); } if (empty($formated)) { $formated[] = [ 'content' => '<div class="type--datarow"><div class="datarow__left"><span>No results found...</span></div></div>', 'url' => '#', 'category' => '', 'total' => 0 ]; } $jsonResponse = new JsonResponse($formated, 200); } catch (Exception $e) { $jsonResponse = new JsonResponse(['message' => $e->getMessage()], 500); } $jsonResponse->send(); return exit(); }
php
public function boot() { if (!$this->isValid()) { return false; } $serviceProvider = new \Antares\Customfields\CustomFieldsServiceProvider(app()); $serviceProvider->register(); $serviceProvider->boot(); $query = e($this->request->input('search')); $cacheKey = 'search_' . snake_case($query); $formated = []; try { //$formated = Cache::remember($cacheKey, 5, function() use($query) { $datatables = config('search.datatables', []); foreach ($datatables as $classname) { $datatable = $this->getDatatableInstance($classname); if (!$datatable) { continue; } request()->merge(['inline_search' => ['value' => $query, 'regex' => false]]); $formated = array_merge($formated, app('antares-search-row-decorator')->setDatatable($datatable)->getRows()); } if (empty($formated)) { $formated[] = [ 'content' => '<div class="type--datarow"><div class="datarow__left"><span>No results found...</span></div></div>', 'url' => '#', 'category' => '', 'total' => 0 ]; } $jsonResponse = new JsonResponse($formated, 200); } catch (Exception $e) { $jsonResponse = new JsonResponse(['message' => $e->getMessage()], 500); } $jsonResponse->send(); return exit(); }
[ "public", "function", "boot", "(", ")", "{", "if", "(", "!", "$", "this", "->", "isValid", "(", ")", ")", "{", "return", "false", ";", "}", "$", "serviceProvider", "=", "new", "\\", "Antares", "\\", "Customfields", "\\", "CustomFieldsServiceProvider", "(", "app", "(", ")", ")", ";", "$", "serviceProvider", "->", "register", "(", ")", ";", "$", "serviceProvider", "->", "boot", "(", ")", ";", "$", "query", "=", "e", "(", "$", "this", "->", "request", "->", "input", "(", "'search'", ")", ")", ";", "$", "cacheKey", "=", "'search_'", ".", "snake_case", "(", "$", "query", ")", ";", "$", "formated", "=", "[", "]", ";", "try", "{", "//$formated = Cache::remember($cacheKey, 5, function() use($query) {", "$", "datatables", "=", "config", "(", "'search.datatables'", ",", "[", "]", ")", ";", "foreach", "(", "$", "datatables", "as", "$", "classname", ")", "{", "$", "datatable", "=", "$", "this", "->", "getDatatableInstance", "(", "$", "classname", ")", ";", "if", "(", "!", "$", "datatable", ")", "{", "continue", ";", "}", "request", "(", ")", "->", "merge", "(", "[", "'inline_search'", "=>", "[", "'value'", "=>", "$", "query", ",", "'regex'", "=>", "false", "]", "]", ")", ";", "$", "formated", "=", "array_merge", "(", "$", "formated", ",", "app", "(", "'antares-search-row-decorator'", ")", "->", "setDatatable", "(", "$", "datatable", ")", "->", "getRows", "(", ")", ")", ";", "}", "if", "(", "empty", "(", "$", "formated", ")", ")", "{", "$", "formated", "[", "]", "=", "[", "'content'", "=>", "'<div class=\"type--datarow\"><div class=\"datarow__left\"><span>No results found...</span></div></div>'", ",", "'url'", "=>", "'#'", ",", "'category'", "=>", "''", ",", "'total'", "=>", "0", "]", ";", "}", "$", "jsonResponse", "=", "new", "JsonResponse", "(", "$", "formated", ",", "200", ")", ";", "}", "catch", "(", "Exception", "$", "e", ")", "{", "$", "jsonResponse", "=", "new", "JsonResponse", "(", "[", "'message'", "=>", "$", "e", "->", "getMessage", "(", ")", "]", ",", "500", ")", ";", "}", "$", "jsonResponse", "->", "send", "(", ")", ";", "return", "exit", "(", ")", ";", "}" ]
Boots search query in lucene indexes @return boolean
[ "Boots", "search", "query", "in", "lucene", "indexes" ]
3bcb994e69c03792d20dfa688a3281f80cd8dde8
https://github.com/antaresproject/search/blob/3bcb994e69c03792d20dfa688a3281f80cd8dde8/src/Response/QueryResponse.php#L98-L136
train
antaresproject/search
src/Response/QueryResponse.php
QueryResponse.getDatatableInstance
protected function getDatatableInstance($classname) { if (!class_exists($classname)) { return false; } $datatable = app($classname); $reflection = new ReflectionClass($datatable); if (($filename = $reflection->getFileName()) && !str_contains($filename, 'core')) { if (!app('antares.extension')->getActiveExtensionByPath($filename)) { return false; } } return $datatable; }
php
protected function getDatatableInstance($classname) { if (!class_exists($classname)) { return false; } $datatable = app($classname); $reflection = new ReflectionClass($datatable); if (($filename = $reflection->getFileName()) && !str_contains($filename, 'core')) { if (!app('antares.extension')->getActiveExtensionByPath($filename)) { return false; } } return $datatable; }
[ "protected", "function", "getDatatableInstance", "(", "$", "classname", ")", "{", "if", "(", "!", "class_exists", "(", "$", "classname", ")", ")", "{", "return", "false", ";", "}", "$", "datatable", "=", "app", "(", "$", "classname", ")", ";", "$", "reflection", "=", "new", "ReflectionClass", "(", "$", "datatable", ")", ";", "if", "(", "(", "$", "filename", "=", "$", "reflection", "->", "getFileName", "(", ")", ")", "&&", "!", "str_contains", "(", "$", "filename", ",", "'core'", ")", ")", "{", "if", "(", "!", "app", "(", "'antares.extension'", ")", "->", "getActiveExtensionByPath", "(", "$", "filename", ")", ")", "{", "return", "false", ";", "}", "}", "return", "$", "datatable", ";", "}" ]
Gets instance of datatable @param String $classname @return boolean
[ "Gets", "instance", "of", "datatable" ]
3bcb994e69c03792d20dfa688a3281f80cd8dde8
https://github.com/antaresproject/search/blob/3bcb994e69c03792d20dfa688a3281f80cd8dde8/src/Response/QueryResponse.php#L144-L157
train
RadialCorp/magento-core
src/app/code/community/Radial/Order/Model/Eav/Entity/Increment/Order.php
Radial_Order_Model_Eav_Entity_Increment_Order._getStoreId
protected function _getStoreId() { $storeEnv = Mage::app()->getStore(); if ($storeEnv->isAdmin()) { /** @var Mage_Adminhtml_Model_Session_Quote */ $quoteSession = $this->_orderHelper->getAdminQuoteSessionModel(); // when in the admin, the store id the order is actually being created // for should be used instead of the admin store id - should be // available in the session $storeEnv = $quoteSession->getStore(); } return $storeEnv->getId(); }
php
protected function _getStoreId() { $storeEnv = Mage::app()->getStore(); if ($storeEnv->isAdmin()) { /** @var Mage_Adminhtml_Model_Session_Quote */ $quoteSession = $this->_orderHelper->getAdminQuoteSessionModel(); // when in the admin, the store id the order is actually being created // for should be used instead of the admin store id - should be // available in the session $storeEnv = $quoteSession->getStore(); } return $storeEnv->getId(); }
[ "protected", "function", "_getStoreId", "(", ")", "{", "$", "storeEnv", "=", "Mage", "::", "app", "(", ")", "->", "getStore", "(", ")", ";", "if", "(", "$", "storeEnv", "->", "isAdmin", "(", ")", ")", "{", "/** @var Mage_Adminhtml_Model_Session_Quote */", "$", "quoteSession", "=", "$", "this", "->", "_orderHelper", "->", "getAdminQuoteSessionModel", "(", ")", ";", "// when in the admin, the store id the order is actually being created", "// for should be used instead of the admin store id - should be", "// available in the session", "$", "storeEnv", "=", "$", "quoteSession", "->", "getStore", "(", ")", ";", "}", "return", "$", "storeEnv", "->", "getId", "(", ")", ";", "}" ]
Get the store id for the order. In non-admin stores, can use the current store. In admin stores, must get the order the quote is actually being created in. @return int
[ "Get", "the", "store", "id", "for", "the", "order", ".", "In", "non", "-", "admin", "stores", "can", "use", "the", "current", "store", ".", "In", "admin", "stores", "must", "get", "the", "order", "the", "quote", "is", "actually", "being", "created", "in", "." ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Order/Model/Eav/Entity/Increment/Order.php#L82-L94
train
RadialCorp/magento-core
src/app/code/community/Radial/Order/Model/Eav/Entity/Increment/Order.php
Radial_Order_Model_Eav_Entity_Increment_Order.getNextId
public function getNextId() { // remove any order prefixes from the last increment id $last = $this->_orderHelper->removeOrderIncrementPrefix($this->getLastId()); // Using bcmath to avoid float/integer overflow. return $this->format(bcadd($last, 1)); }
php
public function getNextId() { // remove any order prefixes from the last increment id $last = $this->_orderHelper->removeOrderIncrementPrefix($this->getLastId()); // Using bcmath to avoid float/integer overflow. return $this->format(bcadd($last, 1)); }
[ "public", "function", "getNextId", "(", ")", "{", "// remove any order prefixes from the last increment id", "$", "last", "=", "$", "this", "->", "_orderHelper", "->", "removeOrderIncrementPrefix", "(", "$", "this", "->", "getLastId", "(", ")", ")", ";", "// Using bcmath to avoid float/integer overflow.", "return", "$", "this", "->", "format", "(", "bcadd", "(", "$", "last", ",", "1", ")", ")", ";", "}" ]
Get the next increment id by incrementing the last id @return string
[ "Get", "the", "next", "increment", "id", "by", "incrementing", "the", "last", "id" ]
9bb5f218d9caf79eab8598f4f8447037a0cc6355
https://github.com/RadialCorp/magento-core/blob/9bb5f218d9caf79eab8598f4f8447037a0cc6355/src/app/code/community/Radial/Order/Model/Eav/Entity/Increment/Order.php#L99-L105
train
sellerlabs/injected
src/SellerLabs/Injected/InjectedTrait.php
InjectedTrait.getDependencyMapping
protected function getDependencyMapping() { $constructor = (new ReflectionClass($this->className)) ->getConstructor(); $dependencies = []; if (!is_null($constructor)) { foreach ($constructor->getParameters() as $param) { $dependencies[$param->getClass()->getName()] = $param->getName(); } } return $dependencies; }
php
protected function getDependencyMapping() { $constructor = (new ReflectionClass($this->className)) ->getConstructor(); $dependencies = []; if (!is_null($constructor)) { foreach ($constructor->getParameters() as $param) { $dependencies[$param->getClass()->getName()] = $param->getName(); } } return $dependencies; }
[ "protected", "function", "getDependencyMapping", "(", ")", "{", "$", "constructor", "=", "(", "new", "ReflectionClass", "(", "$", "this", "->", "className", ")", ")", "->", "getConstructor", "(", ")", ";", "$", "dependencies", "=", "[", "]", ";", "if", "(", "!", "is_null", "(", "$", "constructor", ")", ")", "{", "foreach", "(", "$", "constructor", "->", "getParameters", "(", ")", "as", "$", "param", ")", "{", "$", "dependencies", "[", "$", "param", "->", "getClass", "(", ")", "->", "getName", "(", ")", "]", "=", "$", "param", "->", "getName", "(", ")", ";", "}", "}", "return", "$", "dependencies", ";", "}" ]
Get a mapping of class name => member name dependencies. Important: these must be ordered in the way the class accepts its dependencies. @return array @throws Exception
[ "Get", "a", "mapping", "of", "class", "name", "=", ">", "member", "name", "dependencies", "." ]
89f90334ccc392c67c79fb1eba258b34cfa9edd6
https://github.com/sellerlabs/injected/blob/89f90334ccc392c67c79fb1eba258b34cfa9edd6/src/SellerLabs/Injected/InjectedTrait.php#L32-L46
train