repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_code_tokens
sequencelengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
academic/VipaBibTexBundle | Helper/Bibtex.php | Bibtex._formatAuthor | function _formatAuthor($array)
{
if (!array_key_exists('von', $array)) {
$array['von'] = '';
} else {
$array['von'] = trim($array['von']);
}
if (!array_key_exists('last', $array)) {
$array['last'] = '';
} else {
$array['last'] = trim($array['last']);
}
if (!array_key_exists('jr', $array)) {
$array['jr'] = '';
} else {
$array['jr'] = trim($array['jr']);
}
if (!array_key_exists('first', $array)) {
$array['first'] = '';
} else {
$array['first'] = trim($array['first']);
}
$ret = $this->authorstring;
$ret = str_replace("VON", $array['von'], $ret);
$ret = str_replace("LAST", $array['last'], $ret);
$ret = str_replace("JR,", $array['jr'], $ret);
$ret = str_replace("FIRST", $array['first'], $ret);
return trim(print_r($ret, 1));
} | php | function _formatAuthor($array)
{
if (!array_key_exists('von', $array)) {
$array['von'] = '';
} else {
$array['von'] = trim($array['von']);
}
if (!array_key_exists('last', $array)) {
$array['last'] = '';
} else {
$array['last'] = trim($array['last']);
}
if (!array_key_exists('jr', $array)) {
$array['jr'] = '';
} else {
$array['jr'] = trim($array['jr']);
}
if (!array_key_exists('first', $array)) {
$array['first'] = '';
} else {
$array['first'] = trim($array['first']);
}
$ret = $this->authorstring;
$ret = str_replace("VON", $array['von'], $ret);
$ret = str_replace("LAST", $array['last'], $ret);
$ret = str_replace("JR,", $array['jr'], $ret);
$ret = str_replace("FIRST", $array['first'], $ret);
return trim(print_r($ret, 1));
} | [
"function",
"_formatAuthor",
"(",
"$",
"array",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"'von'",
",",
"$",
"array",
")",
")",
"{",
"$",
"array",
"[",
"'von'",
"]",
"=",
"''",
";",
"}",
"else",
"{",
"$",
"array",
"[",
"'von'",
"]",
"=",
"trim",
"(",
"$",
"array",
"[",
"'von'",
"]",
")",
";",
"}",
"if",
"(",
"!",
"array_key_exists",
"(",
"'last'",
",",
"$",
"array",
")",
")",
"{",
"$",
"array",
"[",
"'last'",
"]",
"=",
"''",
";",
"}",
"else",
"{",
"$",
"array",
"[",
"'last'",
"]",
"=",
"trim",
"(",
"$",
"array",
"[",
"'last'",
"]",
")",
";",
"}",
"if",
"(",
"!",
"array_key_exists",
"(",
"'jr'",
",",
"$",
"array",
")",
")",
"{",
"$",
"array",
"[",
"'jr'",
"]",
"=",
"''",
";",
"}",
"else",
"{",
"$",
"array",
"[",
"'jr'",
"]",
"=",
"trim",
"(",
"$",
"array",
"[",
"'jr'",
"]",
")",
";",
"}",
"if",
"(",
"!",
"array_key_exists",
"(",
"'first'",
",",
"$",
"array",
")",
")",
"{",
"$",
"array",
"[",
"'first'",
"]",
"=",
"''",
";",
"}",
"else",
"{",
"$",
"array",
"[",
"'first'",
"]",
"=",
"trim",
"(",
"$",
"array",
"[",
"'first'",
"]",
")",
";",
"}",
"$",
"ret",
"=",
"$",
"this",
"->",
"authorstring",
";",
"$",
"ret",
"=",
"str_replace",
"(",
"\"VON\"",
",",
"$",
"array",
"[",
"'von'",
"]",
",",
"$",
"ret",
")",
";",
"$",
"ret",
"=",
"str_replace",
"(",
"\"LAST\"",
",",
"$",
"array",
"[",
"'last'",
"]",
",",
"$",
"ret",
")",
";",
"$",
"ret",
"=",
"str_replace",
"(",
"\"JR,\"",
",",
"$",
"array",
"[",
"'jr'",
"]",
",",
"$",
"ret",
")",
";",
"$",
"ret",
"=",
"str_replace",
"(",
"\"FIRST\"",
",",
"$",
"array",
"[",
"'first'",
"]",
",",
"$",
"ret",
")",
";",
"return",
"trim",
"(",
"print_r",
"(",
"$",
"ret",
",",
"1",
")",
")",
";",
"}"
] | Returns the author formatted
The Author is formatted as setted in the authorstring
@access private
@param array $array Author array
@return string the formatted author string | [
"Returns",
"the",
"author",
"formatted"
] | train | https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L938-L967 |
academic/VipaBibTexBundle | Helper/Bibtex.php | Bibtex.bibTex | function bibTex()
{
$bibtex = '';
foreach ($this->data as $entry) {
//Intro
$bibtex .= '@' . strtolower($entry['entryType']) . ' { ' . $entry['cite'] . ",\n";
//Other fields except author
foreach ($entry as $key => $val) {
if ($this->_options['wordWrapWidth'] > 0) {
$val = $this->_wordWrap($val);
}
if (!in_array($key, array('cite', 'entryType', 'author'))) {
$bibtex .= "\t" . $key . ' = {' . $this->_escape_tex($val) . "},\n";
}
}
//Author
$author = null;
if (array_key_exists('author', $entry)) {
if ($this->_options['extractAuthors']) {
$tmparray = array(); //In this array the authors are saved and the joind with an and
foreach ($entry['author'] as $authorentry) {
$tmparray[] = $this->_formatAuthor($authorentry);
}
$author = join(' and ', $tmparray);
} else {
$author = $entry['author'];
}
} else {
$author = '';
}
$bibtex .= "\tauthor = {" . $this->_escape_tex($author) . "}\n";
$bibtex .= "}\n\n";
}
return $bibtex;
} | php | function bibTex()
{
$bibtex = '';
foreach ($this->data as $entry) {
//Intro
$bibtex .= '@' . strtolower($entry['entryType']) . ' { ' . $entry['cite'] . ",\n";
//Other fields except author
foreach ($entry as $key => $val) {
if ($this->_options['wordWrapWidth'] > 0) {
$val = $this->_wordWrap($val);
}
if (!in_array($key, array('cite', 'entryType', 'author'))) {
$bibtex .= "\t" . $key . ' = {' . $this->_escape_tex($val) . "},\n";
}
}
//Author
$author = null;
if (array_key_exists('author', $entry)) {
if ($this->_options['extractAuthors']) {
$tmparray = array(); //In this array the authors are saved and the joind with an and
foreach ($entry['author'] as $authorentry) {
$tmparray[] = $this->_formatAuthor($authorentry);
}
$author = join(' and ', $tmparray);
} else {
$author = $entry['author'];
}
} else {
$author = '';
}
$bibtex .= "\tauthor = {" . $this->_escape_tex($author) . "}\n";
$bibtex .= "}\n\n";
}
return $bibtex;
} | [
"function",
"bibTex",
"(",
")",
"{",
"$",
"bibtex",
"=",
"''",
";",
"foreach",
"(",
"$",
"this",
"->",
"data",
"as",
"$",
"entry",
")",
"{",
"//Intro",
"$",
"bibtex",
".=",
"'@'",
".",
"strtolower",
"(",
"$",
"entry",
"[",
"'entryType'",
"]",
")",
".",
"' { '",
".",
"$",
"entry",
"[",
"'cite'",
"]",
".",
"\",\\n\"",
";",
"//Other fields except author",
"foreach",
"(",
"$",
"entry",
"as",
"$",
"key",
"=>",
"$",
"val",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_options",
"[",
"'wordWrapWidth'",
"]",
">",
"0",
")",
"{",
"$",
"val",
"=",
"$",
"this",
"->",
"_wordWrap",
"(",
"$",
"val",
")",
";",
"}",
"if",
"(",
"!",
"in_array",
"(",
"$",
"key",
",",
"array",
"(",
"'cite'",
",",
"'entryType'",
",",
"'author'",
")",
")",
")",
"{",
"$",
"bibtex",
".=",
"\"\\t\"",
".",
"$",
"key",
".",
"' = {'",
".",
"$",
"this",
"->",
"_escape_tex",
"(",
"$",
"val",
")",
".",
"\"},\\n\"",
";",
"}",
"}",
"//Author",
"$",
"author",
"=",
"null",
";",
"if",
"(",
"array_key_exists",
"(",
"'author'",
",",
"$",
"entry",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_options",
"[",
"'extractAuthors'",
"]",
")",
"{",
"$",
"tmparray",
"=",
"array",
"(",
")",
";",
"//In this array the authors are saved and the joind with an and",
"foreach",
"(",
"$",
"entry",
"[",
"'author'",
"]",
"as",
"$",
"authorentry",
")",
"{",
"$",
"tmparray",
"[",
"]",
"=",
"$",
"this",
"->",
"_formatAuthor",
"(",
"$",
"authorentry",
")",
";",
"}",
"$",
"author",
"=",
"join",
"(",
"' and '",
",",
"$",
"tmparray",
")",
";",
"}",
"else",
"{",
"$",
"author",
"=",
"$",
"entry",
"[",
"'author'",
"]",
";",
"}",
"}",
"else",
"{",
"$",
"author",
"=",
"''",
";",
"}",
"$",
"bibtex",
".=",
"\"\\tauthor = {\"",
".",
"$",
"this",
"->",
"_escape_tex",
"(",
"$",
"author",
")",
".",
"\"}\\n\"",
";",
"$",
"bibtex",
".=",
"\"}\\n\\n\"",
";",
"}",
"return",
"$",
"bibtex",
";",
"}"
] | Converts the stored BibTex entries to a BibTex String
In the field list, the author is the last field.
@access public
@return string The BibTex string | [
"Converts",
"the",
"stored",
"BibTex",
"entries",
"to",
"a",
"BibTex",
"String"
] | train | https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L977-L1013 |
academic/VipaBibTexBundle | Helper/Bibtex.php | Bibtex.getStatistic | function getStatistic()
{
$ret = array();
foreach ($this->data as $entry) {
if (array_key_exists($entry['entryType'], $ret)) {
$ret[$entry['entryType']]++;
} else {
$ret[$entry['entryType']] = 1;
}
}
return $ret;
} | php | function getStatistic()
{
$ret = array();
foreach ($this->data as $entry) {
if (array_key_exists($entry['entryType'], $ret)) {
$ret[$entry['entryType']]++;
} else {
$ret[$entry['entryType']] = 1;
}
}
return $ret;
} | [
"function",
"getStatistic",
"(",
")",
"{",
"$",
"ret",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"data",
"as",
"$",
"entry",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"entry",
"[",
"'entryType'",
"]",
",",
"$",
"ret",
")",
")",
"{",
"$",
"ret",
"[",
"$",
"entry",
"[",
"'entryType'",
"]",
"]",
"++",
";",
"}",
"else",
"{",
"$",
"ret",
"[",
"$",
"entry",
"[",
"'entryType'",
"]",
"]",
"=",
"1",
";",
"}",
"}",
"return",
"$",
"ret",
";",
"}"
] | Returns statistic
This functions returns a hash table. The keys are the different
entry types and the values are the amount of these entries.
@access public
@return array Hash Table with the data | [
"Returns",
"statistic"
] | train | https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L1036-L1047 |
academic/VipaBibTexBundle | Helper/Bibtex.php | Bibtex.rtf | function rtf()
{
$ret = "{\\rtf\n";
foreach ($this->data as $entry) {
$line = $this->rtfstring;
$title = '';
$journal = '';
$year = '';
$authors = '';
if (array_key_exists('title', $entry)) {
$title = $this->_unwrap($entry['title']);
}
if (array_key_exists('journal', $entry)) {
$journal = $this->_unwrap($entry['journal']);
}
if (array_key_exists('year', $entry)) {
$year = $this->_unwrap($entry['year']);
}
if (array_key_exists('author', $entry)) {
if ($this->_options['extractAuthors']) {
$tmparray = array(); //In this array the authors are saved and the joind with an and
foreach ($entry['author'] as $authorentry) {
$tmparray[] = $this->_formatAuthor($authorentry);
}
$authors = join(', ', $tmparray);
} else {
$authors = $entry['author'];
}
}
if (('' != $title) || ('' != $journal) || ('' != $year) || ('' != $authors)) {
$line = str_replace("TITLE", $title, $line);
$line = str_replace("JOURNAL", $journal, $line);
$line = str_replace("YEAR", $year, $line);
$line = str_replace("AUTHORS", $authors, $line);
$line .= "\n\\par\n";
$ret .= $line;
} else {
$this->_generateWarning('WARNING_LINE_WAS_NOT_CONVERTED', '', print_r($entry, 1));
}
}
$ret .= '}';
return $ret;
} | php | function rtf()
{
$ret = "{\\rtf\n";
foreach ($this->data as $entry) {
$line = $this->rtfstring;
$title = '';
$journal = '';
$year = '';
$authors = '';
if (array_key_exists('title', $entry)) {
$title = $this->_unwrap($entry['title']);
}
if (array_key_exists('journal', $entry)) {
$journal = $this->_unwrap($entry['journal']);
}
if (array_key_exists('year', $entry)) {
$year = $this->_unwrap($entry['year']);
}
if (array_key_exists('author', $entry)) {
if ($this->_options['extractAuthors']) {
$tmparray = array(); //In this array the authors are saved and the joind with an and
foreach ($entry['author'] as $authorentry) {
$tmparray[] = $this->_formatAuthor($authorentry);
}
$authors = join(', ', $tmparray);
} else {
$authors = $entry['author'];
}
}
if (('' != $title) || ('' != $journal) || ('' != $year) || ('' != $authors)) {
$line = str_replace("TITLE", $title, $line);
$line = str_replace("JOURNAL", $journal, $line);
$line = str_replace("YEAR", $year, $line);
$line = str_replace("AUTHORS", $authors, $line);
$line .= "\n\\par\n";
$ret .= $line;
} else {
$this->_generateWarning('WARNING_LINE_WAS_NOT_CONVERTED', '', print_r($entry, 1));
}
}
$ret .= '}';
return $ret;
} | [
"function",
"rtf",
"(",
")",
"{",
"$",
"ret",
"=",
"\"{\\\\rtf\\n\"",
";",
"foreach",
"(",
"$",
"this",
"->",
"data",
"as",
"$",
"entry",
")",
"{",
"$",
"line",
"=",
"$",
"this",
"->",
"rtfstring",
";",
"$",
"title",
"=",
"''",
";",
"$",
"journal",
"=",
"''",
";",
"$",
"year",
"=",
"''",
";",
"$",
"authors",
"=",
"''",
";",
"if",
"(",
"array_key_exists",
"(",
"'title'",
",",
"$",
"entry",
")",
")",
"{",
"$",
"title",
"=",
"$",
"this",
"->",
"_unwrap",
"(",
"$",
"entry",
"[",
"'title'",
"]",
")",
";",
"}",
"if",
"(",
"array_key_exists",
"(",
"'journal'",
",",
"$",
"entry",
")",
")",
"{",
"$",
"journal",
"=",
"$",
"this",
"->",
"_unwrap",
"(",
"$",
"entry",
"[",
"'journal'",
"]",
")",
";",
"}",
"if",
"(",
"array_key_exists",
"(",
"'year'",
",",
"$",
"entry",
")",
")",
"{",
"$",
"year",
"=",
"$",
"this",
"->",
"_unwrap",
"(",
"$",
"entry",
"[",
"'year'",
"]",
")",
";",
"}",
"if",
"(",
"array_key_exists",
"(",
"'author'",
",",
"$",
"entry",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_options",
"[",
"'extractAuthors'",
"]",
")",
"{",
"$",
"tmparray",
"=",
"array",
"(",
")",
";",
"//In this array the authors are saved and the joind with an and",
"foreach",
"(",
"$",
"entry",
"[",
"'author'",
"]",
"as",
"$",
"authorentry",
")",
"{",
"$",
"tmparray",
"[",
"]",
"=",
"$",
"this",
"->",
"_formatAuthor",
"(",
"$",
"authorentry",
")",
";",
"}",
"$",
"authors",
"=",
"join",
"(",
"', '",
",",
"$",
"tmparray",
")",
";",
"}",
"else",
"{",
"$",
"authors",
"=",
"$",
"entry",
"[",
"'author'",
"]",
";",
"}",
"}",
"if",
"(",
"(",
"''",
"!=",
"$",
"title",
")",
"||",
"(",
"''",
"!=",
"$",
"journal",
")",
"||",
"(",
"''",
"!=",
"$",
"year",
")",
"||",
"(",
"''",
"!=",
"$",
"authors",
")",
")",
"{",
"$",
"line",
"=",
"str_replace",
"(",
"\"TITLE\"",
",",
"$",
"title",
",",
"$",
"line",
")",
";",
"$",
"line",
"=",
"str_replace",
"(",
"\"JOURNAL\"",
",",
"$",
"journal",
",",
"$",
"line",
")",
";",
"$",
"line",
"=",
"str_replace",
"(",
"\"YEAR\"",
",",
"$",
"year",
",",
"$",
"line",
")",
";",
"$",
"line",
"=",
"str_replace",
"(",
"\"AUTHORS\"",
",",
"$",
"authors",
",",
"$",
"line",
")",
";",
"$",
"line",
".=",
"\"\\n\\\\par\\n\"",
";",
"$",
"ret",
".=",
"$",
"line",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"_generateWarning",
"(",
"'WARNING_LINE_WAS_NOT_CONVERTED'",
",",
"''",
",",
"print_r",
"(",
"$",
"entry",
",",
"1",
")",
")",
";",
"}",
"}",
"$",
"ret",
".=",
"'}'",
";",
"return",
"$",
"ret",
";",
"}"
] | Returns the stored data in RTF format
This method simply returns a RTF formatted string. This is done very
simple and is not intended for heavy using and fine formatting. This
should be done by BibTex! It is intended to give some kind of quick
preview or to send someone a reference list as word/rtf format (even
some people in the scientific field still use word). If you want to
change the default format you have to override the class variable
"rtfstring". This variable is used and the placeholders simply replaced.
Lines with no data cause an warning!
@return string the RTF Strings | [
"Returns",
"the",
"stored",
"data",
"in",
"RTF",
"format"
] | train | https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L1063-L1105 |
academic/VipaBibTexBundle | Helper/Bibtex.php | Bibtex._escape_tex | function _escape_tex($tex)
{
$tex = str_replace("\\", "\\\\", $tex);
$tex = str_replace('#', '\#', $tex);
$tex = str_replace('$', '\$', $tex);
$tex = str_replace('%', '\%', $tex);
$tex = str_replace('^', '\^', $tex);
$tex = str_replace('&', '\&', $tex);
$tex = str_replace('_', '\_', $tex);
$tex = str_replace('{', '\{', $tex);
$tex = str_replace('}', '\}', $tex);
return ($tex);
} | php | function _escape_tex($tex)
{
$tex = str_replace("\\", "\\\\", $tex);
$tex = str_replace('#', '\#', $tex);
$tex = str_replace('$', '\$', $tex);
$tex = str_replace('%', '\%', $tex);
$tex = str_replace('^', '\^', $tex);
$tex = str_replace('&', '\&', $tex);
$tex = str_replace('_', '\_', $tex);
$tex = str_replace('{', '\{', $tex);
$tex = str_replace('}', '\}', $tex);
return ($tex);
} | [
"function",
"_escape_tex",
"(",
"$",
"tex",
")",
"{",
"$",
"tex",
"=",
"str_replace",
"(",
"\"\\\\\"",
",",
"\"\\\\\\\\\"",
",",
"$",
"tex",
")",
";",
"$",
"tex",
"=",
"str_replace",
"(",
"'#'",
",",
"'\\#'",
",",
"$",
"tex",
")",
";",
"$",
"tex",
"=",
"str_replace",
"(",
"'$'",
",",
"'\\$'",
",",
"$",
"tex",
")",
";",
"$",
"tex",
"=",
"str_replace",
"(",
"'%'",
",",
"'\\%'",
",",
"$",
"tex",
")",
";",
"$",
"tex",
"=",
"str_replace",
"(",
"'^'",
",",
"'\\^'",
",",
"$",
"tex",
")",
";",
"$",
"tex",
"=",
"str_replace",
"(",
"'&'",
",",
"'\\&'",
",",
"$",
"tex",
")",
";",
"$",
"tex",
"=",
"str_replace",
"(",
"'_'",
",",
"'\\_'",
",",
"$",
"tex",
")",
";",
"$",
"tex",
"=",
"str_replace",
"(",
"'{'",
",",
"'\\{'",
",",
"$",
"tex",
")",
";",
"$",
"tex",
"=",
"str_replace",
"(",
"'}'",
",",
"'\\}'",
",",
"$",
"tex",
")",
";",
"return",
"(",
"$",
"tex",
")",
";",
"}"
] | Returns a string with special TeX characters escaped.
This method is to be used with any method which is exporting TeX, such
as the bibTex method. A series of string replace operations are
performed on the input string, and the escaped string is returned.
This code is taken from the Text_Wiki Pear package.
@author Jeremy Cowgar <[email protected]>
@access private
@param string $txt the TeX string
@return string the escaped TeX string | [
"Returns",
"a",
"string",
"with",
"special",
"TeX",
"characters",
"escaped",
"."
] | train | https://github.com/academic/VipaBibTexBundle/blob/1cd82b0961e1a9fee804a85fd774d1384c3e089b/Helper/Bibtex.php#L1179-L1191 |
mustardandrew/muan-laravel-acl | src/Middleware/PermissionMiddleware.php | PermissionMiddleware.handle | public function handle($request, Closure $next, $permission)
{
if (! $user = $request->user()) {
abort(403, "Access denied!");
}
if (! $user->can($permission)) {
abort(403, "Access denied!");
}
return $next($request);
} | php | public function handle($request, Closure $next, $permission)
{
if (! $user = $request->user()) {
abort(403, "Access denied!");
}
if (! $user->can($permission)) {
abort(403, "Access denied!");
}
return $next($request);
} | [
"public",
"function",
"handle",
"(",
"$",
"request",
",",
"Closure",
"$",
"next",
",",
"$",
"permission",
")",
"{",
"if",
"(",
"!",
"$",
"user",
"=",
"$",
"request",
"->",
"user",
"(",
")",
")",
"{",
"abort",
"(",
"403",
",",
"\"Access denied!\"",
")",
";",
"}",
"if",
"(",
"!",
"$",
"user",
"->",
"can",
"(",
"$",
"permission",
")",
")",
"{",
"abort",
"(",
"403",
",",
"\"Access denied!\"",
")",
";",
"}",
"return",
"$",
"next",
"(",
"$",
"request",
")",
";",
"}"
] | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@param string $role
@return mixed | [
"Handle",
"an",
"incoming",
"request",
"."
] | train | https://github.com/mustardandrew/muan-laravel-acl/blob/b5f23340b5536babb98d9fd0d727a7a3371c97d5/src/Middleware/PermissionMiddleware.php#L23-L34 |
zicht/z | src/Zicht/Tool/Script/Tokenizer.php | Tokenizer.getTokens | public function getTokens($string, &$needle = 0)
{
$exprTokenizer = new ExpressionTokenizer();
$ret = array();
$depth = 0;
$needle = 0;
$len = strlen($string);
while ($needle < $len) {
$before = $needle;
$substr = substr($string, $needle);
if ($depth === 0) {
// match either '$(' or '@(' and mark that as an EXPR_START token.
if (preg_match('/^([$@])\(/', $substr, $m)) {
$needle += strlen($m[0]);
$ret[] = new Token(Token::EXPR_START, $m[0]);
// record expression depth, to make sure the usage of parentheses inside the expression doesn't
// break tokenization (e.g. '$( ("foo") )'
$depth++;
} else {
// store the current token in a temp var for appending, in case it's a DATA token
$token = end($ret);
// handle escaping of the $( syntax, '$$(' becomes '$('
if (preg_match('/^\$\$\(/', $substr, $m)) {
$value = substr($m[0], 1);
$needle += strlen($m[0]);
} else {
$value = $string{$needle};
$needle += strlen($value);
}
// if the current token is DATA, and the previous token is DATA, append the value to the previous
// and ignore the current.
if ($token && $token->match(Token::DATA)) {
$token->value .= $value;
unset($token);
} else {
$ret[] = new Token(Token::DATA, $value);
}
}
} else {
$ret = array_merge($ret, $exprTokenizer->getTokens($string, $needle));
$depth = 0;
}
if ($before === $needle) {
// safety net.
throw new \UnexpectedValueException(
"Unexpected input near token {$string{$needle}}, unsupported character"
);
}
}
return $ret;
} | php | public function getTokens($string, &$needle = 0)
{
$exprTokenizer = new ExpressionTokenizer();
$ret = array();
$depth = 0;
$needle = 0;
$len = strlen($string);
while ($needle < $len) {
$before = $needle;
$substr = substr($string, $needle);
if ($depth === 0) {
// match either '$(' or '@(' and mark that as an EXPR_START token.
if (preg_match('/^([$@])\(/', $substr, $m)) {
$needle += strlen($m[0]);
$ret[] = new Token(Token::EXPR_START, $m[0]);
// record expression depth, to make sure the usage of parentheses inside the expression doesn't
// break tokenization (e.g. '$( ("foo") )'
$depth++;
} else {
// store the current token in a temp var for appending, in case it's a DATA token
$token = end($ret);
// handle escaping of the $( syntax, '$$(' becomes '$('
if (preg_match('/^\$\$\(/', $substr, $m)) {
$value = substr($m[0], 1);
$needle += strlen($m[0]);
} else {
$value = $string{$needle};
$needle += strlen($value);
}
// if the current token is DATA, and the previous token is DATA, append the value to the previous
// and ignore the current.
if ($token && $token->match(Token::DATA)) {
$token->value .= $value;
unset($token);
} else {
$ret[] = new Token(Token::DATA, $value);
}
}
} else {
$ret = array_merge($ret, $exprTokenizer->getTokens($string, $needle));
$depth = 0;
}
if ($before === $needle) {
// safety net.
throw new \UnexpectedValueException(
"Unexpected input near token {$string{$needle}}, unsupported character"
);
}
}
return $ret;
} | [
"public",
"function",
"getTokens",
"(",
"$",
"string",
",",
"&",
"$",
"needle",
"=",
"0",
")",
"{",
"$",
"exprTokenizer",
"=",
"new",
"ExpressionTokenizer",
"(",
")",
";",
"$",
"ret",
"=",
"array",
"(",
")",
";",
"$",
"depth",
"=",
"0",
";",
"$",
"needle",
"=",
"0",
";",
"$",
"len",
"=",
"strlen",
"(",
"$",
"string",
")",
";",
"while",
"(",
"$",
"needle",
"<",
"$",
"len",
")",
"{",
"$",
"before",
"=",
"$",
"needle",
";",
"$",
"substr",
"=",
"substr",
"(",
"$",
"string",
",",
"$",
"needle",
")",
";",
"if",
"(",
"$",
"depth",
"===",
"0",
")",
"{",
"// match either '$(' or '@(' and mark that as an EXPR_START token.",
"if",
"(",
"preg_match",
"(",
"'/^([$@])\\(/'",
",",
"$",
"substr",
",",
"$",
"m",
")",
")",
"{",
"$",
"needle",
"+=",
"strlen",
"(",
"$",
"m",
"[",
"0",
"]",
")",
";",
"$",
"ret",
"[",
"]",
"=",
"new",
"Token",
"(",
"Token",
"::",
"EXPR_START",
",",
"$",
"m",
"[",
"0",
"]",
")",
";",
"// record expression depth, to make sure the usage of parentheses inside the expression doesn't",
"// break tokenization (e.g. '$( (\"foo\") )'",
"$",
"depth",
"++",
";",
"}",
"else",
"{",
"// store the current token in a temp var for appending, in case it's a DATA token",
"$",
"token",
"=",
"end",
"(",
"$",
"ret",
")",
";",
"// handle escaping of the $( syntax, '$$(' becomes '$('",
"if",
"(",
"preg_match",
"(",
"'/^\\$\\$\\(/'",
",",
"$",
"substr",
",",
"$",
"m",
")",
")",
"{",
"$",
"value",
"=",
"substr",
"(",
"$",
"m",
"[",
"0",
"]",
",",
"1",
")",
";",
"$",
"needle",
"+=",
"strlen",
"(",
"$",
"m",
"[",
"0",
"]",
")",
";",
"}",
"else",
"{",
"$",
"value",
"=",
"$",
"string",
"{",
"$",
"needle",
"}",
";",
"$",
"needle",
"+=",
"strlen",
"(",
"$",
"value",
")",
";",
"}",
"// if the current token is DATA, and the previous token is DATA, append the value to the previous",
"// and ignore the current.",
"if",
"(",
"$",
"token",
"&&",
"$",
"token",
"->",
"match",
"(",
"Token",
"::",
"DATA",
")",
")",
"{",
"$",
"token",
"->",
"value",
".=",
"$",
"value",
";",
"unset",
"(",
"$",
"token",
")",
";",
"}",
"else",
"{",
"$",
"ret",
"[",
"]",
"=",
"new",
"Token",
"(",
"Token",
"::",
"DATA",
",",
"$",
"value",
")",
";",
"}",
"}",
"}",
"else",
"{",
"$",
"ret",
"=",
"array_merge",
"(",
"$",
"ret",
",",
"$",
"exprTokenizer",
"->",
"getTokens",
"(",
"$",
"string",
",",
"$",
"needle",
")",
")",
";",
"$",
"depth",
"=",
"0",
";",
"}",
"if",
"(",
"$",
"before",
"===",
"$",
"needle",
")",
"{",
"// safety net.",
"throw",
"new",
"\\",
"UnexpectedValueException",
"(",
"\"Unexpected input near token {$string{$needle}}, unsupported character\"",
")",
";",
"}",
"}",
"return",
"$",
"ret",
";",
"}"
] | Returns an array of tokens
@param string $string
@param int &$needle
@throws \UnexpectedValueException
@return array | [
"Returns",
"an",
"array",
"of",
"tokens"
] | train | https://github.com/zicht/z/blob/6a1731dad20b018555a96b726a61d4bf8ec8c886/src/Zicht/Tool/Script/Tokenizer.php#L34-L87 |
PeeHaa/AsyncTwitter | src/Api/Client/Client.php | Client.throwFromErrorResponse | private function throwFromErrorResponse(HttpResponse $response, array $body)
{
list($message, $code, $extra) = $this->getErrorStringFromResponseBody($body);
$exceptions = [
400 => BadRequest::class,
401 => Unauthorized::class,
403 => Forbidden::class,
404 => NotFound::class,
406 => NotAcceptable::class,
410 => Gone::class,
420 => RateLimitTriggered::class,
422 => UnprocessableEntity::class,
429 => RateLimitTriggered::class,
500 => ServerError::class,
502 => BadGateway::class,
503 => ServiceUnavailable::class,
504 => GatewayTimeout::class,
];
if (!array_key_exists($response->getStatus(), $exceptions)) {
return;
}
throw new $exceptions[$response->getStatus()]($message, $code, null, $extra);
} | php | private function throwFromErrorResponse(HttpResponse $response, array $body)
{
list($message, $code, $extra) = $this->getErrorStringFromResponseBody($body);
$exceptions = [
400 => BadRequest::class,
401 => Unauthorized::class,
403 => Forbidden::class,
404 => NotFound::class,
406 => NotAcceptable::class,
410 => Gone::class,
420 => RateLimitTriggered::class,
422 => UnprocessableEntity::class,
429 => RateLimitTriggered::class,
500 => ServerError::class,
502 => BadGateway::class,
503 => ServiceUnavailable::class,
504 => GatewayTimeout::class,
];
if (!array_key_exists($response->getStatus(), $exceptions)) {
return;
}
throw new $exceptions[$response->getStatus()]($message, $code, null, $extra);
} | [
"private",
"function",
"throwFromErrorResponse",
"(",
"HttpResponse",
"$",
"response",
",",
"array",
"$",
"body",
")",
"{",
"list",
"(",
"$",
"message",
",",
"$",
"code",
",",
"$",
"extra",
")",
"=",
"$",
"this",
"->",
"getErrorStringFromResponseBody",
"(",
"$",
"body",
")",
";",
"$",
"exceptions",
"=",
"[",
"400",
"=>",
"BadRequest",
"::",
"class",
",",
"401",
"=>",
"Unauthorized",
"::",
"class",
",",
"403",
"=>",
"Forbidden",
"::",
"class",
",",
"404",
"=>",
"NotFound",
"::",
"class",
",",
"406",
"=>",
"NotAcceptable",
"::",
"class",
",",
"410",
"=>",
"Gone",
"::",
"class",
",",
"420",
"=>",
"RateLimitTriggered",
"::",
"class",
",",
"422",
"=>",
"UnprocessableEntity",
"::",
"class",
",",
"429",
"=>",
"RateLimitTriggered",
"::",
"class",
",",
"500",
"=>",
"ServerError",
"::",
"class",
",",
"502",
"=>",
"BadGateway",
"::",
"class",
",",
"503",
"=>",
"ServiceUnavailable",
"::",
"class",
",",
"504",
"=>",
"GatewayTimeout",
"::",
"class",
",",
"]",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"response",
"->",
"getStatus",
"(",
")",
",",
"$",
"exceptions",
")",
")",
"{",
"return",
";",
"}",
"throw",
"new",
"$",
"exceptions",
"[",
"$",
"response",
"->",
"getStatus",
"(",
")",
"]",
"(",
"$",
"message",
",",
"$",
"code",
",",
"null",
",",
"$",
"extra",
")",
";",
"}"
] | https://dev.twitter.com/overview/api/response-codes | [
"https",
":",
"//",
"dev",
".",
"twitter",
".",
"com",
"/",
"overview",
"/",
"api",
"/",
"response",
"-",
"codes"
] | train | https://github.com/PeeHaa/AsyncTwitter/blob/a968909e7ed470bd87a0f25ef0c494338273c29c/src/Api/Client/Client.php#L108-L133 |
mergado/mergado-api-client-php | src/mergadoclient/UrlBuilder.php | UrlBuilder.resetUrl | public function resetUrl()
{
if ($this->mode == 'dev') {
$this->url = static::BASEURL_DEV;
} else if ($this->mode == 'local') {
$this->url = static::BASEURL_LOCAL;
} else {
$this->url = static::BASEURL;
}
} | php | public function resetUrl()
{
if ($this->mode == 'dev') {
$this->url = static::BASEURL_DEV;
} else if ($this->mode == 'local') {
$this->url = static::BASEURL_LOCAL;
} else {
$this->url = static::BASEURL;
}
} | [
"public",
"function",
"resetUrl",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"mode",
"==",
"'dev'",
")",
"{",
"$",
"this",
"->",
"url",
"=",
"static",
"::",
"BASEURL_DEV",
";",
"}",
"else",
"if",
"(",
"$",
"this",
"->",
"mode",
"==",
"'local'",
")",
"{",
"$",
"this",
"->",
"url",
"=",
"static",
"::",
"BASEURL_LOCAL",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"url",
"=",
"static",
"::",
"BASEURL",
";",
"}",
"}"
] | Sets $this->url to base | [
"Sets",
"$this",
"-",
">",
"url",
"to",
"base"
] | train | https://github.com/mergado/mergado-api-client-php/blob/6c13b994a81bf5a3d6f3f791ea1dfbe2c420565f/src/mergadoclient/UrlBuilder.php#L55-L66 |
AOEpeople/Aoe_Layout | app/code/local/Aoe/Layout/Controller/Model.php | Aoe_Layout_Controller_Model.indexAction | public function indexAction()
{
if ($this->getRequest()->isAjax()) {
try {
$this->loadLayout(null, false, false);
$this->getLayout()->getUpdate()->setCacheId(null);
$this->getLayout()->getUpdate()->addHandle(strtolower($this->getFullActionName()) . '_AJAX');
} catch (Exception $e) {
Mage::logException($e);
$this->getResponse()->setHeader('Content-Type', 'application/json');
$this->getResponse()->setBody(Zend_Json::encode(['error' => true, 'message' => $e->getMessage()]));
}
}
$this->loadLayout();
$this->renderLayout();
} | php | public function indexAction()
{
if ($this->getRequest()->isAjax()) {
try {
$this->loadLayout(null, false, false);
$this->getLayout()->getUpdate()->setCacheId(null);
$this->getLayout()->getUpdate()->addHandle(strtolower($this->getFullActionName()) . '_AJAX');
} catch (Exception $e) {
Mage::logException($e);
$this->getResponse()->setHeader('Content-Type', 'application/json');
$this->getResponse()->setBody(Zend_Json::encode(['error' => true, 'message' => $e->getMessage()]));
}
}
$this->loadLayout();
$this->renderLayout();
} | [
"public",
"function",
"indexAction",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"isAjax",
"(",
")",
")",
"{",
"try",
"{",
"$",
"this",
"->",
"loadLayout",
"(",
"null",
",",
"false",
",",
"false",
")",
";",
"$",
"this",
"->",
"getLayout",
"(",
")",
"->",
"getUpdate",
"(",
")",
"->",
"setCacheId",
"(",
"null",
")",
";",
"$",
"this",
"->",
"getLayout",
"(",
")",
"->",
"getUpdate",
"(",
")",
"->",
"addHandle",
"(",
"strtolower",
"(",
"$",
"this",
"->",
"getFullActionName",
"(",
")",
")",
".",
"'_AJAX'",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"Mage",
"::",
"logException",
"(",
"$",
"e",
")",
";",
"$",
"this",
"->",
"getResponse",
"(",
")",
"->",
"setHeader",
"(",
"'Content-Type'",
",",
"'application/json'",
")",
";",
"$",
"this",
"->",
"getResponse",
"(",
")",
"->",
"setBody",
"(",
"Zend_Json",
"::",
"encode",
"(",
"[",
"'error'",
"=>",
"true",
",",
"'message'",
"=>",
"$",
"e",
"->",
"getMessage",
"(",
")",
"]",
")",
")",
";",
"}",
"}",
"$",
"this",
"->",
"loadLayout",
"(",
")",
";",
"$",
"this",
"->",
"renderLayout",
"(",
")",
";",
"}"
] | List existing records via a grid | [
"List",
"existing",
"records",
"via",
"a",
"grid"
] | train | https://github.com/AOEpeople/Aoe_Layout/blob/d88ba3406cf12dbaf09548477133c3cb27d155ed/app/code/local/Aoe/Layout/Controller/Model.php#L8-L24 |
AOEpeople/Aoe_Layout | app/code/local/Aoe/Layout/Controller/Model.php | Aoe_Layout_Controller_Model.viewAction | public function viewAction()
{
$model = $this->loadModel();
if (!$model->getId()) {
$this->_forward('noroute');
return;
}
$this->loadLayout();
$this->renderLayout();
} | php | public function viewAction()
{
$model = $this->loadModel();
if (!$model->getId()) {
$this->_forward('noroute');
return;
}
$this->loadLayout();
$this->renderLayout();
} | [
"public",
"function",
"viewAction",
"(",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"loadModel",
"(",
")",
";",
"if",
"(",
"!",
"$",
"model",
"->",
"getId",
"(",
")",
")",
"{",
"$",
"this",
"->",
"_forward",
"(",
"'noroute'",
")",
";",
"return",
";",
"}",
"$",
"this",
"->",
"loadLayout",
"(",
")",
";",
"$",
"this",
"->",
"renderLayout",
"(",
")",
";",
"}"
] | View existing record | [
"View",
"existing",
"record"
] | train | https://github.com/AOEpeople/Aoe_Layout/blob/d88ba3406cf12dbaf09548477133c3cb27d155ed/app/code/local/Aoe/Layout/Controller/Model.php#L29-L39 |
php-lug/lug | src/Bundle/ResourceBundle/DependencyInjection/Compiler/AbstractRegisterGenericDomainListenerPass.php | AbstractRegisterGenericDomainListenerPass.process | public function process(ContainerBuilder $container)
{
$flashListener = $container->getDefinition($this->listener);
$controllers = $container->findTaggedServiceIds($tag = 'lug.controller');
foreach ($controllers as $controller => $attributes) {
foreach ($attributes as $attribute) {
if (!isset($attribute[$alias = 'resource'])) {
throw new TagAttributeNotFoundException(sprintf(
'The attribute "%s" could not be found for the tag "%s" on the "%s" service.',
$alias,
$tag,
$controller
));
}
foreach ($this->actions as $action) {
foreach ($this->prefixes as $prefix) {
$flashListener->addTag('lug.resource.domain.event_listener', array_merge([
'event' => 'lug.'.$attribute['resource'].'.'.$prefix.'_'.$action,
], $this->event));
}
}
}
}
} | php | public function process(ContainerBuilder $container)
{
$flashListener = $container->getDefinition($this->listener);
$controllers = $container->findTaggedServiceIds($tag = 'lug.controller');
foreach ($controllers as $controller => $attributes) {
foreach ($attributes as $attribute) {
if (!isset($attribute[$alias = 'resource'])) {
throw new TagAttributeNotFoundException(sprintf(
'The attribute "%s" could not be found for the tag "%s" on the "%s" service.',
$alias,
$tag,
$controller
));
}
foreach ($this->actions as $action) {
foreach ($this->prefixes as $prefix) {
$flashListener->addTag('lug.resource.domain.event_listener', array_merge([
'event' => 'lug.'.$attribute['resource'].'.'.$prefix.'_'.$action,
], $this->event));
}
}
}
}
} | [
"public",
"function",
"process",
"(",
"ContainerBuilder",
"$",
"container",
")",
"{",
"$",
"flashListener",
"=",
"$",
"container",
"->",
"getDefinition",
"(",
"$",
"this",
"->",
"listener",
")",
";",
"$",
"controllers",
"=",
"$",
"container",
"->",
"findTaggedServiceIds",
"(",
"$",
"tag",
"=",
"'lug.controller'",
")",
";",
"foreach",
"(",
"$",
"controllers",
"as",
"$",
"controller",
"=>",
"$",
"attributes",
")",
"{",
"foreach",
"(",
"$",
"attributes",
"as",
"$",
"attribute",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"attribute",
"[",
"$",
"alias",
"=",
"'resource'",
"]",
")",
")",
"{",
"throw",
"new",
"TagAttributeNotFoundException",
"(",
"sprintf",
"(",
"'The attribute \"%s\" could not be found for the tag \"%s\" on the \"%s\" service.'",
",",
"$",
"alias",
",",
"$",
"tag",
",",
"$",
"controller",
")",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"actions",
"as",
"$",
"action",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"prefixes",
"as",
"$",
"prefix",
")",
"{",
"$",
"flashListener",
"->",
"addTag",
"(",
"'lug.resource.domain.event_listener'",
",",
"array_merge",
"(",
"[",
"'event'",
"=>",
"'lug.'",
".",
"$",
"attribute",
"[",
"'resource'",
"]",
".",
"'.'",
".",
"$",
"prefix",
".",
"'_'",
".",
"$",
"action",
",",
"]",
",",
"$",
"this",
"->",
"event",
")",
")",
";",
"}",
"}",
"}",
"}",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/php-lug/lug/blob/81c109f187eba0a60f17e8cc59984ebb31841db7/src/Bundle/ResourceBundle/DependencyInjection/Compiler/AbstractRegisterGenericDomainListenerPass.php#L62-L87 |
simialbi/yii2-simialbi-base | i18n/TranslationTrait.php | TranslationTrait.registerTranslations | public function registerTranslations() {
$reflector = new \ReflectionClass(static::class);
$dir = rtrim(dirname($reflector->getFileName()), '\\/');
$dir = rtrim(preg_replace('#widgets$#', '', $dir), '\\/') . DIRECTORY_SEPARATOR . 'messages';
$category = str_replace(StringHelper::basename(static::class), '', static::class);
$category = rtrim(str_replace(['\\', 'yii2/', 'widgets', 'models'], ['/', ''], $category), '/') . '*';
if (!is_dir($dir)) {
return;
}
Yii::$app->i18n->translations[$category] = [
'class' => 'yii\i18n\GettextMessageSource',
'sourceLanguage' => 'en-US',
'basePath' => $dir,
'forceTranslation' => true
];
} | php | public function registerTranslations() {
$reflector = new \ReflectionClass(static::class);
$dir = rtrim(dirname($reflector->getFileName()), '\\/');
$dir = rtrim(preg_replace('#widgets$#', '', $dir), '\\/') . DIRECTORY_SEPARATOR . 'messages';
$category = str_replace(StringHelper::basename(static::class), '', static::class);
$category = rtrim(str_replace(['\\', 'yii2/', 'widgets', 'models'], ['/', ''], $category), '/') . '*';
if (!is_dir($dir)) {
return;
}
Yii::$app->i18n->translations[$category] = [
'class' => 'yii\i18n\GettextMessageSource',
'sourceLanguage' => 'en-US',
'basePath' => $dir,
'forceTranslation' => true
];
} | [
"public",
"function",
"registerTranslations",
"(",
")",
"{",
"$",
"reflector",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"static",
"::",
"class",
")",
";",
"$",
"dir",
"=",
"rtrim",
"(",
"dirname",
"(",
"$",
"reflector",
"->",
"getFileName",
"(",
")",
")",
",",
"'\\\\/'",
")",
";",
"$",
"dir",
"=",
"rtrim",
"(",
"preg_replace",
"(",
"'#widgets$#'",
",",
"''",
",",
"$",
"dir",
")",
",",
"'\\\\/'",
")",
".",
"DIRECTORY_SEPARATOR",
".",
"'messages'",
";",
"$",
"category",
"=",
"str_replace",
"(",
"StringHelper",
"::",
"basename",
"(",
"static",
"::",
"class",
")",
",",
"''",
",",
"static",
"::",
"class",
")",
";",
"$",
"category",
"=",
"rtrim",
"(",
"str_replace",
"(",
"[",
"'\\\\'",
",",
"'yii2/'",
",",
"'widgets'",
",",
"'models'",
"]",
",",
"[",
"'/'",
",",
"''",
"]",
",",
"$",
"category",
")",
",",
"'/'",
")",
".",
"'*'",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"dir",
")",
")",
"{",
"return",
";",
"}",
"Yii",
"::",
"$",
"app",
"->",
"i18n",
"->",
"translations",
"[",
"$",
"category",
"]",
"=",
"[",
"'class'",
"=>",
"'yii\\i18n\\GettextMessageSource'",
",",
"'sourceLanguage'",
"=>",
"'en-US'",
",",
"'basePath'",
"=>",
"$",
"dir",
",",
"'forceTranslation'",
"=>",
"true",
"]",
";",
"}"
] | Init translations
@throws \ReflectionException | [
"Init",
"translations"
] | train | https://github.com/simialbi/yii2-simialbi-base/blob/f68d3ee64f52c6dfb0aa31ffc14f5ced5aabdbb7/i18n/TranslationTrait.php#L24-L41 |
WellCommerce/StandardEditionBundle | DataFixtures/ORM/LoadOrderStatusData.php | LoadOrderStatusData.load | public function load(ObjectManager $manager)
{
if (!$this->isEnabled()) {
return;
}
foreach ($this->getStatuses() as $key => $sample) {
$status = new OrderStatus();
$status->setEnabled(1);
$status->setOrderStatusGroup($this->getReference($sample['order_status_group_reference']));
foreach ($this->getLocales() as $locale) {
$status->translate($locale->getCode())->setName($sample['name']);
$status->translate($locale->getCode())->setDefaultComment($sample['default_comment']);
}
$status->mergeNewTranslations();
$manager->persist($status);
$this->setReference('order_status_' . $key, $status);
}
$manager->flush();
} | php | public function load(ObjectManager $manager)
{
if (!$this->isEnabled()) {
return;
}
foreach ($this->getStatuses() as $key => $sample) {
$status = new OrderStatus();
$status->setEnabled(1);
$status->setOrderStatusGroup($this->getReference($sample['order_status_group_reference']));
foreach ($this->getLocales() as $locale) {
$status->translate($locale->getCode())->setName($sample['name']);
$status->translate($locale->getCode())->setDefaultComment($sample['default_comment']);
}
$status->mergeNewTranslations();
$manager->persist($status);
$this->setReference('order_status_' . $key, $status);
}
$manager->flush();
} | [
"public",
"function",
"load",
"(",
"ObjectManager",
"$",
"manager",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isEnabled",
"(",
")",
")",
"{",
"return",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"getStatuses",
"(",
")",
"as",
"$",
"key",
"=>",
"$",
"sample",
")",
"{",
"$",
"status",
"=",
"new",
"OrderStatus",
"(",
")",
";",
"$",
"status",
"->",
"setEnabled",
"(",
"1",
")",
";",
"$",
"status",
"->",
"setOrderStatusGroup",
"(",
"$",
"this",
"->",
"getReference",
"(",
"$",
"sample",
"[",
"'order_status_group_reference'",
"]",
")",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getLocales",
"(",
")",
"as",
"$",
"locale",
")",
"{",
"$",
"status",
"->",
"translate",
"(",
"$",
"locale",
"->",
"getCode",
"(",
")",
")",
"->",
"setName",
"(",
"$",
"sample",
"[",
"'name'",
"]",
")",
";",
"$",
"status",
"->",
"translate",
"(",
"$",
"locale",
"->",
"getCode",
"(",
")",
")",
"->",
"setDefaultComment",
"(",
"$",
"sample",
"[",
"'default_comment'",
"]",
")",
";",
"}",
"$",
"status",
"->",
"mergeNewTranslations",
"(",
")",
";",
"$",
"manager",
"->",
"persist",
"(",
"$",
"status",
")",
";",
"$",
"this",
"->",
"setReference",
"(",
"'order_status_'",
".",
"$",
"key",
",",
"$",
"status",
")",
";",
"}",
"$",
"manager",
"->",
"flush",
"(",
")",
";",
"}"
] | {@inheritDoc} | [
"{"
] | train | https://github.com/WellCommerce/StandardEditionBundle/blob/6367bd20bbb6bde37c710a6ba87ae72b5f05f61e/DataFixtures/ORM/LoadOrderStatusData.php#L30-L51 |
odiaseo/pagebuilder | src/PageBuilder/Util/Widget.php | Widget.init | public function init()
{
if ($this->isCacheEnabled() and file_exists(self::CACHE_LOCATION)) {
$store = include self::CACHE_LOCATION;
} else {
$store = [];
$finalList = [];
$config = $this->serviceManager->get('config');
$dirLocations = (array)$config['pagebuilder']['widgets']['paths'];
foreach ($dirLocations as $namespace => $dirLocation) {
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($dirLocation, \FilesystemIterator::SKIP_DOTS),
\RecursiveIteratorIterator::CHILD_FIRST
);
/** @var $splFileInfo \SplFileInfo */
foreach ($iterator as $splFileInfo) {
$ext = substr(basename($splFileInfo->getFilename()), -4);
if ($splFileInfo->isFile() and $ext == '.php') {
$widgetId = substr(basename($splFileInfo->getFilename()), 0, -4);
$className = substr(
$namespace . str_replace(
'/', "\\", str_replace($dirLocation, '', $splFileInfo->getPathname())
),
0, -4
);
$reflection = new \ReflectionClass($className);
if ($reflection->isInstantiable()
and $reflection->implementsInterface('PageBuilder\WidgetInterface')
) {
$attributes = $reflection->getDefaultProperties();
$id = !empty($attributes['id']) ? preg_replace(
'/[^a-z]/i', '',
$attributes['id']
)
: $widgetId;
$id = strtolower($id);
$category = basename(dirname($splFileInfo->getPathname()));
$data = [
'id' => $id,
'class' => $className,
'category' => ($category == 'Widget') ? 'General' : $category,
'title' => $attributes['name'] ?: $widgetId,
'description' => $attributes['description'] ?: 'No description found',
'options' => $attributes['options'],
];
$path = [$id => $data];
$store[0][$id] = $data;
} else {
continue;
}
} else {
$dirName = $splFileInfo->getFilename();
$path = [$dirName => []];
}
for ($depth = $iterator->getDepth() - 1; $depth >= 0; $depth--) {
$dirName = $iterator->getSubIterator($depth)->current()->getFilename();
$path = [$dirName => $path];
}
uasort(
$path,
function ($a, $b) {
return strcmp($a['title'], $b['title']);
}
);
$finalList = array_merge_recursive($finalList, $path);
}
}
$store[1] = $finalList;
if ($this->isCacheEnabled()) {
$data = '<?php return ' . var_export($store, true) . ' ;';
file_put_contents(self::CACHE_LOCATION, $data);
}
}
$this->dataStore = $store;
} | php | public function init()
{
if ($this->isCacheEnabled() and file_exists(self::CACHE_LOCATION)) {
$store = include self::CACHE_LOCATION;
} else {
$store = [];
$finalList = [];
$config = $this->serviceManager->get('config');
$dirLocations = (array)$config['pagebuilder']['widgets']['paths'];
foreach ($dirLocations as $namespace => $dirLocation) {
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($dirLocation, \FilesystemIterator::SKIP_DOTS),
\RecursiveIteratorIterator::CHILD_FIRST
);
/** @var $splFileInfo \SplFileInfo */
foreach ($iterator as $splFileInfo) {
$ext = substr(basename($splFileInfo->getFilename()), -4);
if ($splFileInfo->isFile() and $ext == '.php') {
$widgetId = substr(basename($splFileInfo->getFilename()), 0, -4);
$className = substr(
$namespace . str_replace(
'/', "\\", str_replace($dirLocation, '', $splFileInfo->getPathname())
),
0, -4
);
$reflection = new \ReflectionClass($className);
if ($reflection->isInstantiable()
and $reflection->implementsInterface('PageBuilder\WidgetInterface')
) {
$attributes = $reflection->getDefaultProperties();
$id = !empty($attributes['id']) ? preg_replace(
'/[^a-z]/i', '',
$attributes['id']
)
: $widgetId;
$id = strtolower($id);
$category = basename(dirname($splFileInfo->getPathname()));
$data = [
'id' => $id,
'class' => $className,
'category' => ($category == 'Widget') ? 'General' : $category,
'title' => $attributes['name'] ?: $widgetId,
'description' => $attributes['description'] ?: 'No description found',
'options' => $attributes['options'],
];
$path = [$id => $data];
$store[0][$id] = $data;
} else {
continue;
}
} else {
$dirName = $splFileInfo->getFilename();
$path = [$dirName => []];
}
for ($depth = $iterator->getDepth() - 1; $depth >= 0; $depth--) {
$dirName = $iterator->getSubIterator($depth)->current()->getFilename();
$path = [$dirName => $path];
}
uasort(
$path,
function ($a, $b) {
return strcmp($a['title'], $b['title']);
}
);
$finalList = array_merge_recursive($finalList, $path);
}
}
$store[1] = $finalList;
if ($this->isCacheEnabled()) {
$data = '<?php return ' . var_export($store, true) . ' ;';
file_put_contents(self::CACHE_LOCATION, $data);
}
}
$this->dataStore = $store;
} | [
"public",
"function",
"init",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isCacheEnabled",
"(",
")",
"and",
"file_exists",
"(",
"self",
"::",
"CACHE_LOCATION",
")",
")",
"{",
"$",
"store",
"=",
"include",
"self",
"::",
"CACHE_LOCATION",
";",
"}",
"else",
"{",
"$",
"store",
"=",
"[",
"]",
";",
"$",
"finalList",
"=",
"[",
"]",
";",
"$",
"config",
"=",
"$",
"this",
"->",
"serviceManager",
"->",
"get",
"(",
"'config'",
")",
";",
"$",
"dirLocations",
"=",
"(",
"array",
")",
"$",
"config",
"[",
"'pagebuilder'",
"]",
"[",
"'widgets'",
"]",
"[",
"'paths'",
"]",
";",
"foreach",
"(",
"$",
"dirLocations",
"as",
"$",
"namespace",
"=>",
"$",
"dirLocation",
")",
"{",
"$",
"iterator",
"=",
"new",
"\\",
"RecursiveIteratorIterator",
"(",
"new",
"\\",
"RecursiveDirectoryIterator",
"(",
"$",
"dirLocation",
",",
"\\",
"FilesystemIterator",
"::",
"SKIP_DOTS",
")",
",",
"\\",
"RecursiveIteratorIterator",
"::",
"CHILD_FIRST",
")",
";",
"/** @var $splFileInfo \\SplFileInfo */",
"foreach",
"(",
"$",
"iterator",
"as",
"$",
"splFileInfo",
")",
"{",
"$",
"ext",
"=",
"substr",
"(",
"basename",
"(",
"$",
"splFileInfo",
"->",
"getFilename",
"(",
")",
")",
",",
"-",
"4",
")",
";",
"if",
"(",
"$",
"splFileInfo",
"->",
"isFile",
"(",
")",
"and",
"$",
"ext",
"==",
"'.php'",
")",
"{",
"$",
"widgetId",
"=",
"substr",
"(",
"basename",
"(",
"$",
"splFileInfo",
"->",
"getFilename",
"(",
")",
")",
",",
"0",
",",
"-",
"4",
")",
";",
"$",
"className",
"=",
"substr",
"(",
"$",
"namespace",
".",
"str_replace",
"(",
"'/'",
",",
"\"\\\\\"",
",",
"str_replace",
"(",
"$",
"dirLocation",
",",
"''",
",",
"$",
"splFileInfo",
"->",
"getPathname",
"(",
")",
")",
")",
",",
"0",
",",
"-",
"4",
")",
";",
"$",
"reflection",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"className",
")",
";",
"if",
"(",
"$",
"reflection",
"->",
"isInstantiable",
"(",
")",
"and",
"$",
"reflection",
"->",
"implementsInterface",
"(",
"'PageBuilder\\WidgetInterface'",
")",
")",
"{",
"$",
"attributes",
"=",
"$",
"reflection",
"->",
"getDefaultProperties",
"(",
")",
";",
"$",
"id",
"=",
"!",
"empty",
"(",
"$",
"attributes",
"[",
"'id'",
"]",
")",
"?",
"preg_replace",
"(",
"'/[^a-z]/i'",
",",
"''",
",",
"$",
"attributes",
"[",
"'id'",
"]",
")",
":",
"$",
"widgetId",
";",
"$",
"id",
"=",
"strtolower",
"(",
"$",
"id",
")",
";",
"$",
"category",
"=",
"basename",
"(",
"dirname",
"(",
"$",
"splFileInfo",
"->",
"getPathname",
"(",
")",
")",
")",
";",
"$",
"data",
"=",
"[",
"'id'",
"=>",
"$",
"id",
",",
"'class'",
"=>",
"$",
"className",
",",
"'category'",
"=>",
"(",
"$",
"category",
"==",
"'Widget'",
")",
"?",
"'General'",
":",
"$",
"category",
",",
"'title'",
"=>",
"$",
"attributes",
"[",
"'name'",
"]",
"?",
":",
"$",
"widgetId",
",",
"'description'",
"=>",
"$",
"attributes",
"[",
"'description'",
"]",
"?",
":",
"'No description found'",
",",
"'options'",
"=>",
"$",
"attributes",
"[",
"'options'",
"]",
",",
"]",
";",
"$",
"path",
"=",
"[",
"$",
"id",
"=>",
"$",
"data",
"]",
";",
"$",
"store",
"[",
"0",
"]",
"[",
"$",
"id",
"]",
"=",
"$",
"data",
";",
"}",
"else",
"{",
"continue",
";",
"}",
"}",
"else",
"{",
"$",
"dirName",
"=",
"$",
"splFileInfo",
"->",
"getFilename",
"(",
")",
";",
"$",
"path",
"=",
"[",
"$",
"dirName",
"=>",
"[",
"]",
"]",
";",
"}",
"for",
"(",
"$",
"depth",
"=",
"$",
"iterator",
"->",
"getDepth",
"(",
")",
"-",
"1",
";",
"$",
"depth",
">=",
"0",
";",
"$",
"depth",
"--",
")",
"{",
"$",
"dirName",
"=",
"$",
"iterator",
"->",
"getSubIterator",
"(",
"$",
"depth",
")",
"->",
"current",
"(",
")",
"->",
"getFilename",
"(",
")",
";",
"$",
"path",
"=",
"[",
"$",
"dirName",
"=>",
"$",
"path",
"]",
";",
"}",
"uasort",
"(",
"$",
"path",
",",
"function",
"(",
"$",
"a",
",",
"$",
"b",
")",
"{",
"return",
"strcmp",
"(",
"$",
"a",
"[",
"'title'",
"]",
",",
"$",
"b",
"[",
"'title'",
"]",
")",
";",
"}",
")",
";",
"$",
"finalList",
"=",
"array_merge_recursive",
"(",
"$",
"finalList",
",",
"$",
"path",
")",
";",
"}",
"}",
"$",
"store",
"[",
"1",
"]",
"=",
"$",
"finalList",
";",
"if",
"(",
"$",
"this",
"->",
"isCacheEnabled",
"(",
")",
")",
"{",
"$",
"data",
"=",
"'<?php return '",
".",
"var_export",
"(",
"$",
"store",
",",
"true",
")",
".",
"' ;'",
";",
"file_put_contents",
"(",
"self",
"::",
"CACHE_LOCATION",
",",
"$",
"data",
")",
";",
"}",
"}",
"$",
"this",
"->",
"dataStore",
"=",
"$",
"store",
";",
"}"
] | Gets lists of available widgets
@return array | [
"Gets",
"lists",
"of",
"available",
"widgets"
] | train | https://github.com/odiaseo/pagebuilder/blob/88ef7cccf305368561307efe4ca07fac8e5774f3/src/PageBuilder/Util/Widget.php#L48-L134 |
odiaseo/pagebuilder | src/PageBuilder/Util/Widget.php | Widget.widgetExist | public function widgetExist($name)
{
$name = strtolower($name);
return isset($this->dataStore[0][$name]) ? $this->dataStore[0][$name] : false;
} | php | public function widgetExist($name)
{
$name = strtolower($name);
return isset($this->dataStore[0][$name]) ? $this->dataStore[0][$name] : false;
} | [
"public",
"function",
"widgetExist",
"(",
"$",
"name",
")",
"{",
"$",
"name",
"=",
"strtolower",
"(",
"$",
"name",
")",
";",
"return",
"isset",
"(",
"$",
"this",
"->",
"dataStore",
"[",
"0",
"]",
"[",
"$",
"name",
"]",
")",
"?",
"$",
"this",
"->",
"dataStore",
"[",
"0",
"]",
"[",
"$",
"name",
"]",
":",
"false",
";",
"}"
] | Checks if a widget exists
@param $name
@return bool | [
"Checks",
"if",
"a",
"widget",
"exists"
] | train | https://github.com/odiaseo/pagebuilder/blob/88ef7cccf305368561307efe4ca07fac8e5774f3/src/PageBuilder/Util/Widget.php#L143-L148 |
webdevvie/pheanstalk-task-queue-bundle | Command/Example/ExampleWorkerCommand.php | ExampleWorkerCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$message = $input->getOption('message');
$output->write("I HAVE A MESSAGE FOR YOU!");
$wait = intval($input->getArgument('wait'));
for ($counter = 0; $counter < $wait; $counter++) {
$output->write(".");
sleep(1);
}
$output->writeLn($message);
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$message = $input->getOption('message');
$output->write("I HAVE A MESSAGE FOR YOU!");
$wait = intval($input->getArgument('wait'));
for ($counter = 0; $counter < $wait; $counter++) {
$output->write(".");
sleep(1);
}
$output->writeLn($message);
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"message",
"=",
"$",
"input",
"->",
"getOption",
"(",
"'message'",
")",
";",
"$",
"output",
"->",
"write",
"(",
"\"I HAVE A MESSAGE FOR YOU!\"",
")",
";",
"$",
"wait",
"=",
"intval",
"(",
"$",
"input",
"->",
"getArgument",
"(",
"'wait'",
")",
")",
";",
"for",
"(",
"$",
"counter",
"=",
"0",
";",
"$",
"counter",
"<",
"$",
"wait",
";",
"$",
"counter",
"++",
")",
"{",
"$",
"output",
"->",
"write",
"(",
"\".\"",
")",
";",
"sleep",
"(",
"1",
")",
";",
"}",
"$",
"output",
"->",
"writeLn",
"(",
"$",
"message",
")",
";",
"}"
] | {@inheritDoc}
@param InputInterface $input
@param OutputInterface $output
@return void | [
"{",
"@inheritDoc",
"}"
] | train | https://github.com/webdevvie/pheanstalk-task-queue-bundle/blob/db5e63a8f844e345dc2e69ce8e94b32d851020eb/Command/Example/ExampleWorkerCommand.php#L40-L50 |
inhere/php-librarys | src/Helpers/PhpError.php | PhpError.toArray | public static function toArray(array $lastError, $catcher = null)
{
$digest = 'Fatal Error (' . self::codeToString($lastError['type']) . '): ' . $lastError['message'];
$data = [
'code' => $lastError['type'],
'message' => $lastError['message'],
'file' => $lastError['file'],
'line' => $lastError['line'],
'catcher' => __METHOD__,
];
if ($catcher) {
$data['catcher'] = $catcher;
}
return [$digest, $data];
} | php | public static function toArray(array $lastError, $catcher = null)
{
$digest = 'Fatal Error (' . self::codeToString($lastError['type']) . '): ' . $lastError['message'];
$data = [
'code' => $lastError['type'],
'message' => $lastError['message'],
'file' => $lastError['file'],
'line' => $lastError['line'],
'catcher' => __METHOD__,
];
if ($catcher) {
$data['catcher'] = $catcher;
}
return [$digest, $data];
} | [
"public",
"static",
"function",
"toArray",
"(",
"array",
"$",
"lastError",
",",
"$",
"catcher",
"=",
"null",
")",
"{",
"$",
"digest",
"=",
"'Fatal Error ('",
".",
"self",
"::",
"codeToString",
"(",
"$",
"lastError",
"[",
"'type'",
"]",
")",
".",
"'): '",
".",
"$",
"lastError",
"[",
"'message'",
"]",
";",
"$",
"data",
"=",
"[",
"'code'",
"=>",
"$",
"lastError",
"[",
"'type'",
"]",
",",
"'message'",
"=>",
"$",
"lastError",
"[",
"'message'",
"]",
",",
"'file'",
"=>",
"$",
"lastError",
"[",
"'file'",
"]",
",",
"'line'",
"=>",
"$",
"lastError",
"[",
"'line'",
"]",
",",
"'catcher'",
"=>",
"__METHOD__",
",",
"]",
";",
"if",
"(",
"$",
"catcher",
")",
"{",
"$",
"data",
"[",
"'catcher'",
"]",
"=",
"$",
"catcher",
";",
"}",
"return",
"[",
"$",
"digest",
",",
"$",
"data",
"]",
";",
"}"
] | $lastError = error_get_last();
@param array $lastError
@param null|string $catcher
@return array | [
"$lastError",
"=",
"error_get_last",
"()",
";"
] | train | https://github.com/inhere/php-librarys/blob/e6ca598685469794f310e3ab0e2bc19519cd0ae6/src/Helpers/PhpError.php#L26-L42 |
ezsystems/ezcomments-ls-extension | classes/ezcomnotifcationmanager.php | ezcomNotificationManager.sendNotificationInMany | public function sendNotificationInMany( $subscriber, $contentObject, $comment, $tpl = null )
{
if ( is_null( $tpl ) )
{
$tpl = eZTemplate::factory();
}
$tpl->setVariable( 'subscriber', $subscriber );
$tpl->setVariable( 'contentobject', $contentObject );
$tpl->setVariable( 'comment', $comment );
$subject = $tpl->fetch( $this->subjectTemplatePath );
$body = $tpl->fetch( $this->bodyTemplatePath );
$this->executeSending( $subject, $body, $subscriber );
} | php | public function sendNotificationInMany( $subscriber, $contentObject, $comment, $tpl = null )
{
if ( is_null( $tpl ) )
{
$tpl = eZTemplate::factory();
}
$tpl->setVariable( 'subscriber', $subscriber );
$tpl->setVariable( 'contentobject', $contentObject );
$tpl->setVariable( 'comment', $comment );
$subject = $tpl->fetch( $this->subjectTemplatePath );
$body = $tpl->fetch( $this->bodyTemplatePath );
$this->executeSending( $subject, $body, $subscriber );
} | [
"public",
"function",
"sendNotificationInMany",
"(",
"$",
"subscriber",
",",
"$",
"contentObject",
",",
"$",
"comment",
",",
"$",
"tpl",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"tpl",
")",
")",
"{",
"$",
"tpl",
"=",
"eZTemplate",
"::",
"factory",
"(",
")",
";",
"}",
"$",
"tpl",
"->",
"setVariable",
"(",
"'subscriber'",
",",
"$",
"subscriber",
")",
";",
"$",
"tpl",
"->",
"setVariable",
"(",
"'contentobject'",
",",
"$",
"contentObject",
")",
";",
"$",
"tpl",
"->",
"setVariable",
"(",
"'comment'",
",",
"$",
"comment",
")",
";",
"$",
"subject",
"=",
"$",
"tpl",
"->",
"fetch",
"(",
"$",
"this",
"->",
"subjectTemplatePath",
")",
";",
"$",
"body",
"=",
"$",
"tpl",
"->",
"fetch",
"(",
"$",
"this",
"->",
"bodyTemplatePath",
")",
";",
"$",
"this",
"->",
"executeSending",
"(",
"$",
"subject",
",",
"$",
"body",
",",
"$",
"subscriber",
")",
";",
"}"
] | send one notification with one comment by one comment
Exception if error happens
@param $subscriber
@param $contentObject
@param $comment
@param $tpl
@return void | [
"send",
"one",
"notification",
"with",
"one",
"comment",
"by",
"one",
"comment",
"Exception",
"if",
"error",
"happens"
] | train | https://github.com/ezsystems/ezcomments-ls-extension/blob/2b4cd8c34d4a77813e4d6a9c5a0d317a274c63c5/classes/ezcomnotifcationmanager.php#L41-L54 |
ezsystems/ezcomments-ls-extension | classes/ezcomnotifcationmanager.php | ezcomNotificationManager.sendNotificationInOne | public function sendNotificationInOne( $subscriber, $contentObject, $commentList = null, $tpl = null )
{
if ( is_null( $tpl ) )
{
$tpl = eZTemplate::factory();
}
$tpl->setVariable( 'subscriber', $subscriber );
$tpl->setVariable( 'contentobject', $contentObject );
if ( !is_null( $commentList ) )
{
$tpl->setVariable( 'comment_list', $commentList );
}
$subject = $tpl->fetch( $this->multiSubjectTemplatePath );
$body = $tpl->fetch( $this->multiBodyTemplatePath );
$this->executeSending( $subject, $body, $subscriber );
} | php | public function sendNotificationInOne( $subscriber, $contentObject, $commentList = null, $tpl = null )
{
if ( is_null( $tpl ) )
{
$tpl = eZTemplate::factory();
}
$tpl->setVariable( 'subscriber', $subscriber );
$tpl->setVariable( 'contentobject', $contentObject );
if ( !is_null( $commentList ) )
{
$tpl->setVariable( 'comment_list', $commentList );
}
$subject = $tpl->fetch( $this->multiSubjectTemplatePath );
$body = $tpl->fetch( $this->multiBodyTemplatePath );
$this->executeSending( $subject, $body, $subscriber );
} | [
"public",
"function",
"sendNotificationInOne",
"(",
"$",
"subscriber",
",",
"$",
"contentObject",
",",
"$",
"commentList",
"=",
"null",
",",
"$",
"tpl",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"tpl",
")",
")",
"{",
"$",
"tpl",
"=",
"eZTemplate",
"::",
"factory",
"(",
")",
";",
"}",
"$",
"tpl",
"->",
"setVariable",
"(",
"'subscriber'",
",",
"$",
"subscriber",
")",
";",
"$",
"tpl",
"->",
"setVariable",
"(",
"'contentobject'",
",",
"$",
"contentObject",
")",
";",
"if",
"(",
"!",
"is_null",
"(",
"$",
"commentList",
")",
")",
"{",
"$",
"tpl",
"->",
"setVariable",
"(",
"'comment_list'",
",",
"$",
"commentList",
")",
";",
"}",
"$",
"subject",
"=",
"$",
"tpl",
"->",
"fetch",
"(",
"$",
"this",
"->",
"multiSubjectTemplatePath",
")",
";",
"$",
"body",
"=",
"$",
"tpl",
"->",
"fetch",
"(",
"$",
"this",
"->",
"multiBodyTemplatePath",
")",
";",
"$",
"this",
"->",
"executeSending",
"(",
"$",
"subject",
",",
"$",
"body",
",",
"$",
"subscriber",
")",
";",
"}"
] | send notification with all comment in one notification
Exception if error happens
@param $subscriber
@param $contentObject
@param $commentList comment list to the subscriber, which can be null.
@param $tpl
@return void | [
"send",
"notification",
"with",
"all",
"comment",
"in",
"one",
"notification",
"Exception",
"if",
"error",
"happens"
] | train | https://github.com/ezsystems/ezcomments-ls-extension/blob/2b4cd8c34d4a77813e4d6a9c5a0d317a274c63c5/classes/ezcomnotifcationmanager.php#L65-L80 |
ezsystems/ezcomments-ls-extension | classes/ezcomnotifcationmanager.php | ezcomNotificationManager.instance | public static function instance( $className = null )
{
if ( is_null( $className ) )
{
$ini = eZINI::instance( 'ezcomments.ini' );
$className = $ini->variable( 'NotificationSettings', 'NotificationManagerClass' );
}
if ( !isset( self::$instance ) )
{
self::$instance = new $className();
}
return self::$instance;
} | php | public static function instance( $className = null )
{
if ( is_null( $className ) )
{
$ini = eZINI::instance( 'ezcomments.ini' );
$className = $ini->variable( 'NotificationSettings', 'NotificationManagerClass' );
}
if ( !isset( self::$instance ) )
{
self::$instance = new $className();
}
return self::$instance;
} | [
"public",
"static",
"function",
"instance",
"(",
"$",
"className",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"className",
")",
")",
"{",
"$",
"ini",
"=",
"eZINI",
"::",
"instance",
"(",
"'ezcomments.ini'",
")",
";",
"$",
"className",
"=",
"$",
"ini",
"->",
"variable",
"(",
"'NotificationSettings'",
",",
"'NotificationManagerClass'",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"instance",
")",
")",
"{",
"self",
"::",
"$",
"instance",
"=",
"new",
"$",
"className",
"(",
")",
";",
"}",
"return",
"self",
"::",
"$",
"instance",
";",
"}"
] | create instance of the object
@param string $className
@return ezcomNotificationManager | [
"create",
"instance",
"of",
"the",
"object"
] | train | https://github.com/ezsystems/ezcomments-ls-extension/blob/2b4cd8c34d4a77813e4d6a9c5a0d317a274c63c5/classes/ezcomnotifcationmanager.php#L87-L99 |
ezsystems/ezcomments-ls-extension | classes/ezcomnotifcationmanager.php | ezcomNotificationManager.create | public static function create( $className = null )
{
if ( is_null( $className ) )
{
$ini = eZINI::instance( 'ezcomments.ini' );
$className = $ini->variable( 'NotificationSettings', 'NotificationManagerClass' );
}
return new $className();
} | php | public static function create( $className = null )
{
if ( is_null( $className ) )
{
$ini = eZINI::instance( 'ezcomments.ini' );
$className = $ini->variable( 'NotificationSettings', 'NotificationManagerClass' );
}
return new $className();
} | [
"public",
"static",
"function",
"create",
"(",
"$",
"className",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"className",
")",
")",
"{",
"$",
"ini",
"=",
"eZINI",
"::",
"instance",
"(",
"'ezcomments.ini'",
")",
";",
"$",
"className",
"=",
"$",
"ini",
"->",
"variable",
"(",
"'NotificationSettings'",
",",
"'NotificationManagerClass'",
")",
";",
"}",
"return",
"new",
"$",
"className",
"(",
")",
";",
"}"
] | create instance of the object without using singleton
@param string $className
@return ezcomNotificationManager | [
"create",
"instance",
"of",
"the",
"object",
"without",
"using",
"singleton"
] | train | https://github.com/ezsystems/ezcomments-ls-extension/blob/2b4cd8c34d4a77813e4d6a9c5a0d317a274c63c5/classes/ezcomnotifcationmanager.php#L106-L114 |
DomAndTom/dnt_laravel-swagger-alpha_framework | src/controllers/BaseController.php | BaseController.resources | public function resources()
{
$options = Config::get('laravel-swagger::getResourceListOptions');
$excludedPath = Config::get('laravel-swagger::excludedPath');
$swagger = new Swagger($this->getPaths(), $excludedPath);
if (Config::get('laravel-swagger::cache')) {
$resourceList = Cache::remember('resourceList', $this->getExpireAt(), function() use ($swagger, $options)
{
return $swagger->getResourceList($options);
});
} else {
$resourceList = $swagger->getResourceList($options);
}
return $resourceList;
} | php | public function resources()
{
$options = Config::get('laravel-swagger::getResourceListOptions');
$excludedPath = Config::get('laravel-swagger::excludedPath');
$swagger = new Swagger($this->getPaths(), $excludedPath);
if (Config::get('laravel-swagger::cache')) {
$resourceList = Cache::remember('resourceList', $this->getExpireAt(), function() use ($swagger, $options)
{
return $swagger->getResourceList($options);
});
} else {
$resourceList = $swagger->getResourceList($options);
}
return $resourceList;
} | [
"public",
"function",
"resources",
"(",
")",
"{",
"$",
"options",
"=",
"Config",
"::",
"get",
"(",
"'laravel-swagger::getResourceListOptions'",
")",
";",
"$",
"excludedPath",
"=",
"Config",
"::",
"get",
"(",
"'laravel-swagger::excludedPath'",
")",
";",
"$",
"swagger",
"=",
"new",
"Swagger",
"(",
"$",
"this",
"->",
"getPaths",
"(",
")",
",",
"$",
"excludedPath",
")",
";",
"if",
"(",
"Config",
"::",
"get",
"(",
"'laravel-swagger::cache'",
")",
")",
"{",
"$",
"resourceList",
"=",
"Cache",
"::",
"remember",
"(",
"'resourceList'",
",",
"$",
"this",
"->",
"getExpireAt",
"(",
")",
",",
"function",
"(",
")",
"use",
"(",
"$",
"swagger",
",",
"$",
"options",
")",
"{",
"return",
"$",
"swagger",
"->",
"getResourceList",
"(",
"$",
"options",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"$",
"resourceList",
"=",
"$",
"swagger",
"->",
"getResourceList",
"(",
"$",
"options",
")",
";",
"}",
"return",
"$",
"resourceList",
";",
"}"
] | Show all available Resources | [
"Show",
"all",
"available",
"Resources"
] | train | https://github.com/DomAndTom/dnt_laravel-swagger-alpha_framework/blob/489fc5398583682b8372bdadd6631a4cbff6099f/src/controllers/BaseController.php#L29-L46 |
DomAndTom/dnt_laravel-swagger-alpha_framework | src/controllers/BaseController.php | BaseController.showResource | public function showResource($name)
{
$options = Config::get('laravel-swagger::getResourceOptions');
$resourceName = "/" . str_replace("-", "/", $name);
$excludedPath = Config::get('laravel-swagger::excludedPath');
$swagger = new Swagger($this->getPaths(), $excludedPath);
if (Config::get('laravel-swagger::cache') && Cache::has('resource_'.$resourceName)) {
$resource = Cache::get('resource_'.$resourceName);
} else {
if (!in_array($resourceName, $swagger->getResourceNames())) {
App::abort(404, 'Resource not found');
}
// Pet demo uses the main laravel-swagger route.
if ($resourceName == '/petdemo') {
$options['defaultBasePath'] = route('swagger-index');
}
$resource = $swagger->getResource($resourceName, $options);
}
if (Config::get('laravel-swagger::cache') && !Cache::has('resource_'.$resourceName)) {
Cache::put('resource_'.$resourceName, $resource, $this->getExpireAt());
}
return $resource;
} | php | public function showResource($name)
{
$options = Config::get('laravel-swagger::getResourceOptions');
$resourceName = "/" . str_replace("-", "/", $name);
$excludedPath = Config::get('laravel-swagger::excludedPath');
$swagger = new Swagger($this->getPaths(), $excludedPath);
if (Config::get('laravel-swagger::cache') && Cache::has('resource_'.$resourceName)) {
$resource = Cache::get('resource_'.$resourceName);
} else {
if (!in_array($resourceName, $swagger->getResourceNames())) {
App::abort(404, 'Resource not found');
}
// Pet demo uses the main laravel-swagger route.
if ($resourceName == '/petdemo') {
$options['defaultBasePath'] = route('swagger-index');
}
$resource = $swagger->getResource($resourceName, $options);
}
if (Config::get('laravel-swagger::cache') && !Cache::has('resource_'.$resourceName)) {
Cache::put('resource_'.$resourceName, $resource, $this->getExpireAt());
}
return $resource;
} | [
"public",
"function",
"showResource",
"(",
"$",
"name",
")",
"{",
"$",
"options",
"=",
"Config",
"::",
"get",
"(",
"'laravel-swagger::getResourceOptions'",
")",
";",
"$",
"resourceName",
"=",
"\"/\"",
".",
"str_replace",
"(",
"\"-\"",
",",
"\"/\"",
",",
"$",
"name",
")",
";",
"$",
"excludedPath",
"=",
"Config",
"::",
"get",
"(",
"'laravel-swagger::excludedPath'",
")",
";",
"$",
"swagger",
"=",
"new",
"Swagger",
"(",
"$",
"this",
"->",
"getPaths",
"(",
")",
",",
"$",
"excludedPath",
")",
";",
"if",
"(",
"Config",
"::",
"get",
"(",
"'laravel-swagger::cache'",
")",
"&&",
"Cache",
"::",
"has",
"(",
"'resource_'",
".",
"$",
"resourceName",
")",
")",
"{",
"$",
"resource",
"=",
"Cache",
"::",
"get",
"(",
"'resource_'",
".",
"$",
"resourceName",
")",
";",
"}",
"else",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"resourceName",
",",
"$",
"swagger",
"->",
"getResourceNames",
"(",
")",
")",
")",
"{",
"App",
"::",
"abort",
"(",
"404",
",",
"'Resource not found'",
")",
";",
"}",
"// Pet demo uses the main laravel-swagger route.",
"if",
"(",
"$",
"resourceName",
"==",
"'/petdemo'",
")",
"{",
"$",
"options",
"[",
"'defaultBasePath'",
"]",
"=",
"route",
"(",
"'swagger-index'",
")",
";",
"}",
"$",
"resource",
"=",
"$",
"swagger",
"->",
"getResource",
"(",
"$",
"resourceName",
",",
"$",
"options",
")",
";",
"}",
"if",
"(",
"Config",
"::",
"get",
"(",
"'laravel-swagger::cache'",
")",
"&&",
"!",
"Cache",
"::",
"has",
"(",
"'resource_'",
".",
"$",
"resourceName",
")",
")",
"{",
"Cache",
"::",
"put",
"(",
"'resource_'",
".",
"$",
"resourceName",
",",
"$",
"resource",
",",
"$",
"this",
"->",
"getExpireAt",
"(",
")",
")",
";",
"}",
"return",
"$",
"resource",
";",
"}"
] | Show an specific Resource | [
"Show",
"an",
"specific",
"Resource"
] | train | https://github.com/DomAndTom/dnt_laravel-swagger-alpha_framework/blob/489fc5398583682b8372bdadd6631a4cbff6099f/src/controllers/BaseController.php#L51-L79 |
DomAndTom/dnt_laravel-swagger-alpha_framework | src/controllers/BaseController.php | BaseController.getPaths | private function getPaths()
{
$paths = Config::get('laravel-swagger::paths');
if (Config::get('laravel-swagger::showDemo') ) {
$paths[] = __DIR__.'/demo';
$paths[] = __DIR__.'/../models';
}
return $paths;
} | php | private function getPaths()
{
$paths = Config::get('laravel-swagger::paths');
if (Config::get('laravel-swagger::showDemo') ) {
$paths[] = __DIR__.'/demo';
$paths[] = __DIR__.'/../models';
}
return $paths;
} | [
"private",
"function",
"getPaths",
"(",
")",
"{",
"$",
"paths",
"=",
"Config",
"::",
"get",
"(",
"'laravel-swagger::paths'",
")",
";",
"if",
"(",
"Config",
"::",
"get",
"(",
"'laravel-swagger::showDemo'",
")",
")",
"{",
"$",
"paths",
"[",
"]",
"=",
"__DIR__",
".",
"'/demo'",
";",
"$",
"paths",
"[",
"]",
"=",
"__DIR__",
".",
"'/../models'",
";",
"}",
"return",
"$",
"paths",
";",
"}"
] | Get Paths | [
"Get",
"Paths"
] | train | https://github.com/DomAndTom/dnt_laravel-swagger-alpha_framework/blob/489fc5398583682b8372bdadd6631a4cbff6099f/src/controllers/BaseController.php#L84-L94 |
eghojansu/moe | src/tools/Image.php | Image.resize | function resize($width,$height,$crop=TRUE,$enlarge=TRUE) {
// Adjust dimensions; retain aspect ratio
$ratio=($origw=imagesx($this->data))/($origh=imagesy($this->data));
if (!$crop) {
if ($width/$ratio<=$height)
$height=$width/$ratio;
else
$width=$height*$ratio;
}
if (!$enlarge) {
$width=min($origw,$width);
$height=min($origh,$height);
}
// Create blank image
$tmp=imagecreatetruecolor($width,$height);
imagesavealpha($tmp,TRUE);
imagefill($tmp,0,0,IMG_COLOR_TRANSPARENT);
// Resize
if ($crop) {
if ($width/$ratio<=$height) {
$cropw=$origh*$width/$height;
imagecopyresampled($tmp,$this->data,
0,0,($origw-$cropw)/2,0,$width,$height,$cropw,$origh);
}
else {
$croph=$origw*$height/$width;
imagecopyresampled($tmp,$this->data,
0,0,0,($origh-$croph)/2,$width,$height,$origw,$croph);
}
}
else
imagecopyresampled($tmp,$this->data,
0,0,0,0,$width,$height,$origw,$origh);
imagedestroy($this->data);
$this->data=$tmp;
return $this->save();
} | php | function resize($width,$height,$crop=TRUE,$enlarge=TRUE) {
// Adjust dimensions; retain aspect ratio
$ratio=($origw=imagesx($this->data))/($origh=imagesy($this->data));
if (!$crop) {
if ($width/$ratio<=$height)
$height=$width/$ratio;
else
$width=$height*$ratio;
}
if (!$enlarge) {
$width=min($origw,$width);
$height=min($origh,$height);
}
// Create blank image
$tmp=imagecreatetruecolor($width,$height);
imagesavealpha($tmp,TRUE);
imagefill($tmp,0,0,IMG_COLOR_TRANSPARENT);
// Resize
if ($crop) {
if ($width/$ratio<=$height) {
$cropw=$origh*$width/$height;
imagecopyresampled($tmp,$this->data,
0,0,($origw-$cropw)/2,0,$width,$height,$cropw,$origh);
}
else {
$croph=$origw*$height/$width;
imagecopyresampled($tmp,$this->data,
0,0,0,($origh-$croph)/2,$width,$height,$origw,$croph);
}
}
else
imagecopyresampled($tmp,$this->data,
0,0,0,0,$width,$height,$origw,$origh);
imagedestroy($this->data);
$this->data=$tmp;
return $this->save();
} | [
"function",
"resize",
"(",
"$",
"width",
",",
"$",
"height",
",",
"$",
"crop",
"=",
"TRUE",
",",
"$",
"enlarge",
"=",
"TRUE",
")",
"{",
"// Adjust dimensions; retain aspect ratio",
"$",
"ratio",
"=",
"(",
"$",
"origw",
"=",
"imagesx",
"(",
"$",
"this",
"->",
"data",
")",
")",
"/",
"(",
"$",
"origh",
"=",
"imagesy",
"(",
"$",
"this",
"->",
"data",
")",
")",
";",
"if",
"(",
"!",
"$",
"crop",
")",
"{",
"if",
"(",
"$",
"width",
"/",
"$",
"ratio",
"<=",
"$",
"height",
")",
"$",
"height",
"=",
"$",
"width",
"/",
"$",
"ratio",
";",
"else",
"$",
"width",
"=",
"$",
"height",
"*",
"$",
"ratio",
";",
"}",
"if",
"(",
"!",
"$",
"enlarge",
")",
"{",
"$",
"width",
"=",
"min",
"(",
"$",
"origw",
",",
"$",
"width",
")",
";",
"$",
"height",
"=",
"min",
"(",
"$",
"origh",
",",
"$",
"height",
")",
";",
"}",
"// Create blank image",
"$",
"tmp",
"=",
"imagecreatetruecolor",
"(",
"$",
"width",
",",
"$",
"height",
")",
";",
"imagesavealpha",
"(",
"$",
"tmp",
",",
"TRUE",
")",
";",
"imagefill",
"(",
"$",
"tmp",
",",
"0",
",",
"0",
",",
"IMG_COLOR_TRANSPARENT",
")",
";",
"// Resize",
"if",
"(",
"$",
"crop",
")",
"{",
"if",
"(",
"$",
"width",
"/",
"$",
"ratio",
"<=",
"$",
"height",
")",
"{",
"$",
"cropw",
"=",
"$",
"origh",
"*",
"$",
"width",
"/",
"$",
"height",
";",
"imagecopyresampled",
"(",
"$",
"tmp",
",",
"$",
"this",
"->",
"data",
",",
"0",
",",
"0",
",",
"(",
"$",
"origw",
"-",
"$",
"cropw",
")",
"/",
"2",
",",
"0",
",",
"$",
"width",
",",
"$",
"height",
",",
"$",
"cropw",
",",
"$",
"origh",
")",
";",
"}",
"else",
"{",
"$",
"croph",
"=",
"$",
"origw",
"*",
"$",
"height",
"/",
"$",
"width",
";",
"imagecopyresampled",
"(",
"$",
"tmp",
",",
"$",
"this",
"->",
"data",
",",
"0",
",",
"0",
",",
"0",
",",
"(",
"$",
"origh",
"-",
"$",
"croph",
")",
"/",
"2",
",",
"$",
"width",
",",
"$",
"height",
",",
"$",
"origw",
",",
"$",
"croph",
")",
";",
"}",
"}",
"else",
"imagecopyresampled",
"(",
"$",
"tmp",
",",
"$",
"this",
"->",
"data",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"$",
"width",
",",
"$",
"height",
",",
"$",
"origw",
",",
"$",
"origh",
")",
";",
"imagedestroy",
"(",
"$",
"this",
"->",
"data",
")",
";",
"$",
"this",
"->",
"data",
"=",
"$",
"tmp",
";",
"return",
"$",
"this",
"->",
"save",
"(",
")",
";",
"}"
] | Resize image (Maintain aspect ratio); Crop relative to center
if flag is enabled; Enlargement allowed if flag is enabled
@return object
@param $width int
@param $height int
@param $crop bool
@param $enlarge bool | [
"Resize",
"image",
"(",
"Maintain",
"aspect",
"ratio",
")",
";",
"Crop",
"relative",
"to",
"center",
"if",
"flag",
"is",
"enabled",
";",
"Enlargement",
"allowed",
"if",
"flag",
"is",
"enabled"
] | train | https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/tools/Image.php#L212-L248 |
eghojansu/moe | src/tools/Image.php | Image.save | function save() {
$fw=Base::instance();
if ($this->flag) {
if (!is_dir($dir=$fw->get('TEMP')))
mkdir($dir,Base::MODE,TRUE);
$this->count++;
$fw->write($dir.'/'.
$fw->hash($fw->get('ROOT').$fw->get('BASE')).'.'.
$fw->hash($this->file).'-'.$this->count.'.png',
$this->dump());
}
return $this;
} | php | function save() {
$fw=Base::instance();
if ($this->flag) {
if (!is_dir($dir=$fw->get('TEMP')))
mkdir($dir,Base::MODE,TRUE);
$this->count++;
$fw->write($dir.'/'.
$fw->hash($fw->get('ROOT').$fw->get('BASE')).'.'.
$fw->hash($this->file).'-'.$this->count.'.png',
$this->dump());
}
return $this;
} | [
"function",
"save",
"(",
")",
"{",
"$",
"fw",
"=",
"Base",
"::",
"instance",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"flag",
")",
"{",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"dir",
"=",
"$",
"fw",
"->",
"get",
"(",
"'TEMP'",
")",
")",
")",
"mkdir",
"(",
"$",
"dir",
",",
"Base",
"::",
"MODE",
",",
"TRUE",
")",
";",
"$",
"this",
"->",
"count",
"++",
";",
"$",
"fw",
"->",
"write",
"(",
"$",
"dir",
".",
"'/'",
".",
"$",
"fw",
"->",
"hash",
"(",
"$",
"fw",
"->",
"get",
"(",
"'ROOT'",
")",
".",
"$",
"fw",
"->",
"get",
"(",
"'BASE'",
")",
")",
".",
"'.'",
".",
"$",
"fw",
"->",
"hash",
"(",
"$",
"this",
"->",
"file",
")",
".",
"'-'",
".",
"$",
"this",
"->",
"count",
".",
"'.png'",
",",
"$",
"this",
"->",
"dump",
"(",
")",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Save current state
@return object | [
"Save",
"current",
"state"
] | train | https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/tools/Image.php#L480-L492 |
eghojansu/moe | src/tools/Image.php | Image.restore | function restore($state=1) {
$fw=Base::instance();
if ($this->flag && is_file($file=($path=$fw->get('TEMP').
$fw->hash($fw->get('ROOT').$fw->get('BASE')).'.'.
$fw->hash($this->file).'-').$state.'.png')) {
if (is_resource($this->data))
imagedestroy($this->data);
$this->data=imagecreatefromstring($fw->read($file));
imagesavealpha($this->data,TRUE);
foreach (glob($path.'*.png',GLOB_NOSORT) as $match)
if (preg_match('/-(\d+)\.png/',$match,$parts) &&
$parts[1]>$state)
@unlink($match);
$this->count=$state;
}
return $this;
} | php | function restore($state=1) {
$fw=Base::instance();
if ($this->flag && is_file($file=($path=$fw->get('TEMP').
$fw->hash($fw->get('ROOT').$fw->get('BASE')).'.'.
$fw->hash($this->file).'-').$state.'.png')) {
if (is_resource($this->data))
imagedestroy($this->data);
$this->data=imagecreatefromstring($fw->read($file));
imagesavealpha($this->data,TRUE);
foreach (glob($path.'*.png',GLOB_NOSORT) as $match)
if (preg_match('/-(\d+)\.png/',$match,$parts) &&
$parts[1]>$state)
@unlink($match);
$this->count=$state;
}
return $this;
} | [
"function",
"restore",
"(",
"$",
"state",
"=",
"1",
")",
"{",
"$",
"fw",
"=",
"Base",
"::",
"instance",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"flag",
"&&",
"is_file",
"(",
"$",
"file",
"=",
"(",
"$",
"path",
"=",
"$",
"fw",
"->",
"get",
"(",
"'TEMP'",
")",
".",
"$",
"fw",
"->",
"hash",
"(",
"$",
"fw",
"->",
"get",
"(",
"'ROOT'",
")",
".",
"$",
"fw",
"->",
"get",
"(",
"'BASE'",
")",
")",
".",
"'.'",
".",
"$",
"fw",
"->",
"hash",
"(",
"$",
"this",
"->",
"file",
")",
".",
"'-'",
")",
".",
"$",
"state",
".",
"'.png'",
")",
")",
"{",
"if",
"(",
"is_resource",
"(",
"$",
"this",
"->",
"data",
")",
")",
"imagedestroy",
"(",
"$",
"this",
"->",
"data",
")",
";",
"$",
"this",
"->",
"data",
"=",
"imagecreatefromstring",
"(",
"$",
"fw",
"->",
"read",
"(",
"$",
"file",
")",
")",
";",
"imagesavealpha",
"(",
"$",
"this",
"->",
"data",
",",
"TRUE",
")",
";",
"foreach",
"(",
"glob",
"(",
"$",
"path",
".",
"'*.png'",
",",
"GLOB_NOSORT",
")",
"as",
"$",
"match",
")",
"if",
"(",
"preg_match",
"(",
"'/-(\\d+)\\.png/'",
",",
"$",
"match",
",",
"$",
"parts",
")",
"&&",
"$",
"parts",
"[",
"1",
"]",
">",
"$",
"state",
")",
"@",
"unlink",
"(",
"$",
"match",
")",
";",
"$",
"this",
"->",
"count",
"=",
"$",
"state",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Revert to specified state
@return object
@param $state int | [
"Revert",
"to",
"specified",
"state"
] | train | https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/tools/Image.php#L499-L515 |
eghojansu/moe | src/tools/Image.php | Image.load | function load($str) {
$this->data=imagecreatefromstring($str);
imagesavealpha($this->data,TRUE);
$this->save();
return $this;
} | php | function load($str) {
$this->data=imagecreatefromstring($str);
imagesavealpha($this->data,TRUE);
$this->save();
return $this;
} | [
"function",
"load",
"(",
"$",
"str",
")",
"{",
"$",
"this",
"->",
"data",
"=",
"imagecreatefromstring",
"(",
"$",
"str",
")",
";",
"imagesavealpha",
"(",
"$",
"this",
"->",
"data",
",",
"TRUE",
")",
";",
"$",
"this",
"->",
"save",
"(",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Load string
@return object
@param $str string | [
"Load",
"string"
] | train | https://github.com/eghojansu/moe/blob/f58ec75a3116d1a572782256e2b38bb9aab95e3c/src/tools/Image.php#L535-L540 |
ericomgroup/PusheNotification | src/PushNotification.php | PushNotification.execute | private function execute($content)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Token '.$this->token, 'Content-Type: application/json', 'Accept: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode((object) $content));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if(!$result)
return curl_error( $ch );
return $result;
} | php | private function execute($content)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Token '.$this->token, 'Content-Type: application/json', 'Accept: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode((object) $content));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if(!$result)
return curl_error( $ch );
return $result;
} | [
"private",
"function",
"execute",
"(",
"$",
"content",
")",
"{",
"$",
"ch",
"=",
"curl_init",
"(",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_URL",
",",
"$",
"this",
"->",
"url",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_HTTPHEADER",
",",
"[",
"'Authorization: Token '",
".",
"$",
"this",
"->",
"token",
",",
"'Content-Type: application/json'",
",",
"'Accept: application/json'",
"]",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_POSTFIELDS",
",",
"json_encode",
"(",
"(",
"object",
")",
"$",
"content",
")",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_POST",
",",
"true",
")",
";",
"curl_setopt",
"(",
"$",
"ch",
",",
"CURLOPT_RETURNTRANSFER",
",",
"true",
")",
";",
"$",
"result",
"=",
"curl_exec",
"(",
"$",
"ch",
")",
";",
"if",
"(",
"!",
"$",
"result",
")",
"return",
"curl_error",
"(",
"$",
"ch",
")",
";",
"return",
"$",
"result",
";",
"}"
] | @param $content
@return mixed|string | [
"@param",
"$content"
] | train | https://github.com/ericomgroup/PusheNotification/blob/65e39fbb77f9bad5c5912f50b81e7d76de4b2b76/src/PushNotification.php#L124-L142 |
thupan/framework | src/Service/Redirect.php | Redirect.to | public static function to($location, $data = null)
{
$location = ($location === '/') ? URL : URL . $location;
$c = ($data) ? '?twigformfields='.base64_encode(json_encode($data)) : null;
header('Location: ' . $location . $c);
exit;
} | php | public static function to($location, $data = null)
{
$location = ($location === '/') ? URL : URL . $location;
$c = ($data) ? '?twigformfields='.base64_encode(json_encode($data)) : null;
header('Location: ' . $location . $c);
exit;
} | [
"public",
"static",
"function",
"to",
"(",
"$",
"location",
",",
"$",
"data",
"=",
"null",
")",
"{",
"$",
"location",
"=",
"(",
"$",
"location",
"===",
"'/'",
")",
"?",
"URL",
":",
"URL",
".",
"$",
"location",
";",
"$",
"c",
"=",
"(",
"$",
"data",
")",
"?",
"'?twigformfields='",
".",
"base64_encode",
"(",
"json_encode",
"(",
"$",
"data",
")",
")",
":",
"null",
";",
"header",
"(",
"'Location: '",
".",
"$",
"location",
".",
"$",
"c",
")",
";",
"exit",
";",
"}"
] | Método público para redirecionar uma página.
@method to()
@param string
@return none | [
"Método",
"público",
"para",
"redirecionar",
"uma",
"página",
"."
] | train | https://github.com/thupan/framework/blob/43193c67e87942930fb0cbc53aa069b60b27e749/src/Service/Redirect.php#L21-L28 |
alevilar/ristorantino-vendor | Mesa/Model/Mesa.php | Mesa.beforeDelete | public function beforeDelete($cascade = true) {
if ($this->id) {
WsPaxaposConnect::sendMesa((int)$this->id, "mesa:delete");
}
return parent::beforeDelete($cascade);
} | php | public function beforeDelete($cascade = true) {
if ($this->id) {
WsPaxaposConnect::sendMesa((int)$this->id, "mesa:delete");
}
return parent::beforeDelete($cascade);
} | [
"public",
"function",
"beforeDelete",
"(",
"$",
"cascade",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"id",
")",
"{",
"WsPaxaposConnect",
"::",
"sendMesa",
"(",
"(",
"int",
")",
"$",
"this",
"->",
"id",
",",
"\"mesa:delete\"",
")",
";",
"}",
"return",
"parent",
"::",
"beforeDelete",
"(",
"$",
"cascade",
")",
";",
"}"
] | Called before every deletion operation.
@return void
@link http://book.cakephp.org/2.0/en/models/callback-methods.html#afterdelete | [
"Called",
"before",
"every",
"deletion",
"operation",
"."
] | train | https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Mesa/Model/Mesa.php#L255-L261 |
alevilar/ristorantino-vendor | Mesa/Model/Mesa.php | Mesa.__processStateChanges | private function __processStateChanges ( $evName = 'Before') {
$this->changedState = false;
$this->changedNewState = false;
$estadoAnterior = $this->field('estado_id');
if ( empty($this->data['Mesa']['estado_id']) ) {
return false;
}
$nuevoEstado = $this->data['Mesa']['estado_id'];
if ( $estadoAnterior != $nuevoEstado ) {
// set new estado_id
$this->changedState = $estadoAnterior;
$this->changedNewState = $nuevoEstado;
}
return $this->changedState;
} | php | private function __processStateChanges ( $evName = 'Before') {
$this->changedState = false;
$this->changedNewState = false;
$estadoAnterior = $this->field('estado_id');
if ( empty($this->data['Mesa']['estado_id']) ) {
return false;
}
$nuevoEstado = $this->data['Mesa']['estado_id'];
if ( $estadoAnterior != $nuevoEstado ) {
// set new estado_id
$this->changedState = $estadoAnterior;
$this->changedNewState = $nuevoEstado;
}
return $this->changedState;
} | [
"private",
"function",
"__processStateChanges",
"(",
"$",
"evName",
"=",
"'Before'",
")",
"{",
"$",
"this",
"->",
"changedState",
"=",
"false",
";",
"$",
"this",
"->",
"changedNewState",
"=",
"false",
";",
"$",
"estadoAnterior",
"=",
"$",
"this",
"->",
"field",
"(",
"'estado_id'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"data",
"[",
"'Mesa'",
"]",
"[",
"'estado_id'",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"nuevoEstado",
"=",
"$",
"this",
"->",
"data",
"[",
"'Mesa'",
"]",
"[",
"'estado_id'",
"]",
";",
"if",
"(",
"$",
"estadoAnterior",
"!=",
"$",
"nuevoEstado",
")",
"{",
"// set new estado_id\t\t",
"$",
"this",
"->",
"changedState",
"=",
"$",
"estadoAnterior",
";",
"$",
"this",
"->",
"changedNewState",
"=",
"$",
"nuevoEstado",
";",
"}",
"return",
"$",
"this",
"->",
"changedState",
";",
"}"
] | Procesa el Cambio de estado llenando el atributo $this->changedState
con el nuevo ID del estado que fue moficiado
Si el estado no fue modificado la funcion devuelve FALSE, al igual que
$this->changedState permanecera en FALSE
@param String $evName Nombre prefixo del evento, generalemnte voy a usar "Before" y "After"
@return false si nada cambio, sino el ID del nuevo estado | [
"Procesa",
"el",
"Cambio",
"de",
"estado",
"llenando",
"el",
"atributo",
"$this",
"-",
">",
"changedState",
"con",
"el",
"nuevo",
"ID",
"del",
"estado",
"que",
"fue",
"moficiado",
"Si",
"el",
"estado",
"no",
"fue",
"modificado",
"la",
"funcion",
"devuelve",
"FALSE",
"al",
"igual",
"que",
"$this",
"-",
">",
"changedState",
"permanecera",
"en",
"FALSE"
] | train | https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Mesa/Model/Mesa.php#L346-L363 |
alevilar/ristorantino-vendor | Mesa/Model/Mesa.php | Mesa.cerrar_mesa | function cerrar_mesa( $mesa_id = null, $save = true, $silent = false )
{
if ( !empty( $this->data['Mesa']['id'] ) ) {
$this->id = $this->data['Mesa']['id'];
}
$this->id = ( $mesa_id == null ) ? $this->id : $mesa_id;
if ( !$this->exists( $this->id ) ) {
throw new NotFoundException(__('La Mesa ID# no existe', $this->id));
}
$data['Mesa']['id'] = $this->id;
$data['Mesa']['estado_id'] = MESA_CERRADA;
$data['Mesa']['time_cerro'] = date( "Y-m-d H:i:s");
$data['Mesa']['time_cobro'] = DATETIME_NULL;
//$data['Mesa']['silent'] = $silent; // no trigger del event
// si no hay que guardar nada, regresar
if ( $save ) {
if ( !$this->save( $data ) ) {
throw new CakeException("Error al guardar mesa cerrar mesa");
}
}
return true;
} | php | function cerrar_mesa( $mesa_id = null, $save = true, $silent = false )
{
if ( !empty( $this->data['Mesa']['id'] ) ) {
$this->id = $this->data['Mesa']['id'];
}
$this->id = ( $mesa_id == null ) ? $this->id : $mesa_id;
if ( !$this->exists( $this->id ) ) {
throw new NotFoundException(__('La Mesa ID# no existe', $this->id));
}
$data['Mesa']['id'] = $this->id;
$data['Mesa']['estado_id'] = MESA_CERRADA;
$data['Mesa']['time_cerro'] = date( "Y-m-d H:i:s");
$data['Mesa']['time_cobro'] = DATETIME_NULL;
//$data['Mesa']['silent'] = $silent; // no trigger del event
// si no hay que guardar nada, regresar
if ( $save ) {
if ( !$this->save( $data ) ) {
throw new CakeException("Error al guardar mesa cerrar mesa");
}
}
return true;
} | [
"function",
"cerrar_mesa",
"(",
"$",
"mesa_id",
"=",
"null",
",",
"$",
"save",
"=",
"true",
",",
"$",
"silent",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"data",
"[",
"'Mesa'",
"]",
"[",
"'id'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"id",
"=",
"$",
"this",
"->",
"data",
"[",
"'Mesa'",
"]",
"[",
"'id'",
"]",
";",
"}",
"$",
"this",
"->",
"id",
"=",
"(",
"$",
"mesa_id",
"==",
"null",
")",
"?",
"$",
"this",
"->",
"id",
":",
"$",
"mesa_id",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"exists",
"(",
"$",
"this",
"->",
"id",
")",
")",
"{",
"throw",
"new",
"NotFoundException",
"(",
"__",
"(",
"'La Mesa ID# no existe'",
",",
"$",
"this",
"->",
"id",
")",
")",
";",
"}",
"$",
"data",
"[",
"'Mesa'",
"]",
"[",
"'id'",
"]",
"=",
"$",
"this",
"->",
"id",
";",
"$",
"data",
"[",
"'Mesa'",
"]",
"[",
"'estado_id'",
"]",
"=",
"MESA_CERRADA",
";",
"$",
"data",
"[",
"'Mesa'",
"]",
"[",
"'time_cerro'",
"]",
"=",
"date",
"(",
"\"Y-m-d H:i:s\"",
")",
";",
"$",
"data",
"[",
"'Mesa'",
"]",
"[",
"'time_cobro'",
"]",
"=",
"DATETIME_NULL",
";",
"//$data['Mesa']['silent'] = $silent; // no trigger del event",
"// si no hay que guardar nada, regresar",
"if",
"(",
"$",
"save",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"save",
"(",
"$",
"data",
")",
")",
"{",
"throw",
"new",
"CakeException",
"(",
"\"Error al guardar mesa cerrar mesa\"",
")",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | } | [
"}"
] | train | https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Mesa/Model/Mesa.php#L449-L474 |
alevilar/ristorantino-vendor | Mesa/Model/Mesa.php | Mesa.calcular_valor_cubierto | function calcular_valor_cubierto ( $mesaId = null ) {
if (!empty($mesaId)) {
$this->id = $mesaId;
}
$cant_comensales = $this->field('cant_comensales');
$precioCubierto = Configure::read('Restaurante.valorCubierto');
$valor_cubierto = 0;
if ($precioCubierto > 0) {
$valor_cubierto = $precioCubierto * $cant_comensales;
}
return $valor_cubierto;
} | php | function calcular_valor_cubierto ( $mesaId = null ) {
if (!empty($mesaId)) {
$this->id = $mesaId;
}
$cant_comensales = $this->field('cant_comensales');
$precioCubierto = Configure::read('Restaurante.valorCubierto');
$valor_cubierto = 0;
if ($precioCubierto > 0) {
$valor_cubierto = $precioCubierto * $cant_comensales;
}
return $valor_cubierto;
} | [
"function",
"calcular_valor_cubierto",
"(",
"$",
"mesaId",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"mesaId",
")",
")",
"{",
"$",
"this",
"->",
"id",
"=",
"$",
"mesaId",
";",
"}",
"$",
"cant_comensales",
"=",
"$",
"this",
"->",
"field",
"(",
"'cant_comensales'",
")",
";",
"$",
"precioCubierto",
"=",
"Configure",
"::",
"read",
"(",
"'Restaurante.valorCubierto'",
")",
";",
"$",
"valor_cubierto",
"=",
"0",
";",
"if",
"(",
"$",
"precioCubierto",
">",
"0",
")",
"{",
"$",
"valor_cubierto",
"=",
"$",
"precioCubierto",
"*",
"$",
"cant_comensales",
";",
"}",
"return",
"$",
"valor_cubierto",
";",
"}"
] | Funcion que calcula el precio del cubierto
@param Integer $mesaId default NULL
@return Float precio del cubierto | [
"Funcion",
"que",
"calcula",
"el",
"precio",
"del",
"cubierto"
] | train | https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Mesa/Model/Mesa.php#L559-L572 |
alevilar/ristorantino-vendor | Mesa/Model/Mesa.php | Mesa.calcular_total | function calcular_total($id = null){
if (!empty($id)) $this->id = $id;
$subtotal = $this->calcular_subtotal();
$totalPorcentajeDescuento = $this->calcular_descuentos();
$conversionDescuento = 1-($totalPorcentajeDescuento/100);
$total = cqs_round( $subtotal * $conversionDescuento );
return $total;
} | php | function calcular_total($id = null){
if (!empty($id)) $this->id = $id;
$subtotal = $this->calcular_subtotal();
$totalPorcentajeDescuento = $this->calcular_descuentos();
$conversionDescuento = 1-($totalPorcentajeDescuento/100);
$total = cqs_round( $subtotal * $conversionDescuento );
return $total;
} | [
"function",
"calcular_total",
"(",
"$",
"id",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"id",
")",
")",
"$",
"this",
"->",
"id",
"=",
"$",
"id",
";",
"$",
"subtotal",
"=",
"$",
"this",
"->",
"calcular_subtotal",
"(",
")",
";",
"$",
"totalPorcentajeDescuento",
"=",
"$",
"this",
"->",
"calcular_descuentos",
"(",
")",
";",
"$",
"conversionDescuento",
"=",
"1",
"-",
"(",
"$",
"totalPorcentajeDescuento",
"/",
"100",
")",
";",
"$",
"total",
"=",
"cqs_round",
"(",
"$",
"subtotal",
"*",
"$",
"conversionDescuento",
")",
";",
"return",
"$",
"total",
";",
"}"
] | Calcula el total de la mesa cuyo id fue seteado en $this->Mesa->id
return @total el valor | [
"Calcula",
"el",
"total",
"de",
"la",
"mesa",
"cuyo",
"id",
"fue",
"seteado",
"en",
"$this",
"-",
">",
"Mesa",
"-",
">",
"id",
"return"
] | train | https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Mesa/Model/Mesa.php#L580-L591 |
alevilar/ristorantino-vendor | Mesa/Model/Mesa.php | Mesa.ultimasCobradas | function ultimasCobradas($limit = 20){
$conditions = array("Mesa.estado_id >=" => MESA_COBRADA);
$mesas = $this->find('all', array(
'conditions'=>$conditions,
'limit' => $limit,
));
return $mesas;
} | php | function ultimasCobradas($limit = 20){
$conditions = array("Mesa.estado_id >=" => MESA_COBRADA);
$mesas = $this->find('all', array(
'conditions'=>$conditions,
'limit' => $limit,
));
return $mesas;
} | [
"function",
"ultimasCobradas",
"(",
"$",
"limit",
"=",
"20",
")",
"{",
"$",
"conditions",
"=",
"array",
"(",
"\"Mesa.estado_id >=\"",
"=>",
"MESA_COBRADA",
")",
";",
"$",
"mesas",
"=",
"$",
"this",
"->",
"find",
"(",
"'all'",
",",
"array",
"(",
"'conditions'",
"=>",
"$",
"conditions",
",",
"'limit'",
"=>",
"$",
"limit",
",",
")",
")",
";",
"return",
"$",
"mesas",
";",
"}"
] | } | [
"}"
] | train | https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Mesa/Model/Mesa.php#L616-L626 |
alevilar/ristorantino-vendor | Mesa/Model/Mesa.php | Mesa.estaCobrada | function estaCobrada($id = null, $force_db = false){
$ret = false;
if (!empty($id)){
$this->id = $id;
}
if ( !empty($this->data[$this->name]['estado_id']) ){
$ret = $this->data[$this->name]['estado_id'] == MESA_COBRADA;
}
if ( $force_db) {
// lo busco en BBDD
$ret = $this->find('count', array(
'conditions' => array(
'Mesa.estado_id' => MESA_COBRADA,
'Mesa.id' => $this->id,
)
));
}
return $ret;
} | php | function estaCobrada($id = null, $force_db = false){
$ret = false;
if (!empty($id)){
$this->id = $id;
}
if ( !empty($this->data[$this->name]['estado_id']) ){
$ret = $this->data[$this->name]['estado_id'] == MESA_COBRADA;
}
if ( $force_db) {
// lo busco en BBDD
$ret = $this->find('count', array(
'conditions' => array(
'Mesa.estado_id' => MESA_COBRADA,
'Mesa.id' => $this->id,
)
));
}
return $ret;
} | [
"function",
"estaCobrada",
"(",
"$",
"id",
"=",
"null",
",",
"$",
"force_db",
"=",
"false",
")",
"{",
"$",
"ret",
"=",
"false",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"id",
")",
")",
"{",
"$",
"this",
"->",
"id",
"=",
"$",
"id",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"data",
"[",
"$",
"this",
"->",
"name",
"]",
"[",
"'estado_id'",
"]",
")",
")",
"{",
"$",
"ret",
"=",
"$",
"this",
"->",
"data",
"[",
"$",
"this",
"->",
"name",
"]",
"[",
"'estado_id'",
"]",
"==",
"MESA_COBRADA",
";",
"}",
"if",
"(",
"$",
"force_db",
")",
"{",
"// lo busco en BBDD ",
"$",
"ret",
"=",
"$",
"this",
"->",
"find",
"(",
"'count'",
",",
"array",
"(",
"'conditions'",
"=>",
"array",
"(",
"'Mesa.estado_id'",
"=>",
"MESA_COBRADA",
",",
"'Mesa.id'",
"=>",
"$",
"this",
"->",
"id",
",",
")",
")",
")",
";",
"}",
"return",
"$",
"ret",
";",
"}"
] | Dice si una mesa esta cobrada o no
@param integer $id
@param boolean $force_db indica si quiero forzar para que busque en la BBDD
@return boolean | [
"Dice",
"si",
"una",
"mesa",
"esta",
"cobrada",
"o",
"no"
] | train | https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Mesa/Model/Mesa.php#L746-L768 |
alevilar/ristorantino-vendor | Mesa/Model/Mesa.php | Mesa.estaAbierta | function estaAbierta($id = null){
if (!empty($id)){
$this->id = $id;
}
// lo busco en BBDD
$ret = $this->find('count', array(
'conditions' => array(
'Mesa.estado_id' => MESA_ABIERTA,
'Mesa.id' => $this->id,
)
));
return ($ret > 0);
} | php | function estaAbierta($id = null){
if (!empty($id)){
$this->id = $id;
}
// lo busco en BBDD
$ret = $this->find('count', array(
'conditions' => array(
'Mesa.estado_id' => MESA_ABIERTA,
'Mesa.id' => $this->id,
)
));
return ($ret > 0);
} | [
"function",
"estaAbierta",
"(",
"$",
"id",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"id",
")",
")",
"{",
"$",
"this",
"->",
"id",
"=",
"$",
"id",
";",
"}",
"// lo busco en BBDD ",
"$",
"ret",
"=",
"$",
"this",
"->",
"find",
"(",
"'count'",
",",
"array",
"(",
"'conditions'",
"=>",
"array",
"(",
"'Mesa.estado_id'",
"=>",
"MESA_ABIERTA",
",",
"'Mesa.id'",
"=>",
"$",
"this",
"->",
"id",
",",
")",
")",
")",
";",
"return",
"(",
"$",
"ret",
">",
"0",
")",
";",
"}"
] | Dice si una mesa esta abierta o no
@param integer $id
@return boolean | [
"Dice",
"si",
"una",
"mesa",
"esta",
"abierta",
"o",
"no"
] | train | https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Mesa/Model/Mesa.php#L780-L793 |
alevilar/ristorantino-vendor | Mesa/Model/Mesa.php | Mesa.totalesDeMesasEntre | function totalesDeMesasEntre($fechaDesde = '', $fechaHasta = '', $conds = array()){
$horarioCorte = Configure::read('Horario.corte_del_dia');
if ( $horarioCorte < 10 ) {
$horarioCorte = "0$horarioCorte";
}
$sqlHorarioDeCorte = "DATE(SUBTIME(Mesa.checkin, '$horarioCorte:00:00'))";
$desde = empty($fechaDesde) ? date('Y-m-d', strtotime('now')) : $fechaDesde;
$hasta = empty($fechaHasta) ? date('Y-m-d', strtotime('now')) : $fechaHasta;
$defaultOrder = array();
$defaultFields = array(
'count(*) as "cant_mesas"',
'sum(Mesa.cant_comensales) as "cant_cubiertos"',
'sum(Mesa.subtotal) as "subtotal"',
'sum(Mesa.total) as "total"',
'sum(Mesa.total)/sum(Mesa.cant_comensales) as "promedio_cubiertos"',
"$sqlHorarioDeCorte as fecha",
);
$defaultGroup = array(
"$sqlHorarioDeCorte" ,
);
if ( empty($conds['order'])) {
$defaultOrder = array(
"Mesa.checkin DESC"
);
}
$defaultConditions = array(
'Mesa.deleted' => '0', // mesas no borradas
"$sqlHorarioDeCorte BETWEEN '$desde' AND '$hasta'"
);
$ops = array(
'fields' => $defaultFields,
'conditions' => $defaultConditions,
'group' => $defaultGroup,
'order' => $defaultOrder,
);
$ops = array_merge_recursive($ops, $conds);
$mesas = $this->find('all', $ops);
return $mesas;
} | php | function totalesDeMesasEntre($fechaDesde = '', $fechaHasta = '', $conds = array()){
$horarioCorte = Configure::read('Horario.corte_del_dia');
if ( $horarioCorte < 10 ) {
$horarioCorte = "0$horarioCorte";
}
$sqlHorarioDeCorte = "DATE(SUBTIME(Mesa.checkin, '$horarioCorte:00:00'))";
$desde = empty($fechaDesde) ? date('Y-m-d', strtotime('now')) : $fechaDesde;
$hasta = empty($fechaHasta) ? date('Y-m-d', strtotime('now')) : $fechaHasta;
$defaultOrder = array();
$defaultFields = array(
'count(*) as "cant_mesas"',
'sum(Mesa.cant_comensales) as "cant_cubiertos"',
'sum(Mesa.subtotal) as "subtotal"',
'sum(Mesa.total) as "total"',
'sum(Mesa.total)/sum(Mesa.cant_comensales) as "promedio_cubiertos"',
"$sqlHorarioDeCorte as fecha",
);
$defaultGroup = array(
"$sqlHorarioDeCorte" ,
);
if ( empty($conds['order'])) {
$defaultOrder = array(
"Mesa.checkin DESC"
);
}
$defaultConditions = array(
'Mesa.deleted' => '0', // mesas no borradas
"$sqlHorarioDeCorte BETWEEN '$desde' AND '$hasta'"
);
$ops = array(
'fields' => $defaultFields,
'conditions' => $defaultConditions,
'group' => $defaultGroup,
'order' => $defaultOrder,
);
$ops = array_merge_recursive($ops, $conds);
$mesas = $this->find('all', $ops);
return $mesas;
} | [
"function",
"totalesDeMesasEntre",
"(",
"$",
"fechaDesde",
"=",
"''",
",",
"$",
"fechaHasta",
"=",
"''",
",",
"$",
"conds",
"=",
"array",
"(",
")",
")",
"{",
"$",
"horarioCorte",
"=",
"Configure",
"::",
"read",
"(",
"'Horario.corte_del_dia'",
")",
";",
"if",
"(",
"$",
"horarioCorte",
"<",
"10",
")",
"{",
"$",
"horarioCorte",
"=",
"\"0$horarioCorte\"",
";",
"}",
"$",
"sqlHorarioDeCorte",
"=",
"\"DATE(SUBTIME(Mesa.checkin, '$horarioCorte:00:00'))\"",
";",
"$",
"desde",
"=",
"empty",
"(",
"$",
"fechaDesde",
")",
"?",
"date",
"(",
"'Y-m-d'",
",",
"strtotime",
"(",
"'now'",
")",
")",
":",
"$",
"fechaDesde",
";",
"$",
"hasta",
"=",
"empty",
"(",
"$",
"fechaHasta",
")",
"?",
"date",
"(",
"'Y-m-d'",
",",
"strtotime",
"(",
"'now'",
")",
")",
":",
"$",
"fechaHasta",
";",
"$",
"defaultOrder",
"=",
"array",
"(",
")",
";",
"$",
"defaultFields",
"=",
"array",
"(",
"'count(*) as \"cant_mesas\"'",
",",
"'sum(Mesa.cant_comensales) as \"cant_cubiertos\"'",
",",
"'sum(Mesa.subtotal) as \"subtotal\"'",
",",
"'sum(Mesa.total) as \"total\"'",
",",
"'sum(Mesa.total)/sum(Mesa.cant_comensales) as \"promedio_cubiertos\"'",
",",
"\"$sqlHorarioDeCorte as fecha\"",
",",
")",
";",
"$",
"defaultGroup",
"=",
"array",
"(",
"\"$sqlHorarioDeCorte\"",
",",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"conds",
"[",
"'order'",
"]",
")",
")",
"{",
"$",
"defaultOrder",
"=",
"array",
"(",
"\"Mesa.checkin DESC\"",
")",
";",
"}",
"$",
"defaultConditions",
"=",
"array",
"(",
"'Mesa.deleted'",
"=>",
"'0'",
",",
"// mesas no borradas",
"\"$sqlHorarioDeCorte BETWEEN '$desde' AND '$hasta'\"",
")",
";",
"$",
"ops",
"=",
"array",
"(",
"'fields'",
"=>",
"$",
"defaultFields",
",",
"'conditions'",
"=>",
"$",
"defaultConditions",
",",
"'group'",
"=>",
"$",
"defaultGroup",
",",
"'order'",
"=>",
"$",
"defaultOrder",
",",
")",
";",
"$",
"ops",
"=",
"array_merge_recursive",
"(",
"$",
"ops",
",",
"$",
"conds",
")",
";",
"$",
"mesas",
"=",
"$",
"this",
"->",
"find",
"(",
"'all'",
",",
"$",
"ops",
")",
";",
"return",
"$",
"mesas",
";",
"}"
] | Me devuelve un listado agrupado por dia de mesas. Util para estadistica y contabilidad
@param type $fechaDesde string formato de fecha debe ser del tip AÑO-mes-dia Y-m-d
@param type $fechaHasta string formato de fecha debe ser del tip AÑO-mes-dia Y-m-d
@param type $conds array de condiciones extra | [
"Me",
"devuelve",
"un",
"listado",
"agrupado",
"por",
"dia",
"de",
"mesas",
".",
"Util",
"para",
"estadistica",
"y",
"contabilidad"
] | train | https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Mesa/Model/Mesa.php#L826-L868 |
alevilar/ristorantino-vendor | Mesa/Model/Mesa.php | Mesa.getMesasForRoom | public function getMesasForRoom($nombre_mesa_id, $left, $right) {
$this->recursive = 0;
$options = array('conditions' => array(
'Mesa.checkin <=' => $right . ' 00:00:00',
'Mesa.checkout >=' => $left . ' 23:59:59',
'Mesa.nombre_mesa_id' => $nombre_mesa_id
));
// print_r($this->find('all', $options));die;
return $this->find('all', $options);
} | php | public function getMesasForRoom($nombre_mesa_id, $left, $right) {
$this->recursive = 0;
$options = array('conditions' => array(
'Mesa.checkin <=' => $right . ' 00:00:00',
'Mesa.checkout >=' => $left . ' 23:59:59',
'Mesa.nombre_mesa_id' => $nombre_mesa_id
));
// print_r($this->find('all', $options));die;
return $this->find('all', $options);
} | [
"public",
"function",
"getMesasForRoom",
"(",
"$",
"nombre_mesa_id",
",",
"$",
"left",
",",
"$",
"right",
")",
"{",
"$",
"this",
"->",
"recursive",
"=",
"0",
";",
"$",
"options",
"=",
"array",
"(",
"'conditions'",
"=>",
"array",
"(",
"'Mesa.checkin <='",
"=>",
"$",
"right",
".",
"' 00:00:00'",
",",
"'Mesa.checkout >='",
"=>",
"$",
"left",
".",
"' 23:59:59'",
",",
"'Mesa.nombre_mesa_id'",
"=>",
"$",
"nombre_mesa_id",
")",
")",
";",
"// print_r($this->find('all', $options));die;",
"return",
"$",
"this",
"->",
"find",
"(",
"'all'",
",",
"$",
"options",
")",
";",
"}"
] | Description
@param type $nombre_mesa_id
@param type $left
@param type $right
@return type | [
"Description"
] | train | https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Mesa/Model/Mesa.php#L897-L906 |
alevilar/ristorantino-vendor | Mesa/Model/Mesa.php | Mesa.changeRoomStateIfTodayInPeriod | public function changeRoomStateIfTodayInPeriod($room, $checkin, $checkout) {
if (!is_array($room) && (is_string($room) || is_int($room))) {
$room = $this->Room->findById($room);
}
$today = date('Y-m-d');
if ($this->hasRoomMesaInDate($room, $today)) {
return $this->Room->changeRoomState($room, 2); // 2 = Ocupada
} else {
if ($room['Room']['room_state_id'] != 4) {
return $this->Room->changeRoomState($room, 1);
}
}
} | php | public function changeRoomStateIfTodayInPeriod($room, $checkin, $checkout) {
if (!is_array($room) && (is_string($room) || is_int($room))) {
$room = $this->Room->findById($room);
}
$today = date('Y-m-d');
if ($this->hasRoomMesaInDate($room, $today)) {
return $this->Room->changeRoomState($room, 2); // 2 = Ocupada
} else {
if ($room['Room']['room_state_id'] != 4) {
return $this->Room->changeRoomState($room, 1);
}
}
} | [
"public",
"function",
"changeRoomStateIfTodayInPeriod",
"(",
"$",
"room",
",",
"$",
"checkin",
",",
"$",
"checkout",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"room",
")",
"&&",
"(",
"is_string",
"(",
"$",
"room",
")",
"||",
"is_int",
"(",
"$",
"room",
")",
")",
")",
"{",
"$",
"room",
"=",
"$",
"this",
"->",
"Room",
"->",
"findById",
"(",
"$",
"room",
")",
";",
"}",
"$",
"today",
"=",
"date",
"(",
"'Y-m-d'",
")",
";",
"if",
"(",
"$",
"this",
"->",
"hasRoomMesaInDate",
"(",
"$",
"room",
",",
"$",
"today",
")",
")",
"{",
"return",
"$",
"this",
"->",
"Room",
"->",
"changeRoomState",
"(",
"$",
"room",
",",
"2",
")",
";",
"// 2 = Ocupada",
"}",
"else",
"{",
"if",
"(",
"$",
"room",
"[",
"'Room'",
"]",
"[",
"'room_state_id'",
"]",
"!=",
"4",
")",
"{",
"return",
"$",
"this",
"->",
"Room",
"->",
"changeRoomState",
"(",
"$",
"room",
",",
"1",
")",
";",
"}",
"}",
"}"
] | change the room state if today is between period of Mesa for a given nombre_mesa_id or room object
@param int|array $room
@param string $checkin
@param string $checkout
@return void | [
"change",
"the",
"room",
"state",
"if",
"today",
"is",
"between",
"period",
"of",
"Mesa",
"for",
"a",
"given",
"nombre_mesa_id",
"or",
"room",
"object"
] | train | https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Mesa/Model/Mesa.php#L945-L957 |
ouropencode/dachi | src/Console/Application.php | Application.create | public static function create() {
$app = new CLIApplication('Dachi', Kernel::getVersion(true));
$commands = array(
new \Dachi\Core\Console\Command\TestCommand(),
new \Dachi\Core\Console\Command\CreateCommand(),
new \Dachi\Core\Console\Command\DocumentCommand(),
/** run under 'dachi:all' **/
new \Dachi\Core\Console\Command\RouteCommand(),
new \Dachi\Core\Console\Command\ModulesCommand(),
new \Dachi\Core\Console\Command\ConfigCommand(),
new \Dachi\Core\Console\Command\AllCommand()
/** end run under 'dachi:all' **/
);
foreach($commands as $commandClass) {
$app->add($commandClass);
}
$app->run();
} | php | public static function create() {
$app = new CLIApplication('Dachi', Kernel::getVersion(true));
$commands = array(
new \Dachi\Core\Console\Command\TestCommand(),
new \Dachi\Core\Console\Command\CreateCommand(),
new \Dachi\Core\Console\Command\DocumentCommand(),
/** run under 'dachi:all' **/
new \Dachi\Core\Console\Command\RouteCommand(),
new \Dachi\Core\Console\Command\ModulesCommand(),
new \Dachi\Core\Console\Command\ConfigCommand(),
new \Dachi\Core\Console\Command\AllCommand()
/** end run under 'dachi:all' **/
);
foreach($commands as $commandClass) {
$app->add($commandClass);
}
$app->run();
} | [
"public",
"static",
"function",
"create",
"(",
")",
"{",
"$",
"app",
"=",
"new",
"CLIApplication",
"(",
"'Dachi'",
",",
"Kernel",
"::",
"getVersion",
"(",
"true",
")",
")",
";",
"$",
"commands",
"=",
"array",
"(",
"new",
"\\",
"Dachi",
"\\",
"Core",
"\\",
"Console",
"\\",
"Command",
"\\",
"TestCommand",
"(",
")",
",",
"new",
"\\",
"Dachi",
"\\",
"Core",
"\\",
"Console",
"\\",
"Command",
"\\",
"CreateCommand",
"(",
")",
",",
"new",
"\\",
"Dachi",
"\\",
"Core",
"\\",
"Console",
"\\",
"Command",
"\\",
"DocumentCommand",
"(",
")",
",",
"/** run under 'dachi:all' **/",
"new",
"\\",
"Dachi",
"\\",
"Core",
"\\",
"Console",
"\\",
"Command",
"\\",
"RouteCommand",
"(",
")",
",",
"new",
"\\",
"Dachi",
"\\",
"Core",
"\\",
"Console",
"\\",
"Command",
"\\",
"ModulesCommand",
"(",
")",
",",
"new",
"\\",
"Dachi",
"\\",
"Core",
"\\",
"Console",
"\\",
"Command",
"\\",
"ConfigCommand",
"(",
")",
",",
"new",
"\\",
"Dachi",
"\\",
"Core",
"\\",
"Console",
"\\",
"Command",
"\\",
"AllCommand",
"(",
")",
"/** end run under 'dachi:all' **/",
")",
";",
"foreach",
"(",
"$",
"commands",
"as",
"$",
"commandClass",
")",
"{",
"$",
"app",
"->",
"add",
"(",
"$",
"commandClass",
")",
";",
"}",
"$",
"app",
"->",
"run",
"(",
")",
";",
"}"
] | Create the CLI application
@return null | [
"Create",
"the",
"CLI",
"application"
] | train | https://github.com/ouropencode/dachi/blob/a0e1daf269d0345afbb859ce20ef9da6decd7efe/src/Console/Application.php#L21-L43 |
heidelpay/PhpDoc | src/phpDocumentor/Parser/ServiceProvider.php | ServiceProvider.register | public function register(Application $app)
{
if (!isset($app['descriptor.builder'])) {
throw new Exception\MissingDependencyException(
'The builder object that is used to construct the ProjectDescriptor is missing'
);
}
$app['parser'] = $app->share(
function ($app) {
$parser = new Parser();
$parser->setStopwatch($app['kernel.stopwatch']);
$parser->setLogger($app['monolog']);
return $parser;
}
);
$app['markdown'] = $app->share(
function () {
return \Parsedown::instance();
}
);
/** @var Translator $translator */
$translator = $app['translator'];
$translator->addTranslationFolder(__DIR__ . DIRECTORY_SEPARATOR . 'Messages');
$app['parser.files'] = new Collection();
$app->command(new ParseCommand($app['descriptor.builder'], $app['parser'], $translator, $app['parser.files']));
} | php | public function register(Application $app)
{
if (!isset($app['descriptor.builder'])) {
throw new Exception\MissingDependencyException(
'The builder object that is used to construct the ProjectDescriptor is missing'
);
}
$app['parser'] = $app->share(
function ($app) {
$parser = new Parser();
$parser->setStopwatch($app['kernel.stopwatch']);
$parser->setLogger($app['monolog']);
return $parser;
}
);
$app['markdown'] = $app->share(
function () {
return \Parsedown::instance();
}
);
/** @var Translator $translator */
$translator = $app['translator'];
$translator->addTranslationFolder(__DIR__ . DIRECTORY_SEPARATOR . 'Messages');
$app['parser.files'] = new Collection();
$app->command(new ParseCommand($app['descriptor.builder'], $app['parser'], $translator, $app['parser.files']));
} | [
"public",
"function",
"register",
"(",
"Application",
"$",
"app",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"app",
"[",
"'descriptor.builder'",
"]",
")",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"MissingDependencyException",
"(",
"'The builder object that is used to construct the ProjectDescriptor is missing'",
")",
";",
"}",
"$",
"app",
"[",
"'parser'",
"]",
"=",
"$",
"app",
"->",
"share",
"(",
"function",
"(",
"$",
"app",
")",
"{",
"$",
"parser",
"=",
"new",
"Parser",
"(",
")",
";",
"$",
"parser",
"->",
"setStopwatch",
"(",
"$",
"app",
"[",
"'kernel.stopwatch'",
"]",
")",
";",
"$",
"parser",
"->",
"setLogger",
"(",
"$",
"app",
"[",
"'monolog'",
"]",
")",
";",
"return",
"$",
"parser",
";",
"}",
")",
";",
"$",
"app",
"[",
"'markdown'",
"]",
"=",
"$",
"app",
"->",
"share",
"(",
"function",
"(",
")",
"{",
"return",
"\\",
"Parsedown",
"::",
"instance",
"(",
")",
";",
"}",
")",
";",
"/** @var Translator $translator */",
"$",
"translator",
"=",
"$",
"app",
"[",
"'translator'",
"]",
";",
"$",
"translator",
"->",
"addTranslationFolder",
"(",
"__DIR__",
".",
"DIRECTORY_SEPARATOR",
".",
"'Messages'",
")",
";",
"$",
"app",
"[",
"'parser.files'",
"]",
"=",
"new",
"Collection",
"(",
")",
";",
"$",
"app",
"->",
"command",
"(",
"new",
"ParseCommand",
"(",
"$",
"app",
"[",
"'descriptor.builder'",
"]",
",",
"$",
"app",
"[",
"'parser'",
"]",
",",
"$",
"translator",
",",
"$",
"app",
"[",
"'parser.files'",
"]",
")",
")",
";",
"}"
] | Registers services on the given app.
@param Application $app An Application instance
@throws Exception\MissingDependencyException if the Descriptor Builder is not present.
@return void | [
"Registers",
"services",
"on",
"the",
"given",
"app",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Parser/ServiceProvider.php#L36-L66 |
heidelpay/PhpDoc | src/phpDocumentor/Parser/ServiceProvider.php | ServiceProvider.validateDocBlocks | public function validateDocBlocks($data)
{
/** @var \phpDocumentor\Reflection\BaseReflector $element */
$element = $data->getSubject();
/** @var \phpDocumentor\Reflection\DocBlock $docblock */
$docblock = $data->getDocblock();
// get the type of element
$type = substr(
get_class($element),
strrpos(get_class($element), '\\') + 1,
-9 // Reflector
);
// no docblock, or docblock should be ignored, so no reason to validate
if ($docblock && $docblock->hasTag('ignore')) {
return;
}
$validatorOptions = $this->loadConfiguration();
foreach (array('Deprecated', 'Required', $type) as $validator) {
// todo: move to a factory or builder class
$class = 'phpDocumentor\Plugin\Core\Parser\DocBlock\Validator\\' . $validator . 'Validator';
if (class_exists($class)) {
/** @var ValidatorAbstract $val */
$val = new $class($element->getName(), $docblock, $element);
$val->setOptions($validatorOptions);
$val->isValid($element);
}
}
} | php | public function validateDocBlocks($data)
{
/** @var \phpDocumentor\Reflection\BaseReflector $element */
$element = $data->getSubject();
/** @var \phpDocumentor\Reflection\DocBlock $docblock */
$docblock = $data->getDocblock();
// get the type of element
$type = substr(
get_class($element),
strrpos(get_class($element), '\\') + 1,
-9 // Reflector
);
// no docblock, or docblock should be ignored, so no reason to validate
if ($docblock && $docblock->hasTag('ignore')) {
return;
}
$validatorOptions = $this->loadConfiguration();
foreach (array('Deprecated', 'Required', $type) as $validator) {
// todo: move to a factory or builder class
$class = 'phpDocumentor\Plugin\Core\Parser\DocBlock\Validator\\' . $validator . 'Validator';
if (class_exists($class)) {
/** @var ValidatorAbstract $val */
$val = new $class($element->getName(), $docblock, $element);
$val->setOptions($validatorOptions);
$val->isValid($element);
}
}
} | [
"public",
"function",
"validateDocBlocks",
"(",
"$",
"data",
")",
"{",
"/** @var \\phpDocumentor\\Reflection\\BaseReflector $element */",
"$",
"element",
"=",
"$",
"data",
"->",
"getSubject",
"(",
")",
";",
"/** @var \\phpDocumentor\\Reflection\\DocBlock $docblock */",
"$",
"docblock",
"=",
"$",
"data",
"->",
"getDocblock",
"(",
")",
";",
"// get the type of element",
"$",
"type",
"=",
"substr",
"(",
"get_class",
"(",
"$",
"element",
")",
",",
"strrpos",
"(",
"get_class",
"(",
"$",
"element",
")",
",",
"'\\\\'",
")",
"+",
"1",
",",
"-",
"9",
"// Reflector",
")",
";",
"// no docblock, or docblock should be ignored, so no reason to validate",
"if",
"(",
"$",
"docblock",
"&&",
"$",
"docblock",
"->",
"hasTag",
"(",
"'ignore'",
")",
")",
"{",
"return",
";",
"}",
"$",
"validatorOptions",
"=",
"$",
"this",
"->",
"loadConfiguration",
"(",
")",
";",
"foreach",
"(",
"array",
"(",
"'Deprecated'",
",",
"'Required'",
",",
"$",
"type",
")",
"as",
"$",
"validator",
")",
"{",
"// todo: move to a factory or builder class",
"$",
"class",
"=",
"'phpDocumentor\\Plugin\\Core\\Parser\\DocBlock\\Validator\\\\'",
".",
"$",
"validator",
".",
"'Validator'",
";",
"if",
"(",
"class_exists",
"(",
"$",
"class",
")",
")",
"{",
"/** @var ValidatorAbstract $val */",
"$",
"val",
"=",
"new",
"$",
"class",
"(",
"$",
"element",
"->",
"getName",
"(",
")",
",",
"$",
"docblock",
",",
"$",
"element",
")",
";",
"$",
"val",
"->",
"setOptions",
"(",
"$",
"validatorOptions",
")",
";",
"$",
"val",
"->",
"isValid",
"(",
"$",
"element",
")",
";",
"}",
"}",
"}"
] | Checks all phpDocumentor whether they match the given rules.
@param PostDocBlockExtractionEvent $data Event object containing the parameters.
@todo convert this method to the new style validators; this method is not invoked anymore
@return void | [
"Checks",
"all",
"phpDocumentor",
"whether",
"they",
"match",
"the",
"given",
"rules",
"."
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Parser/ServiceProvider.php#L77-L110 |
heidelpay/PhpDoc | src/phpDocumentor/Parser/ServiceProvider.php | ServiceProvider.loadConfigurationByElement | protected function loadConfigurationByElement($configOptions, $configType)
{
$validatorOptions = array();
if (isset($configOptions[$configType]->tag)) {
foreach ($configOptions[$configType]->tag as $tag) {
$tagName = (string) $tag['name'];
if (isset($tag->element)) {
foreach ($tag->element as $type) {
$typeName = (string) $type;
$validatorOptions[$typeName][] = $tagName;
}
} else {
$validatorOptions['__ALL__'][] = $tagName;
}
}
}
return $validatorOptions;
} | php | protected function loadConfigurationByElement($configOptions, $configType)
{
$validatorOptions = array();
if (isset($configOptions[$configType]->tag)) {
foreach ($configOptions[$configType]->tag as $tag) {
$tagName = (string) $tag['name'];
if (isset($tag->element)) {
foreach ($tag->element as $type) {
$typeName = (string) $type;
$validatorOptions[$typeName][] = $tagName;
}
} else {
$validatorOptions['__ALL__'][] = $tagName;
}
}
}
return $validatorOptions;
} | [
"protected",
"function",
"loadConfigurationByElement",
"(",
"$",
"configOptions",
",",
"$",
"configType",
")",
"{",
"$",
"validatorOptions",
"=",
"array",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"configOptions",
"[",
"$",
"configType",
"]",
"->",
"tag",
")",
")",
"{",
"foreach",
"(",
"$",
"configOptions",
"[",
"$",
"configType",
"]",
"->",
"tag",
"as",
"$",
"tag",
")",
"{",
"$",
"tagName",
"=",
"(",
"string",
")",
"$",
"tag",
"[",
"'name'",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"tag",
"->",
"element",
")",
")",
"{",
"foreach",
"(",
"$",
"tag",
"->",
"element",
"as",
"$",
"type",
")",
"{",
"$",
"typeName",
"=",
"(",
"string",
")",
"$",
"type",
";",
"$",
"validatorOptions",
"[",
"$",
"typeName",
"]",
"[",
"]",
"=",
"$",
"tagName",
";",
"}",
"}",
"else",
"{",
"$",
"validatorOptions",
"[",
"'__ALL__'",
"]",
"[",
"]",
"=",
"$",
"tagName",
";",
"}",
"}",
"}",
"return",
"$",
"validatorOptions",
";",
"}"
] | Load the configuration for given element (deprecated/required)
@param array $configOptions The configuration from the plugin.xml file
@param string $configType Required/Deprecated for the time being
@return array | [
"Load",
"the",
"configuration",
"for",
"given",
"element",
"(",
"deprecated",
"/",
"required",
")"
] | train | https://github.com/heidelpay/PhpDoc/blob/5ac9e842cbd4cbb70900533b240c131f3515ee02/src/phpDocumentor/Parser/ServiceProvider.php#L139-L160 |
neat-php/database | classes/Connection.php | Connection.pdo | public function pdo(PDO $pdo = null)
{
if ($pdo) {
$this->pdo = $pdo;
}
return $this->pdo;
} | php | public function pdo(PDO $pdo = null)
{
if ($pdo) {
$this->pdo = $pdo;
}
return $this->pdo;
} | [
"public",
"function",
"pdo",
"(",
"PDO",
"$",
"pdo",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"pdo",
")",
"{",
"$",
"this",
"->",
"pdo",
"=",
"$",
"pdo",
";",
"}",
"return",
"$",
"this",
"->",
"pdo",
";",
"}"
] | Get or set PDO instance
@param PDO $pdo (optional)
@return PDO | [
"Get",
"or",
"set",
"PDO",
"instance"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Connection.php#L64-L71 |
neat-php/database | classes/Connection.php | Connection.quote | public function quote($value)
{
if ($value === null) {
return 'NULL';
}
if ($value instanceof DateTimeInterface) {
return $this->pdo->quote($value->format('Y-m-d H:i:s'));
}
if (is_array($value)) {
return implode(',', array_map([$this, 'quote'], $value));
}
if (is_bool($value)) {
return $this->pdo->quote($value ? 1 : 0);
}
return $this->pdo->quote($value);
} | php | public function quote($value)
{
if ($value === null) {
return 'NULL';
}
if ($value instanceof DateTimeInterface) {
return $this->pdo->quote($value->format('Y-m-d H:i:s'));
}
if (is_array($value)) {
return implode(',', array_map([$this, 'quote'], $value));
}
if (is_bool($value)) {
return $this->pdo->quote($value ? 1 : 0);
}
return $this->pdo->quote($value);
} | [
"public",
"function",
"quote",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"return",
"'NULL'",
";",
"}",
"if",
"(",
"$",
"value",
"instanceof",
"DateTimeInterface",
")",
"{",
"return",
"$",
"this",
"->",
"pdo",
"->",
"quote",
"(",
"$",
"value",
"->",
"format",
"(",
"'Y-m-d H:i:s'",
")",
")",
";",
"}",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"return",
"implode",
"(",
"','",
",",
"array_map",
"(",
"[",
"$",
"this",
",",
"'quote'",
"]",
",",
"$",
"value",
")",
")",
";",
"}",
"if",
"(",
"is_bool",
"(",
"$",
"value",
")",
")",
"{",
"return",
"$",
"this",
"->",
"pdo",
"->",
"quote",
"(",
"$",
"value",
"?",
"1",
":",
"0",
")",
";",
"}",
"return",
"$",
"this",
"->",
"pdo",
"->",
"quote",
"(",
"$",
"value",
")",
";",
"}"
] | Quote a value (protecting against SQL injection)
@param string|null|DateTimeInterface|array|bool $value
@return string | [
"Quote",
"a",
"value",
"(",
"protecting",
"against",
"SQL",
"injection",
")"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Connection.php#L79-L95 |
neat-php/database | classes/Connection.php | Connection.quoteIdentifier | public function quoteIdentifier($identifier)
{
$parts = explode(".", $identifier);
if (count($parts) > 1) {
return $this->quoteIdentifier($parts[0]) . '.' . $this->quoteIdentifier($parts[1]);
}
return '`' . str_replace('`', '``', $identifier) . '`';
} | php | public function quoteIdentifier($identifier)
{
$parts = explode(".", $identifier);
if (count($parts) > 1) {
return $this->quoteIdentifier($parts[0]) . '.' . $this->quoteIdentifier($parts[1]);
}
return '`' . str_replace('`', '``', $identifier) . '`';
} | [
"public",
"function",
"quoteIdentifier",
"(",
"$",
"identifier",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"\".\"",
",",
"$",
"identifier",
")",
";",
"if",
"(",
"count",
"(",
"$",
"parts",
")",
">",
"1",
")",
"{",
"return",
"$",
"this",
"->",
"quoteIdentifier",
"(",
"$",
"parts",
"[",
"0",
"]",
")",
".",
"'.'",
".",
"$",
"this",
"->",
"quoteIdentifier",
"(",
"$",
"parts",
"[",
"1",
"]",
")",
";",
"}",
"return",
"'`'",
".",
"str_replace",
"(",
"'`'",
",",
"'``'",
",",
"$",
"identifier",
")",
".",
"'`'",
";",
"}"
] | Quote an identifier for MySQL query usage
@param string $identifier
@return string | [
"Quote",
"an",
"identifier",
"for",
"MySQL",
"query",
"usage"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Connection.php#L103-L111 |
neat-php/database | classes/Connection.php | Connection.merge | public function merge($query, array $data)
{
$expression = "/(\\?)(?=(?:[^']|'[^']*')*$)/";
$callback = function () use (&$data) {
if (!$data) {
return '?';
}
return $this->quote(array_shift($data));
};
return preg_replace_callback($expression, $callback, $query);
} | php | public function merge($query, array $data)
{
$expression = "/(\\?)(?=(?:[^']|'[^']*')*$)/";
$callback = function () use (&$data) {
if (!$data) {
return '?';
}
return $this->quote(array_shift($data));
};
return preg_replace_callback($expression, $callback, $query);
} | [
"public",
"function",
"merge",
"(",
"$",
"query",
",",
"array",
"$",
"data",
")",
"{",
"$",
"expression",
"=",
"\"/(\\\\?)(?=(?:[^']|'[^']*')*$)/\"",
";",
"$",
"callback",
"=",
"function",
"(",
")",
"use",
"(",
"&",
"$",
"data",
")",
"{",
"if",
"(",
"!",
"$",
"data",
")",
"{",
"return",
"'?'",
";",
"}",
"return",
"$",
"this",
"->",
"quote",
"(",
"array_shift",
"(",
"$",
"data",
")",
")",
";",
"}",
";",
"return",
"preg_replace_callback",
"(",
"$",
"expression",
",",
"$",
"callback",
",",
"$",
"query",
")",
";",
"}"
] | Merge data into an SQL query with placeholders
@param string $query
@param array $data
@return string | [
"Merge",
"data",
"into",
"an",
"SQL",
"query",
"with",
"placeholders"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Connection.php#L120-L132 |
neat-php/database | classes/Connection.php | Connection.query | public function query($query, ...$data)
{
if ($data) {
$query = $this->merge($query, $data);
}
try {
$statement = $this->pdo->query($query);
return new Result($statement);
} catch (PDOException $exception) {
throw new QueryException($exception, $query);
}
} | php | public function query($query, ...$data)
{
if ($data) {
$query = $this->merge($query, $data);
}
try {
$statement = $this->pdo->query($query);
return new Result($statement);
} catch (PDOException $exception) {
throw new QueryException($exception, $query);
}
} | [
"public",
"function",
"query",
"(",
"$",
"query",
",",
"...",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"data",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"merge",
"(",
"$",
"query",
",",
"$",
"data",
")",
";",
"}",
"try",
"{",
"$",
"statement",
"=",
"$",
"this",
"->",
"pdo",
"->",
"query",
"(",
"$",
"query",
")",
";",
"return",
"new",
"Result",
"(",
"$",
"statement",
")",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"exception",
")",
"{",
"throw",
"new",
"QueryException",
"(",
"$",
"exception",
",",
"$",
"query",
")",
";",
"}",
"}"
] | Run a query and return the result
The result can be interactively fetched, but only once due to the
forward-only cursor being used to fetch the results.
@param string $query
@param mixed ...$data
@return Result
@throws QueryException | [
"Run",
"a",
"query",
"and",
"return",
"the",
"result"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Connection.php#L145-L158 |
neat-php/database | classes/Connection.php | Connection.fetch | public function fetch($query, ...$data)
{
if ($data) {
$query = $this->merge($query, $data);
}
try {
$statement = $this->pdo->query($query);
return new FetchedResult($statement->fetchAll(PDO::FETCH_ASSOC));
} catch (PDOException $exception) {
throw new QueryException($exception, $query);
}
} | php | public function fetch($query, ...$data)
{
if ($data) {
$query = $this->merge($query, $data);
}
try {
$statement = $this->pdo->query($query);
return new FetchedResult($statement->fetchAll(PDO::FETCH_ASSOC));
} catch (PDOException $exception) {
throw new QueryException($exception, $query);
}
} | [
"public",
"function",
"fetch",
"(",
"$",
"query",
",",
"...",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"data",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"merge",
"(",
"$",
"query",
",",
"$",
"data",
")",
";",
"}",
"try",
"{",
"$",
"statement",
"=",
"$",
"this",
"->",
"pdo",
"->",
"query",
"(",
"$",
"query",
")",
";",
"return",
"new",
"FetchedResult",
"(",
"$",
"statement",
"->",
"fetchAll",
"(",
"PDO",
"::",
"FETCH_ASSOC",
")",
")",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"exception",
")",
"{",
"throw",
"new",
"QueryException",
"(",
"$",
"exception",
",",
"$",
"query",
")",
";",
"}",
"}"
] | Run a query and eagerly fetch the result into memory
Allows the result to be used more than once, for example when you
want to count the result and then iterate over it. Normally the
result would be entirely consumed after counting its rows.
@param string $query
@param mixed ...$data
@return FetchedResult
@throws QueryException | [
"Run",
"a",
"query",
"and",
"eagerly",
"fetch",
"the",
"result",
"into",
"memory"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Connection.php#L172-L185 |
neat-php/database | classes/Connection.php | Connection.execute | public function execute($query, ...$data)
{
if ($data) {
$query = $this->merge($query, $data);
}
try {
return $this->pdo->exec($query);
} catch (PDOException $exception) {
throw new QueryException($exception, $query);
}
} | php | public function execute($query, ...$data)
{
if ($data) {
$query = $this->merge($query, $data);
}
try {
return $this->pdo->exec($query);
} catch (PDOException $exception) {
throw new QueryException($exception, $query);
}
} | [
"public",
"function",
"execute",
"(",
"$",
"query",
",",
"...",
"$",
"data",
")",
"{",
"if",
"(",
"$",
"data",
")",
"{",
"$",
"query",
"=",
"$",
"this",
"->",
"merge",
"(",
"$",
"query",
",",
"$",
"data",
")",
";",
"}",
"try",
"{",
"return",
"$",
"this",
"->",
"pdo",
"->",
"exec",
"(",
"$",
"query",
")",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"exception",
")",
"{",
"throw",
"new",
"QueryException",
"(",
"$",
"exception",
",",
"$",
"query",
")",
";",
"}",
"}"
] | Execute a query and return the number of rows affected
@param string $query
@param mixed ...$data
@return int
@throws QueryException | [
"Execute",
"a",
"query",
"and",
"return",
"the",
"number",
"of",
"rows",
"affected"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Connection.php#L195-L206 |
neat-php/database | classes/Connection.php | Connection.insert | public function insert($table, array $data = null)
{
$insert = $this->build()->insert($table);
if ($data) {
return $insert->values($data)->execute();
}
return $insert;
} | php | public function insert($table, array $data = null)
{
$insert = $this->build()->insert($table);
if ($data) {
return $insert->values($data)->execute();
}
return $insert;
} | [
"public",
"function",
"insert",
"(",
"$",
"table",
",",
"array",
"$",
"data",
"=",
"null",
")",
"{",
"$",
"insert",
"=",
"$",
"this",
"->",
"build",
"(",
")",
"->",
"insert",
"(",
"$",
"table",
")",
";",
"if",
"(",
"$",
"data",
")",
"{",
"return",
"$",
"insert",
"->",
"values",
"(",
"$",
"data",
")",
"->",
"execute",
"(",
")",
";",
"}",
"return",
"$",
"insert",
";",
"}"
] | Insert data into a table
When all parameters are specified, the insert query is immediately
executed and the number of rows affected will be returned. Otherwise
the query builder is returned so you can extend the query further.
@param string $table
@param array $data (optional)
@return Query|int
@throws QueryException | [
"Insert",
"data",
"into",
"a",
"table"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Connection.php#L251-L259 |
neat-php/database | classes/Connection.php | Connection.update | public function update($table, array $data = null, $where = null)
{
$update = $this->build()->update($table);
if ($data) {
$update->set($data);
}
if ($where) {
$update->where($where);
}
if ($data && $where) {
return $update->execute();
}
return $update;
} | php | public function update($table, array $data = null, $where = null)
{
$update = $this->build()->update($table);
if ($data) {
$update->set($data);
}
if ($where) {
$update->where($where);
}
if ($data && $where) {
return $update->execute();
}
return $update;
} | [
"public",
"function",
"update",
"(",
"$",
"table",
",",
"array",
"$",
"data",
"=",
"null",
",",
"$",
"where",
"=",
"null",
")",
"{",
"$",
"update",
"=",
"$",
"this",
"->",
"build",
"(",
")",
"->",
"update",
"(",
"$",
"table",
")",
";",
"if",
"(",
"$",
"data",
")",
"{",
"$",
"update",
"->",
"set",
"(",
"$",
"data",
")",
";",
"}",
"if",
"(",
"$",
"where",
")",
"{",
"$",
"update",
"->",
"where",
"(",
"$",
"where",
")",
";",
"}",
"if",
"(",
"$",
"data",
"&&",
"$",
"where",
")",
"{",
"return",
"$",
"update",
"->",
"execute",
"(",
")",
";",
"}",
"return",
"$",
"update",
";",
"}"
] | Update data in a table
When all parameters are specified, the update query is immediately
executed and the number of rows affected will be returned. Otherwise
the query builder is returned so you can extend the query further.
@param string $table
@param array $data (optional)
@param array|string $where (optional)
@return Query|int
@throws QueryException | [
"Update",
"data",
"in",
"a",
"table"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Connection.php#L274-L288 |
neat-php/database | classes/Connection.php | Connection.delete | public function delete($table, $where = null)
{
$delete = $this->build()->delete($table);
if ($where) {
return $delete->where($where)->execute();
}
return $delete;
} | php | public function delete($table, $where = null)
{
$delete = $this->build()->delete($table);
if ($where) {
return $delete->where($where)->execute();
}
return $delete;
} | [
"public",
"function",
"delete",
"(",
"$",
"table",
",",
"$",
"where",
"=",
"null",
")",
"{",
"$",
"delete",
"=",
"$",
"this",
"->",
"build",
"(",
")",
"->",
"delete",
"(",
"$",
"table",
")",
";",
"if",
"(",
"$",
"where",
")",
"{",
"return",
"$",
"delete",
"->",
"where",
"(",
"$",
"where",
")",
"->",
"execute",
"(",
")",
";",
"}",
"return",
"$",
"delete",
";",
"}"
] | Delete from a table
When all parameters are specified, the delete query is immediately
executed and the number of rows affected will be returned. Otherwise
the query builder is returned so you can extend the query further.
@param string $table
@param array|string $where (optional)
@return Query|int
@throws QueryException | [
"Delete",
"from",
"a",
"table"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Connection.php#L302-L310 |
neat-php/database | classes/Connection.php | Connection.start | public function start()
{
if ($this->started) {
throw new \RuntimeException('Cannot start nested transaction');
}
if (!$this->pdo->beginTransaction()) {
throw new \RuntimeException('Failed to start transaction');
}
$this->started = true;
} | php | public function start()
{
if ($this->started) {
throw new \RuntimeException('Cannot start nested transaction');
}
if (!$this->pdo->beginTransaction()) {
throw new \RuntimeException('Failed to start transaction');
}
$this->started = true;
} | [
"public",
"function",
"start",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"started",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Cannot start nested transaction'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"pdo",
"->",
"beginTransaction",
"(",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Failed to start transaction'",
")",
";",
"}",
"$",
"this",
"->",
"started",
"=",
"true",
";",
"}"
] | Start transaction | [
"Start",
"transaction"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Connection.php#L315-L325 |
neat-php/database | classes/Connection.php | Connection.commit | public function commit()
{
if (!$this->started) {
throw new \RuntimeException('Cannot commit transaction before start');
}
if (!$this->pdo->commit()) {
throw new \RuntimeException('Failed to commit transaction');
}
$this->started = false;
} | php | public function commit()
{
if (!$this->started) {
throw new \RuntimeException('Cannot commit transaction before start');
}
if (!$this->pdo->commit()) {
throw new \RuntimeException('Failed to commit transaction');
}
$this->started = false;
} | [
"public",
"function",
"commit",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"started",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Cannot commit transaction before start'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"pdo",
"->",
"commit",
"(",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Failed to commit transaction'",
")",
";",
"}",
"$",
"this",
"->",
"started",
"=",
"false",
";",
"}"
] | Commit transaction | [
"Commit",
"transaction"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Connection.php#L330-L340 |
neat-php/database | classes/Connection.php | Connection.rollback | public function rollback()
{
if (!$this->started) {
throw new \RuntimeException('Cannot rollback transaction before start');
}
if (!$this->pdo->rollBack()) {
throw new \RuntimeException('Failed to rollback transaction');
}
$this->started = false;
} | php | public function rollback()
{
if (!$this->started) {
throw new \RuntimeException('Cannot rollback transaction before start');
}
if (!$this->pdo->rollBack()) {
throw new \RuntimeException('Failed to rollback transaction');
}
$this->started = false;
} | [
"public",
"function",
"rollback",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"started",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Cannot rollback transaction before start'",
")",
";",
"}",
"if",
"(",
"!",
"$",
"this",
"->",
"pdo",
"->",
"rollBack",
"(",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Failed to rollback transaction'",
")",
";",
"}",
"$",
"this",
"->",
"started",
"=",
"false",
";",
"}"
] | Rollback transaction | [
"Rollback",
"transaction"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Connection.php#L345-L355 |
neat-php/database | classes/Connection.php | Connection.transaction | public function transaction(callable $closure)
{
$this->start();
try {
$result = $closure();
} catch (\Throwable $e) {
$this->rollback();
throw $e;
}
$this->commit();
return $result;
} | php | public function transaction(callable $closure)
{
$this->start();
try {
$result = $closure();
} catch (\Throwable $e) {
$this->rollback();
throw $e;
}
$this->commit();
return $result;
} | [
"public",
"function",
"transaction",
"(",
"callable",
"$",
"closure",
")",
"{",
"$",
"this",
"->",
"start",
"(",
")",
";",
"try",
"{",
"$",
"result",
"=",
"$",
"closure",
"(",
")",
";",
"}",
"catch",
"(",
"\\",
"Throwable",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"rollback",
"(",
")",
";",
"throw",
"$",
"e",
";",
"}",
"$",
"this",
"->",
"commit",
"(",
")",
";",
"return",
"$",
"result",
";",
"}"
] | Run a closure inside a transaction
Begins a transaction before running the closure and commits the
transaction afterwards. When the closure emits an exception or
throwable error, the transaction will be rolled back.
@param callable $closure Closure without required parameters
@return mixed Closure return value
@throws \Throwable Exceptions thrown by the closure | [
"Run",
"a",
"closure",
"inside",
"a",
"transaction"
] | train | https://github.com/neat-php/database/blob/7b4b66c8f1bc63e50925f12712b9eedcfb2a98ff/classes/Connection.php#L368-L380 |
surebert/surebert-framework | src/sb/Encryption/ForTransmission.php | ForTransmission.encrypt | public function encrypt($string)
{
$td = mcrypt_module_open($this->cypher, '', $this->mode, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), mcrypt_RAND);
mcrypt_generic_init($td, $this->key, $iv);
$encrypted = mcrypt_generic($td, $string);
mcrypt_generic_deinit($td);
return $iv.$encrypted;
} | php | public function encrypt($string)
{
$td = mcrypt_module_open($this->cypher, '', $this->mode, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), mcrypt_RAND);
mcrypt_generic_init($td, $this->key, $iv);
$encrypted = mcrypt_generic($td, $string);
mcrypt_generic_deinit($td);
return $iv.$encrypted;
} | [
"public",
"function",
"encrypt",
"(",
"$",
"string",
")",
"{",
"$",
"td",
"=",
"mcrypt_module_open",
"(",
"$",
"this",
"->",
"cypher",
",",
"''",
",",
"$",
"this",
"->",
"mode",
",",
"''",
")",
";",
"$",
"iv",
"=",
"mcrypt_create_iv",
"(",
"mcrypt_enc_get_iv_size",
"(",
"$",
"td",
")",
",",
"mcrypt_RAND",
")",
";",
"mcrypt_generic_init",
"(",
"$",
"td",
",",
"$",
"this",
"->",
"key",
",",
"$",
"iv",
")",
";",
"$",
"encrypted",
"=",
"mcrypt_generic",
"(",
"$",
"td",
",",
"$",
"string",
")",
";",
"mcrypt_generic_deinit",
"(",
"$",
"td",
")",
";",
"return",
"$",
"iv",
".",
"$",
"encrypted",
";",
"}"
] | Encrypts a string
@param $string The string of data to encrypt | [
"Encrypts",
"a",
"string"
] | train | https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/Encryption/ForTransmission.php#L43-L52 |
surebert/surebert-framework | src/sb/Encryption/ForTransmission.php | ForTransmission.decrypt | public function decrypt($string)
{
$decrypted = "";
$td = mcrypt_module_open($this->cypher, '', $this->mode, '');
$ivsize = mcrypt_enc_get_iv_size($td);
$iv = substr($string, 0, $ivsize);
$string = substr($string, $ivsize);
if ($iv) {
mcrypt_generic_init($td, $this->key, $iv);
$decrypted = mdecrypt_generic($td, $string);
}
return rtrim($decrypted);
} | php | public function decrypt($string)
{
$decrypted = "";
$td = mcrypt_module_open($this->cypher, '', $this->mode, '');
$ivsize = mcrypt_enc_get_iv_size($td);
$iv = substr($string, 0, $ivsize);
$string = substr($string, $ivsize);
if ($iv) {
mcrypt_generic_init($td, $this->key, $iv);
$decrypted = mdecrypt_generic($td, $string);
}
return rtrim($decrypted);
} | [
"public",
"function",
"decrypt",
"(",
"$",
"string",
")",
"{",
"$",
"decrypted",
"=",
"\"\"",
";",
"$",
"td",
"=",
"mcrypt_module_open",
"(",
"$",
"this",
"->",
"cypher",
",",
"''",
",",
"$",
"this",
"->",
"mode",
",",
"''",
")",
";",
"$",
"ivsize",
"=",
"mcrypt_enc_get_iv_size",
"(",
"$",
"td",
")",
";",
"$",
"iv",
"=",
"substr",
"(",
"$",
"string",
",",
"0",
",",
"$",
"ivsize",
")",
";",
"$",
"string",
"=",
"substr",
"(",
"$",
"string",
",",
"$",
"ivsize",
")",
";",
"if",
"(",
"$",
"iv",
")",
"{",
"mcrypt_generic_init",
"(",
"$",
"td",
",",
"$",
"this",
"->",
"key",
",",
"$",
"iv",
")",
";",
"$",
"decrypted",
"=",
"mdecrypt_generic",
"(",
"$",
"td",
",",
"$",
"string",
")",
";",
"}",
"return",
"rtrim",
"(",
"$",
"decrypted",
")",
";",
"}"
] | Decrypts a string
@param $string The data to decrypt | [
"Decrypts",
"a",
"string"
] | train | https://github.com/surebert/surebert-framework/blob/f2f32eb693bd39385ceb93355efb5b2a429f27ce/src/sb/Encryption/ForTransmission.php#L58-L72 |
alevilar/ristorantino-vendor | Printers/Utility/ReceiptPrint.php | ReceiptPrint.comanda | public static function comanda ( Comanda $Comanda )
{
$comanda_id = $Comanda->id;
$productos_x_comanda = array();
// se supone que en una comanda yo no voy a tener productos que se impriman en comanderas distitas
// (esto es separado desde el mismo controlador y se manda aimprimir a comandas diferentes)
// pero , por las dudas que ésto suceda, cuando yo listo los productos de una comanda, me los separa para ser impreso en Comanderas distintas
// Entonces, por lo genral (SIEMPRE) se imprimiria x 1 sola Comandera en este método del Componente
$comanderas_involucradas = $Comanda->comanderas_involucradas($comanda_id);
// genero el array lindo paraimprimir por cada comanda
// o sea, genero un renglón de la comanda
// por ejmeplo me queraria algo asi:
// "1) Milanesa de pollo\n"
$comanderasRet = array();
foreach($comanderas_involucradas as $printer_id):
if ( !empty($printer_id) ) {
$ret = Printaitor::send( $Comanda, $printer_id, 'comandas');
$comanderasRet[$printer_id] = $ret;
}
endforeach;
return $comanderasRet;
} | php | public static function comanda ( Comanda $Comanda )
{
$comanda_id = $Comanda->id;
$productos_x_comanda = array();
// se supone que en una comanda yo no voy a tener productos que se impriman en comanderas distitas
// (esto es separado desde el mismo controlador y se manda aimprimir a comandas diferentes)
// pero , por las dudas que ésto suceda, cuando yo listo los productos de una comanda, me los separa para ser impreso en Comanderas distintas
// Entonces, por lo genral (SIEMPRE) se imprimiria x 1 sola Comandera en este método del Componente
$comanderas_involucradas = $Comanda->comanderas_involucradas($comanda_id);
// genero el array lindo paraimprimir por cada comanda
// o sea, genero un renglón de la comanda
// por ejmeplo me queraria algo asi:
// "1) Milanesa de pollo\n"
$comanderasRet = array();
foreach($comanderas_involucradas as $printer_id):
if ( !empty($printer_id) ) {
$ret = Printaitor::send( $Comanda, $printer_id, 'comandas');
$comanderasRet[$printer_id] = $ret;
}
endforeach;
return $comanderasRet;
} | [
"public",
"static",
"function",
"comanda",
"(",
"Comanda",
"$",
"Comanda",
")",
"{",
"$",
"comanda_id",
"=",
"$",
"Comanda",
"->",
"id",
";",
"$",
"productos_x_comanda",
"=",
"array",
"(",
")",
";",
"// se supone que en una comanda yo no voy a tener productos que se impriman en comanderas distitas",
"// (esto es separado desde el mismo controlador y se manda aimprimir a comandas diferentes)",
"// pero , por las dudas que ésto suceda, cuando yo listo los productos de una comanda, me los separa para ser impreso en Comanderas distintas",
"// Entonces, por lo genral (SIEMPRE) se imprimiria x 1 sola Comandera en este método del Componente",
"$",
"comanderas_involucradas",
"=",
"$",
"Comanda",
"->",
"comanderas_involucradas",
"(",
"$",
"comanda_id",
")",
";",
"// genero el array lindo paraimprimir por cada comanda",
"// o sea, genero un renglón de la comanda",
"// por ejmeplo me queraria algo asi:",
"// \"1) Milanesa de pollo\\n\"",
"$",
"comanderasRet",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"comanderas_involucradas",
"as",
"$",
"printer_id",
")",
":",
"if",
"(",
"!",
"empty",
"(",
"$",
"printer_id",
")",
")",
"{",
"$",
"ret",
"=",
"Printaitor",
"::",
"send",
"(",
"$",
"Comanda",
",",
"$",
"printer_id",
",",
"'comandas'",
")",
";",
"$",
"comanderasRet",
"[",
"$",
"printer_id",
"]",
"=",
"$",
"ret",
";",
"}",
"endforeach",
";",
"return",
"$",
"comanderasRet",
";",
"}"
] | Imprime una comanda en particular
@param id $comanda_id
@return null | [
"Imprime",
"una",
"comanda",
"en",
"particular"
] | train | https://github.com/alevilar/ristorantino-vendor/blob/6b91a1e20cc0ba09a1968d77e3de6512cfa2d966/Printers/Utility/ReceiptPrint.php#L21-L46 |
gregorybesson/PlaygroundCms | src/Entity/Dynablock.php | Dynablock.populate | public function populate($data = array())
{
$this->title = (isset($data['title'])) ? $data['title'] : null;
$this->dynarea = (isset($data['dynarea'])) ? $data['dynarea'] : null;
if (isset($data['is_active']) && $data['is_active'] != null) {
$this->is_active = $data['is_active'];
}
if (isset($data['position']) && $data['position'] != null) {
$this->position = $data['position'];
}
$this->identifier = (isset($data['identifier'])) ? $data['identifier'] : null;
$this->type = (isset($data['type'])) ? $data['type'] : null;
} | php | public function populate($data = array())
{
$this->title = (isset($data['title'])) ? $data['title'] : null;
$this->dynarea = (isset($data['dynarea'])) ? $data['dynarea'] : null;
if (isset($data['is_active']) && $data['is_active'] != null) {
$this->is_active = $data['is_active'];
}
if (isset($data['position']) && $data['position'] != null) {
$this->position = $data['position'];
}
$this->identifier = (isset($data['identifier'])) ? $data['identifier'] : null;
$this->type = (isset($data['type'])) ? $data['type'] : null;
} | [
"public",
"function",
"populate",
"(",
"$",
"data",
"=",
"array",
"(",
")",
")",
"{",
"$",
"this",
"->",
"title",
"=",
"(",
"isset",
"(",
"$",
"data",
"[",
"'title'",
"]",
")",
")",
"?",
"$",
"data",
"[",
"'title'",
"]",
":",
"null",
";",
"$",
"this",
"->",
"dynarea",
"=",
"(",
"isset",
"(",
"$",
"data",
"[",
"'dynarea'",
"]",
")",
")",
"?",
"$",
"data",
"[",
"'dynarea'",
"]",
":",
"null",
";",
"if",
"(",
"isset",
"(",
"$",
"data",
"[",
"'is_active'",
"]",
")",
"&&",
"$",
"data",
"[",
"'is_active'",
"]",
"!=",
"null",
")",
"{",
"$",
"this",
"->",
"is_active",
"=",
"$",
"data",
"[",
"'is_active'",
"]",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"data",
"[",
"'position'",
"]",
")",
"&&",
"$",
"data",
"[",
"'position'",
"]",
"!=",
"null",
")",
"{",
"$",
"this",
"->",
"position",
"=",
"$",
"data",
"[",
"'position'",
"]",
";",
"}",
"$",
"this",
"->",
"identifier",
"=",
"(",
"isset",
"(",
"$",
"data",
"[",
"'identifier'",
"]",
")",
")",
"?",
"$",
"data",
"[",
"'identifier'",
"]",
":",
"null",
";",
"$",
"this",
"->",
"type",
"=",
"(",
"isset",
"(",
"$",
"data",
"[",
"'type'",
"]",
")",
")",
"?",
"$",
"data",
"[",
"'type'",
"]",
":",
"null",
";",
"}"
] | Populate from an array.
@param array $data | [
"Populate",
"from",
"an",
"array",
"."
] | train | https://github.com/gregorybesson/PlaygroundCms/blob/e929a283f2a6e82d4f248c930f7aa454ce20cbc3/src/Entity/Dynablock.php#L264-L276 |
sinri/Ark-Core | src/ArkLogger.php | ArkLogger.generateLog | protected function generateLog($level, $message, $object = '', $enforceEndOfLine = true)
{
$now = date('Y-m-d H:i:s');
$level_string = "[{$level}]";
$log = "{$now} {$level_string} ";
if ($this->showProcessID) {
$log .= "PID: " . getmypid() . " ";
}
$log .= "{$message} |";
$log .= is_string($object) ? $object : json_encode($object, JSON_UNESCAPED_UNICODE);
if ($enforceEndOfLine) $log .= PHP_EOL;
return $log;
} | php | protected function generateLog($level, $message, $object = '', $enforceEndOfLine = true)
{
$now = date('Y-m-d H:i:s');
$level_string = "[{$level}]";
$log = "{$now} {$level_string} ";
if ($this->showProcessID) {
$log .= "PID: " . getmypid() . " ";
}
$log .= "{$message} |";
$log .= is_string($object) ? $object : json_encode($object, JSON_UNESCAPED_UNICODE);
if ($enforceEndOfLine) $log .= PHP_EOL;
return $log;
} | [
"protected",
"function",
"generateLog",
"(",
"$",
"level",
",",
"$",
"message",
",",
"$",
"object",
"=",
"''",
",",
"$",
"enforceEndOfLine",
"=",
"true",
")",
"{",
"$",
"now",
"=",
"date",
"(",
"'Y-m-d H:i:s'",
")",
";",
"$",
"level_string",
"=",
"\"[{$level}]\"",
";",
"$",
"log",
"=",
"\"{$now} {$level_string} \"",
";",
"if",
"(",
"$",
"this",
"->",
"showProcessID",
")",
"{",
"$",
"log",
".=",
"\"PID: \"",
".",
"getmypid",
"(",
")",
".",
"\" \"",
";",
"}",
"$",
"log",
".=",
"\"{$message} |\"",
";",
"$",
"log",
".=",
"is_string",
"(",
"$",
"object",
")",
"?",
"$",
"object",
":",
"json_encode",
"(",
"$",
"object",
",",
"JSON_UNESCAPED_UNICODE",
")",
";",
"if",
"(",
"$",
"enforceEndOfLine",
")",
"$",
"log",
".=",
"PHP_EOL",
";",
"return",
"$",
"log",
";",
"}"
] | Return the string format log content
@param $level
@param $message
@param string|array $object
@param bool $enforceEndOfLine @since 2.1
@return string | [
"Return",
"the",
"string",
"format",
"log",
"content"
] | train | https://github.com/sinri/Ark-Core/blob/fb5715e72b500ddc08dd52d9701d713fe49f48c6/src/ArkLogger.php#L156-L170 |
sinri/Ark-Core | src/ArkLogger.php | ArkLogger.decideTargetFile | protected function decideTargetFile()
{
if (empty($this->targetLogDir)) {
return false;
}
if (!file_exists($this->targetLogDir)) {
@mkdir($this->targetLogDir, 0777, true);
}
return $this->getCurrentLogFilePath();
} | php | protected function decideTargetFile()
{
if (empty($this->targetLogDir)) {
return false;
}
if (!file_exists($this->targetLogDir)) {
@mkdir($this->targetLogDir, 0777, true);
}
return $this->getCurrentLogFilePath();
} | [
"protected",
"function",
"decideTargetFile",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"targetLogDir",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"this",
"->",
"targetLogDir",
")",
")",
"{",
"@",
"mkdir",
"(",
"$",
"this",
"->",
"targetLogDir",
",",
"0777",
",",
"true",
")",
";",
"}",
"return",
"$",
"this",
"->",
"getCurrentLogFilePath",
"(",
")",
";",
"}"
] | Return the target file path which log would be written into.
If target log directory not set, return false.
@return bool|string | [
"Return",
"the",
"target",
"file",
"path",
"which",
"log",
"would",
"be",
"written",
"into",
".",
"If",
"target",
"log",
"directory",
"not",
"set",
"return",
"false",
"."
] | train | https://github.com/sinri/Ark-Core/blob/fb5715e72b500ddc08dd52d9701d713fe49f48c6/src/ArkLogger.php#L177-L187 |
sinri/Ark-Core | src/ArkLogger.php | ArkLogger.getCurrentLogFilePath | public function getCurrentLogFilePath()
{
$rotateTimeMark = "";
if ($this->rotateTimeFormat !== null) {
$rotateTimeMark .= "-" . date($this->rotateTimeFormat);
}
if (is_callable($this->prefix)) {
$prefix = call_user_func_array($this->prefix, []);
// not check prefix here, let user ensure this correctness
} else {
$prefix = $this->prefix;
}
return $this->targetLogDir . '/log' . (empty($this->prefix) ? '' : "-" . $prefix) . $rotateTimeMark . '.log';
} | php | public function getCurrentLogFilePath()
{
$rotateTimeMark = "";
if ($this->rotateTimeFormat !== null) {
$rotateTimeMark .= "-" . date($this->rotateTimeFormat);
}
if (is_callable($this->prefix)) {
$prefix = call_user_func_array($this->prefix, []);
// not check prefix here, let user ensure this correctness
} else {
$prefix = $this->prefix;
}
return $this->targetLogDir . '/log' . (empty($this->prefix) ? '' : "-" . $prefix) . $rotateTimeMark . '.log';
} | [
"public",
"function",
"getCurrentLogFilePath",
"(",
")",
"{",
"$",
"rotateTimeMark",
"=",
"\"\"",
";",
"if",
"(",
"$",
"this",
"->",
"rotateTimeFormat",
"!==",
"null",
")",
"{",
"$",
"rotateTimeMark",
".=",
"\"-\"",
".",
"date",
"(",
"$",
"this",
"->",
"rotateTimeFormat",
")",
";",
"}",
"if",
"(",
"is_callable",
"(",
"$",
"this",
"->",
"prefix",
")",
")",
"{",
"$",
"prefix",
"=",
"call_user_func_array",
"(",
"$",
"this",
"->",
"prefix",
",",
"[",
"]",
")",
";",
"// not check prefix here, let user ensure this correctness",
"}",
"else",
"{",
"$",
"prefix",
"=",
"$",
"this",
"->",
"prefix",
";",
"}",
"return",
"$",
"this",
"->",
"targetLogDir",
".",
"'/log'",
".",
"(",
"empty",
"(",
"$",
"this",
"->",
"prefix",
")",
"?",
"''",
":",
"\"-\"",
".",
"$",
"prefix",
")",
".",
"$",
"rotateTimeMark",
".",
"'.log'",
";",
"}"
] | Sometime you may need to know where the log file is
@return string
@since 2.2 | [
"Sometime",
"you",
"may",
"need",
"to",
"know",
"where",
"the",
"log",
"file",
"is"
] | train | https://github.com/sinri/Ark-Core/blob/fb5715e72b500ddc08dd52d9701d713fe49f48c6/src/ArkLogger.php#L194-L208 |
sinri/Ark-Core | src/ArkLogger.php | ArkLogger.print | public function print($level, $message, array $context = array(), $enforceEndOfLine = true)
{
if ($this->shouldIgnoreThisLog($level)) {
return;
}
$msg = $this->generateLog($level, $message, $context, $enforceEndOfLine);
echo $msg;
} | php | public function print($level, $message, array $context = array(), $enforceEndOfLine = true)
{
if ($this->shouldIgnoreThisLog($level)) {
return;
}
$msg = $this->generateLog($level, $message, $context, $enforceEndOfLine);
echo $msg;
} | [
"public",
"function",
"print",
"(",
"$",
"level",
",",
"$",
"message",
",",
"array",
"$",
"context",
"=",
"array",
"(",
")",
",",
"$",
"enforceEndOfLine",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"shouldIgnoreThisLog",
"(",
"$",
"level",
")",
")",
"{",
"return",
";",
"}",
"$",
"msg",
"=",
"$",
"this",
"->",
"generateLog",
"(",
"$",
"level",
",",
"$",
"message",
",",
"$",
"context",
",",
"$",
"enforceEndOfLine",
")",
";",
"echo",
"$",
"msg",
";",
"}"
] | If you want to output log directly to STDOUT, use this.
@since 2.0 renamed from echo to print
@param $level
@param $message
@param array $context
@param bool $enforceEndOfLine @since 2.1 | [
"If",
"you",
"want",
"to",
"output",
"log",
"directly",
"to",
"STDOUT",
"use",
"this",
"."
] | train | https://github.com/sinri/Ark-Core/blob/fb5715e72b500ddc08dd52d9701d713fe49f48c6/src/ArkLogger.php#L234-L241 |
beberlei/WhitewashingLogglyBundle | Monolog/Handler/LogglyHandler.php | LogglyHandler.send | protected function send($message, array $records)
{
$fp = fsockopen($this->getTransport(), $this->port, $errno, $errstr, 30);
if (!$fp) {
return false;
}
$request = "POST /inputs/".$this->key." HTTP/1.1\r\n";
$request.= "Host: ".$this->host."\r\n";
$request.= "User-Agent: Whitewashing LogglyBundle " . WhitewashingLogglyBundle::VERSION . "\r\n";
$request.= "Content-Type: application/json\r\n";
$request.= "Content-Length: ".strlen($message)."\r\n";
$request.= "Connection: Close\r\n\r\n";
$request.= $message;
fwrite($fp, $request);
fclose($fp);
return true;
} | php | protected function send($message, array $records)
{
$fp = fsockopen($this->getTransport(), $this->port, $errno, $errstr, 30);
if (!$fp) {
return false;
}
$request = "POST /inputs/".$this->key." HTTP/1.1\r\n";
$request.= "Host: ".$this->host."\r\n";
$request.= "User-Agent: Whitewashing LogglyBundle " . WhitewashingLogglyBundle::VERSION . "\r\n";
$request.= "Content-Type: application/json\r\n";
$request.= "Content-Length: ".strlen($message)."\r\n";
$request.= "Connection: Close\r\n\r\n";
$request.= $message;
fwrite($fp, $request);
fclose($fp);
return true;
} | [
"protected",
"function",
"send",
"(",
"$",
"message",
",",
"array",
"$",
"records",
")",
"{",
"$",
"fp",
"=",
"fsockopen",
"(",
"$",
"this",
"->",
"getTransport",
"(",
")",
",",
"$",
"this",
"->",
"port",
",",
"$",
"errno",
",",
"$",
"errstr",
",",
"30",
")",
";",
"if",
"(",
"!",
"$",
"fp",
")",
"{",
"return",
"false",
";",
"}",
"$",
"request",
"=",
"\"POST /inputs/\"",
".",
"$",
"this",
"->",
"key",
".",
"\" HTTP/1.1\\r\\n\"",
";",
"$",
"request",
".=",
"\"Host: \"",
".",
"$",
"this",
"->",
"host",
".",
"\"\\r\\n\"",
";",
"$",
"request",
".=",
"\"User-Agent: Whitewashing LogglyBundle \"",
".",
"WhitewashingLogglyBundle",
"::",
"VERSION",
".",
"\"\\r\\n\"",
";",
"$",
"request",
".=",
"\"Content-Type: application/json\\r\\n\"",
";",
"$",
"request",
".=",
"\"Content-Length: \"",
".",
"strlen",
"(",
"$",
"message",
")",
".",
"\"\\r\\n\"",
";",
"$",
"request",
".=",
"\"Connection: Close\\r\\n\\r\\n\"",
";",
"$",
"request",
".=",
"$",
"message",
";",
"fwrite",
"(",
"$",
"fp",
",",
"$",
"request",
")",
";",
"fclose",
"(",
"$",
"fp",
")",
";",
"return",
"true",
";",
"}"
] | {@inheritDoc} | [
"{"
] | train | https://github.com/beberlei/WhitewashingLogglyBundle/blob/9e5992547cd9fec460421e6516c44dafa92c0b91/Monolog/Handler/LogglyHandler.php#L81-L100 |
songshenzong/log | src/DataCollector/MultiAuthCollector.php | MultiAuthCollector.resolveUser | private function resolveUser(Guard $guard)
{
// if we're logging in using remember token
// then we must resolve user „manually”
// to prevent csrf token regeneration
$usingSession = $guard instanceof SessionGuard;
$recaller = $usingSession ? $guard->getRequest()->cookies->get($guard->getRecallerName()) : null;
if ($usingSession && !is_null($recaller)) {
list($id, $token) = explode('|', $recaller);
return $guard->getProvider()->retrieveByToken($id, $token);
} else {
return $guard->user();
}
} | php | private function resolveUser(Guard $guard)
{
// if we're logging in using remember token
// then we must resolve user „manually”
// to prevent csrf token regeneration
$usingSession = $guard instanceof SessionGuard;
$recaller = $usingSession ? $guard->getRequest()->cookies->get($guard->getRecallerName()) : null;
if ($usingSession && !is_null($recaller)) {
list($id, $token) = explode('|', $recaller);
return $guard->getProvider()->retrieveByToken($id, $token);
} else {
return $guard->user();
}
} | [
"private",
"function",
"resolveUser",
"(",
"Guard",
"$",
"guard",
")",
"{",
"// if we're logging in using remember token",
"// then we must resolve user „manually”",
"// to prevent csrf token regeneration",
"$",
"usingSession",
"=",
"$",
"guard",
"instanceof",
"SessionGuard",
";",
"$",
"recaller",
"=",
"$",
"usingSession",
"?",
"$",
"guard",
"->",
"getRequest",
"(",
")",
"->",
"cookies",
"->",
"get",
"(",
"$",
"guard",
"->",
"getRecallerName",
"(",
")",
")",
":",
"null",
";",
"if",
"(",
"$",
"usingSession",
"&&",
"!",
"is_null",
"(",
"$",
"recaller",
")",
")",
"{",
"list",
"(",
"$",
"id",
",",
"$",
"token",
")",
"=",
"explode",
"(",
"'|'",
",",
"$",
"recaller",
")",
";",
"return",
"$",
"guard",
"->",
"getProvider",
"(",
")",
"->",
"retrieveByToken",
"(",
"$",
"id",
",",
"$",
"token",
")",
";",
"}",
"else",
"{",
"return",
"$",
"guard",
"->",
"user",
"(",
")",
";",
"}",
"}"
] | @param Guard $guard
@return mixed | [
"@param",
"Guard",
"$guard"
] | train | https://github.com/songshenzong/log/blob/b1e01f7994da47737866eabf82367490eab17c46/src/DataCollector/MultiAuthCollector.php#L61-L76 |
nabab/bbn | src/bbn/appui/history.php | history._get_db | private static function _get_db(): ?bbn\db
{
if ( self::$db && self::$db->check() ){
return self::$db;
}
return null;
} | php | private static function _get_db(): ?bbn\db
{
if ( self::$db && self::$db->check() ){
return self::$db;
}
return null;
} | [
"private",
"static",
"function",
"_get_db",
"(",
")",
":",
"?",
"bbn",
"\\",
"db",
"{",
"if",
"(",
"self",
"::",
"$",
"db",
"&&",
"self",
"::",
"$",
"db",
"->",
"check",
"(",
")",
")",
"{",
"return",
"self",
"::",
"$",
"db",
";",
"}",
"return",
"null",
";",
"}"
] | Returns the database connection object.
@return bbn\db | [
"Returns",
"the",
"database",
"connection",
"object",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/history.php#L49-L55 |
nabab/bbn | src/bbn/appui/history.php | history._get_databases | private static function _get_databases(): ?databases
{
if ( self::check() ){
if ( !self::$databases_obj && ($db = self::_get_db()) ){
self::$databases_obj = new databases($db);
}
return self::$databases_obj;
}
return null;
} | php | private static function _get_databases(): ?databases
{
if ( self::check() ){
if ( !self::$databases_obj && ($db = self::_get_db()) ){
self::$databases_obj = new databases($db);
}
return self::$databases_obj;
}
return null;
} | [
"private",
"static",
"function",
"_get_databases",
"(",
")",
":",
"?",
"databases",
"{",
"if",
"(",
"self",
"::",
"check",
"(",
")",
")",
"{",
"if",
"(",
"!",
"self",
"::",
"$",
"databases_obj",
"&&",
"(",
"$",
"db",
"=",
"self",
"::",
"_get_db",
"(",
")",
")",
")",
"{",
"self",
"::",
"$",
"databases_obj",
"=",
"new",
"databases",
"(",
"$",
"db",
")",
";",
"}",
"return",
"self",
"::",
"$",
"databases_obj",
";",
"}",
"return",
"null",
";",
"}"
] | Returns an instance of the appui\database class.
@return databases | [
"Returns",
"an",
"instance",
"of",
"the",
"appui",
"\\",
"database",
"class",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/history.php#L62-L71 |
nabab/bbn | src/bbn/appui/history.php | history._insert | private static function _insert(array $cfg): int
{
if (
isset($cfg['column'], $cfg['line'], $cfg['chrono']) &&
self::check() &&
($db = self::_get_db())
){
// Recording the last ID
$id = $db->last_id();
$last = self::$db->last();
$last_params = self::$db->last_params;
self::disable();
if ( !array_key_exists('old', $cfg) ){
$cfg['ref'] = null;
$cfg['val'] = null;
}
else if (
bbn\str::is_uid($cfg['old']) &&
self::$db->count(self::$table_uids, ['bbn_uid' => $cfg['old']])
){
$cfg['ref'] = $cfg['old'];
$cfg['val'] = null;
}
else{
$cfg['ref'] = null;
$cfg['val'] = $cfg['old'];
}
// New row in the history table
if ( $res = $db->insert(self::$table, [
'opr' => $cfg['operation'],
'uid' => $cfg['line'],
'col' => $cfg['column'],
'val' => $cfg['val'],
'ref' => $cfg['ref'],
'tst' => self::$date ?: $cfg['chrono'],
'usr' => self::$user
]) ){
// Set back the original last ID
$db->set_last_insert_id($id);
}
self::$db->last_query = $last;
self::$db->last_params = $last_params;
self::enable();
return $res;
}
return 0;
} | php | private static function _insert(array $cfg): int
{
if (
isset($cfg['column'], $cfg['line'], $cfg['chrono']) &&
self::check() &&
($db = self::_get_db())
){
// Recording the last ID
$id = $db->last_id();
$last = self::$db->last();
$last_params = self::$db->last_params;
self::disable();
if ( !array_key_exists('old', $cfg) ){
$cfg['ref'] = null;
$cfg['val'] = null;
}
else if (
bbn\str::is_uid($cfg['old']) &&
self::$db->count(self::$table_uids, ['bbn_uid' => $cfg['old']])
){
$cfg['ref'] = $cfg['old'];
$cfg['val'] = null;
}
else{
$cfg['ref'] = null;
$cfg['val'] = $cfg['old'];
}
// New row in the history table
if ( $res = $db->insert(self::$table, [
'opr' => $cfg['operation'],
'uid' => $cfg['line'],
'col' => $cfg['column'],
'val' => $cfg['val'],
'ref' => $cfg['ref'],
'tst' => self::$date ?: $cfg['chrono'],
'usr' => self::$user
]) ){
// Set back the original last ID
$db->set_last_insert_id($id);
}
self::$db->last_query = $last;
self::$db->last_params = $last_params;
self::enable();
return $res;
}
return 0;
} | [
"private",
"static",
"function",
"_insert",
"(",
"array",
"$",
"cfg",
")",
":",
"int",
"{",
"if",
"(",
"isset",
"(",
"$",
"cfg",
"[",
"'column'",
"]",
",",
"$",
"cfg",
"[",
"'line'",
"]",
",",
"$",
"cfg",
"[",
"'chrono'",
"]",
")",
"&&",
"self",
"::",
"check",
"(",
")",
"&&",
"(",
"$",
"db",
"=",
"self",
"::",
"_get_db",
"(",
")",
")",
")",
"{",
"// Recording the last ID",
"$",
"id",
"=",
"$",
"db",
"->",
"last_id",
"(",
")",
";",
"$",
"last",
"=",
"self",
"::",
"$",
"db",
"->",
"last",
"(",
")",
";",
"$",
"last_params",
"=",
"self",
"::",
"$",
"db",
"->",
"last_params",
";",
"self",
"::",
"disable",
"(",
")",
";",
"if",
"(",
"!",
"array_key_exists",
"(",
"'old'",
",",
"$",
"cfg",
")",
")",
"{",
"$",
"cfg",
"[",
"'ref'",
"]",
"=",
"null",
";",
"$",
"cfg",
"[",
"'val'",
"]",
"=",
"null",
";",
"}",
"else",
"if",
"(",
"bbn",
"\\",
"str",
"::",
"is_uid",
"(",
"$",
"cfg",
"[",
"'old'",
"]",
")",
"&&",
"self",
"::",
"$",
"db",
"->",
"count",
"(",
"self",
"::",
"$",
"table_uids",
",",
"[",
"'bbn_uid'",
"=>",
"$",
"cfg",
"[",
"'old'",
"]",
"]",
")",
")",
"{",
"$",
"cfg",
"[",
"'ref'",
"]",
"=",
"$",
"cfg",
"[",
"'old'",
"]",
";",
"$",
"cfg",
"[",
"'val'",
"]",
"=",
"null",
";",
"}",
"else",
"{",
"$",
"cfg",
"[",
"'ref'",
"]",
"=",
"null",
";",
"$",
"cfg",
"[",
"'val'",
"]",
"=",
"$",
"cfg",
"[",
"'old'",
"]",
";",
"}",
"// New row in the history table",
"if",
"(",
"$",
"res",
"=",
"$",
"db",
"->",
"insert",
"(",
"self",
"::",
"$",
"table",
",",
"[",
"'opr'",
"=>",
"$",
"cfg",
"[",
"'operation'",
"]",
",",
"'uid'",
"=>",
"$",
"cfg",
"[",
"'line'",
"]",
",",
"'col'",
"=>",
"$",
"cfg",
"[",
"'column'",
"]",
",",
"'val'",
"=>",
"$",
"cfg",
"[",
"'val'",
"]",
",",
"'ref'",
"=>",
"$",
"cfg",
"[",
"'ref'",
"]",
",",
"'tst'",
"=>",
"self",
"::",
"$",
"date",
"?",
":",
"$",
"cfg",
"[",
"'chrono'",
"]",
",",
"'usr'",
"=>",
"self",
"::",
"$",
"user",
"]",
")",
")",
"{",
"// Set back the original last ID",
"$",
"db",
"->",
"set_last_insert_id",
"(",
"$",
"id",
")",
";",
"}",
"self",
"::",
"$",
"db",
"->",
"last_query",
"=",
"$",
"last",
";",
"self",
"::",
"$",
"db",
"->",
"last_params",
"=",
"$",
"last_params",
";",
"self",
"::",
"enable",
"(",
")",
";",
"return",
"$",
"res",
";",
"}",
"return",
"0",
";",
"}"
] | Adds a row in the history table
@param array $cfg
@return int | [
"Adds",
"a",
"row",
"in",
"the",
"history",
"table"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/history.php#L79-L125 |
nabab/bbn | src/bbn/appui/history.php | history._get_table_where | private static function _get_table_where(string $table): ?string
{
if (
bbn\str::check_name($table) &&
($db = self::_get_db()) &&
($databases_obj = self::_get_databases()) &&
($model = $databases_obj->modelize($table))
){
$col = $db->escape('col');
$where_ar = [];
foreach ( $model['fields'] as $k => $f ){
if ( !empty($f['id_option']) ){
$where_ar[] = $col.' = UNHEX("'.$db->escape_value($f['id_option']).'")';
}
}
if ( \count($where_ar) ){
return implode(' OR ', $where_ar);
}
}
return null;
} | php | private static function _get_table_where(string $table): ?string
{
if (
bbn\str::check_name($table) &&
($db = self::_get_db()) &&
($databases_obj = self::_get_databases()) &&
($model = $databases_obj->modelize($table))
){
$col = $db->escape('col');
$where_ar = [];
foreach ( $model['fields'] as $k => $f ){
if ( !empty($f['id_option']) ){
$where_ar[] = $col.' = UNHEX("'.$db->escape_value($f['id_option']).'")';
}
}
if ( \count($where_ar) ){
return implode(' OR ', $where_ar);
}
}
return null;
} | [
"private",
"static",
"function",
"_get_table_where",
"(",
"string",
"$",
"table",
")",
":",
"?",
"string",
"{",
"if",
"(",
"bbn",
"\\",
"str",
"::",
"check_name",
"(",
"$",
"table",
")",
"&&",
"(",
"$",
"db",
"=",
"self",
"::",
"_get_db",
"(",
")",
")",
"&&",
"(",
"$",
"databases_obj",
"=",
"self",
"::",
"_get_databases",
"(",
")",
")",
"&&",
"(",
"$",
"model",
"=",
"$",
"databases_obj",
"->",
"modelize",
"(",
"$",
"table",
")",
")",
")",
"{",
"$",
"col",
"=",
"$",
"db",
"->",
"escape",
"(",
"'col'",
")",
";",
"$",
"where_ar",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"model",
"[",
"'fields'",
"]",
"as",
"$",
"k",
"=>",
"$",
"f",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"f",
"[",
"'id_option'",
"]",
")",
")",
"{",
"$",
"where_ar",
"[",
"]",
"=",
"$",
"col",
".",
"' = UNHEX(\"'",
".",
"$",
"db",
"->",
"escape_value",
"(",
"$",
"f",
"[",
"'id_option'",
"]",
")",
".",
"'\")'",
";",
"}",
"}",
"if",
"(",
"\\",
"count",
"(",
"$",
"where_ar",
")",
")",
"{",
"return",
"implode",
"(",
"' OR '",
",",
"$",
"where_ar",
")",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Get a string for the WHERE in the query with all the columns selection
@param string $table
@return string|null | [
"Get",
"a",
"string",
"for",
"the",
"WHERE",
"in",
"the",
"query",
"with",
"all",
"the",
"columns",
"selection"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/history.php#L132-L152 |
nabab/bbn | src/bbn/appui/history.php | history.get_id_column | public static function get_id_column(string $column, string $table): ?string
{
if (
($db = self::_get_db()) &&
($full_table = $db->tfn($table)) &&
($databases_obj = self::_get_databases())
){
[$database, $table] = explode('.', $full_table);
return $databases_obj->column_id($column, $table, $database, self::$db->host);
}
return false;
} | php | public static function get_id_column(string $column, string $table): ?string
{
if (
($db = self::_get_db()) &&
($full_table = $db->tfn($table)) &&
($databases_obj = self::_get_databases())
){
[$database, $table] = explode('.', $full_table);
return $databases_obj->column_id($column, $table, $database, self::$db->host);
}
return false;
} | [
"public",
"static",
"function",
"get_id_column",
"(",
"string",
"$",
"column",
",",
"string",
"$",
"table",
")",
":",
"?",
"string",
"{",
"if",
"(",
"(",
"$",
"db",
"=",
"self",
"::",
"_get_db",
"(",
")",
")",
"&&",
"(",
"$",
"full_table",
"=",
"$",
"db",
"->",
"tfn",
"(",
"$",
"table",
")",
")",
"&&",
"(",
"$",
"databases_obj",
"=",
"self",
"::",
"_get_databases",
"(",
")",
")",
")",
"{",
"[",
"$",
"database",
",",
"$",
"table",
"]",
"=",
"explode",
"(",
"'.'",
",",
"$",
"full_table",
")",
";",
"return",
"$",
"databases_obj",
"->",
"column_id",
"(",
"$",
"column",
",",
"$",
"table",
",",
"$",
"database",
",",
"self",
"::",
"$",
"db",
"->",
"host",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Returns the column's corresponding option's ID
@param $column string
@param $table string
@return null|string | [
"Returns",
"the",
"column",
"s",
"corresponding",
"option",
"s",
"ID"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/history.php#L160-L171 |
nabab/bbn | src/bbn/appui/history.php | history.init | public static function init(bbn\db $db, array $cfg = []): void
{
/** @var string $hash Unique hash for this DB connection (so we don't init twice a same connection) */
$hash = $db->get_hash();
if ( !\in_array($hash, self::$dbs, true) && $db->check() ){
// Adding the connection to the list of connections
self::$dbs[] = $hash;
/** @var bbn\db db */
self::$db = $db;
$vars = get_class_vars(__CLASS__);
foreach ( $cfg as $cf_name => $cf_value ){
if ( array_key_exists($cf_name, $vars) ){
self::$$cf_name = $cf_value;
}
}
if ( !self::$admin_db ){
self::$admin_db = self::$db->current;
}
self::$table = self::$admin_db.'.'.self::$prefix.'history';
self::$table_uids = self::$admin_db.'.'.self::$prefix.'history_uids';
self::$ok = true;
self::$is_used = true;
self::$links = self::$db->get_foreign_keys('bbn_uid', self::$prefix.'history_uids', self::$admin_db);
self::$db->set_trigger('\\bbn\\appui\\history::trigger');
}
} | php | public static function init(bbn\db $db, array $cfg = []): void
{
/** @var string $hash Unique hash for this DB connection (so we don't init twice a same connection) */
$hash = $db->get_hash();
if ( !\in_array($hash, self::$dbs, true) && $db->check() ){
// Adding the connection to the list of connections
self::$dbs[] = $hash;
/** @var bbn\db db */
self::$db = $db;
$vars = get_class_vars(__CLASS__);
foreach ( $cfg as $cf_name => $cf_value ){
if ( array_key_exists($cf_name, $vars) ){
self::$$cf_name = $cf_value;
}
}
if ( !self::$admin_db ){
self::$admin_db = self::$db->current;
}
self::$table = self::$admin_db.'.'.self::$prefix.'history';
self::$table_uids = self::$admin_db.'.'.self::$prefix.'history_uids';
self::$ok = true;
self::$is_used = true;
self::$links = self::$db->get_foreign_keys('bbn_uid', self::$prefix.'history_uids', self::$admin_db);
self::$db->set_trigger('\\bbn\\appui\\history::trigger');
}
} | [
"public",
"static",
"function",
"init",
"(",
"bbn",
"\\",
"db",
"$",
"db",
",",
"array",
"$",
"cfg",
"=",
"[",
"]",
")",
":",
"void",
"{",
"/** @var string $hash Unique hash for this DB connection (so we don't init twice a same connection) */",
"$",
"hash",
"=",
"$",
"db",
"->",
"get_hash",
"(",
")",
";",
"if",
"(",
"!",
"\\",
"in_array",
"(",
"$",
"hash",
",",
"self",
"::",
"$",
"dbs",
",",
"true",
")",
"&&",
"$",
"db",
"->",
"check",
"(",
")",
")",
"{",
"// Adding the connection to the list of connections",
"self",
"::",
"$",
"dbs",
"[",
"]",
"=",
"$",
"hash",
";",
"/** @var bbn\\db db */",
"self",
"::",
"$",
"db",
"=",
"$",
"db",
";",
"$",
"vars",
"=",
"get_class_vars",
"(",
"__CLASS__",
")",
";",
"foreach",
"(",
"$",
"cfg",
"as",
"$",
"cf_name",
"=>",
"$",
"cf_value",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"cf_name",
",",
"$",
"vars",
")",
")",
"{",
"self",
"::",
"$",
"$",
"cf_name",
"=",
"$",
"cf_value",
";",
"}",
"}",
"if",
"(",
"!",
"self",
"::",
"$",
"admin_db",
")",
"{",
"self",
"::",
"$",
"admin_db",
"=",
"self",
"::",
"$",
"db",
"->",
"current",
";",
"}",
"self",
"::",
"$",
"table",
"=",
"self",
"::",
"$",
"admin_db",
".",
"'.'",
".",
"self",
"::",
"$",
"prefix",
".",
"'history'",
";",
"self",
"::",
"$",
"table_uids",
"=",
"self",
"::",
"$",
"admin_db",
".",
"'.'",
".",
"self",
"::",
"$",
"prefix",
".",
"'history_uids'",
";",
"self",
"::",
"$",
"ok",
"=",
"true",
";",
"self",
"::",
"$",
"is_used",
"=",
"true",
";",
"self",
"::",
"$",
"links",
"=",
"self",
"::",
"$",
"db",
"->",
"get_foreign_keys",
"(",
"'bbn_uid'",
",",
"self",
"::",
"$",
"prefix",
".",
"'history_uids'",
",",
"self",
"::",
"$",
"admin_db",
")",
";",
"self",
"::",
"$",
"db",
"->",
"set_trigger",
"(",
"'\\\\bbn\\\\appui\\\\history::trigger'",
")",
";",
"}",
"}"
] | Initializes
@param bbn\db $db
@param array $cfg
@return void | [
"Initializes"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/history.php#L179-L204 |
nabab/bbn | src/bbn/appui/history.php | history.check | public static function check(): bool
{
return
isset(self::$user, self::$table, self::$db) &&
self::is_init() &&
self::_get_db();
} | php | public static function check(): bool
{
return
isset(self::$user, self::$table, self::$db) &&
self::is_init() &&
self::_get_db();
} | [
"public",
"static",
"function",
"check",
"(",
")",
":",
"bool",
"{",
"return",
"isset",
"(",
"self",
"::",
"$",
"user",
",",
"self",
"::",
"$",
"table",
",",
"self",
"::",
"$",
"db",
")",
"&&",
"self",
"::",
"is_init",
"(",
")",
"&&",
"self",
"::",
"_get_db",
"(",
")",
";",
"}"
] | Checks if all history parameters are set in order to read and write into history
@return bool | [
"Checks",
"if",
"all",
"history",
"parameters",
"are",
"set",
"in",
"order",
"to",
"read",
"and",
"write",
"into",
"history"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/history.php#L257-L263 |
nabab/bbn | src/bbn/appui/history.php | history.has_history | public static function has_history(bbn\db $db): bool
{
$hash = $db->get_hash();
return \in_array($hash, self::$dbs, true);
} | php | public static function has_history(bbn\db $db): bool
{
$hash = $db->get_hash();
return \in_array($hash, self::$dbs, true);
} | [
"public",
"static",
"function",
"has_history",
"(",
"bbn",
"\\",
"db",
"$",
"db",
")",
":",
"bool",
"{",
"$",
"hash",
"=",
"$",
"db",
"->",
"get_hash",
"(",
")",
";",
"return",
"\\",
"in_array",
"(",
"$",
"hash",
",",
"self",
"::",
"$",
"dbs",
",",
"true",
")",
";",
"}"
] | Returns true if the given DB connection is configured for history
@param bbn\db $db
@return bool | [
"Returns",
"true",
"if",
"the",
"given",
"DB",
"connection",
"is",
"configured",
"for",
"history"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/history.php#L271-L275 |
nabab/bbn | src/bbn/appui/history.php | history.delete | public static function delete(string $id): bool
{
if ( $id && ($db = self::_get_db()) ){
return $db->delete(self::$table_uids, ['bbn_uid' => $id]);
}
return false;
} | php | public static function delete(string $id): bool
{
if ( $id && ($db = self::_get_db()) ){
return $db->delete(self::$table_uids, ['bbn_uid' => $id]);
}
return false;
} | [
"public",
"static",
"function",
"delete",
"(",
"string",
"$",
"id",
")",
":",
"bool",
"{",
"if",
"(",
"$",
"id",
"&&",
"(",
"$",
"db",
"=",
"self",
"::",
"_get_db",
"(",
")",
")",
")",
"{",
"return",
"$",
"db",
"->",
"delete",
"(",
"self",
"::",
"$",
"table_uids",
",",
"[",
"'bbn_uid'",
"=>",
"$",
"id",
"]",
")",
";",
"}",
"return",
"false",
";",
"}"
] | Effectively deletes a row (deletes the row, the history row and the ID row)
@param string $id
@return bool | [
"Effectively",
"deletes",
"a",
"row",
"(",
"deletes",
"the",
"row",
"the",
"history",
"row",
"and",
"the",
"ID",
"row",
")"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/history.php#L283-L289 |
nabab/bbn | src/bbn/appui/history.php | history.set_column | public static function set_column(string $column): void
{
if ( bbn\str::check_name($column) ){
self::$column = $column;
}
} | php | public static function set_column(string $column): void
{
if ( bbn\str::check_name($column) ){
self::$column = $column;
}
} | [
"public",
"static",
"function",
"set_column",
"(",
"string",
"$",
"column",
")",
":",
"void",
"{",
"if",
"(",
"bbn",
"\\",
"str",
"::",
"check_name",
"(",
"$",
"column",
")",
")",
"{",
"self",
"::",
"$",
"column",
"=",
"$",
"column",
";",
"}",
"}"
] | Sets the "active" column name
@param string $column
@return void | [
"Sets",
"the",
"active",
"column",
"name"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/history.php#L297-L302 |
nabab/bbn | src/bbn/appui/history.php | history.set_admin_db | public static function set_admin_db(string $db_name): void
{
// Sets the history table name
if ( bbn\str::check_name($db_name) ){
self::$admin_db = $db_name;
self::$table = self::$admin_db.'.'.self::$prefix.'history';
}
} | php | public static function set_admin_db(string $db_name): void
{
// Sets the history table name
if ( bbn\str::check_name($db_name) ){
self::$admin_db = $db_name;
self::$table = self::$admin_db.'.'.self::$prefix.'history';
}
} | [
"public",
"static",
"function",
"set_admin_db",
"(",
"string",
"$",
"db_name",
")",
":",
"void",
"{",
"// Sets the history table name",
"if",
"(",
"bbn",
"\\",
"str",
"::",
"check_name",
"(",
"$",
"db_name",
")",
")",
"{",
"self",
"::",
"$",
"admin_db",
"=",
"$",
"db_name",
";",
"self",
"::",
"$",
"table",
"=",
"self",
"::",
"$",
"admin_db",
".",
"'.'",
".",
"self",
"::",
"$",
"prefix",
".",
"'history'",
";",
"}",
"}"
] | Sets the history table name
@param string $db_name
@return void | [
"Sets",
"the",
"history",
"table",
"name"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/history.php#L353-L360 |
nabab/bbn | src/bbn/appui/history.php | history.set_user | public static function set_user($user): void
{
// Sets the history table name
if ( bbn\str::is_uid($user) ){
self::$user = $user;
}
} | php | public static function set_user($user): void
{
// Sets the history table name
if ( bbn\str::is_uid($user) ){
self::$user = $user;
}
} | [
"public",
"static",
"function",
"set_user",
"(",
"$",
"user",
")",
":",
"void",
"{",
"// Sets the history table name",
"if",
"(",
"bbn",
"\\",
"str",
"::",
"is_uid",
"(",
"$",
"user",
")",
")",
"{",
"self",
"::",
"$",
"user",
"=",
"$",
"user",
";",
"}",
"}"
] | Sets the user ID that will be used to fill the user_id field
@param $user
@return void | [
"Sets",
"the",
"user",
"ID",
"that",
"will",
"be",
"used",
"to",
"fill",
"the",
"user_id",
"field"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/history.php#L367-L373 |
nabab/bbn | src/bbn/appui/history.php | history.get_table_cfg | public static function get_table_cfg(string $table, bool $force = false): ?array
{
// Check history is enabled and table's name correct
if (
($db = self::_get_db()) &&
($dbc = self::_get_databases()) &&
($table = $db->tfn($table))
){
if ( $force || !isset(self::$structures[$table]) ){
self::$structures[$table] = [
'history' => false,
'primary' => false,
'primary_type' => null,
'primary_length' => 0,
'auto_increment' => false,
'id' => null,
'fields' => []
];
if (
($model = $dbc->modelize($table)) &&
self::is_linked($table) &&
isset($model['keys']['PRIMARY']) &&
(\count($model['keys']['PRIMARY']['columns']) === 1) &&
($primary = $model['keys']['PRIMARY']['columns'][0]) &&
!empty($model['fields'][$primary])
){
// Looking for the config of the table
self::$structures[$table]['history'] = 1;
self::$structures[$table]['primary'] = $primary;
self::$structures[$table]['primary_type'] = $model['fields'][$primary]['type'];
self::$structures[$table]['primary_length'] = $model['fields'][$primary]['maxlength'];
self::$structures[$table]['auto_increment'] = isset($model['fields'][$primary]['extra']) && ($model['fields'][$primary]['extra'] === 'auto_increment');
self::$structures[$table]['id'] = $dbc->table_id($db->tsn($table), $db->current);
self::$structures[$table]['fields'] = array_filter($model['fields'], function($a){
return $a['id_option'] !== null;
});
}
}
// The table exists and has history
if ( isset(self::$structures[$table]) && !empty(self::$structures[$table]['history']) ){
return self::$structures[$table];
}
}
return null;
} | php | public static function get_table_cfg(string $table, bool $force = false): ?array
{
// Check history is enabled and table's name correct
if (
($db = self::_get_db()) &&
($dbc = self::_get_databases()) &&
($table = $db->tfn($table))
){
if ( $force || !isset(self::$structures[$table]) ){
self::$structures[$table] = [
'history' => false,
'primary' => false,
'primary_type' => null,
'primary_length' => 0,
'auto_increment' => false,
'id' => null,
'fields' => []
];
if (
($model = $dbc->modelize($table)) &&
self::is_linked($table) &&
isset($model['keys']['PRIMARY']) &&
(\count($model['keys']['PRIMARY']['columns']) === 1) &&
($primary = $model['keys']['PRIMARY']['columns'][0]) &&
!empty($model['fields'][$primary])
){
// Looking for the config of the table
self::$structures[$table]['history'] = 1;
self::$structures[$table]['primary'] = $primary;
self::$structures[$table]['primary_type'] = $model['fields'][$primary]['type'];
self::$structures[$table]['primary_length'] = $model['fields'][$primary]['maxlength'];
self::$structures[$table]['auto_increment'] = isset($model['fields'][$primary]['extra']) && ($model['fields'][$primary]['extra'] === 'auto_increment');
self::$structures[$table]['id'] = $dbc->table_id($db->tsn($table), $db->current);
self::$structures[$table]['fields'] = array_filter($model['fields'], function($a){
return $a['id_option'] !== null;
});
}
}
// The table exists and has history
if ( isset(self::$structures[$table]) && !empty(self::$structures[$table]['history']) ){
return self::$structures[$table];
}
}
return null;
} | [
"public",
"static",
"function",
"get_table_cfg",
"(",
"string",
"$",
"table",
",",
"bool",
"$",
"force",
"=",
"false",
")",
":",
"?",
"array",
"{",
"// Check history is enabled and table's name correct",
"if",
"(",
"(",
"$",
"db",
"=",
"self",
"::",
"_get_db",
"(",
")",
")",
"&&",
"(",
"$",
"dbc",
"=",
"self",
"::",
"_get_databases",
"(",
")",
")",
"&&",
"(",
"$",
"table",
"=",
"$",
"db",
"->",
"tfn",
"(",
"$",
"table",
")",
")",
")",
"{",
"if",
"(",
"$",
"force",
"||",
"!",
"isset",
"(",
"self",
"::",
"$",
"structures",
"[",
"$",
"table",
"]",
")",
")",
"{",
"self",
"::",
"$",
"structures",
"[",
"$",
"table",
"]",
"=",
"[",
"'history'",
"=>",
"false",
",",
"'primary'",
"=>",
"false",
",",
"'primary_type'",
"=>",
"null",
",",
"'primary_length'",
"=>",
"0",
",",
"'auto_increment'",
"=>",
"false",
",",
"'id'",
"=>",
"null",
",",
"'fields'",
"=>",
"[",
"]",
"]",
";",
"if",
"(",
"(",
"$",
"model",
"=",
"$",
"dbc",
"->",
"modelize",
"(",
"$",
"table",
")",
")",
"&&",
"self",
"::",
"is_linked",
"(",
"$",
"table",
")",
"&&",
"isset",
"(",
"$",
"model",
"[",
"'keys'",
"]",
"[",
"'PRIMARY'",
"]",
")",
"&&",
"(",
"\\",
"count",
"(",
"$",
"model",
"[",
"'keys'",
"]",
"[",
"'PRIMARY'",
"]",
"[",
"'columns'",
"]",
")",
"===",
"1",
")",
"&&",
"(",
"$",
"primary",
"=",
"$",
"model",
"[",
"'keys'",
"]",
"[",
"'PRIMARY'",
"]",
"[",
"'columns'",
"]",
"[",
"0",
"]",
")",
"&&",
"!",
"empty",
"(",
"$",
"model",
"[",
"'fields'",
"]",
"[",
"$",
"primary",
"]",
")",
")",
"{",
"// Looking for the config of the table",
"self",
"::",
"$",
"structures",
"[",
"$",
"table",
"]",
"[",
"'history'",
"]",
"=",
"1",
";",
"self",
"::",
"$",
"structures",
"[",
"$",
"table",
"]",
"[",
"'primary'",
"]",
"=",
"$",
"primary",
";",
"self",
"::",
"$",
"structures",
"[",
"$",
"table",
"]",
"[",
"'primary_type'",
"]",
"=",
"$",
"model",
"[",
"'fields'",
"]",
"[",
"$",
"primary",
"]",
"[",
"'type'",
"]",
";",
"self",
"::",
"$",
"structures",
"[",
"$",
"table",
"]",
"[",
"'primary_length'",
"]",
"=",
"$",
"model",
"[",
"'fields'",
"]",
"[",
"$",
"primary",
"]",
"[",
"'maxlength'",
"]",
";",
"self",
"::",
"$",
"structures",
"[",
"$",
"table",
"]",
"[",
"'auto_increment'",
"]",
"=",
"isset",
"(",
"$",
"model",
"[",
"'fields'",
"]",
"[",
"$",
"primary",
"]",
"[",
"'extra'",
"]",
")",
"&&",
"(",
"$",
"model",
"[",
"'fields'",
"]",
"[",
"$",
"primary",
"]",
"[",
"'extra'",
"]",
"===",
"'auto_increment'",
")",
";",
"self",
"::",
"$",
"structures",
"[",
"$",
"table",
"]",
"[",
"'id'",
"]",
"=",
"$",
"dbc",
"->",
"table_id",
"(",
"$",
"db",
"->",
"tsn",
"(",
"$",
"table",
")",
",",
"$",
"db",
"->",
"current",
")",
";",
"self",
"::",
"$",
"structures",
"[",
"$",
"table",
"]",
"[",
"'fields'",
"]",
"=",
"array_filter",
"(",
"$",
"model",
"[",
"'fields'",
"]",
",",
"function",
"(",
"$",
"a",
")",
"{",
"return",
"$",
"a",
"[",
"'id_option'",
"]",
"!==",
"null",
";",
"}",
")",
";",
"}",
"}",
"// The table exists and has history",
"if",
"(",
"isset",
"(",
"self",
"::",
"$",
"structures",
"[",
"$",
"table",
"]",
")",
"&&",
"!",
"empty",
"(",
"self",
"::",
"$",
"structures",
"[",
"$",
"table",
"]",
"[",
"'history'",
"]",
")",
")",
"{",
"return",
"self",
"::",
"$",
"structures",
"[",
"$",
"table",
"]",
";",
"}",
"}",
"return",
"null",
";",
"}"
] | Gets all information about a given table
@param string $table
@param bool $force
@return null|array Table's full name | [
"Gets",
"all",
"information",
"about",
"a",
"given",
"table"
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/history.php#L888-L932 |
nabab/bbn | src/bbn/appui/history.php | history.trigger | public static function trigger(array $cfg): array
{
if ( !self::is_enabled() || !($db = self::_get_db()) ){
return $cfg;
}
$tables = $cfg['tables'] ?? (array)$cfg['table'];
// Will return false if disabled, the table doesn't exist, or doesn't have history
if (
($cfg['kind'] === 'SELECT') &&
($cfg['moment'] === 'before') &&
!empty($cfg['tables']) &&
!in_array($db->tfn(self::$table), $cfg['tables_full'], true) &&
!in_array($db->tfn(self::$table_uids), $cfg['tables_full'], true)
){
$change = 0;
if ( !isset($cfg['history']) ){
$cfg['history'] = [];
$new_join = [];
foreach ( $cfg['join'] as $i => $t ){
$post_join = false;
$model = $db->modelize($t['table']);
if (
isset($model['keys']['PRIMARY']) &&
($model['keys']['PRIMARY']['ref_table'] === $db->csn(self::$table_uids))
){
$change++;
if ( $t['type'] !== 'left' ){
$post_join = [
'table' => $db->tsn(self::$table_uids),
'alias' => $db->tsn(self::$table_uids).$change,
'type' => $t['type'] ?? 'right',
'on' => [
'conditions' => [
[
'field' => $db->cfn('bbn_uid', self::$table_uids.$change),
'operator' => 'eq',
'exp' => $db->cfn(
$model['keys']['PRIMARY']['columns'][0],
!empty($t['alias']) ? $t['alias'] : $t['table'],
true
)
], [
'field' => $db->cfn('bbn_active', self::$table_uids.$change),
'operator' => '=',
'exp' => '1'
]
],
'logic' => 'AND'
]
];
}
else{
$join_alias = $t;
$alias = strtolower(bbn\str::genpwd());
$join_alias['alias'] = $alias;
$join_alias['on']['conditions'] = $db->replace_table_in_conditions($join_alias['on']['conditions'], !empty($t['alias']) ? $t['alias'] : $t['table'], $alias);
$new_join[] = $join_alias;
$t['on'] = [
'conditions' => [
[
'field' => $db->cfn('bbn_uid', self::$table_uids.$change),
'operator' => 'eq',
'exp' => $db->cfn($model['keys']['PRIMARY']['columns'][0], !empty($t['alias']) ? $t['alias'] : $t['table'], true)
], [
'field' => $db->cfn('bbn_active', self::$table_uids.$change),
'operator' => '=',
'exp' => '1'
]
],
'logic' => 'AND'
];
$new_join[] = [
'table' => $db->tsn(self::$table_uids),
'alias' => $db->tsn(self::$table_uids).$change,
'type' => 'left',
'on' => [
'conditions' => [
[
'field' => $db->cfn('bbn_uid', self::$table_uids.$change),
'operator' => 'eq',
'exp' => $db->cfn($model['keys']['PRIMARY']['columns'][0], $alias, true)
]
],
'logic' => 'AND'
]
];
}
}
$new_join[] = $t;
if ( $post_join ){
$new_join[] = $post_join;
}
}
foreach ( $cfg['tables'] as $alias => $table ){
$model = $db->modelize($table);
if (
isset($model['keys']['PRIMARY']['ref_table']) &&
($db->tfn($model['keys']['PRIMARY']['ref_db'].'.'.$model['keys']['PRIMARY']['ref_table']) === self::$table_uids)
){
$change++;
$new_join[] = [
'table' => self::$table_uids,
'alias' => $db->tsn(self::$table_uids).$change,
'on' => [
'conditions' => [
[
'field' => $db->cfn(self::$table_uids.$change.'.bbn_uid'),
'operator' => 'eq',
'exp' => $db->cfn($model['keys']['PRIMARY']['columns'][0], \is_string($alias) ? $alias : $table, true)
], [
'field' => $db->cfn(self::$table_uids.$change.'.bbn_active'),
'operator' => '=',
'exp' => '1'
]
],
'logic' => 'AND'
]
];
}
}
if ( $change ){
$cfg['join'] = $new_join;
$cfg['where'] = $cfg['filters'];
$cfg = $db->reprocess_cfg($cfg);
}
}
}
if (
$cfg['write'] &&
($table = $db->tfn(current($tables))) &&
($s = self::get_table_cfg($table))
){
// This happens before the query is executed
if ( $cfg['moment'] === 'before' ){
$primary_where = false;
$primary_defined = false;
$primary_value = false;
$idx = \bbn\x::find($cfg['values_desc'], ['primary' => true]);
if ( $idx !== false ){
$primary_where = $cfg['values'][$idx];
}
$idx = array_search($s['primary'], $cfg['fields'], true);
if ( ($idx !== false) && isset($cfg['values'][$idx]) ){
$primary_defined = $cfg['generate_id'] ? false : true;
$primary_value = $cfg['values'][$idx];
}
switch ( $cfg['kind'] ){
case 'INSERT':
// If the primary is specified and already exists in a row in deleted state
// (if it exists in active state, DB will return its standard error but it's not this class' problem)
if ( !$primary_defined ){
// Checks if there is a unique value (non based on UID)
$modelize = $db->modelize($table);
$keys = $modelize['keys'];
unset($keys['PRIMARY']);
foreach ( $keys as $key ){
if ( !empty($key['unique']) && !empty($key['columns']) ){
$fields = [];
$exit = false;
foreach ( $key['columns'] as $col ){
$col_idx = array_search($col, $cfg['fields'], true);
if ( ($col_idx === false) || \is_null($cfg['values'][$col_idx]) ){
$exit = true;
break;
}
else {
$fields[] = [
'field' => $col,
'operator' => 'eq',
'value' => $cfg['values'][$col_idx]
];
}
}
if ( $exit ){
continue;
}
self::disable();
if ( $tmp = $db->select_one([
'tables' => [$table],
'fields' => [$s['primary']],
'join' => [[
'table' => self::$table_uids,
'on' => [[
'field' => $db->cfn('bbn_uid', self::$table_uids),
'operator' => 'eq',
'exp' => $db->cfn($s['primary'], $table, true)
]]
]],
'where' => [
'conditions' => $fields,
'logic' => 'AND'
]
]) ){
$primary_value = $tmp;
$primary_defined = true;
self::enable();
break;
}
self::enable();
}
}
}
//\bbn\x::log([$primary_defined, $primary_value], 'mirko2');
if (
$primary_defined &&
($db->select_one(self::$table_uids, self::$column, ['bbn_uid' => $primary_value]) === 0) &&
//($all = self::$db->rselect($table, [], [$s['primary'] => $primary_value]))
($all = self::$db->rselect([
'table' => $table,
'fields' => $cfg['fields'],
'join' => [[
'table' => self::$table_uids,
'on' => [
'conditions' => [[
'field' => $s['primary'],
'exp' => 'bbn_uid'
], [
'field' => self::$column,
'value' => 0
]]
]
]],
'where' => [
'conditions' => [[
'field' => $s['primary'],
'value' => $primary_value
]]
]
]))
){
// We won't execute the after trigger
$cfg['trig'] = false;
// Real query's execution will be prevented
$cfg['run'] = false;
$cfg['value'] = 0;
/** @var array $update The values to be updated */
$update = [];
// We update each element which needs to (the new ones different from the old, and the old ones different from the default)
foreach ( $all as $k => $v ){
if ( $k !== $s['primary'] ){
$idx = array_search($k, $cfg['fields'], true);
if ( $idx !== false ){
if ( $v !== $cfg['values'][$idx] ){
$update[$k] = $cfg['values'][$idx];
}
}
else if ( $v !== $s['fields'][$k]['default'] ){
$update[$k] = $s['fields'][$k]['default'];
}
}
}
self::disable();
if ( $cfg['value'] = self::$db->update(self::$table_uids, ['bbn_active' => 1], [
['bbn_uid', '=', $primary_value]
]) ){
if ( \count($update) > 0 ){
self::enable();
self::$db->update($table, $update, [
$s['primary'] => $primary_value
]);
}
$cfg['history'][] = [
'operation' => 'RESTORE',
'column' => $s['fields'][$s['primary']]['id_option'],
'line' => $primary_value,
'chrono' => microtime(true)
];
}
self::enable();
}
else {
self::disable();
if ( $primary_defined && !self::$db->count($table, [$s['primary'] => $primary_value]) ){
$primary_defined = false;
}
if ( !$primary_defined && self::$db->insert(self::$table_uids, [
'bbn_uid' => $primary_value,
'bbn_table' => $s['id']
]) ){
$cfg['history'][] = [
'operation' => 'INSERT',
'column' => $s['fields'][$s['primary']]['id_option'],
'line' => $primary_value,
'chrono' => microtime(true)
];
self::$db->set_last_insert_id($primary_value);
}
self::enable();
}
break;
case 'UPDATE':
// ********** CHANGED BY MIRKO *************
/*if ( $primary_defined ){
$where = [$s['primary'] => $primary_value];
// If the only update regards the history field
$row = self::$db->rselect($table, array_keys($cfg['fields']), $where);
$time = microtime(true);
foreach ( $cfg['values'] as $k => $v ){
if (
($row[$k] !== $v) &&
isset($s['fields'][$k])
){
$cfg['history'][] = [
'operation' => 'UPDATE',
'column' => $s['fields'][$k]['id_option'],
'line' => $primary_value,
'old' => $row[$k],
'chrono' => $time
];
}
}
}*/
if (
$primary_where &&
($row = self::$db->rselect($table, $cfg['fields'], [$s['primary'] => $primary_where]))
){
$time = microtime(true);
foreach ( $cfg['fields'] as $i => $idx ){
$csn = self::$db->csn($idx);
if (
isset($s['fields'][$csn]) &&
($row[$csn] !== $cfg['values'][$i])
){
$cfg['history'][] = [
'operation' => 'UPDATE',
'column' => $s['fields'][$csn]['id_option'],
'line' => $primary_where,
'old' => $row[$csn],
'chrono' => $time
];
}
}
}
// Case where the primary is not defined, we'll update each primary instead
else if ( $ids = self::$db->get_column_values($table, $s['primary'], $cfg['filters']) ){
// We won't execute the after trigger
$cfg['trig'] = false;
// Real query's execution will be prevented
$cfg['run'] = false;
$cfg['value'] = 0;
$tmp = [];
foreach ( $cfg['fields'] as $i => $f ){
$tmp[$f] = $cfg['values'][$i];
}
foreach ( $ids as $id ){
$cfg['value'] += self::$db->update($table, $tmp, [$s['primary'] => $id]);
}
// ****************************************
}
break;
// Nothing is really deleted, the hcol is just set to 0
case 'DELETE':
// We won't execute the after trigger
$cfg['trig'] = false;
// Real query's execution will be prevented
$cfg['run'] = false;
$cfg['value'] = 0;
// Case where the primary is not defined, we'll delete based on each primary instead
if ( !$primary_where ){
$ids = self::$db->get_column_values($table, $s['primary'], $cfg['filters']);
foreach ( $ids as $id ){
$cfg['value'] += self::$db->delete($table, [$s['primary'] => $id]);
}
}
else {
self::disable();
$cfg['value'] = self::$db->update(self::$table_uids, [
'bbn_active' => 0
], [
'bbn_uid' => $primary_where
]);
//var_dump("HIST", $primary_where);
self::enable();
if ( $cfg['value'] ){
$cfg['trig'] = 1;
// And we insert into the history table
$cfg['history'][] = [
'operation' => 'DELETE',
'column' => $s['fields'][$s['primary']]['id_option'],
'line' => $primary_where,
'old' => NULL,
'chrono' => microtime(true)
];
}
}
break;
}
}
else if (
($cfg['moment'] === 'after') &&
isset($cfg['history'])
){
foreach ($cfg['history'] as $h){
self::_insert($h);
}
unset($cfg['history']);
}
}
return $cfg;
} | php | public static function trigger(array $cfg): array
{
if ( !self::is_enabled() || !($db = self::_get_db()) ){
return $cfg;
}
$tables = $cfg['tables'] ?? (array)$cfg['table'];
// Will return false if disabled, the table doesn't exist, or doesn't have history
if (
($cfg['kind'] === 'SELECT') &&
($cfg['moment'] === 'before') &&
!empty($cfg['tables']) &&
!in_array($db->tfn(self::$table), $cfg['tables_full'], true) &&
!in_array($db->tfn(self::$table_uids), $cfg['tables_full'], true)
){
$change = 0;
if ( !isset($cfg['history']) ){
$cfg['history'] = [];
$new_join = [];
foreach ( $cfg['join'] as $i => $t ){
$post_join = false;
$model = $db->modelize($t['table']);
if (
isset($model['keys']['PRIMARY']) &&
($model['keys']['PRIMARY']['ref_table'] === $db->csn(self::$table_uids))
){
$change++;
if ( $t['type'] !== 'left' ){
$post_join = [
'table' => $db->tsn(self::$table_uids),
'alias' => $db->tsn(self::$table_uids).$change,
'type' => $t['type'] ?? 'right',
'on' => [
'conditions' => [
[
'field' => $db->cfn('bbn_uid', self::$table_uids.$change),
'operator' => 'eq',
'exp' => $db->cfn(
$model['keys']['PRIMARY']['columns'][0],
!empty($t['alias']) ? $t['alias'] : $t['table'],
true
)
], [
'field' => $db->cfn('bbn_active', self::$table_uids.$change),
'operator' => '=',
'exp' => '1'
]
],
'logic' => 'AND'
]
];
}
else{
$join_alias = $t;
$alias = strtolower(bbn\str::genpwd());
$join_alias['alias'] = $alias;
$join_alias['on']['conditions'] = $db->replace_table_in_conditions($join_alias['on']['conditions'], !empty($t['alias']) ? $t['alias'] : $t['table'], $alias);
$new_join[] = $join_alias;
$t['on'] = [
'conditions' => [
[
'field' => $db->cfn('bbn_uid', self::$table_uids.$change),
'operator' => 'eq',
'exp' => $db->cfn($model['keys']['PRIMARY']['columns'][0], !empty($t['alias']) ? $t['alias'] : $t['table'], true)
], [
'field' => $db->cfn('bbn_active', self::$table_uids.$change),
'operator' => '=',
'exp' => '1'
]
],
'logic' => 'AND'
];
$new_join[] = [
'table' => $db->tsn(self::$table_uids),
'alias' => $db->tsn(self::$table_uids).$change,
'type' => 'left',
'on' => [
'conditions' => [
[
'field' => $db->cfn('bbn_uid', self::$table_uids.$change),
'operator' => 'eq',
'exp' => $db->cfn($model['keys']['PRIMARY']['columns'][0], $alias, true)
]
],
'logic' => 'AND'
]
];
}
}
$new_join[] = $t;
if ( $post_join ){
$new_join[] = $post_join;
}
}
foreach ( $cfg['tables'] as $alias => $table ){
$model = $db->modelize($table);
if (
isset($model['keys']['PRIMARY']['ref_table']) &&
($db->tfn($model['keys']['PRIMARY']['ref_db'].'.'.$model['keys']['PRIMARY']['ref_table']) === self::$table_uids)
){
$change++;
$new_join[] = [
'table' => self::$table_uids,
'alias' => $db->tsn(self::$table_uids).$change,
'on' => [
'conditions' => [
[
'field' => $db->cfn(self::$table_uids.$change.'.bbn_uid'),
'operator' => 'eq',
'exp' => $db->cfn($model['keys']['PRIMARY']['columns'][0], \is_string($alias) ? $alias : $table, true)
], [
'field' => $db->cfn(self::$table_uids.$change.'.bbn_active'),
'operator' => '=',
'exp' => '1'
]
],
'logic' => 'AND'
]
];
}
}
if ( $change ){
$cfg['join'] = $new_join;
$cfg['where'] = $cfg['filters'];
$cfg = $db->reprocess_cfg($cfg);
}
}
}
if (
$cfg['write'] &&
($table = $db->tfn(current($tables))) &&
($s = self::get_table_cfg($table))
){
// This happens before the query is executed
if ( $cfg['moment'] === 'before' ){
$primary_where = false;
$primary_defined = false;
$primary_value = false;
$idx = \bbn\x::find($cfg['values_desc'], ['primary' => true]);
if ( $idx !== false ){
$primary_where = $cfg['values'][$idx];
}
$idx = array_search($s['primary'], $cfg['fields'], true);
if ( ($idx !== false) && isset($cfg['values'][$idx]) ){
$primary_defined = $cfg['generate_id'] ? false : true;
$primary_value = $cfg['values'][$idx];
}
switch ( $cfg['kind'] ){
case 'INSERT':
// If the primary is specified and already exists in a row in deleted state
// (if it exists in active state, DB will return its standard error but it's not this class' problem)
if ( !$primary_defined ){
// Checks if there is a unique value (non based on UID)
$modelize = $db->modelize($table);
$keys = $modelize['keys'];
unset($keys['PRIMARY']);
foreach ( $keys as $key ){
if ( !empty($key['unique']) && !empty($key['columns']) ){
$fields = [];
$exit = false;
foreach ( $key['columns'] as $col ){
$col_idx = array_search($col, $cfg['fields'], true);
if ( ($col_idx === false) || \is_null($cfg['values'][$col_idx]) ){
$exit = true;
break;
}
else {
$fields[] = [
'field' => $col,
'operator' => 'eq',
'value' => $cfg['values'][$col_idx]
];
}
}
if ( $exit ){
continue;
}
self::disable();
if ( $tmp = $db->select_one([
'tables' => [$table],
'fields' => [$s['primary']],
'join' => [[
'table' => self::$table_uids,
'on' => [[
'field' => $db->cfn('bbn_uid', self::$table_uids),
'operator' => 'eq',
'exp' => $db->cfn($s['primary'], $table, true)
]]
]],
'where' => [
'conditions' => $fields,
'logic' => 'AND'
]
]) ){
$primary_value = $tmp;
$primary_defined = true;
self::enable();
break;
}
self::enable();
}
}
}
//\bbn\x::log([$primary_defined, $primary_value], 'mirko2');
if (
$primary_defined &&
($db->select_one(self::$table_uids, self::$column, ['bbn_uid' => $primary_value]) === 0) &&
//($all = self::$db->rselect($table, [], [$s['primary'] => $primary_value]))
($all = self::$db->rselect([
'table' => $table,
'fields' => $cfg['fields'],
'join' => [[
'table' => self::$table_uids,
'on' => [
'conditions' => [[
'field' => $s['primary'],
'exp' => 'bbn_uid'
], [
'field' => self::$column,
'value' => 0
]]
]
]],
'where' => [
'conditions' => [[
'field' => $s['primary'],
'value' => $primary_value
]]
]
]))
){
// We won't execute the after trigger
$cfg['trig'] = false;
// Real query's execution will be prevented
$cfg['run'] = false;
$cfg['value'] = 0;
/** @var array $update The values to be updated */
$update = [];
// We update each element which needs to (the new ones different from the old, and the old ones different from the default)
foreach ( $all as $k => $v ){
if ( $k !== $s['primary'] ){
$idx = array_search($k, $cfg['fields'], true);
if ( $idx !== false ){
if ( $v !== $cfg['values'][$idx] ){
$update[$k] = $cfg['values'][$idx];
}
}
else if ( $v !== $s['fields'][$k]['default'] ){
$update[$k] = $s['fields'][$k]['default'];
}
}
}
self::disable();
if ( $cfg['value'] = self::$db->update(self::$table_uids, ['bbn_active' => 1], [
['bbn_uid', '=', $primary_value]
]) ){
if ( \count($update) > 0 ){
self::enable();
self::$db->update($table, $update, [
$s['primary'] => $primary_value
]);
}
$cfg['history'][] = [
'operation' => 'RESTORE',
'column' => $s['fields'][$s['primary']]['id_option'],
'line' => $primary_value,
'chrono' => microtime(true)
];
}
self::enable();
}
else {
self::disable();
if ( $primary_defined && !self::$db->count($table, [$s['primary'] => $primary_value]) ){
$primary_defined = false;
}
if ( !$primary_defined && self::$db->insert(self::$table_uids, [
'bbn_uid' => $primary_value,
'bbn_table' => $s['id']
]) ){
$cfg['history'][] = [
'operation' => 'INSERT',
'column' => $s['fields'][$s['primary']]['id_option'],
'line' => $primary_value,
'chrono' => microtime(true)
];
self::$db->set_last_insert_id($primary_value);
}
self::enable();
}
break;
case 'UPDATE':
// ********** CHANGED BY MIRKO *************
/*if ( $primary_defined ){
$where = [$s['primary'] => $primary_value];
// If the only update regards the history field
$row = self::$db->rselect($table, array_keys($cfg['fields']), $where);
$time = microtime(true);
foreach ( $cfg['values'] as $k => $v ){
if (
($row[$k] !== $v) &&
isset($s['fields'][$k])
){
$cfg['history'][] = [
'operation' => 'UPDATE',
'column' => $s['fields'][$k]['id_option'],
'line' => $primary_value,
'old' => $row[$k],
'chrono' => $time
];
}
}
}*/
if (
$primary_where &&
($row = self::$db->rselect($table, $cfg['fields'], [$s['primary'] => $primary_where]))
){
$time = microtime(true);
foreach ( $cfg['fields'] as $i => $idx ){
$csn = self::$db->csn($idx);
if (
isset($s['fields'][$csn]) &&
($row[$csn] !== $cfg['values'][$i])
){
$cfg['history'][] = [
'operation' => 'UPDATE',
'column' => $s['fields'][$csn]['id_option'],
'line' => $primary_where,
'old' => $row[$csn],
'chrono' => $time
];
}
}
}
// Case where the primary is not defined, we'll update each primary instead
else if ( $ids = self::$db->get_column_values($table, $s['primary'], $cfg['filters']) ){
// We won't execute the after trigger
$cfg['trig'] = false;
// Real query's execution will be prevented
$cfg['run'] = false;
$cfg['value'] = 0;
$tmp = [];
foreach ( $cfg['fields'] as $i => $f ){
$tmp[$f] = $cfg['values'][$i];
}
foreach ( $ids as $id ){
$cfg['value'] += self::$db->update($table, $tmp, [$s['primary'] => $id]);
}
// ****************************************
}
break;
// Nothing is really deleted, the hcol is just set to 0
case 'DELETE':
// We won't execute the after trigger
$cfg['trig'] = false;
// Real query's execution will be prevented
$cfg['run'] = false;
$cfg['value'] = 0;
// Case where the primary is not defined, we'll delete based on each primary instead
if ( !$primary_where ){
$ids = self::$db->get_column_values($table, $s['primary'], $cfg['filters']);
foreach ( $ids as $id ){
$cfg['value'] += self::$db->delete($table, [$s['primary'] => $id]);
}
}
else {
self::disable();
$cfg['value'] = self::$db->update(self::$table_uids, [
'bbn_active' => 0
], [
'bbn_uid' => $primary_where
]);
//var_dump("HIST", $primary_where);
self::enable();
if ( $cfg['value'] ){
$cfg['trig'] = 1;
// And we insert into the history table
$cfg['history'][] = [
'operation' => 'DELETE',
'column' => $s['fields'][$s['primary']]['id_option'],
'line' => $primary_where,
'old' => NULL,
'chrono' => microtime(true)
];
}
}
break;
}
}
else if (
($cfg['moment'] === 'after') &&
isset($cfg['history'])
){
foreach ($cfg['history'] as $h){
self::_insert($h);
}
unset($cfg['history']);
}
}
return $cfg;
} | [
"public",
"static",
"function",
"trigger",
"(",
"array",
"$",
"cfg",
")",
":",
"array",
"{",
"if",
"(",
"!",
"self",
"::",
"is_enabled",
"(",
")",
"||",
"!",
"(",
"$",
"db",
"=",
"self",
"::",
"_get_db",
"(",
")",
")",
")",
"{",
"return",
"$",
"cfg",
";",
"}",
"$",
"tables",
"=",
"$",
"cfg",
"[",
"'tables'",
"]",
"??",
"(",
"array",
")",
"$",
"cfg",
"[",
"'table'",
"]",
";",
"// Will return false if disabled, the table doesn't exist, or doesn't have history",
"if",
"(",
"(",
"$",
"cfg",
"[",
"'kind'",
"]",
"===",
"'SELECT'",
")",
"&&",
"(",
"$",
"cfg",
"[",
"'moment'",
"]",
"===",
"'before'",
")",
"&&",
"!",
"empty",
"(",
"$",
"cfg",
"[",
"'tables'",
"]",
")",
"&&",
"!",
"in_array",
"(",
"$",
"db",
"->",
"tfn",
"(",
"self",
"::",
"$",
"table",
")",
",",
"$",
"cfg",
"[",
"'tables_full'",
"]",
",",
"true",
")",
"&&",
"!",
"in_array",
"(",
"$",
"db",
"->",
"tfn",
"(",
"self",
"::",
"$",
"table_uids",
")",
",",
"$",
"cfg",
"[",
"'tables_full'",
"]",
",",
"true",
")",
")",
"{",
"$",
"change",
"=",
"0",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"cfg",
"[",
"'history'",
"]",
")",
")",
"{",
"$",
"cfg",
"[",
"'history'",
"]",
"=",
"[",
"]",
";",
"$",
"new_join",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"cfg",
"[",
"'join'",
"]",
"as",
"$",
"i",
"=>",
"$",
"t",
")",
"{",
"$",
"post_join",
"=",
"false",
";",
"$",
"model",
"=",
"$",
"db",
"->",
"modelize",
"(",
"$",
"t",
"[",
"'table'",
"]",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"model",
"[",
"'keys'",
"]",
"[",
"'PRIMARY'",
"]",
")",
"&&",
"(",
"$",
"model",
"[",
"'keys'",
"]",
"[",
"'PRIMARY'",
"]",
"[",
"'ref_table'",
"]",
"===",
"$",
"db",
"->",
"csn",
"(",
"self",
"::",
"$",
"table_uids",
")",
")",
")",
"{",
"$",
"change",
"++",
";",
"if",
"(",
"$",
"t",
"[",
"'type'",
"]",
"!==",
"'left'",
")",
"{",
"$",
"post_join",
"=",
"[",
"'table'",
"=>",
"$",
"db",
"->",
"tsn",
"(",
"self",
"::",
"$",
"table_uids",
")",
",",
"'alias'",
"=>",
"$",
"db",
"->",
"tsn",
"(",
"self",
"::",
"$",
"table_uids",
")",
".",
"$",
"change",
",",
"'type'",
"=>",
"$",
"t",
"[",
"'type'",
"]",
"??",
"'right'",
",",
"'on'",
"=>",
"[",
"'conditions'",
"=>",
"[",
"[",
"'field'",
"=>",
"$",
"db",
"->",
"cfn",
"(",
"'bbn_uid'",
",",
"self",
"::",
"$",
"table_uids",
".",
"$",
"change",
")",
",",
"'operator'",
"=>",
"'eq'",
",",
"'exp'",
"=>",
"$",
"db",
"->",
"cfn",
"(",
"$",
"model",
"[",
"'keys'",
"]",
"[",
"'PRIMARY'",
"]",
"[",
"'columns'",
"]",
"[",
"0",
"]",
",",
"!",
"empty",
"(",
"$",
"t",
"[",
"'alias'",
"]",
")",
"?",
"$",
"t",
"[",
"'alias'",
"]",
":",
"$",
"t",
"[",
"'table'",
"]",
",",
"true",
")",
"]",
",",
"[",
"'field'",
"=>",
"$",
"db",
"->",
"cfn",
"(",
"'bbn_active'",
",",
"self",
"::",
"$",
"table_uids",
".",
"$",
"change",
")",
",",
"'operator'",
"=>",
"'='",
",",
"'exp'",
"=>",
"'1'",
"]",
"]",
",",
"'logic'",
"=>",
"'AND'",
"]",
"]",
";",
"}",
"else",
"{",
"$",
"join_alias",
"=",
"$",
"t",
";",
"$",
"alias",
"=",
"strtolower",
"(",
"bbn",
"\\",
"str",
"::",
"genpwd",
"(",
")",
")",
";",
"$",
"join_alias",
"[",
"'alias'",
"]",
"=",
"$",
"alias",
";",
"$",
"join_alias",
"[",
"'on'",
"]",
"[",
"'conditions'",
"]",
"=",
"$",
"db",
"->",
"replace_table_in_conditions",
"(",
"$",
"join_alias",
"[",
"'on'",
"]",
"[",
"'conditions'",
"]",
",",
"!",
"empty",
"(",
"$",
"t",
"[",
"'alias'",
"]",
")",
"?",
"$",
"t",
"[",
"'alias'",
"]",
":",
"$",
"t",
"[",
"'table'",
"]",
",",
"$",
"alias",
")",
";",
"$",
"new_join",
"[",
"]",
"=",
"$",
"join_alias",
";",
"$",
"t",
"[",
"'on'",
"]",
"=",
"[",
"'conditions'",
"=>",
"[",
"[",
"'field'",
"=>",
"$",
"db",
"->",
"cfn",
"(",
"'bbn_uid'",
",",
"self",
"::",
"$",
"table_uids",
".",
"$",
"change",
")",
",",
"'operator'",
"=>",
"'eq'",
",",
"'exp'",
"=>",
"$",
"db",
"->",
"cfn",
"(",
"$",
"model",
"[",
"'keys'",
"]",
"[",
"'PRIMARY'",
"]",
"[",
"'columns'",
"]",
"[",
"0",
"]",
",",
"!",
"empty",
"(",
"$",
"t",
"[",
"'alias'",
"]",
")",
"?",
"$",
"t",
"[",
"'alias'",
"]",
":",
"$",
"t",
"[",
"'table'",
"]",
",",
"true",
")",
"]",
",",
"[",
"'field'",
"=>",
"$",
"db",
"->",
"cfn",
"(",
"'bbn_active'",
",",
"self",
"::",
"$",
"table_uids",
".",
"$",
"change",
")",
",",
"'operator'",
"=>",
"'='",
",",
"'exp'",
"=>",
"'1'",
"]",
"]",
",",
"'logic'",
"=>",
"'AND'",
"]",
";",
"$",
"new_join",
"[",
"]",
"=",
"[",
"'table'",
"=>",
"$",
"db",
"->",
"tsn",
"(",
"self",
"::",
"$",
"table_uids",
")",
",",
"'alias'",
"=>",
"$",
"db",
"->",
"tsn",
"(",
"self",
"::",
"$",
"table_uids",
")",
".",
"$",
"change",
",",
"'type'",
"=>",
"'left'",
",",
"'on'",
"=>",
"[",
"'conditions'",
"=>",
"[",
"[",
"'field'",
"=>",
"$",
"db",
"->",
"cfn",
"(",
"'bbn_uid'",
",",
"self",
"::",
"$",
"table_uids",
".",
"$",
"change",
")",
",",
"'operator'",
"=>",
"'eq'",
",",
"'exp'",
"=>",
"$",
"db",
"->",
"cfn",
"(",
"$",
"model",
"[",
"'keys'",
"]",
"[",
"'PRIMARY'",
"]",
"[",
"'columns'",
"]",
"[",
"0",
"]",
",",
"$",
"alias",
",",
"true",
")",
"]",
"]",
",",
"'logic'",
"=>",
"'AND'",
"]",
"]",
";",
"}",
"}",
"$",
"new_join",
"[",
"]",
"=",
"$",
"t",
";",
"if",
"(",
"$",
"post_join",
")",
"{",
"$",
"new_join",
"[",
"]",
"=",
"$",
"post_join",
";",
"}",
"}",
"foreach",
"(",
"$",
"cfg",
"[",
"'tables'",
"]",
"as",
"$",
"alias",
"=>",
"$",
"table",
")",
"{",
"$",
"model",
"=",
"$",
"db",
"->",
"modelize",
"(",
"$",
"table",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"model",
"[",
"'keys'",
"]",
"[",
"'PRIMARY'",
"]",
"[",
"'ref_table'",
"]",
")",
"&&",
"(",
"$",
"db",
"->",
"tfn",
"(",
"$",
"model",
"[",
"'keys'",
"]",
"[",
"'PRIMARY'",
"]",
"[",
"'ref_db'",
"]",
".",
"'.'",
".",
"$",
"model",
"[",
"'keys'",
"]",
"[",
"'PRIMARY'",
"]",
"[",
"'ref_table'",
"]",
")",
"===",
"self",
"::",
"$",
"table_uids",
")",
")",
"{",
"$",
"change",
"++",
";",
"$",
"new_join",
"[",
"]",
"=",
"[",
"'table'",
"=>",
"self",
"::",
"$",
"table_uids",
",",
"'alias'",
"=>",
"$",
"db",
"->",
"tsn",
"(",
"self",
"::",
"$",
"table_uids",
")",
".",
"$",
"change",
",",
"'on'",
"=>",
"[",
"'conditions'",
"=>",
"[",
"[",
"'field'",
"=>",
"$",
"db",
"->",
"cfn",
"(",
"self",
"::",
"$",
"table_uids",
".",
"$",
"change",
".",
"'.bbn_uid'",
")",
",",
"'operator'",
"=>",
"'eq'",
",",
"'exp'",
"=>",
"$",
"db",
"->",
"cfn",
"(",
"$",
"model",
"[",
"'keys'",
"]",
"[",
"'PRIMARY'",
"]",
"[",
"'columns'",
"]",
"[",
"0",
"]",
",",
"\\",
"is_string",
"(",
"$",
"alias",
")",
"?",
"$",
"alias",
":",
"$",
"table",
",",
"true",
")",
"]",
",",
"[",
"'field'",
"=>",
"$",
"db",
"->",
"cfn",
"(",
"self",
"::",
"$",
"table_uids",
".",
"$",
"change",
".",
"'.bbn_active'",
")",
",",
"'operator'",
"=>",
"'='",
",",
"'exp'",
"=>",
"'1'",
"]",
"]",
",",
"'logic'",
"=>",
"'AND'",
"]",
"]",
";",
"}",
"}",
"if",
"(",
"$",
"change",
")",
"{",
"$",
"cfg",
"[",
"'join'",
"]",
"=",
"$",
"new_join",
";",
"$",
"cfg",
"[",
"'where'",
"]",
"=",
"$",
"cfg",
"[",
"'filters'",
"]",
";",
"$",
"cfg",
"=",
"$",
"db",
"->",
"reprocess_cfg",
"(",
"$",
"cfg",
")",
";",
"}",
"}",
"}",
"if",
"(",
"$",
"cfg",
"[",
"'write'",
"]",
"&&",
"(",
"$",
"table",
"=",
"$",
"db",
"->",
"tfn",
"(",
"current",
"(",
"$",
"tables",
")",
")",
")",
"&&",
"(",
"$",
"s",
"=",
"self",
"::",
"get_table_cfg",
"(",
"$",
"table",
")",
")",
")",
"{",
"// This happens before the query is executed",
"if",
"(",
"$",
"cfg",
"[",
"'moment'",
"]",
"===",
"'before'",
")",
"{",
"$",
"primary_where",
"=",
"false",
";",
"$",
"primary_defined",
"=",
"false",
";",
"$",
"primary_value",
"=",
"false",
";",
"$",
"idx",
"=",
"\\",
"bbn",
"\\",
"x",
"::",
"find",
"(",
"$",
"cfg",
"[",
"'values_desc'",
"]",
",",
"[",
"'primary'",
"=>",
"true",
"]",
")",
";",
"if",
"(",
"$",
"idx",
"!==",
"false",
")",
"{",
"$",
"primary_where",
"=",
"$",
"cfg",
"[",
"'values'",
"]",
"[",
"$",
"idx",
"]",
";",
"}",
"$",
"idx",
"=",
"array_search",
"(",
"$",
"s",
"[",
"'primary'",
"]",
",",
"$",
"cfg",
"[",
"'fields'",
"]",
",",
"true",
")",
";",
"if",
"(",
"(",
"$",
"idx",
"!==",
"false",
")",
"&&",
"isset",
"(",
"$",
"cfg",
"[",
"'values'",
"]",
"[",
"$",
"idx",
"]",
")",
")",
"{",
"$",
"primary_defined",
"=",
"$",
"cfg",
"[",
"'generate_id'",
"]",
"?",
"false",
":",
"true",
";",
"$",
"primary_value",
"=",
"$",
"cfg",
"[",
"'values'",
"]",
"[",
"$",
"idx",
"]",
";",
"}",
"switch",
"(",
"$",
"cfg",
"[",
"'kind'",
"]",
")",
"{",
"case",
"'INSERT'",
":",
"// If the primary is specified and already exists in a row in deleted state",
"// (if it exists in active state, DB will return its standard error but it's not this class' problem)",
"if",
"(",
"!",
"$",
"primary_defined",
")",
"{",
"// Checks if there is a unique value (non based on UID)",
"$",
"modelize",
"=",
"$",
"db",
"->",
"modelize",
"(",
"$",
"table",
")",
";",
"$",
"keys",
"=",
"$",
"modelize",
"[",
"'keys'",
"]",
";",
"unset",
"(",
"$",
"keys",
"[",
"'PRIMARY'",
"]",
")",
";",
"foreach",
"(",
"$",
"keys",
"as",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"key",
"[",
"'unique'",
"]",
")",
"&&",
"!",
"empty",
"(",
"$",
"key",
"[",
"'columns'",
"]",
")",
")",
"{",
"$",
"fields",
"=",
"[",
"]",
";",
"$",
"exit",
"=",
"false",
";",
"foreach",
"(",
"$",
"key",
"[",
"'columns'",
"]",
"as",
"$",
"col",
")",
"{",
"$",
"col_idx",
"=",
"array_search",
"(",
"$",
"col",
",",
"$",
"cfg",
"[",
"'fields'",
"]",
",",
"true",
")",
";",
"if",
"(",
"(",
"$",
"col_idx",
"===",
"false",
")",
"||",
"\\",
"is_null",
"(",
"$",
"cfg",
"[",
"'values'",
"]",
"[",
"$",
"col_idx",
"]",
")",
")",
"{",
"$",
"exit",
"=",
"true",
";",
"break",
";",
"}",
"else",
"{",
"$",
"fields",
"[",
"]",
"=",
"[",
"'field'",
"=>",
"$",
"col",
",",
"'operator'",
"=>",
"'eq'",
",",
"'value'",
"=>",
"$",
"cfg",
"[",
"'values'",
"]",
"[",
"$",
"col_idx",
"]",
"]",
";",
"}",
"}",
"if",
"(",
"$",
"exit",
")",
"{",
"continue",
";",
"}",
"self",
"::",
"disable",
"(",
")",
";",
"if",
"(",
"$",
"tmp",
"=",
"$",
"db",
"->",
"select_one",
"(",
"[",
"'tables'",
"=>",
"[",
"$",
"table",
"]",
",",
"'fields'",
"=>",
"[",
"$",
"s",
"[",
"'primary'",
"]",
"]",
",",
"'join'",
"=>",
"[",
"[",
"'table'",
"=>",
"self",
"::",
"$",
"table_uids",
",",
"'on'",
"=>",
"[",
"[",
"'field'",
"=>",
"$",
"db",
"->",
"cfn",
"(",
"'bbn_uid'",
",",
"self",
"::",
"$",
"table_uids",
")",
",",
"'operator'",
"=>",
"'eq'",
",",
"'exp'",
"=>",
"$",
"db",
"->",
"cfn",
"(",
"$",
"s",
"[",
"'primary'",
"]",
",",
"$",
"table",
",",
"true",
")",
"]",
"]",
"]",
"]",
",",
"'where'",
"=>",
"[",
"'conditions'",
"=>",
"$",
"fields",
",",
"'logic'",
"=>",
"'AND'",
"]",
"]",
")",
")",
"{",
"$",
"primary_value",
"=",
"$",
"tmp",
";",
"$",
"primary_defined",
"=",
"true",
";",
"self",
"::",
"enable",
"(",
")",
";",
"break",
";",
"}",
"self",
"::",
"enable",
"(",
")",
";",
"}",
"}",
"}",
"//\\bbn\\x::log([$primary_defined, $primary_value], 'mirko2');",
"if",
"(",
"$",
"primary_defined",
"&&",
"(",
"$",
"db",
"->",
"select_one",
"(",
"self",
"::",
"$",
"table_uids",
",",
"self",
"::",
"$",
"column",
",",
"[",
"'bbn_uid'",
"=>",
"$",
"primary_value",
"]",
")",
"===",
"0",
")",
"&&",
"//($all = self::$db->rselect($table, [], [$s['primary'] => $primary_value]))",
"(",
"$",
"all",
"=",
"self",
"::",
"$",
"db",
"->",
"rselect",
"(",
"[",
"'table'",
"=>",
"$",
"table",
",",
"'fields'",
"=>",
"$",
"cfg",
"[",
"'fields'",
"]",
",",
"'join'",
"=>",
"[",
"[",
"'table'",
"=>",
"self",
"::",
"$",
"table_uids",
",",
"'on'",
"=>",
"[",
"'conditions'",
"=>",
"[",
"[",
"'field'",
"=>",
"$",
"s",
"[",
"'primary'",
"]",
",",
"'exp'",
"=>",
"'bbn_uid'",
"]",
",",
"[",
"'field'",
"=>",
"self",
"::",
"$",
"column",
",",
"'value'",
"=>",
"0",
"]",
"]",
"]",
"]",
"]",
",",
"'where'",
"=>",
"[",
"'conditions'",
"=>",
"[",
"[",
"'field'",
"=>",
"$",
"s",
"[",
"'primary'",
"]",
",",
"'value'",
"=>",
"$",
"primary_value",
"]",
"]",
"]",
"]",
")",
")",
")",
"{",
"// We won't execute the after trigger",
"$",
"cfg",
"[",
"'trig'",
"]",
"=",
"false",
";",
"// Real query's execution will be prevented",
"$",
"cfg",
"[",
"'run'",
"]",
"=",
"false",
";",
"$",
"cfg",
"[",
"'value'",
"]",
"=",
"0",
";",
"/** @var array $update The values to be updated */",
"$",
"update",
"=",
"[",
"]",
";",
"// We update each element which needs to (the new ones different from the old, and the old ones different from the default)",
"foreach",
"(",
"$",
"all",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"if",
"(",
"$",
"k",
"!==",
"$",
"s",
"[",
"'primary'",
"]",
")",
"{",
"$",
"idx",
"=",
"array_search",
"(",
"$",
"k",
",",
"$",
"cfg",
"[",
"'fields'",
"]",
",",
"true",
")",
";",
"if",
"(",
"$",
"idx",
"!==",
"false",
")",
"{",
"if",
"(",
"$",
"v",
"!==",
"$",
"cfg",
"[",
"'values'",
"]",
"[",
"$",
"idx",
"]",
")",
"{",
"$",
"update",
"[",
"$",
"k",
"]",
"=",
"$",
"cfg",
"[",
"'values'",
"]",
"[",
"$",
"idx",
"]",
";",
"}",
"}",
"else",
"if",
"(",
"$",
"v",
"!==",
"$",
"s",
"[",
"'fields'",
"]",
"[",
"$",
"k",
"]",
"[",
"'default'",
"]",
")",
"{",
"$",
"update",
"[",
"$",
"k",
"]",
"=",
"$",
"s",
"[",
"'fields'",
"]",
"[",
"$",
"k",
"]",
"[",
"'default'",
"]",
";",
"}",
"}",
"}",
"self",
"::",
"disable",
"(",
")",
";",
"if",
"(",
"$",
"cfg",
"[",
"'value'",
"]",
"=",
"self",
"::",
"$",
"db",
"->",
"update",
"(",
"self",
"::",
"$",
"table_uids",
",",
"[",
"'bbn_active'",
"=>",
"1",
"]",
",",
"[",
"[",
"'bbn_uid'",
",",
"'='",
",",
"$",
"primary_value",
"]",
"]",
")",
")",
"{",
"if",
"(",
"\\",
"count",
"(",
"$",
"update",
")",
">",
"0",
")",
"{",
"self",
"::",
"enable",
"(",
")",
";",
"self",
"::",
"$",
"db",
"->",
"update",
"(",
"$",
"table",
",",
"$",
"update",
",",
"[",
"$",
"s",
"[",
"'primary'",
"]",
"=>",
"$",
"primary_value",
"]",
")",
";",
"}",
"$",
"cfg",
"[",
"'history'",
"]",
"[",
"]",
"=",
"[",
"'operation'",
"=>",
"'RESTORE'",
",",
"'column'",
"=>",
"$",
"s",
"[",
"'fields'",
"]",
"[",
"$",
"s",
"[",
"'primary'",
"]",
"]",
"[",
"'id_option'",
"]",
",",
"'line'",
"=>",
"$",
"primary_value",
",",
"'chrono'",
"=>",
"microtime",
"(",
"true",
")",
"]",
";",
"}",
"self",
"::",
"enable",
"(",
")",
";",
"}",
"else",
"{",
"self",
"::",
"disable",
"(",
")",
";",
"if",
"(",
"$",
"primary_defined",
"&&",
"!",
"self",
"::",
"$",
"db",
"->",
"count",
"(",
"$",
"table",
",",
"[",
"$",
"s",
"[",
"'primary'",
"]",
"=>",
"$",
"primary_value",
"]",
")",
")",
"{",
"$",
"primary_defined",
"=",
"false",
";",
"}",
"if",
"(",
"!",
"$",
"primary_defined",
"&&",
"self",
"::",
"$",
"db",
"->",
"insert",
"(",
"self",
"::",
"$",
"table_uids",
",",
"[",
"'bbn_uid'",
"=>",
"$",
"primary_value",
",",
"'bbn_table'",
"=>",
"$",
"s",
"[",
"'id'",
"]",
"]",
")",
")",
"{",
"$",
"cfg",
"[",
"'history'",
"]",
"[",
"]",
"=",
"[",
"'operation'",
"=>",
"'INSERT'",
",",
"'column'",
"=>",
"$",
"s",
"[",
"'fields'",
"]",
"[",
"$",
"s",
"[",
"'primary'",
"]",
"]",
"[",
"'id_option'",
"]",
",",
"'line'",
"=>",
"$",
"primary_value",
",",
"'chrono'",
"=>",
"microtime",
"(",
"true",
")",
"]",
";",
"self",
"::",
"$",
"db",
"->",
"set_last_insert_id",
"(",
"$",
"primary_value",
")",
";",
"}",
"self",
"::",
"enable",
"(",
")",
";",
"}",
"break",
";",
"case",
"'UPDATE'",
":",
"// ********** CHANGED BY MIRKO *************",
"/*if ( $primary_defined ){\n $where = [$s['primary'] => $primary_value];\n // If the only update regards the history field\n $row = self::$db->rselect($table, array_keys($cfg['fields']), $where);\n $time = microtime(true);\n foreach ( $cfg['values'] as $k => $v ){\n if (\n ($row[$k] !== $v) &&\n isset($s['fields'][$k])\n ){\n $cfg['history'][] = [\n 'operation' => 'UPDATE',\n 'column' => $s['fields'][$k]['id_option'],\n 'line' => $primary_value,\n 'old' => $row[$k],\n 'chrono' => $time\n ];\n }\n }\n }*/",
"if",
"(",
"$",
"primary_where",
"&&",
"(",
"$",
"row",
"=",
"self",
"::",
"$",
"db",
"->",
"rselect",
"(",
"$",
"table",
",",
"$",
"cfg",
"[",
"'fields'",
"]",
",",
"[",
"$",
"s",
"[",
"'primary'",
"]",
"=>",
"$",
"primary_where",
"]",
")",
")",
")",
"{",
"$",
"time",
"=",
"microtime",
"(",
"true",
")",
";",
"foreach",
"(",
"$",
"cfg",
"[",
"'fields'",
"]",
"as",
"$",
"i",
"=>",
"$",
"idx",
")",
"{",
"$",
"csn",
"=",
"self",
"::",
"$",
"db",
"->",
"csn",
"(",
"$",
"idx",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"s",
"[",
"'fields'",
"]",
"[",
"$",
"csn",
"]",
")",
"&&",
"(",
"$",
"row",
"[",
"$",
"csn",
"]",
"!==",
"$",
"cfg",
"[",
"'values'",
"]",
"[",
"$",
"i",
"]",
")",
")",
"{",
"$",
"cfg",
"[",
"'history'",
"]",
"[",
"]",
"=",
"[",
"'operation'",
"=>",
"'UPDATE'",
",",
"'column'",
"=>",
"$",
"s",
"[",
"'fields'",
"]",
"[",
"$",
"csn",
"]",
"[",
"'id_option'",
"]",
",",
"'line'",
"=>",
"$",
"primary_where",
",",
"'old'",
"=>",
"$",
"row",
"[",
"$",
"csn",
"]",
",",
"'chrono'",
"=>",
"$",
"time",
"]",
";",
"}",
"}",
"}",
"// Case where the primary is not defined, we'll update each primary instead",
"else",
"if",
"(",
"$",
"ids",
"=",
"self",
"::",
"$",
"db",
"->",
"get_column_values",
"(",
"$",
"table",
",",
"$",
"s",
"[",
"'primary'",
"]",
",",
"$",
"cfg",
"[",
"'filters'",
"]",
")",
")",
"{",
"// We won't execute the after trigger",
"$",
"cfg",
"[",
"'trig'",
"]",
"=",
"false",
";",
"// Real query's execution will be prevented",
"$",
"cfg",
"[",
"'run'",
"]",
"=",
"false",
";",
"$",
"cfg",
"[",
"'value'",
"]",
"=",
"0",
";",
"$",
"tmp",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"cfg",
"[",
"'fields'",
"]",
"as",
"$",
"i",
"=>",
"$",
"f",
")",
"{",
"$",
"tmp",
"[",
"$",
"f",
"]",
"=",
"$",
"cfg",
"[",
"'values'",
"]",
"[",
"$",
"i",
"]",
";",
"}",
"foreach",
"(",
"$",
"ids",
"as",
"$",
"id",
")",
"{",
"$",
"cfg",
"[",
"'value'",
"]",
"+=",
"self",
"::",
"$",
"db",
"->",
"update",
"(",
"$",
"table",
",",
"$",
"tmp",
",",
"[",
"$",
"s",
"[",
"'primary'",
"]",
"=>",
"$",
"id",
"]",
")",
";",
"}",
"// ****************************************",
"}",
"break",
";",
"// Nothing is really deleted, the hcol is just set to 0",
"case",
"'DELETE'",
":",
"// We won't execute the after trigger",
"$",
"cfg",
"[",
"'trig'",
"]",
"=",
"false",
";",
"// Real query's execution will be prevented",
"$",
"cfg",
"[",
"'run'",
"]",
"=",
"false",
";",
"$",
"cfg",
"[",
"'value'",
"]",
"=",
"0",
";",
"// Case where the primary is not defined, we'll delete based on each primary instead",
"if",
"(",
"!",
"$",
"primary_where",
")",
"{",
"$",
"ids",
"=",
"self",
"::",
"$",
"db",
"->",
"get_column_values",
"(",
"$",
"table",
",",
"$",
"s",
"[",
"'primary'",
"]",
",",
"$",
"cfg",
"[",
"'filters'",
"]",
")",
";",
"foreach",
"(",
"$",
"ids",
"as",
"$",
"id",
")",
"{",
"$",
"cfg",
"[",
"'value'",
"]",
"+=",
"self",
"::",
"$",
"db",
"->",
"delete",
"(",
"$",
"table",
",",
"[",
"$",
"s",
"[",
"'primary'",
"]",
"=>",
"$",
"id",
"]",
")",
";",
"}",
"}",
"else",
"{",
"self",
"::",
"disable",
"(",
")",
";",
"$",
"cfg",
"[",
"'value'",
"]",
"=",
"self",
"::",
"$",
"db",
"->",
"update",
"(",
"self",
"::",
"$",
"table_uids",
",",
"[",
"'bbn_active'",
"=>",
"0",
"]",
",",
"[",
"'bbn_uid'",
"=>",
"$",
"primary_where",
"]",
")",
";",
"//var_dump(\"HIST\", $primary_where);",
"self",
"::",
"enable",
"(",
")",
";",
"if",
"(",
"$",
"cfg",
"[",
"'value'",
"]",
")",
"{",
"$",
"cfg",
"[",
"'trig'",
"]",
"=",
"1",
";",
"// And we insert into the history table",
"$",
"cfg",
"[",
"'history'",
"]",
"[",
"]",
"=",
"[",
"'operation'",
"=>",
"'DELETE'",
",",
"'column'",
"=>",
"$",
"s",
"[",
"'fields'",
"]",
"[",
"$",
"s",
"[",
"'primary'",
"]",
"]",
"[",
"'id_option'",
"]",
",",
"'line'",
"=>",
"$",
"primary_where",
",",
"'old'",
"=>",
"NULL",
",",
"'chrono'",
"=>",
"microtime",
"(",
"true",
")",
"]",
";",
"}",
"}",
"break",
";",
"}",
"}",
"else",
"if",
"(",
"(",
"$",
"cfg",
"[",
"'moment'",
"]",
"===",
"'after'",
")",
"&&",
"isset",
"(",
"$",
"cfg",
"[",
"'history'",
"]",
")",
")",
"{",
"foreach",
"(",
"$",
"cfg",
"[",
"'history'",
"]",
"as",
"$",
"h",
")",
"{",
"self",
"::",
"_insert",
"(",
"$",
"h",
")",
";",
"}",
"unset",
"(",
"$",
"cfg",
"[",
"'history'",
"]",
")",
";",
"}",
"}",
"return",
"$",
"cfg",
";",
"}"
] | The function used by the db trigger
This will basically execute the history query if it's configured for.
@param array $cfg
@internal param string "table" The table for which the history is called
@internal param string "kind" The type of action: select|update|insert|delete
@internal param string "moment" The moment according to the db action: before|after
@internal param array "values" key/value array of fields names and fields values selected/inserted/updated
@internal param array "where" key/value array of fields names and fields values identifying the row
@return array The $cfg array, modified or not | [
"The",
"function",
"used",
"by",
"the",
"db",
"trigger",
"This",
"will",
"basically",
"execute",
"the",
"history",
"query",
"if",
"it",
"s",
"configured",
"for",
"."
] | train | https://github.com/nabab/bbn/blob/439fea2faa0de22fdaae2611833bab8061f40c37/src/bbn/appui/history.php#L958-L1367 |
hametuha/wpametu | src/WPametu/File/Mime.php | Mime.is_image | public function is_image($path){
if( !file_exists($path) || !($info = getimagesize($path)) ){
return false;
}
return (bool) preg_match("/^image\/(jpeg|png|gif)$/", $info['mime']);
} | php | public function is_image($path){
if( !file_exists($path) || !($info = getimagesize($path)) ){
return false;
}
return (bool) preg_match("/^image\/(jpeg|png|gif)$/", $info['mime']);
} | [
"public",
"function",
"is_image",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"path",
")",
"||",
"!",
"(",
"$",
"info",
"=",
"getimagesize",
"(",
"$",
"path",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"(",
"bool",
")",
"preg_match",
"(",
"\"/^image\\/(jpeg|png|gif)$/\"",
",",
"$",
"info",
"[",
"'mime'",
"]",
")",
";",
"}"
] | Detect if specified file is image
@param string $path
@return bool | [
"Detect",
"if",
"specified",
"file",
"is",
"image"
] | train | https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/File/Mime.php#L22-L27 |
hametuha/wpametu | src/WPametu/File/Mime.php | Mime.get_mime | public function get_mime($file){
$type = $this->get_content_type($file);
if( $type ){
$type = array_map('trim', explode(';', $type));
return $type[0];
}else{
return '';
}
} | php | public function get_mime($file){
$type = $this->get_content_type($file);
if( $type ){
$type = array_map('trim', explode(';', $type));
return $type[0];
}else{
return '';
}
} | [
"public",
"function",
"get_mime",
"(",
"$",
"file",
")",
"{",
"$",
"type",
"=",
"$",
"this",
"->",
"get_content_type",
"(",
"$",
"file",
")",
";",
"if",
"(",
"$",
"type",
")",
"{",
"$",
"type",
"=",
"array_map",
"(",
"'trim'",
",",
"explode",
"(",
"';'",
",",
"$",
"type",
")",
")",
";",
"return",
"$",
"type",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"return",
"''",
";",
"}",
"}"
] | Return mime type
@param string $file
@return string | [
"Return",
"mime",
"type"
] | train | https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/File/Mime.php#L35-L43 |
hametuha/wpametu | src/WPametu/File/Mime.php | Mime.get_content_type | public function get_content_type($path){
if( file_exists($path) ){
$info = finfo_open(FILEINFO_MIME);
$type = finfo_file($info, $path) ;
finfo_close($info);
return $type ?: '' ;
}else{
return '';
}
} | php | public function get_content_type($path){
if( file_exists($path) ){
$info = finfo_open(FILEINFO_MIME);
$type = finfo_file($info, $path) ;
finfo_close($info);
return $type ?: '' ;
}else{
return '';
}
} | [
"public",
"function",
"get_content_type",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"file_exists",
"(",
"$",
"path",
")",
")",
"{",
"$",
"info",
"=",
"finfo_open",
"(",
"FILEINFO_MIME",
")",
";",
"$",
"type",
"=",
"finfo_file",
"(",
"$",
"info",
",",
"$",
"path",
")",
";",
"finfo_close",
"(",
"$",
"info",
")",
";",
"return",
"$",
"type",
"?",
":",
"''",
";",
"}",
"else",
"{",
"return",
"''",
";",
"}",
"}"
] | Get content type
@param string $path
@return string | [
"Get",
"content",
"type"
] | train | https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/File/Mime.php#L51-L60 |
hametuha/wpametu | src/WPametu/File/Mime.php | Mime.get_extension | public function get_extension($path){
$type = $this->get_mime($path);
$match = [];
$ext = '';
if( $type ){
foreach( wp_get_mime_types() as $extensions => $content_type ){
if( $content_type == $type ){
$ext = explode('|', $extensions)[0];
break;
}
}
}
return $ext;
} | php | public function get_extension($path){
$type = $this->get_mime($path);
$match = [];
$ext = '';
if( $type ){
foreach( wp_get_mime_types() as $extensions => $content_type ){
if( $content_type == $type ){
$ext = explode('|', $extensions)[0];
break;
}
}
}
return $ext;
} | [
"public",
"function",
"get_extension",
"(",
"$",
"path",
")",
"{",
"$",
"type",
"=",
"$",
"this",
"->",
"get_mime",
"(",
"$",
"path",
")",
";",
"$",
"match",
"=",
"[",
"]",
";",
"$",
"ext",
"=",
"''",
";",
"if",
"(",
"$",
"type",
")",
"{",
"foreach",
"(",
"wp_get_mime_types",
"(",
")",
"as",
"$",
"extensions",
"=>",
"$",
"content_type",
")",
"{",
"if",
"(",
"$",
"content_type",
"==",
"$",
"type",
")",
"{",
"$",
"ext",
"=",
"explode",
"(",
"'|'",
",",
"$",
"extensions",
")",
"[",
"0",
"]",
";",
"break",
";",
"}",
"}",
"}",
"return",
"$",
"ext",
";",
"}"
] | Get extension
@param string $path
@return string | [
"Get",
"extension"
] | train | https://github.com/hametuha/wpametu/blob/0939373800815a8396291143d2a57967340da5aa/src/WPametu/File/Mime.php#L68-L81 |
digipolisgent/robo-digipolis-package-drupal8 | src/PackageDrupal8.php | PackageDrupal8.prepareMirrorDir | protected function prepareMirrorDir()
{
$this->printTaskInfo(sprintf('Preparing directory %s.', $this->tmpDir));
// Only keep web, vendor and config folder.
$folders = new Finder();
$folders->in($this->tmpDir);
$folders->depth(0);
$folders->notPath('/^(' . implode('|', array_map('preg_quote', $this->keepPaths)) . ')$/');
$folders->ignoreDotFiles(false);
$this->fs->remove($folders);
if (empty($this->ignoreFileNames)) {
return;
}
$files = new Finder();
$files->in($this->tmpDir);
$files->ignoreDotFiles(false);
$dotfiles = clone $files;
$files->files();
// Ignore files defined by the dev.
foreach ($this->ignoreFileNames as $fileName) {
$files->name($fileName);
}
$this->fs->remove($files);
// Remove dotfiles except .htaccess.
$dotfiles->path('/(^|\/)\.(?!(htaccess$)).+(\/|$)/');
$this->fs->remove($dotfiles);
} | php | protected function prepareMirrorDir()
{
$this->printTaskInfo(sprintf('Preparing directory %s.', $this->tmpDir));
// Only keep web, vendor and config folder.
$folders = new Finder();
$folders->in($this->tmpDir);
$folders->depth(0);
$folders->notPath('/^(' . implode('|', array_map('preg_quote', $this->keepPaths)) . ')$/');
$folders->ignoreDotFiles(false);
$this->fs->remove($folders);
if (empty($this->ignoreFileNames)) {
return;
}
$files = new Finder();
$files->in($this->tmpDir);
$files->ignoreDotFiles(false);
$dotfiles = clone $files;
$files->files();
// Ignore files defined by the dev.
foreach ($this->ignoreFileNames as $fileName) {
$files->name($fileName);
}
$this->fs->remove($files);
// Remove dotfiles except .htaccess.
$dotfiles->path('/(^|\/)\.(?!(htaccess$)).+(\/|$)/');
$this->fs->remove($dotfiles);
} | [
"protected",
"function",
"prepareMirrorDir",
"(",
")",
"{",
"$",
"this",
"->",
"printTaskInfo",
"(",
"sprintf",
"(",
"'Preparing directory %s.'",
",",
"$",
"this",
"->",
"tmpDir",
")",
")",
";",
"// Only keep web, vendor and config folder.",
"$",
"folders",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"folders",
"->",
"in",
"(",
"$",
"this",
"->",
"tmpDir",
")",
";",
"$",
"folders",
"->",
"depth",
"(",
"0",
")",
";",
"$",
"folders",
"->",
"notPath",
"(",
"'/^('",
".",
"implode",
"(",
"'|'",
",",
"array_map",
"(",
"'preg_quote'",
",",
"$",
"this",
"->",
"keepPaths",
")",
")",
".",
"')$/'",
")",
";",
"$",
"folders",
"->",
"ignoreDotFiles",
"(",
"false",
")",
";",
"$",
"this",
"->",
"fs",
"->",
"remove",
"(",
"$",
"folders",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"ignoreFileNames",
")",
")",
"{",
"return",
";",
"}",
"$",
"files",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"files",
"->",
"in",
"(",
"$",
"this",
"->",
"tmpDir",
")",
";",
"$",
"files",
"->",
"ignoreDotFiles",
"(",
"false",
")",
";",
"$",
"dotfiles",
"=",
"clone",
"$",
"files",
";",
"$",
"files",
"->",
"files",
"(",
")",
";",
"// Ignore files defined by the dev.",
"foreach",
"(",
"$",
"this",
"->",
"ignoreFileNames",
"as",
"$",
"fileName",
")",
"{",
"$",
"files",
"->",
"name",
"(",
"$",
"fileName",
")",
";",
"}",
"$",
"this",
"->",
"fs",
"->",
"remove",
"(",
"$",
"files",
")",
";",
"// Remove dotfiles except .htaccess.",
"$",
"dotfiles",
"->",
"path",
"(",
"'/(^|\\/)\\.(?!(htaccess$)).+(\\/|$)/'",
")",
";",
"$",
"this",
"->",
"fs",
"->",
"remove",
"(",
"$",
"dotfiles",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/digipolisgent/robo-digipolis-package-drupal8/blob/dc03ae0f68d56a027291e9574ff7aa433c27690a/src/PackageDrupal8.php#L86-L117 |
andromeda-framework/doctrine | src/Doctrine/Console/Commands/MetadataMerger.php | MetadataMerger.merge | public function merge(array $metadata): array
{
$tables = [];
foreach ($metadata as $entity) {
$tables[$entity->getTableName()][] = $entity;
}
$merged = [];
foreach ($tables as $table => $metadata) {
if (count($metadata) === 1) {
$merged[] = array_shift($metadata);
continue;
}
$primary = $this->resolvePrimaryMetadata($metadata);
foreach ($metadata as $secondary) {
$primary = $this->mergeMetadata($primary, $secondary);
}
$primary->fieldMappings = $this->mappingCleanup($primary->fieldMappings);
$primary->associationMappings = $this->mappingCleanup($primary->associationMappings);
$merged[] = $primary;
}
return $merged;
} | php | public function merge(array $metadata): array
{
$tables = [];
foreach ($metadata as $entity) {
$tables[$entity->getTableName()][] = $entity;
}
$merged = [];
foreach ($tables as $table => $metadata) {
if (count($metadata) === 1) {
$merged[] = array_shift($metadata);
continue;
}
$primary = $this->resolvePrimaryMetadata($metadata);
foreach ($metadata as $secondary) {
$primary = $this->mergeMetadata($primary, $secondary);
}
$primary->fieldMappings = $this->mappingCleanup($primary->fieldMappings);
$primary->associationMappings = $this->mappingCleanup($primary->associationMappings);
$merged[] = $primary;
}
return $merged;
} | [
"public",
"function",
"merge",
"(",
"array",
"$",
"metadata",
")",
":",
"array",
"{",
"$",
"tables",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"metadata",
"as",
"$",
"entity",
")",
"{",
"$",
"tables",
"[",
"$",
"entity",
"->",
"getTableName",
"(",
")",
"]",
"[",
"]",
"=",
"$",
"entity",
";",
"}",
"$",
"merged",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"tables",
"as",
"$",
"table",
"=>",
"$",
"metadata",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"metadata",
")",
"===",
"1",
")",
"{",
"$",
"merged",
"[",
"]",
"=",
"array_shift",
"(",
"$",
"metadata",
")",
";",
"continue",
";",
"}",
"$",
"primary",
"=",
"$",
"this",
"->",
"resolvePrimaryMetadata",
"(",
"$",
"metadata",
")",
";",
"foreach",
"(",
"$",
"metadata",
"as",
"$",
"secondary",
")",
"{",
"$",
"primary",
"=",
"$",
"this",
"->",
"mergeMetadata",
"(",
"$",
"primary",
",",
"$",
"secondary",
")",
";",
"}",
"$",
"primary",
"->",
"fieldMappings",
"=",
"$",
"this",
"->",
"mappingCleanup",
"(",
"$",
"primary",
"->",
"fieldMappings",
")",
";",
"$",
"primary",
"->",
"associationMappings",
"=",
"$",
"this",
"->",
"mappingCleanup",
"(",
"$",
"primary",
"->",
"associationMappings",
")",
";",
"$",
"merged",
"[",
"]",
"=",
"$",
"primary",
";",
"}",
"return",
"$",
"merged",
";",
"}"
] | Merges metadata of multiple doctrine entities.
Input metadata can contain duplicit tables. If so, metadata for
the same table will be merged into one.
@param ClassMetadata[] $metadata
@return ClassMetadata[] | [
"Merges",
"metadata",
"of",
"multiple",
"doctrine",
"entities",
"."
] | train | https://github.com/andromeda-framework/doctrine/blob/46924d91c09e0b9fbe5764518cbad70e467ffad4/src/Doctrine/Console/Commands/MetadataMerger.php#L40-L66 |
mothership-ec/composer | src/Composer/Command/DiagnoseCommand.php | DiagnoseCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$composer = $this->getComposer(false);
if ($composer) {
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'diagnose', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$this->getIO()->write('Checking composer.json: ', false);
$this->outputResult($this->checkComposerSchema());
}
if ($composer) {
$config = $composer->getConfig();
} else {
$config = Factory::createConfig();
}
$this->rfs = new RemoteFilesystem($this->getIO(), $config);
$this->process = new ProcessExecutor($this->getIO());
$this->getIO()->write('Checking platform settings: ', false);
$this->outputResult($this->checkPlatform());
$this->getIO()->write('Checking git settings: ', false);
$this->outputResult($this->checkGit());
$this->getIO()->write('Checking http connectivity: ', false);
$this->outputResult($this->checkHttp());
$opts = stream_context_get_options(StreamContextFactory::getContext('http://example.org'));
if (!empty($opts['http']['proxy'])) {
$this->getIO()->write('Checking HTTP proxy: ', false);
$this->outputResult($this->checkHttpProxy());
$this->getIO()->write('Checking HTTP proxy support for request_fulluri: ', false);
$this->outputResult($this->checkHttpProxyFullUriRequestParam());
$this->getIO()->write('Checking HTTPS proxy support for request_fulluri: ', false);
$this->outputResult($this->checkHttpsProxyFullUriRequestParam());
}
if ($oauth = $config->get('github-oauth')) {
foreach ($oauth as $domain => $token) {
$this->getIO()->write('Checking '.$domain.' oauth access: ', false);
$this->outputResult($this->checkGithubOauth($domain, $token));
}
} else {
$this->getIO()->write('Checking github.com rate limit: ', false);
try {
$rate = $this->getGithubRateLimit('github.com');
$this->outputResult(true);
if (10 > $rate['remaining']) {
$this->getIO()->write('<warning>WARNING</warning>');
$this->getIO()->write(sprintf(
'<comment>Github has a rate limit on their API. '
. 'You currently have <options=bold>%u</options=bold> '
. 'out of <options=bold>%u</options=bold> requests left.' . PHP_EOL
. 'See https://developer.github.com/v3/#rate-limiting and also' . PHP_EOL
. ' https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens</comment>',
$rate['remaining'],
$rate['limit']
));
}
} catch (\Exception $e) {
if ($e instanceof TransportException && $e->getCode() === 401) {
$this->outputResult('<comment>The oauth token for github.com seems invalid, run "composer config --global --unset github-oauth.github.com" to remove it</comment>');
} else {
$this->outputResult($e);
}
}
}
$this->getIO()->write('Checking disk free space: ', false);
$this->outputResult($this->checkDiskSpace($config));
$this->getIO()->write('Checking composer version: ', false);
$this->outputResult($this->checkVersion());
return $this->failures;
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$composer = $this->getComposer(false);
if ($composer) {
$commandEvent = new CommandEvent(PluginEvents::COMMAND, 'diagnose', $input, $output);
$composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
$this->getIO()->write('Checking composer.json: ', false);
$this->outputResult($this->checkComposerSchema());
}
if ($composer) {
$config = $composer->getConfig();
} else {
$config = Factory::createConfig();
}
$this->rfs = new RemoteFilesystem($this->getIO(), $config);
$this->process = new ProcessExecutor($this->getIO());
$this->getIO()->write('Checking platform settings: ', false);
$this->outputResult($this->checkPlatform());
$this->getIO()->write('Checking git settings: ', false);
$this->outputResult($this->checkGit());
$this->getIO()->write('Checking http connectivity: ', false);
$this->outputResult($this->checkHttp());
$opts = stream_context_get_options(StreamContextFactory::getContext('http://example.org'));
if (!empty($opts['http']['proxy'])) {
$this->getIO()->write('Checking HTTP proxy: ', false);
$this->outputResult($this->checkHttpProxy());
$this->getIO()->write('Checking HTTP proxy support for request_fulluri: ', false);
$this->outputResult($this->checkHttpProxyFullUriRequestParam());
$this->getIO()->write('Checking HTTPS proxy support for request_fulluri: ', false);
$this->outputResult($this->checkHttpsProxyFullUriRequestParam());
}
if ($oauth = $config->get('github-oauth')) {
foreach ($oauth as $domain => $token) {
$this->getIO()->write('Checking '.$domain.' oauth access: ', false);
$this->outputResult($this->checkGithubOauth($domain, $token));
}
} else {
$this->getIO()->write('Checking github.com rate limit: ', false);
try {
$rate = $this->getGithubRateLimit('github.com');
$this->outputResult(true);
if (10 > $rate['remaining']) {
$this->getIO()->write('<warning>WARNING</warning>');
$this->getIO()->write(sprintf(
'<comment>Github has a rate limit on their API. '
. 'You currently have <options=bold>%u</options=bold> '
. 'out of <options=bold>%u</options=bold> requests left.' . PHP_EOL
. 'See https://developer.github.com/v3/#rate-limiting and also' . PHP_EOL
. ' https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens</comment>',
$rate['remaining'],
$rate['limit']
));
}
} catch (\Exception $e) {
if ($e instanceof TransportException && $e->getCode() === 401) {
$this->outputResult('<comment>The oauth token for github.com seems invalid, run "composer config --global --unset github-oauth.github.com" to remove it</comment>');
} else {
$this->outputResult($e);
}
}
}
$this->getIO()->write('Checking disk free space: ', false);
$this->outputResult($this->checkDiskSpace($config));
$this->getIO()->write('Checking composer version: ', false);
$this->outputResult($this->checkVersion());
return $this->failures;
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"composer",
"=",
"$",
"this",
"->",
"getComposer",
"(",
"false",
")",
";",
"if",
"(",
"$",
"composer",
")",
"{",
"$",
"commandEvent",
"=",
"new",
"CommandEvent",
"(",
"PluginEvents",
"::",
"COMMAND",
",",
"'diagnose'",
",",
"$",
"input",
",",
"$",
"output",
")",
";",
"$",
"composer",
"->",
"getEventDispatcher",
"(",
")",
"->",
"dispatch",
"(",
"$",
"commandEvent",
"->",
"getName",
"(",
")",
",",
"$",
"commandEvent",
")",
";",
"$",
"this",
"->",
"getIO",
"(",
")",
"->",
"write",
"(",
"'Checking composer.json: '",
",",
"false",
")",
";",
"$",
"this",
"->",
"outputResult",
"(",
"$",
"this",
"->",
"checkComposerSchema",
"(",
")",
")",
";",
"}",
"if",
"(",
"$",
"composer",
")",
"{",
"$",
"config",
"=",
"$",
"composer",
"->",
"getConfig",
"(",
")",
";",
"}",
"else",
"{",
"$",
"config",
"=",
"Factory",
"::",
"createConfig",
"(",
")",
";",
"}",
"$",
"this",
"->",
"rfs",
"=",
"new",
"RemoteFilesystem",
"(",
"$",
"this",
"->",
"getIO",
"(",
")",
",",
"$",
"config",
")",
";",
"$",
"this",
"->",
"process",
"=",
"new",
"ProcessExecutor",
"(",
"$",
"this",
"->",
"getIO",
"(",
")",
")",
";",
"$",
"this",
"->",
"getIO",
"(",
")",
"->",
"write",
"(",
"'Checking platform settings: '",
",",
"false",
")",
";",
"$",
"this",
"->",
"outputResult",
"(",
"$",
"this",
"->",
"checkPlatform",
"(",
")",
")",
";",
"$",
"this",
"->",
"getIO",
"(",
")",
"->",
"write",
"(",
"'Checking git settings: '",
",",
"false",
")",
";",
"$",
"this",
"->",
"outputResult",
"(",
"$",
"this",
"->",
"checkGit",
"(",
")",
")",
";",
"$",
"this",
"->",
"getIO",
"(",
")",
"->",
"write",
"(",
"'Checking http connectivity: '",
",",
"false",
")",
";",
"$",
"this",
"->",
"outputResult",
"(",
"$",
"this",
"->",
"checkHttp",
"(",
")",
")",
";",
"$",
"opts",
"=",
"stream_context_get_options",
"(",
"StreamContextFactory",
"::",
"getContext",
"(",
"'http://example.org'",
")",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"opts",
"[",
"'http'",
"]",
"[",
"'proxy'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"getIO",
"(",
")",
"->",
"write",
"(",
"'Checking HTTP proxy: '",
",",
"false",
")",
";",
"$",
"this",
"->",
"outputResult",
"(",
"$",
"this",
"->",
"checkHttpProxy",
"(",
")",
")",
";",
"$",
"this",
"->",
"getIO",
"(",
")",
"->",
"write",
"(",
"'Checking HTTP proxy support for request_fulluri: '",
",",
"false",
")",
";",
"$",
"this",
"->",
"outputResult",
"(",
"$",
"this",
"->",
"checkHttpProxyFullUriRequestParam",
"(",
")",
")",
";",
"$",
"this",
"->",
"getIO",
"(",
")",
"->",
"write",
"(",
"'Checking HTTPS proxy support for request_fulluri: '",
",",
"false",
")",
";",
"$",
"this",
"->",
"outputResult",
"(",
"$",
"this",
"->",
"checkHttpsProxyFullUriRequestParam",
"(",
")",
")",
";",
"}",
"if",
"(",
"$",
"oauth",
"=",
"$",
"config",
"->",
"get",
"(",
"'github-oauth'",
")",
")",
"{",
"foreach",
"(",
"$",
"oauth",
"as",
"$",
"domain",
"=>",
"$",
"token",
")",
"{",
"$",
"this",
"->",
"getIO",
"(",
")",
"->",
"write",
"(",
"'Checking '",
".",
"$",
"domain",
".",
"' oauth access: '",
",",
"false",
")",
";",
"$",
"this",
"->",
"outputResult",
"(",
"$",
"this",
"->",
"checkGithubOauth",
"(",
"$",
"domain",
",",
"$",
"token",
")",
")",
";",
"}",
"}",
"else",
"{",
"$",
"this",
"->",
"getIO",
"(",
")",
"->",
"write",
"(",
"'Checking github.com rate limit: '",
",",
"false",
")",
";",
"try",
"{",
"$",
"rate",
"=",
"$",
"this",
"->",
"getGithubRateLimit",
"(",
"'github.com'",
")",
";",
"$",
"this",
"->",
"outputResult",
"(",
"true",
")",
";",
"if",
"(",
"10",
">",
"$",
"rate",
"[",
"'remaining'",
"]",
")",
"{",
"$",
"this",
"->",
"getIO",
"(",
")",
"->",
"write",
"(",
"'<warning>WARNING</warning>'",
")",
";",
"$",
"this",
"->",
"getIO",
"(",
")",
"->",
"write",
"(",
"sprintf",
"(",
"'<comment>Github has a rate limit on their API. '",
".",
"'You currently have <options=bold>%u</options=bold> '",
".",
"'out of <options=bold>%u</options=bold> requests left.'",
".",
"PHP_EOL",
".",
"'See https://developer.github.com/v3/#rate-limiting and also'",
".",
"PHP_EOL",
".",
"' https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens</comment>'",
",",
"$",
"rate",
"[",
"'remaining'",
"]",
",",
"$",
"rate",
"[",
"'limit'",
"]",
")",
")",
";",
"}",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"if",
"(",
"$",
"e",
"instanceof",
"TransportException",
"&&",
"$",
"e",
"->",
"getCode",
"(",
")",
"===",
"401",
")",
"{",
"$",
"this",
"->",
"outputResult",
"(",
"'<comment>The oauth token for github.com seems invalid, run \"composer config --global --unset github-oauth.github.com\" to remove it</comment>'",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"outputResult",
"(",
"$",
"e",
")",
";",
"}",
"}",
"}",
"$",
"this",
"->",
"getIO",
"(",
")",
"->",
"write",
"(",
"'Checking disk free space: '",
",",
"false",
")",
";",
"$",
"this",
"->",
"outputResult",
"(",
"$",
"this",
"->",
"checkDiskSpace",
"(",
"$",
"config",
")",
")",
";",
"$",
"this",
"->",
"getIO",
"(",
")",
"->",
"write",
"(",
"'Checking composer version: '",
",",
"false",
")",
";",
"$",
"this",
"->",
"outputResult",
"(",
"$",
"this",
"->",
"checkVersion",
"(",
")",
")",
";",
"return",
"$",
"this",
"->",
"failures",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/mothership-ec/composer/blob/fa6ad031a939d8d33b211e428fdbdd28cfce238c/src/Composer/Command/DiagnoseCommand.php#L57-L135 |
comodojo/daemon | src/Comodojo/Daemon/Daemon.php | Daemon.init | public function init() {
$args = $this->console->arguments;
$args->parse();
if ( $args->defined('hardstart') ) {
$this->hardstart();
}
if ( $args->defined('daemon') ) {
$this->daemonize();
} else if ( $args->defined('foreground') ) {
if ( $args->defined('verbose') ) {
$this->logger->pushHandler(new LogHandler());
}
$this->start();
} else {
$this->console->pad()->green()->usage();
$this->end(0);
}
} | php | public function init() {
$args = $this->console->arguments;
$args->parse();
if ( $args->defined('hardstart') ) {
$this->hardstart();
}
if ( $args->defined('daemon') ) {
$this->daemonize();
} else if ( $args->defined('foreground') ) {
if ( $args->defined('verbose') ) {
$this->logger->pushHandler(new LogHandler());
}
$this->start();
} else {
$this->console->pad()->green()->usage();
$this->end(0);
}
} | [
"public",
"function",
"init",
"(",
")",
"{",
"$",
"args",
"=",
"$",
"this",
"->",
"console",
"->",
"arguments",
";",
"$",
"args",
"->",
"parse",
"(",
")",
";",
"if",
"(",
"$",
"args",
"->",
"defined",
"(",
"'hardstart'",
")",
")",
"{",
"$",
"this",
"->",
"hardstart",
"(",
")",
";",
"}",
"if",
"(",
"$",
"args",
"->",
"defined",
"(",
"'daemon'",
")",
")",
"{",
"$",
"this",
"->",
"daemonize",
"(",
")",
";",
"}",
"else",
"if",
"(",
"$",
"args",
"->",
"defined",
"(",
"'foreground'",
")",
")",
"{",
"if",
"(",
"$",
"args",
"->",
"defined",
"(",
"'verbose'",
")",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"pushHandler",
"(",
"new",
"LogHandler",
"(",
")",
")",
";",
"}",
"$",
"this",
"->",
"start",
"(",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"console",
"->",
"pad",
"(",
")",
"->",
"green",
"(",
")",
"->",
"usage",
"(",
")",
";",
"$",
"this",
"->",
"end",
"(",
"0",
")",
";",
"}",
"}"
] | Parse console arguments and init the daemon | [
"Parse",
"console",
"arguments",
"and",
"init",
"the",
"daemon"
] | train | https://github.com/comodojo/daemon/blob/361b0a3a91dc7720dd3bec448bb4ca47d0ef0292/src/Comodojo/Daemon/Daemon.php#L133-L164 |
comodojo/daemon | src/Comodojo/Daemon/Daemon.php | Daemon.daemonize | public function daemonize() {
// fork script
$pid = $this->fork();
// detach from current terminal (if any)
$this->detach();
// update pid reference (we have a new daemon)
$this->pid = $pid;
// start process daemon
$this->start();
} | php | public function daemonize() {
// fork script
$pid = $this->fork();
// detach from current terminal (if any)
$this->detach();
// update pid reference (we have a new daemon)
$this->pid = $pid;
// start process daemon
$this->start();
} | [
"public",
"function",
"daemonize",
"(",
")",
"{",
"// fork script",
"$",
"pid",
"=",
"$",
"this",
"->",
"fork",
"(",
")",
";",
"// detach from current terminal (if any)",
"$",
"this",
"->",
"detach",
"(",
")",
";",
"// update pid reference (we have a new daemon)",
"$",
"this",
"->",
"pid",
"=",
"$",
"pid",
";",
"// start process daemon",
"$",
"this",
"->",
"start",
"(",
")",
";",
"}"
] | Start as a daemon, forking main process and detaching it from terminal | [
"Start",
"as",
"a",
"daemon",
"forking",
"main",
"process",
"and",
"detaching",
"it",
"from",
"terminal"
] | train | https://github.com/comodojo/daemon/blob/361b0a3a91dc7720dd3bec448bb4ca47d0ef0292/src/Comodojo/Daemon/Daemon.php#L170-L184 |
comodojo/daemon | src/Comodojo/Daemon/Daemon.php | Daemon.start | public function start() {
// we're activating!
$this->is_active = true;
$this->setup();
foreach ( $this->workers as $name => $worker ) {
$this->workers->start($name);
}
$this->becomeSupervisor();
// start listening on socket
try {
$this->socket->listen();
} catch (SocketException $e) {
// something did wrong on socket...
$this->logger->error($e->getMessage());
$this->stop();
$this->end(0);
}
// loop closed; if I'm the supervisor, I should clean everything
if ( $this->is_supervisor && $this->is_active ) {
$this->stop();
$this->end(0);
}
} | php | public function start() {
// we're activating!
$this->is_active = true;
$this->setup();
foreach ( $this->workers as $name => $worker ) {
$this->workers->start($name);
}
$this->becomeSupervisor();
// start listening on socket
try {
$this->socket->listen();
} catch (SocketException $e) {
// something did wrong on socket...
$this->logger->error($e->getMessage());
$this->stop();
$this->end(0);
}
// loop closed; if I'm the supervisor, I should clean everything
if ( $this->is_supervisor && $this->is_active ) {
$this->stop();
$this->end(0);
}
} | [
"public",
"function",
"start",
"(",
")",
"{",
"// we're activating!",
"$",
"this",
"->",
"is_active",
"=",
"true",
";",
"$",
"this",
"->",
"setup",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"workers",
"as",
"$",
"name",
"=>",
"$",
"worker",
")",
"{",
"$",
"this",
"->",
"workers",
"->",
"start",
"(",
"$",
"name",
")",
";",
"}",
"$",
"this",
"->",
"becomeSupervisor",
"(",
")",
";",
"// start listening on socket",
"try",
"{",
"$",
"this",
"->",
"socket",
"->",
"listen",
"(",
")",
";",
"}",
"catch",
"(",
"SocketException",
"$",
"e",
")",
"{",
"// something did wrong on socket...",
"$",
"this",
"->",
"logger",
"->",
"error",
"(",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"$",
"this",
"->",
"stop",
"(",
")",
";",
"$",
"this",
"->",
"end",
"(",
"0",
")",
";",
"}",
"// loop closed; if I'm the supervisor, I should clean everything",
"if",
"(",
"$",
"this",
"->",
"is_supervisor",
"&&",
"$",
"this",
"->",
"is_active",
")",
"{",
"$",
"this",
"->",
"stop",
"(",
")",
";",
"$",
"this",
"->",
"end",
"(",
"0",
")",
";",
"}",
"}"
] | Start the process, creating socket and spinning up workers (if any) | [
"Start",
"the",
"process",
"creating",
"socket",
"and",
"spinning",
"up",
"workers",
"(",
"if",
"any",
")"
] | train | https://github.com/comodojo/daemon/blob/361b0a3a91dc7720dd3bec448bb4ca47d0ef0292/src/Comodojo/Daemon/Daemon.php#L190-L225 |
comodojo/daemon | src/Comodojo/Daemon/Daemon.php | Daemon.stop | public function stop() {
$this->logger->notice("Stopping daemon...");
$this->events->removeAllListeners('daemon.posix.'.SIGCHLD);
$this->socket->close();
$this->workers->stop();
$this->pidlock->release();
$this->is_active = false;
} | php | public function stop() {
$this->logger->notice("Stopping daemon...");
$this->events->removeAllListeners('daemon.posix.'.SIGCHLD);
$this->socket->close();
$this->workers->stop();
$this->pidlock->release();
$this->is_active = false;
} | [
"public",
"function",
"stop",
"(",
")",
"{",
"$",
"this",
"->",
"logger",
"->",
"notice",
"(",
"\"Stopping daemon...\"",
")",
";",
"$",
"this",
"->",
"events",
"->",
"removeAllListeners",
"(",
"'daemon.posix.'",
".",
"SIGCHLD",
")",
";",
"$",
"this",
"->",
"socket",
"->",
"close",
"(",
")",
";",
"$",
"this",
"->",
"workers",
"->",
"stop",
"(",
")",
";",
"$",
"this",
"->",
"pidlock",
"->",
"release",
"(",
")",
";",
"$",
"this",
"->",
"is_active",
"=",
"false",
";",
"}"
] | Stop the daemon, closing the socket and stopping all the workers (if any) | [
"Stop",
"the",
"daemon",
"closing",
"the",
"socket",
"and",
"stopping",
"all",
"the",
"workers",
"(",
"if",
"any",
")"
] | train | https://github.com/comodojo/daemon/blob/361b0a3a91dc7720dd3bec448bb4ca47d0ef0292/src/Comodojo/Daemon/Daemon.php#L231-L245 |
comodojo/daemon | src/Comodojo/Daemon/Daemon.php | Daemon.declass | public function declass() {
// remove supervisor flag
$this->is_supervisor = false;
// Unsubscribe supervisor default events (if any)
$this->events->removeAllListeners('daemon.posix.'.SIGTERM);
$this->events->removeAllListeners('daemon.posix.'.SIGINT);
$this->events->removeAllListeners('daemon.socket.loop');
// unset supervisor components
unset($this->pidlock);
unset($this->socket);
unset($this->workers);
unset($this->console);
} | php | public function declass() {
// remove supervisor flag
$this->is_supervisor = false;
// Unsubscribe supervisor default events (if any)
$this->events->removeAllListeners('daemon.posix.'.SIGTERM);
$this->events->removeAllListeners('daemon.posix.'.SIGINT);
$this->events->removeAllListeners('daemon.socket.loop');
// unset supervisor components
unset($this->pidlock);
unset($this->socket);
unset($this->workers);
unset($this->console);
} | [
"public",
"function",
"declass",
"(",
")",
"{",
"// remove supervisor flag",
"$",
"this",
"->",
"is_supervisor",
"=",
"false",
";",
"// Unsubscribe supervisor default events (if any)",
"$",
"this",
"->",
"events",
"->",
"removeAllListeners",
"(",
"'daemon.posix.'",
".",
"SIGTERM",
")",
";",
"$",
"this",
"->",
"events",
"->",
"removeAllListeners",
"(",
"'daemon.posix.'",
".",
"SIGINT",
")",
";",
"$",
"this",
"->",
"events",
"->",
"removeAllListeners",
"(",
"'daemon.socket.loop'",
")",
";",
"// unset supervisor components",
"unset",
"(",
"$",
"this",
"->",
"pidlock",
")",
";",
"unset",
"(",
"$",
"this",
"->",
"socket",
")",
";",
"unset",
"(",
"$",
"this",
"->",
"workers",
")",
";",
"unset",
"(",
"$",
"this",
"->",
"console",
")",
";",
"}"
] | Declass the daemon to a normal supervised process (daemon to worker transition) | [
"Declass",
"the",
"daemon",
"to",
"a",
"normal",
"supervised",
"process",
"(",
"daemon",
"to",
"worker",
"transition",
")"
] | train | https://github.com/comodojo/daemon/blob/361b0a3a91dc7720dd3bec448bb4ca47d0ef0292/src/Comodojo/Daemon/Daemon.php#L286-L302 |
digipolisgent/robo-digipolis-general | src/DetermineProjectRoot.php | DetermineProjectRoot.run | public function run()
{
$finder = clone $this->finder;
$finder->in([$this->dir])->exclude($this->exclude)->depth('<=' . $this->depth)->files();
$rootCandidates = [];
foreach ($this->searchFiles as $searchFile) {
$fileFinder = clone $finder;
$fileFinder->name($searchFile);
foreach ($fileFinder->getIterator() as $file) {
$rootCandidates[] = dirname($file->getRealPath());
}
if ($rootCandidates) {
break;
}
}
usort(
$rootCandidates,
function ($a, $b) {
return count(explode(DIRECTORY_SEPARATOR, $a)) - count(explode(DIRECTORY_SEPARATOR, $b));
}
);
$root = $rootCandidates ? reset($rootCandidates) : getcwd();
$this->printTaskInfo(sprintf('Settings %s to %s.', $this->configKey, $root));
$this->getConfig()->set($this->configKey, $root);
return Result::success($this, 'Found root at ' . $root . '.');
} | php | public function run()
{
$finder = clone $this->finder;
$finder->in([$this->dir])->exclude($this->exclude)->depth('<=' . $this->depth)->files();
$rootCandidates = [];
foreach ($this->searchFiles as $searchFile) {
$fileFinder = clone $finder;
$fileFinder->name($searchFile);
foreach ($fileFinder->getIterator() as $file) {
$rootCandidates[] = dirname($file->getRealPath());
}
if ($rootCandidates) {
break;
}
}
usort(
$rootCandidates,
function ($a, $b) {
return count(explode(DIRECTORY_SEPARATOR, $a)) - count(explode(DIRECTORY_SEPARATOR, $b));
}
);
$root = $rootCandidates ? reset($rootCandidates) : getcwd();
$this->printTaskInfo(sprintf('Settings %s to %s.', $this->configKey, $root));
$this->getConfig()->set($this->configKey, $root);
return Result::success($this, 'Found root at ' . $root . '.');
} | [
"public",
"function",
"run",
"(",
")",
"{",
"$",
"finder",
"=",
"clone",
"$",
"this",
"->",
"finder",
";",
"$",
"finder",
"->",
"in",
"(",
"[",
"$",
"this",
"->",
"dir",
"]",
")",
"->",
"exclude",
"(",
"$",
"this",
"->",
"exclude",
")",
"->",
"depth",
"(",
"'<='",
".",
"$",
"this",
"->",
"depth",
")",
"->",
"files",
"(",
")",
";",
"$",
"rootCandidates",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"searchFiles",
"as",
"$",
"searchFile",
")",
"{",
"$",
"fileFinder",
"=",
"clone",
"$",
"finder",
";",
"$",
"fileFinder",
"->",
"name",
"(",
"$",
"searchFile",
")",
";",
"foreach",
"(",
"$",
"fileFinder",
"->",
"getIterator",
"(",
")",
"as",
"$",
"file",
")",
"{",
"$",
"rootCandidates",
"[",
"]",
"=",
"dirname",
"(",
"$",
"file",
"->",
"getRealPath",
"(",
")",
")",
";",
"}",
"if",
"(",
"$",
"rootCandidates",
")",
"{",
"break",
";",
"}",
"}",
"usort",
"(",
"$",
"rootCandidates",
",",
"function",
"(",
"$",
"a",
",",
"$",
"b",
")",
"{",
"return",
"count",
"(",
"explode",
"(",
"DIRECTORY_SEPARATOR",
",",
"$",
"a",
")",
")",
"-",
"count",
"(",
"explode",
"(",
"DIRECTORY_SEPARATOR",
",",
"$",
"b",
")",
")",
";",
"}",
")",
";",
"$",
"root",
"=",
"$",
"rootCandidates",
"?",
"reset",
"(",
"$",
"rootCandidates",
")",
":",
"getcwd",
"(",
")",
";",
"$",
"this",
"->",
"printTaskInfo",
"(",
"sprintf",
"(",
"'Settings %s to %s.'",
",",
"$",
"this",
"->",
"configKey",
",",
"$",
"root",
")",
")",
";",
"$",
"this",
"->",
"getConfig",
"(",
")",
"->",
"set",
"(",
"$",
"this",
"->",
"configKey",
",",
"$",
"root",
")",
";",
"return",
"Result",
"::",
"success",
"(",
"$",
"this",
",",
"'Found root at '",
".",
"$",
"root",
".",
"'.'",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/digipolisgent/robo-digipolis-general/blob/66f0806c9ed7bd4e5aaf3f57ae1363f6aaae7cd9/src/DetermineProjectRoot.php#L149-L175 |
dreamfactorysoftware/df-cache | src/Services/Redis.php | Redis.setStore | protected function setStore($config)
{
Session::replaceLookups($config, true);
$host = array_get($config, 'host');
$port = array_get($config, 'port', static::PORT);
$databaseIndex = array_get($config, 'database_index', 0);
$password = array_get($config, 'password');
$options = array_get($config, 'options');
$server = [
'cluster' => false,
'default' => [
'host' => $host,
'port' => $port,
'database' => $databaseIndex,
'password' => $password
]
];
if (!empty($options)) {
$server['default'] = array_merge($options, $server['default']);
}
$redisDatabase = new RedisManager(env('REDIS_CLIENT', 'predis'), $server);
$redisStore = new RedisStore($redisDatabase);
$this->store = \Cache::repository($redisStore);
} | php | protected function setStore($config)
{
Session::replaceLookups($config, true);
$host = array_get($config, 'host');
$port = array_get($config, 'port', static::PORT);
$databaseIndex = array_get($config, 'database_index', 0);
$password = array_get($config, 'password');
$options = array_get($config, 'options');
$server = [
'cluster' => false,
'default' => [
'host' => $host,
'port' => $port,
'database' => $databaseIndex,
'password' => $password
]
];
if (!empty($options)) {
$server['default'] = array_merge($options, $server['default']);
}
$redisDatabase = new RedisManager(env('REDIS_CLIENT', 'predis'), $server);
$redisStore = new RedisStore($redisDatabase);
$this->store = \Cache::repository($redisStore);
} | [
"protected",
"function",
"setStore",
"(",
"$",
"config",
")",
"{",
"Session",
"::",
"replaceLookups",
"(",
"$",
"config",
",",
"true",
")",
";",
"$",
"host",
"=",
"array_get",
"(",
"$",
"config",
",",
"'host'",
")",
";",
"$",
"port",
"=",
"array_get",
"(",
"$",
"config",
",",
"'port'",
",",
"static",
"::",
"PORT",
")",
";",
"$",
"databaseIndex",
"=",
"array_get",
"(",
"$",
"config",
",",
"'database_index'",
",",
"0",
")",
";",
"$",
"password",
"=",
"array_get",
"(",
"$",
"config",
",",
"'password'",
")",
";",
"$",
"options",
"=",
"array_get",
"(",
"$",
"config",
",",
"'options'",
")",
";",
"$",
"server",
"=",
"[",
"'cluster'",
"=>",
"false",
",",
"'default'",
"=>",
"[",
"'host'",
"=>",
"$",
"host",
",",
"'port'",
"=>",
"$",
"port",
",",
"'database'",
"=>",
"$",
"databaseIndex",
",",
"'password'",
"=>",
"$",
"password",
"]",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"options",
")",
")",
"{",
"$",
"server",
"[",
"'default'",
"]",
"=",
"array_merge",
"(",
"$",
"options",
",",
"$",
"server",
"[",
"'default'",
"]",
")",
";",
"}",
"$",
"redisDatabase",
"=",
"new",
"RedisManager",
"(",
"env",
"(",
"'REDIS_CLIENT'",
",",
"'predis'",
")",
",",
"$",
"server",
")",
";",
"$",
"redisStore",
"=",
"new",
"RedisStore",
"(",
"$",
"redisDatabase",
")",
";",
"$",
"this",
"->",
"store",
"=",
"\\",
"Cache",
"::",
"repository",
"(",
"$",
"redisStore",
")",
";",
"}"
] | {@inheritdoc} | [
"{"
] | train | https://github.com/dreamfactorysoftware/df-cache/blob/6a2aa5dc2fc7963ce89fd7e8f3d51483d2499451/src/Services/Redis.php#L14-L40 |
Eresus/EresusCMS | src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/php_array/reader.php | ezcDbSchemaPhpArrayReader.loadFromFile | public function loadFromFile( $file )
{
if ( !file_exists( $file ) )
{
throw new ezcBaseFileNotFoundException( $file, 'schema' );
}
$schema = include $file;
if ( !is_array( $schema ) || count( $schema ) != 2 )
{
throw new ezcDbSchemaInvalidSchemaException( 'File does not have the correct structure' );
}
// @TODO: Add validator call here
return new ezcDbSchema( $schema[0], $schema[1] );
} | php | public function loadFromFile( $file )
{
if ( !file_exists( $file ) )
{
throw new ezcBaseFileNotFoundException( $file, 'schema' );
}
$schema = include $file;
if ( !is_array( $schema ) || count( $schema ) != 2 )
{
throw new ezcDbSchemaInvalidSchemaException( 'File does not have the correct structure' );
}
// @TODO: Add validator call here
return new ezcDbSchema( $schema[0], $schema[1] );
} | [
"public",
"function",
"loadFromFile",
"(",
"$",
"file",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"file",
")",
")",
"{",
"throw",
"new",
"ezcBaseFileNotFoundException",
"(",
"$",
"file",
",",
"'schema'",
")",
";",
"}",
"$",
"schema",
"=",
"include",
"$",
"file",
";",
"if",
"(",
"!",
"is_array",
"(",
"$",
"schema",
")",
"||",
"count",
"(",
"$",
"schema",
")",
"!=",
"2",
")",
"{",
"throw",
"new",
"ezcDbSchemaInvalidSchemaException",
"(",
"'File does not have the correct structure'",
")",
";",
"}",
"// @TODO: Add validator call here",
"return",
"new",
"ezcDbSchema",
"(",
"$",
"schema",
"[",
"0",
"]",
",",
"$",
"schema",
"[",
"1",
"]",
")",
";",
"}"
] | Returns the database schema stored in the file $file
@throws ezcBaseFileNotFoundException if the file $file could not be
found.
@throws ezcDbSchemaInvalidSchemaException if the data in the $file is
corrupt or when the file could not be opened.
@param string $file
@return ezcDbSchema | [
"Returns",
"the",
"database",
"schema",
"stored",
"in",
"the",
"file",
"$file"
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/php_array/reader.php#L54-L69 |
Eresus/EresusCMS | src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/php_array/reader.php | ezcDbSchemaPhpArrayReader.loadDiffFromFile | public function loadDiffFromFile( $file )
{
if ( !file_exists( $file ) )
{
throw new ezcBaseFileNotFoundException( $file, 'differences schema' );
}
$schema = include $file;
if ( !is_object( $schema ) || get_class( $schema ) != 'ezcDbSchemaDiff' )
{
throw new ezcDbSchemaInvalidSchemaException( 'File does not have the correct structure' );
}
return $schema;
} | php | public function loadDiffFromFile( $file )
{
if ( !file_exists( $file ) )
{
throw new ezcBaseFileNotFoundException( $file, 'differences schema' );
}
$schema = include $file;
if ( !is_object( $schema ) || get_class( $schema ) != 'ezcDbSchemaDiff' )
{
throw new ezcDbSchemaInvalidSchemaException( 'File does not have the correct structure' );
}
return $schema;
} | [
"public",
"function",
"loadDiffFromFile",
"(",
"$",
"file",
")",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"file",
")",
")",
"{",
"throw",
"new",
"ezcBaseFileNotFoundException",
"(",
"$",
"file",
",",
"'differences schema'",
")",
";",
"}",
"$",
"schema",
"=",
"include",
"$",
"file",
";",
"if",
"(",
"!",
"is_object",
"(",
"$",
"schema",
")",
"||",
"get_class",
"(",
"$",
"schema",
")",
"!=",
"'ezcDbSchemaDiff'",
")",
"{",
"throw",
"new",
"ezcDbSchemaInvalidSchemaException",
"(",
"'File does not have the correct structure'",
")",
";",
"}",
"return",
"$",
"schema",
";",
"}"
] | Returns the database differences stored in the file $file
@throws ezcBaseFileNotFoundException if the file $file could not be
found.
@throws ezcDbSchemaInvalidSchemaException if the data in the $file is
corrupt or when the file could not be opened.
@param string $file
@return ezcDbSchemaDiff | [
"Returns",
"the",
"database",
"differences",
"stored",
"in",
"the",
"file",
"$file"
] | train | https://github.com/Eresus/EresusCMS/blob/b0afc661105f0a2f65d49abac13956cc93c5188d/src/core/framework/core/3rdparty/ezcomponents/DatabaseSchema/src/handlers/php_array/reader.php#L82-L96 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.