repo
stringlengths 6
63
| path
stringlengths 5
140
| func_name
stringlengths 3
151
| original_string
stringlengths 84
13k
| language
stringclasses 1
value | code
stringlengths 84
13k
| code_tokens
sequence | docstring
stringlengths 3
47.2k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 91
247
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
zeyon/rest | src/localizer.php | Localizer.getInstance | public static function getInstance($arrAccepted=array(), $strDefault='de') {
if (self::$instance === NULL)
self::$instance = new self($arrAccepted, $strDefault);
return self::$instance;
} | php | public static function getInstance($arrAccepted=array(), $strDefault='de') {
if (self::$instance === NULL)
self::$instance = new self($arrAccepted, $strDefault);
return self::$instance;
} | [
"public",
"static",
"function",
"getInstance",
"(",
"$",
"arrAccepted",
"=",
"array",
"(",
")",
",",
"$",
"strDefault",
"=",
"'de'",
")",
"{",
"if",
"(",
"self",
"::",
"$",
"instance",
"===",
"NULL",
")",
"self",
"::",
"$",
"instance",
"=",
"new",
"self",
"(",
"$",
"arrAccepted",
",",
"$",
"strDefault",
")",
";",
"return",
"self",
"::",
"$",
"instance",
";",
"}"
] | Return the current instance
@param array $arrAccepted All accepted languages
@param string $strDefault Default language code
@return Localizer | [
"Return",
"the",
"current",
"instance"
] | da73bd5799c9c44a3b36f618d9cbe769f1541ff1 | https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L54-L58 | train |
zeyon/rest | src/localizer.php | Localizer.fileFormatDir | private function fileFormatDir($strDirectory, $strSlash=DIRECTORY_SEPARATOR) {
return substr($strDirectory, -1) != $strSlash ? $strDirectory.$strSlash : $strDirectory;
} | php | private function fileFormatDir($strDirectory, $strSlash=DIRECTORY_SEPARATOR) {
return substr($strDirectory, -1) != $strSlash ? $strDirectory.$strSlash : $strDirectory;
} | [
"private",
"function",
"fileFormatDir",
"(",
"$",
"strDirectory",
",",
"$",
"strSlash",
"=",
"DIRECTORY_SEPARATOR",
")",
"{",
"return",
"substr",
"(",
"$",
"strDirectory",
",",
"-",
"1",
")",
"!=",
"$",
"strSlash",
"?",
"$",
"strDirectory",
".",
"$",
"strSlash",
":",
"$",
"strDirectory",
";",
"}"
] | Makes sure the directory ends with a slash
@param string $strDirectory
@return string | [
"Makes",
"sure",
"the",
"directory",
"ends",
"with",
"a",
"slash"
] | da73bd5799c9c44a3b36f618d9cbe769f1541ff1 | https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L66-L68 | train |
zeyon/rest | src/localizer.php | Localizer.load | public function load($strSourcePath, $strCachePath=false, $bolStore=true) {
$strSourcePath = $this->fileFormatDir($strSourcePath);
$strLang = self::init($this->arrAccepted, $this->strDefault, $bolStore);
$this->strCurrent = $strLang;
if ($strCachePath) {
$strCachePath = $this->fileFormatDir($strCachePath);
if (file_exists($strCachePath.$strLang.'.php')) {
include $strCachePath.$strLang.'.php';
if (isset($LANGVAR)) {
$this->setData($LANGVAR);
return $LANGVAR;
}
}
}
$strFilename = $strSourcePath.$strLang.'.'.$this->strFileFormat;
if (!file_exists($strFilename))
throw new \Exception('Locale file not found: '.$strFilename);
switch ($this->strFileFormat) {
case 'yml':
if (!class_exists('\\Spyc'))
throw new \Exception('Spyc YAML parser not loaded!');
$LANGVAR = \Spyc::YAMLLoad($strFilename);
break;
case 'ini':
$LANGVAR = parse_ini_file($strFilename, true);
break;
default:
$LANGVAR = json_decode(file_get_contents($strFilename, true));
break;
}
$this->setData($LANGVAR);
if ($strCachePath)
$this->writeCacheFile($strCachePath, $strLang);
return $LANGVAR;
} | php | public function load($strSourcePath, $strCachePath=false, $bolStore=true) {
$strSourcePath = $this->fileFormatDir($strSourcePath);
$strLang = self::init($this->arrAccepted, $this->strDefault, $bolStore);
$this->strCurrent = $strLang;
if ($strCachePath) {
$strCachePath = $this->fileFormatDir($strCachePath);
if (file_exists($strCachePath.$strLang.'.php')) {
include $strCachePath.$strLang.'.php';
if (isset($LANGVAR)) {
$this->setData($LANGVAR);
return $LANGVAR;
}
}
}
$strFilename = $strSourcePath.$strLang.'.'.$this->strFileFormat;
if (!file_exists($strFilename))
throw new \Exception('Locale file not found: '.$strFilename);
switch ($this->strFileFormat) {
case 'yml':
if (!class_exists('\\Spyc'))
throw new \Exception('Spyc YAML parser not loaded!');
$LANGVAR = \Spyc::YAMLLoad($strFilename);
break;
case 'ini':
$LANGVAR = parse_ini_file($strFilename, true);
break;
default:
$LANGVAR = json_decode(file_get_contents($strFilename, true));
break;
}
$this->setData($LANGVAR);
if ($strCachePath)
$this->writeCacheFile($strCachePath, $strLang);
return $LANGVAR;
} | [
"public",
"function",
"load",
"(",
"$",
"strSourcePath",
",",
"$",
"strCachePath",
"=",
"false",
",",
"$",
"bolStore",
"=",
"true",
")",
"{",
"$",
"strSourcePath",
"=",
"$",
"this",
"->",
"fileFormatDir",
"(",
"$",
"strSourcePath",
")",
";",
"$",
"strLang",
"=",
"self",
"::",
"init",
"(",
"$",
"this",
"->",
"arrAccepted",
",",
"$",
"this",
"->",
"strDefault",
",",
"$",
"bolStore",
")",
";",
"$",
"this",
"->",
"strCurrent",
"=",
"$",
"strLang",
";",
"if",
"(",
"$",
"strCachePath",
")",
"{",
"$",
"strCachePath",
"=",
"$",
"this",
"->",
"fileFormatDir",
"(",
"$",
"strCachePath",
")",
";",
"if",
"(",
"file_exists",
"(",
"$",
"strCachePath",
".",
"$",
"strLang",
".",
"'.php'",
")",
")",
"{",
"include",
"$",
"strCachePath",
".",
"$",
"strLang",
".",
"'.php'",
";",
"if",
"(",
"isset",
"(",
"$",
"LANGVAR",
")",
")",
"{",
"$",
"this",
"->",
"setData",
"(",
"$",
"LANGVAR",
")",
";",
"return",
"$",
"LANGVAR",
";",
"}",
"}",
"}",
"$",
"strFilename",
"=",
"$",
"strSourcePath",
".",
"$",
"strLang",
".",
"'.'",
".",
"$",
"this",
"->",
"strFileFormat",
";",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"strFilename",
")",
")",
"throw",
"new",
"\\",
"Exception",
"(",
"'Locale file not found: '",
".",
"$",
"strFilename",
")",
";",
"switch",
"(",
"$",
"this",
"->",
"strFileFormat",
")",
"{",
"case",
"'yml'",
":",
"if",
"(",
"!",
"class_exists",
"(",
"'\\\\Spyc'",
")",
")",
"throw",
"new",
"\\",
"Exception",
"(",
"'Spyc YAML parser not loaded!'",
")",
";",
"$",
"LANGVAR",
"=",
"\\",
"Spyc",
"::",
"YAMLLoad",
"(",
"$",
"strFilename",
")",
";",
"break",
";",
"case",
"'ini'",
":",
"$",
"LANGVAR",
"=",
"parse_ini_file",
"(",
"$",
"strFilename",
",",
"true",
")",
";",
"break",
";",
"default",
":",
"$",
"LANGVAR",
"=",
"json_decode",
"(",
"file_get_contents",
"(",
"$",
"strFilename",
",",
"true",
")",
")",
";",
"break",
";",
"}",
"$",
"this",
"->",
"setData",
"(",
"$",
"LANGVAR",
")",
";",
"if",
"(",
"$",
"strCachePath",
")",
"$",
"this",
"->",
"writeCacheFile",
"(",
"$",
"strCachePath",
",",
"$",
"strLang",
")",
";",
"return",
"$",
"LANGVAR",
";",
"}"
] | Initialized the language variable
@param string $strSourcePath The source path for all localization files (.yml)
@param string $strCachePath The caching path; if specified, cache files will be enabled
@param bool $bolStore Switch to store language in the current session
@return array The language variable array | [
"Initialized",
"the",
"language",
"variable"
] | da73bd5799c9c44a3b36f618d9cbe769f1541ff1 | https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L78-L122 | train |
zeyon/rest | src/localizer.php | Localizer.get | public function get($strKey, $bolReturnPath=true) {
$data = $this->arrData;
foreach (explode('.', $strKey) as $p) {
if (isset($data[$p]))
$data = $data[$p];
else
return $bolReturnPath ? $this->returnKey($strKey) : false;
}
// if key was not resolved completely
if ( is_array($data) )
return $bolReturnPath ? $this->returnKey($strKey) : false;
return (string) $data;
} | php | public function get($strKey, $bolReturnPath=true) {
$data = $this->arrData;
foreach (explode('.', $strKey) as $p) {
if (isset($data[$p]))
$data = $data[$p];
else
return $bolReturnPath ? $this->returnKey($strKey) : false;
}
// if key was not resolved completely
if ( is_array($data) )
return $bolReturnPath ? $this->returnKey($strKey) : false;
return (string) $data;
} | [
"public",
"function",
"get",
"(",
"$",
"strKey",
",",
"$",
"bolReturnPath",
"=",
"true",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"arrData",
";",
"foreach",
"(",
"explode",
"(",
"'.'",
",",
"$",
"strKey",
")",
"as",
"$",
"p",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"data",
"[",
"$",
"p",
"]",
")",
")",
"$",
"data",
"=",
"$",
"data",
"[",
"$",
"p",
"]",
";",
"else",
"return",
"$",
"bolReturnPath",
"?",
"$",
"this",
"->",
"returnKey",
"(",
"$",
"strKey",
")",
":",
"false",
";",
"}",
"// if key was not resolved completely",
"if",
"(",
"is_array",
"(",
"$",
"data",
")",
")",
"return",
"$",
"bolReturnPath",
"?",
"$",
"this",
"->",
"returnKey",
"(",
"$",
"strKey",
")",
":",
"false",
";",
"return",
"(",
"string",
")",
"$",
"data",
";",
"}"
] | Gets a variable value
@param string $strKey The path for the language variable (e.g. "messages.error.single")
@param bool $bolReturnPath If set the function will return the variable path, instead of FALSE
@return string If the path could not be resolved, the path will be returned instead | [
"Gets",
"a",
"variable",
"value"
] | da73bd5799c9c44a3b36f618d9cbe769f1541ff1 | https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L177-L192 | train |
zeyon/rest | src/localizer.php | Localizer.getDateFormat | public function getDateFormat($strKey) {
$format = $this->get($strKey, false);
return $format ? preg_replace('/%([A-Za-z%])/', '$1', $format) : 'Y-m-d H:i';
} | php | public function getDateFormat($strKey) {
$format = $this->get($strKey, false);
return $format ? preg_replace('/%([A-Za-z%])/', '$1', $format) : 'Y-m-d H:i';
} | [
"public",
"function",
"getDateFormat",
"(",
"$",
"strKey",
")",
"{",
"$",
"format",
"=",
"$",
"this",
"->",
"get",
"(",
"$",
"strKey",
",",
"false",
")",
";",
"return",
"$",
"format",
"?",
"preg_replace",
"(",
"'/%([A-Za-z%])/'",
",",
"'$1'",
",",
"$",
"format",
")",
":",
"'Y-m-d H:i'",
";",
"}"
] | Returns a date string without "%" for PHP compatibiltiy
@param string $strKey The path for the language variable (e.g. "messages.error.single")
@return string The date format string | [
"Returns",
"a",
"date",
"string",
"without",
"%",
"for",
"PHP",
"compatibiltiy"
] | da73bd5799c9c44a3b36f618d9cbe769f1541ff1 | https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L210-L213 | train |
zeyon/rest | src/localizer.php | Localizer.insert | public function insert($strKey, $arrReplace) {
$data = $this->arrData;
foreach (explode('.', $strKey) as $p) {
if (isset($data[$p]))
$data = $data[$p];
else
return $this->returnKey($strKey).'('.json_encode($arrReplace).')';
}
$arrSearch = array();
$arrValues = array();
foreach ($arrReplace as $key => $value) {
$arrSearch[] = '{'.$key.'}';
$arrValues[] = $value;
}
return str_replace($arrSearch, $arrValues, (string) $data);
} | php | public function insert($strKey, $arrReplace) {
$data = $this->arrData;
foreach (explode('.', $strKey) as $p) {
if (isset($data[$p]))
$data = $data[$p];
else
return $this->returnKey($strKey).'('.json_encode($arrReplace).')';
}
$arrSearch = array();
$arrValues = array();
foreach ($arrReplace as $key => $value) {
$arrSearch[] = '{'.$key.'}';
$arrValues[] = $value;
}
return str_replace($arrSearch, $arrValues, (string) $data);
} | [
"public",
"function",
"insert",
"(",
"$",
"strKey",
",",
"$",
"arrReplace",
")",
"{",
"$",
"data",
"=",
"$",
"this",
"->",
"arrData",
";",
"foreach",
"(",
"explode",
"(",
"'.'",
",",
"$",
"strKey",
")",
"as",
"$",
"p",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"data",
"[",
"$",
"p",
"]",
")",
")",
"$",
"data",
"=",
"$",
"data",
"[",
"$",
"p",
"]",
";",
"else",
"return",
"$",
"this",
"->",
"returnKey",
"(",
"$",
"strKey",
")",
".",
"'('",
".",
"json_encode",
"(",
"$",
"arrReplace",
")",
".",
"')'",
";",
"}",
"$",
"arrSearch",
"=",
"array",
"(",
")",
";",
"$",
"arrValues",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"arrReplace",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"arrSearch",
"[",
"]",
"=",
"'{'",
".",
"$",
"key",
".",
"'}'",
";",
"$",
"arrValues",
"[",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"str_replace",
"(",
"$",
"arrSearch",
",",
"$",
"arrValues",
",",
"(",
"string",
")",
"$",
"data",
")",
";",
"}"
] | Gets a variable value and replaces placeholders contained in it
@param string $strKey The path for the language variable (e.g. "messages.error.single")
@param array $arrReplace Associative array containing the placeholder variables
@return string If the path could not be resolved, the path will be returned instead | [
"Gets",
"a",
"variable",
"value",
"and",
"replaces",
"placeholders",
"contained",
"in",
"it"
] | da73bd5799c9c44a3b36f618d9cbe769f1541ff1 | https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L222-L239 | train |
zeyon/rest | src/localizer.php | Localizer.replace | public function replace($strTemplate) {
preg_match_all($this->regex, $strTemplate, $matches);
$arrReplace = array();
foreach ($matches[1] as $match) {
$arrReplace[] = $this->get($match);
}
return str_replace($matches[0], $arrReplace, $strTemplate);
} | php | public function replace($strTemplate) {
preg_match_all($this->regex, $strTemplate, $matches);
$arrReplace = array();
foreach ($matches[1] as $match) {
$arrReplace[] = $this->get($match);
}
return str_replace($matches[0], $arrReplace, $strTemplate);
} | [
"public",
"function",
"replace",
"(",
"$",
"strTemplate",
")",
"{",
"preg_match_all",
"(",
"$",
"this",
"->",
"regex",
",",
"$",
"strTemplate",
",",
"$",
"matches",
")",
";",
"$",
"arrReplace",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"matches",
"[",
"1",
"]",
"as",
"$",
"match",
")",
"{",
"$",
"arrReplace",
"[",
"]",
"=",
"$",
"this",
"->",
"get",
"(",
"$",
"match",
")",
";",
"}",
"return",
"str_replace",
"(",
"$",
"matches",
"[",
"0",
"]",
",",
"$",
"arrReplace",
",",
"$",
"strTemplate",
")",
";",
"}"
] | Insert placeholders into a string
@param string $strTemplate
@return $strTemplate | [
"Insert",
"placeholders",
"into",
"a",
"string"
] | da73bd5799c9c44a3b36f618d9cbe769f1541ff1 | https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L247-L255 | train |
zeyon/rest | src/localizer.php | Localizer.init | public function init($arrAccepted, $strDefault, $bolStore=true) {
$strLang = isset($_GET['lang']) ? $_GET['lang']
: (isset($_SESSION['lang']) ? $_SESSION['lang']
: (isset($_COOKIE['lang']) ? $_COOKIE['lang'] : false));
if (!$strLang || !in_array($strLang, $arrAccepted)) {
$browser = self::askBrowser($arrAccepted, $strDefault);
$strLang = $browser['lang'];
}
if ($bolStore) {
$_SESSION['lang'] = $strLang;
setcookie('lang', $strLang, time() + 315885600);
}
$this->strCurrent = $strLang;
return $strLang;
} | php | public function init($arrAccepted, $strDefault, $bolStore=true) {
$strLang = isset($_GET['lang']) ? $_GET['lang']
: (isset($_SESSION['lang']) ? $_SESSION['lang']
: (isset($_COOKIE['lang']) ? $_COOKIE['lang'] : false));
if (!$strLang || !in_array($strLang, $arrAccepted)) {
$browser = self::askBrowser($arrAccepted, $strDefault);
$strLang = $browser['lang'];
}
if ($bolStore) {
$_SESSION['lang'] = $strLang;
setcookie('lang', $strLang, time() + 315885600);
}
$this->strCurrent = $strLang;
return $strLang;
} | [
"public",
"function",
"init",
"(",
"$",
"arrAccepted",
",",
"$",
"strDefault",
",",
"$",
"bolStore",
"=",
"true",
")",
"{",
"$",
"strLang",
"=",
"isset",
"(",
"$",
"_GET",
"[",
"'lang'",
"]",
")",
"?",
"$",
"_GET",
"[",
"'lang'",
"]",
":",
"(",
"isset",
"(",
"$",
"_SESSION",
"[",
"'lang'",
"]",
")",
"?",
"$",
"_SESSION",
"[",
"'lang'",
"]",
":",
"(",
"isset",
"(",
"$",
"_COOKIE",
"[",
"'lang'",
"]",
")",
"?",
"$",
"_COOKIE",
"[",
"'lang'",
"]",
":",
"false",
")",
")",
";",
"if",
"(",
"!",
"$",
"strLang",
"||",
"!",
"in_array",
"(",
"$",
"strLang",
",",
"$",
"arrAccepted",
")",
")",
"{",
"$",
"browser",
"=",
"self",
"::",
"askBrowser",
"(",
"$",
"arrAccepted",
",",
"$",
"strDefault",
")",
";",
"$",
"strLang",
"=",
"$",
"browser",
"[",
"'lang'",
"]",
";",
"}",
"if",
"(",
"$",
"bolStore",
")",
"{",
"$",
"_SESSION",
"[",
"'lang'",
"]",
"=",
"$",
"strLang",
";",
"setcookie",
"(",
"'lang'",
",",
"$",
"strLang",
",",
"time",
"(",
")",
"+",
"315885600",
")",
";",
"}",
"$",
"this",
"->",
"strCurrent",
"=",
"$",
"strLang",
";",
"return",
"$",
"strLang",
";",
"}"
] | Initialized the language variable and stores it in the session
@param array $arrAccepted All accepted languages
@param string $strDefault Default language code
@param bool $bolStore Switch to store language in the current session | [
"Initialized",
"the",
"language",
"variable",
"and",
"stores",
"it",
"in",
"the",
"session"
] | da73bd5799c9c44a3b36f618d9cbe769f1541ff1 | https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L264-L278 | train |
zeyon/rest | src/localizer.php | Localizer.askBrowser | public static function askBrowser($arrAccepted, $strDefault='de') {
$res = array('lang' => $strDefault, 'other' => array());
try {
$lang_variable = (
isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])
? $_SERVER['HTTP_ACCEPT_LANGUAGE']
: null
);
if ( empty($lang_variable) )
return $res;
$accepted_languages = preg_split('/,\s*/', $lang_variable);
$current_lang = $strDefault;
$current_q = 0;
$other = array();
foreach ($accepted_languages as $accepted_language) {
$res = preg_match('/^([a-z]{1,8}(?:-[a-z]{1,8})*)'.
'(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i', $accepted_language, $matches);
if (!$res)
continue;
$lang_code = explode('-', $matches[1]);
if (isset($matches[2]))
$lang_quality = (float) $matches[2];
else
$lang_quality = 1.0;
while (count($lang_code)) {
$full_code = strtolower(join ('-', $lang_code));
if (in_array($full_code, $arrAccepted)) {
if ($lang_quality > $current_q) {
if ($current_lang)
$other[] = $current_lang;
$current_lang = $full_code;
$current_q = $lang_quality;
break;
} else
$other[] = $full_code;
} else
$other[] = $full_code;
array_pop($lang_code);
}
}
return array('lang' => $current_lang, 'other' => $other);;
} catch (\Exception $e) {
return $res;
}
} | php | public static function askBrowser($arrAccepted, $strDefault='de') {
$res = array('lang' => $strDefault, 'other' => array());
try {
$lang_variable = (
isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])
? $_SERVER['HTTP_ACCEPT_LANGUAGE']
: null
);
if ( empty($lang_variable) )
return $res;
$accepted_languages = preg_split('/,\s*/', $lang_variable);
$current_lang = $strDefault;
$current_q = 0;
$other = array();
foreach ($accepted_languages as $accepted_language) {
$res = preg_match('/^([a-z]{1,8}(?:-[a-z]{1,8})*)'.
'(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i', $accepted_language, $matches);
if (!$res)
continue;
$lang_code = explode('-', $matches[1]);
if (isset($matches[2]))
$lang_quality = (float) $matches[2];
else
$lang_quality = 1.0;
while (count($lang_code)) {
$full_code = strtolower(join ('-', $lang_code));
if (in_array($full_code, $arrAccepted)) {
if ($lang_quality > $current_q) {
if ($current_lang)
$other[] = $current_lang;
$current_lang = $full_code;
$current_q = $lang_quality;
break;
} else
$other[] = $full_code;
} else
$other[] = $full_code;
array_pop($lang_code);
}
}
return array('lang' => $current_lang, 'other' => $other);;
} catch (\Exception $e) {
return $res;
}
} | [
"public",
"static",
"function",
"askBrowser",
"(",
"$",
"arrAccepted",
",",
"$",
"strDefault",
"=",
"'de'",
")",
"{",
"$",
"res",
"=",
"array",
"(",
"'lang'",
"=>",
"$",
"strDefault",
",",
"'other'",
"=>",
"array",
"(",
")",
")",
";",
"try",
"{",
"$",
"lang_variable",
"=",
"(",
"isset",
"(",
"$",
"_SERVER",
"[",
"'HTTP_ACCEPT_LANGUAGE'",
"]",
")",
"?",
"$",
"_SERVER",
"[",
"'HTTP_ACCEPT_LANGUAGE'",
"]",
":",
"null",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"lang_variable",
")",
")",
"return",
"$",
"res",
";",
"$",
"accepted_languages",
"=",
"preg_split",
"(",
"'/,\\s*/'",
",",
"$",
"lang_variable",
")",
";",
"$",
"current_lang",
"=",
"$",
"strDefault",
";",
"$",
"current_q",
"=",
"0",
";",
"$",
"other",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"accepted_languages",
"as",
"$",
"accepted_language",
")",
"{",
"$",
"res",
"=",
"preg_match",
"(",
"'/^([a-z]{1,8}(?:-[a-z]{1,8})*)'",
".",
"'(?:;\\s*q=(0(?:\\.[0-9]{1,3})?|1(?:\\.0{1,3})?))?$/i'",
",",
"$",
"accepted_language",
",",
"$",
"matches",
")",
";",
"if",
"(",
"!",
"$",
"res",
")",
"continue",
";",
"$",
"lang_code",
"=",
"explode",
"(",
"'-'",
",",
"$",
"matches",
"[",
"1",
"]",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"matches",
"[",
"2",
"]",
")",
")",
"$",
"lang_quality",
"=",
"(",
"float",
")",
"$",
"matches",
"[",
"2",
"]",
";",
"else",
"$",
"lang_quality",
"=",
"1.0",
";",
"while",
"(",
"count",
"(",
"$",
"lang_code",
")",
")",
"{",
"$",
"full_code",
"=",
"strtolower",
"(",
"join",
"(",
"'-'",
",",
"$",
"lang_code",
")",
")",
";",
"if",
"(",
"in_array",
"(",
"$",
"full_code",
",",
"$",
"arrAccepted",
")",
")",
"{",
"if",
"(",
"$",
"lang_quality",
">",
"$",
"current_q",
")",
"{",
"if",
"(",
"$",
"current_lang",
")",
"$",
"other",
"[",
"]",
"=",
"$",
"current_lang",
";",
"$",
"current_lang",
"=",
"$",
"full_code",
";",
"$",
"current_q",
"=",
"$",
"lang_quality",
";",
"break",
";",
"}",
"else",
"$",
"other",
"[",
"]",
"=",
"$",
"full_code",
";",
"}",
"else",
"$",
"other",
"[",
"]",
"=",
"$",
"full_code",
";",
"array_pop",
"(",
"$",
"lang_code",
")",
";",
"}",
"}",
"return",
"array",
"(",
"'lang'",
"=>",
"$",
"current_lang",
",",
"'other'",
"=>",
"$",
"other",
")",
";",
";",
"}",
"catch",
"(",
"\\",
"Exception",
"$",
"e",
")",
"{",
"return",
"$",
"res",
";",
"}",
"}"
] | Returns the accepted browser language
@param array $arrAccepted
@param string $strDefault
@return array {'lang': PRIMARY LANGUAGE, 'other': ADDITIONAL LANGUAGES} | [
"Returns",
"the",
"accepted",
"browser",
"language"
] | da73bd5799c9c44a3b36f618d9cbe769f1541ff1 | https://github.com/zeyon/rest/blob/da73bd5799c9c44a3b36f618d9cbe769f1541ff1/src/localizer.php#L287-L338 | train |
anklimsk/cakephp-console-installer | Model/InstallerCheck.php | InstallerCheck.getWebSrvUser | public function getWebSrvUser() {
$result = '';
if ($this->isOsWindows()) {
return $result;
}
$cmd = "ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1 2>/dev/null";
$output = [];
$exitCode = -1;
exec($cmd, $output, $exitCode);
if (($exitCode !== 0) || (count($output) < 1)) {
return $result;
}
$result = array_shift($output);
return $result;
} | php | public function getWebSrvUser() {
$result = '';
if ($this->isOsWindows()) {
return $result;
}
$cmd = "ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\ -f1 2>/dev/null";
$output = [];
$exitCode = -1;
exec($cmd, $output, $exitCode);
if (($exitCode !== 0) || (count($output) < 1)) {
return $result;
}
$result = array_shift($output);
return $result;
} | [
"public",
"function",
"getWebSrvUser",
"(",
")",
"{",
"$",
"result",
"=",
"''",
";",
"if",
"(",
"$",
"this",
"->",
"isOsWindows",
"(",
")",
")",
"{",
"return",
"$",
"result",
";",
"}",
"$",
"cmd",
"=",
"\"ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\\ -f1 2>/dev/null\"",
";",
"$",
"output",
"=",
"[",
"]",
";",
"$",
"exitCode",
"=",
"-",
"1",
";",
"exec",
"(",
"$",
"cmd",
",",
"$",
"output",
",",
"$",
"exitCode",
")",
";",
"if",
"(",
"(",
"$",
"exitCode",
"!==",
"0",
")",
"||",
"(",
"count",
"(",
"$",
"output",
")",
"<",
"1",
")",
")",
"{",
"return",
"$",
"result",
";",
"}",
"$",
"result",
"=",
"array_shift",
"(",
"$",
"output",
")",
";",
"return",
"$",
"result",
";",
"}"
] | Return WEB server user.
@return string Return user name of WEB server | [
"Return",
"WEB",
"server",
"user",
"."
] | 76136550e856ff4f8fd3634b77633f86510f63e9 | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L102-L119 | train |
anklimsk/cakephp-console-installer | Model/InstallerCheck.php | InstallerCheck.getWebSrvUserGroup | public function getWebSrvUserGroup($username = null) {
$result = '';
if ($this->isOsWindows() || empty($username)) {
return $result;
}
$cmd = 'groups ' . $username . ' | head -1 | cut -d\ -f1 2>/dev/null';
$output = [];
$exitCode = -1;
exec($cmd, $output, $exitCode);
if (($exitCode !== 0) || (count($output) < 1)) {
return $result;
}
$result = array_shift($output);
return $result;
} | php | public function getWebSrvUserGroup($username = null) {
$result = '';
if ($this->isOsWindows() || empty($username)) {
return $result;
}
$cmd = 'groups ' . $username . ' | head -1 | cut -d\ -f1 2>/dev/null';
$output = [];
$exitCode = -1;
exec($cmd, $output, $exitCode);
if (($exitCode !== 0) || (count($output) < 1)) {
return $result;
}
$result = array_shift($output);
return $result;
} | [
"public",
"function",
"getWebSrvUserGroup",
"(",
"$",
"username",
"=",
"null",
")",
"{",
"$",
"result",
"=",
"''",
";",
"if",
"(",
"$",
"this",
"->",
"isOsWindows",
"(",
")",
"||",
"empty",
"(",
"$",
"username",
")",
")",
"{",
"return",
"$",
"result",
";",
"}",
"$",
"cmd",
"=",
"'groups '",
".",
"$",
"username",
".",
"' | head -1 | cut -d\\ -f1 2>/dev/null'",
";",
"$",
"output",
"=",
"[",
"]",
";",
"$",
"exitCode",
"=",
"-",
"1",
";",
"exec",
"(",
"$",
"cmd",
",",
"$",
"output",
",",
"$",
"exitCode",
")",
";",
"if",
"(",
"(",
"$",
"exitCode",
"!==",
"0",
")",
"||",
"(",
"count",
"(",
"$",
"output",
")",
"<",
"1",
")",
")",
"{",
"return",
"$",
"result",
";",
"}",
"$",
"result",
"=",
"array_shift",
"(",
"$",
"output",
")",
";",
"return",
"$",
"result",
";",
"}"
] | Return group of user.
@param string $username Username for retrieving group.
@return string Return group of user | [
"Return",
"group",
"of",
"user",
"."
] | 76136550e856ff4f8fd3634b77633f86510f63e9 | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L127-L144 | train |
anklimsk/cakephp-console-installer | Model/InstallerCheck.php | InstallerCheck.isAppInstalled | public function isAppInstalled($configKey = null, $createMarkerFile = true) {
$pathMarkerFileIsInstalled = $this->getPathMarkerFileIsInstalled();
if ($this->_checkMarkerFile($pathMarkerFileIsInstalled)) {
return true;
}
$installTasks = $this->_modelConfigInstaller->getListInstallerTasks();
if (empty($installTasks)) {
return false;
}
if (in_array('check', $installTasks) && ($this->checkPhpVersion() === false)) {
return false;
}
if (in_array('check', $installTasks) && ($this->checkPhpExtensions(true) === false)) {
return false;
}
if (in_array('configdb', $installTasks) && ($this->checkConnectDb(null, true) === false)) {
return false;
}
if (in_array('createdb', $installTasks) && !$this->checkDbTableExists()) {
return false;
}
if (in_array('createsymlinks', $installTasks) && !$this->checkSymLinksExists()) {
return false;
}
if (in_array('createcronjobs', $installTasks) && !$this->checkCronJobsExists()) {
return false;
}
if (!empty($configKey) && !Configure::check($configKey)) {
return false;
}
if (!$createMarkerFile) {
return true;
}
return $this->_createMarkerFile($pathMarkerFileIsInstalled);
} | php | public function isAppInstalled($configKey = null, $createMarkerFile = true) {
$pathMarkerFileIsInstalled = $this->getPathMarkerFileIsInstalled();
if ($this->_checkMarkerFile($pathMarkerFileIsInstalled)) {
return true;
}
$installTasks = $this->_modelConfigInstaller->getListInstallerTasks();
if (empty($installTasks)) {
return false;
}
if (in_array('check', $installTasks) && ($this->checkPhpVersion() === false)) {
return false;
}
if (in_array('check', $installTasks) && ($this->checkPhpExtensions(true) === false)) {
return false;
}
if (in_array('configdb', $installTasks) && ($this->checkConnectDb(null, true) === false)) {
return false;
}
if (in_array('createdb', $installTasks) && !$this->checkDbTableExists()) {
return false;
}
if (in_array('createsymlinks', $installTasks) && !$this->checkSymLinksExists()) {
return false;
}
if (in_array('createcronjobs', $installTasks) && !$this->checkCronJobsExists()) {
return false;
}
if (!empty($configKey) && !Configure::check($configKey)) {
return false;
}
if (!$createMarkerFile) {
return true;
}
return $this->_createMarkerFile($pathMarkerFileIsInstalled);
} | [
"public",
"function",
"isAppInstalled",
"(",
"$",
"configKey",
"=",
"null",
",",
"$",
"createMarkerFile",
"=",
"true",
")",
"{",
"$",
"pathMarkerFileIsInstalled",
"=",
"$",
"this",
"->",
"getPathMarkerFileIsInstalled",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"_checkMarkerFile",
"(",
"$",
"pathMarkerFileIsInstalled",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"installTasks",
"=",
"$",
"this",
"->",
"_modelConfigInstaller",
"->",
"getListInstallerTasks",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"installTasks",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"in_array",
"(",
"'check'",
",",
"$",
"installTasks",
")",
"&&",
"(",
"$",
"this",
"->",
"checkPhpVersion",
"(",
")",
"===",
"false",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"in_array",
"(",
"'check'",
",",
"$",
"installTasks",
")",
"&&",
"(",
"$",
"this",
"->",
"checkPhpExtensions",
"(",
"true",
")",
"===",
"false",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"in_array",
"(",
"'configdb'",
",",
"$",
"installTasks",
")",
"&&",
"(",
"$",
"this",
"->",
"checkConnectDb",
"(",
"null",
",",
"true",
")",
"===",
"false",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"in_array",
"(",
"'createdb'",
",",
"$",
"installTasks",
")",
"&&",
"!",
"$",
"this",
"->",
"checkDbTableExists",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"in_array",
"(",
"'createsymlinks'",
",",
"$",
"installTasks",
")",
"&&",
"!",
"$",
"this",
"->",
"checkSymLinksExists",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"in_array",
"(",
"'createcronjobs'",
",",
"$",
"installTasks",
")",
"&&",
"!",
"$",
"this",
"->",
"checkCronJobsExists",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"configKey",
")",
"&&",
"!",
"Configure",
"::",
"check",
"(",
"$",
"configKey",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"$",
"createMarkerFile",
")",
"{",
"return",
"true",
";",
"}",
"return",
"$",
"this",
"->",
"_createMarkerFile",
"(",
"$",
"pathMarkerFileIsInstalled",
")",
";",
"}"
] | Check application is installed successfully
@param string $configKey The identifier to check configuration
for application.
@param bool $createMarkerFile If True, create marker file,
if application is installed successfully.
@return bool True, if application is installed successfully.
False otherwise. | [
"Check",
"application",
"is",
"installed",
"successfully"
] | 76136550e856ff4f8fd3634b77633f86510f63e9 | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L170-L214 | train |
anklimsk/cakephp-console-installer | Model/InstallerCheck.php | InstallerCheck.isAppReadyToInstall | public function isAppReadyToInstall() {
$checkPHPversion = $this->checkPhpVersion();
if ($checkPHPversion === false) {
return false;
}
$checkPHPextensions = $this->checkPhpExtensions(true);
if ($checkPHPextensions === false) {
return false;
}
return true;
} | php | public function isAppReadyToInstall() {
$checkPHPversion = $this->checkPhpVersion();
if ($checkPHPversion === false) {
return false;
}
$checkPHPextensions = $this->checkPhpExtensions(true);
if ($checkPHPextensions === false) {
return false;
}
return true;
} | [
"public",
"function",
"isAppReadyToInstall",
"(",
")",
"{",
"$",
"checkPHPversion",
"=",
"$",
"this",
"->",
"checkPhpVersion",
"(",
")",
";",
"if",
"(",
"$",
"checkPHPversion",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"$",
"checkPHPextensions",
"=",
"$",
"this",
"->",
"checkPhpExtensions",
"(",
"true",
")",
";",
"if",
"(",
"$",
"checkPHPextensions",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Check application is ready to install
@return bool True, if application is ready to install.
False otherwise. | [
"Check",
"application",
"is",
"ready",
"to",
"install"
] | 76136550e856ff4f8fd3634b77633f86510f63e9 | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L222-L234 | train |
anklimsk/cakephp-console-installer | Model/InstallerCheck.php | InstallerCheck.checkPhpVersion | public function checkPhpVersion() {
$phpVesion = $this->_modelConfigInstaller->getPhpVersionConfig();
if (empty($phpVesion)) {
return null;
}
$result = true;
foreach ($phpVesion as $phpVesionItem) {
if (!is_array($phpVesionItem)) {
continue;
}
$phpVesionItem += ['', null];
list($version, $operator) = $phpVesionItem;
if (empty($operator)) {
$operator = '==';
}
$checkResult = false;
if (!empty($version)) {
$checkResult = version_compare(PHP_VERSION, $version, $operator);
}
if (!$checkResult) {
$result = false;
}
}
return $result;
} | php | public function checkPhpVersion() {
$phpVesion = $this->_modelConfigInstaller->getPhpVersionConfig();
if (empty($phpVesion)) {
return null;
}
$result = true;
foreach ($phpVesion as $phpVesionItem) {
if (!is_array($phpVesionItem)) {
continue;
}
$phpVesionItem += ['', null];
list($version, $operator) = $phpVesionItem;
if (empty($operator)) {
$operator = '==';
}
$checkResult = false;
if (!empty($version)) {
$checkResult = version_compare(PHP_VERSION, $version, $operator);
}
if (!$checkResult) {
$result = false;
}
}
return $result;
} | [
"public",
"function",
"checkPhpVersion",
"(",
")",
"{",
"$",
"phpVesion",
"=",
"$",
"this",
"->",
"_modelConfigInstaller",
"->",
"getPhpVersionConfig",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"phpVesion",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"result",
"=",
"true",
";",
"foreach",
"(",
"$",
"phpVesion",
"as",
"$",
"phpVesionItem",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"phpVesionItem",
")",
")",
"{",
"continue",
";",
"}",
"$",
"phpVesionItem",
"+=",
"[",
"''",
",",
"null",
"]",
";",
"list",
"(",
"$",
"version",
",",
"$",
"operator",
")",
"=",
"$",
"phpVesionItem",
";",
"if",
"(",
"empty",
"(",
"$",
"operator",
")",
")",
"{",
"$",
"operator",
"=",
"'=='",
";",
"}",
"$",
"checkResult",
"=",
"false",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"version",
")",
")",
"{",
"$",
"checkResult",
"=",
"version_compare",
"(",
"PHP_VERSION",
",",
"$",
"version",
",",
"$",
"operator",
")",
";",
"}",
"if",
"(",
"!",
"$",
"checkResult",
")",
"{",
"$",
"result",
"=",
"false",
";",
"}",
"}",
"return",
"$",
"result",
";",
"}"
] | Check version of PHP
@return null|bool Return Null, if checking is not configured.
True, if PHP version is compatible. False otherwise. | [
"Check",
"version",
"of",
"PHP"
] | 76136550e856ff4f8fd3634b77633f86510f63e9 | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L242-L270 | train |
anklimsk/cakephp-console-installer | Model/InstallerCheck.php | InstallerCheck.getListDbConn | public function getListDbConn($path = null) {
if (empty($path)) {
$path = APP;
}
$configFile = $path . 'Config' . DS . 'database.php';
$connections = [];
if (file_exists($configFile)) {
$connections = array_keys(ConnectionManager::enumConnectionObjects());
}
return $connections;
} | php | public function getListDbConn($path = null) {
if (empty($path)) {
$path = APP;
}
$configFile = $path . 'Config' . DS . 'database.php';
$connections = [];
if (file_exists($configFile)) {
$connections = array_keys(ConnectionManager::enumConnectionObjects());
}
return $connections;
} | [
"public",
"function",
"getListDbConn",
"(",
"$",
"path",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"path",
")",
")",
"{",
"$",
"path",
"=",
"APP",
";",
"}",
"$",
"configFile",
"=",
"$",
"path",
".",
"'Config'",
".",
"DS",
".",
"'database.php'",
";",
"$",
"connections",
"=",
"[",
"]",
";",
"if",
"(",
"file_exists",
"(",
"$",
"configFile",
")",
")",
"{",
"$",
"connections",
"=",
"array_keys",
"(",
"ConnectionManager",
"::",
"enumConnectionObjects",
"(",
")",
")",
";",
"}",
"return",
"$",
"connections",
";",
"}"
] | Return list of configured database connection.
@param string $path Path to database connection configuration file.
@return array List of configured database connection. | [
"Return",
"list",
"of",
"configured",
"database",
"connection",
"."
] | 76136550e856ff4f8fd3634b77633f86510f63e9 | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L378-L390 | train |
anklimsk/cakephp-console-installer | Model/InstallerCheck.php | InstallerCheck.checkConnectDb | public function checkConnectDb($path = null, $returnBool = false) {
$connections = $this->getListDbConn($path);
if (empty($connections)) {
return null;
}
$cfgConnections = $this->_modelConfigInstaller->getListDbConnConfigs();
if (empty($cfgConnections)) {
return null;
}
$connections = array_intersect($connections, $cfgConnections);
$notCfgConnections = array_diff($cfgConnections, $connections);
$result = [];
$resultBool = true;
foreach ($connections as $connectionName) {
try {
//@codingStandardsIgnoreStart
$ds = @ConnectionManager::getDataSource($connectionName);
//@codingStandardsIgnoreEnd
$checkResult = $ds->isConnected();
} catch (Exception $exception) {
$checkResult = [$exception->getMessage()];
$attributes = $exception->getAttributes();
if (isset($attributes['message'])) {
$checkResult[] = $attributes['message'];
}
$resultBool = false;
}
if (!$checkResult) {
$resultBool = false;
}
$result[$connectionName] = $checkResult;
}
foreach ($notCfgConnections as $connectionName) {
$result[$connectionName] = false;
$resultBool = false;
}
if ($returnBool) {
return $resultBool;
}
return $result;
} | php | public function checkConnectDb($path = null, $returnBool = false) {
$connections = $this->getListDbConn($path);
if (empty($connections)) {
return null;
}
$cfgConnections = $this->_modelConfigInstaller->getListDbConnConfigs();
if (empty($cfgConnections)) {
return null;
}
$connections = array_intersect($connections, $cfgConnections);
$notCfgConnections = array_diff($cfgConnections, $connections);
$result = [];
$resultBool = true;
foreach ($connections as $connectionName) {
try {
//@codingStandardsIgnoreStart
$ds = @ConnectionManager::getDataSource($connectionName);
//@codingStandardsIgnoreEnd
$checkResult = $ds->isConnected();
} catch (Exception $exception) {
$checkResult = [$exception->getMessage()];
$attributes = $exception->getAttributes();
if (isset($attributes['message'])) {
$checkResult[] = $attributes['message'];
}
$resultBool = false;
}
if (!$checkResult) {
$resultBool = false;
}
$result[$connectionName] = $checkResult;
}
foreach ($notCfgConnections as $connectionName) {
$result[$connectionName] = false;
$resultBool = false;
}
if ($returnBool) {
return $resultBool;
}
return $result;
} | [
"public",
"function",
"checkConnectDb",
"(",
"$",
"path",
"=",
"null",
",",
"$",
"returnBool",
"=",
"false",
")",
"{",
"$",
"connections",
"=",
"$",
"this",
"->",
"getListDbConn",
"(",
"$",
"path",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"connections",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"cfgConnections",
"=",
"$",
"this",
"->",
"_modelConfigInstaller",
"->",
"getListDbConnConfigs",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"cfgConnections",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"connections",
"=",
"array_intersect",
"(",
"$",
"connections",
",",
"$",
"cfgConnections",
")",
";",
"$",
"notCfgConnections",
"=",
"array_diff",
"(",
"$",
"cfgConnections",
",",
"$",
"connections",
")",
";",
"$",
"result",
"=",
"[",
"]",
";",
"$",
"resultBool",
"=",
"true",
";",
"foreach",
"(",
"$",
"connections",
"as",
"$",
"connectionName",
")",
"{",
"try",
"{",
"//@codingStandardsIgnoreStart",
"$",
"ds",
"=",
"@",
"ConnectionManager",
"::",
"getDataSource",
"(",
"$",
"connectionName",
")",
";",
"//@codingStandardsIgnoreEnd",
"$",
"checkResult",
"=",
"$",
"ds",
"->",
"isConnected",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"exception",
")",
"{",
"$",
"checkResult",
"=",
"[",
"$",
"exception",
"->",
"getMessage",
"(",
")",
"]",
";",
"$",
"attributes",
"=",
"$",
"exception",
"->",
"getAttributes",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"attributes",
"[",
"'message'",
"]",
")",
")",
"{",
"$",
"checkResult",
"[",
"]",
"=",
"$",
"attributes",
"[",
"'message'",
"]",
";",
"}",
"$",
"resultBool",
"=",
"false",
";",
"}",
"if",
"(",
"!",
"$",
"checkResult",
")",
"{",
"$",
"resultBool",
"=",
"false",
";",
"}",
"$",
"result",
"[",
"$",
"connectionName",
"]",
"=",
"$",
"checkResult",
";",
"}",
"foreach",
"(",
"$",
"notCfgConnections",
"as",
"$",
"connectionName",
")",
"{",
"$",
"result",
"[",
"$",
"connectionName",
"]",
"=",
"false",
";",
"$",
"resultBool",
"=",
"false",
";",
"}",
"if",
"(",
"$",
"returnBool",
")",
"{",
"return",
"$",
"resultBool",
";",
"}",
"return",
"$",
"result",
";",
"}"
] | Check connections to database
@param string $path Path to database connection configuration file.
@param bool $returnBool If True, return boolean. Otherwise,
return array otherwise in format:
- key - database connection name;
- value - True, if connection success. Otherwise False or Array or
error messages.
@return null|bool|array Return Null, if checking is not configured. | [
"Check",
"connections",
"to",
"database"
] | 76136550e856ff4f8fd3634b77633f86510f63e9 | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L403-L446 | train |
anklimsk/cakephp-console-installer | Model/InstallerCheck.php | InstallerCheck.checkSymLinksExists | public function checkSymLinksExists() {
$symlinksList = $this->_modelConfigInstaller->getListSymlinksCreation();
if (empty($symlinksList)) {
return true;
}
foreach ($symlinksList as $link => $target) {
if (empty($link)) {
continue;
}
if (!file_exists($link) || (!is_link($link) && (DS !== '\\'))) {
return false;
}
if (stripos(readlink($link), $target) !== 0) {
return false;
}
}
return true;
} | php | public function checkSymLinksExists() {
$symlinksList = $this->_modelConfigInstaller->getListSymlinksCreation();
if (empty($symlinksList)) {
return true;
}
foreach ($symlinksList as $link => $target) {
if (empty($link)) {
continue;
}
if (!file_exists($link) || (!is_link($link) && (DS !== '\\'))) {
return false;
}
if (stripos(readlink($link), $target) !== 0) {
return false;
}
}
return true;
} | [
"public",
"function",
"checkSymLinksExists",
"(",
")",
"{",
"$",
"symlinksList",
"=",
"$",
"this",
"->",
"_modelConfigInstaller",
"->",
"getListSymlinksCreation",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"symlinksList",
")",
")",
"{",
"return",
"true",
";",
"}",
"foreach",
"(",
"$",
"symlinksList",
"as",
"$",
"link",
"=>",
"$",
"target",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"link",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"link",
")",
"||",
"(",
"!",
"is_link",
"(",
"$",
"link",
")",
"&&",
"(",
"DS",
"!==",
"'\\\\'",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"stripos",
"(",
"readlink",
"(",
"$",
"link",
")",
",",
"$",
"target",
")",
"!==",
"0",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Check symbolic links exists
@return bool Success | [
"Check",
"symbolic",
"links",
"exists"
] | 76136550e856ff4f8fd3634b77633f86510f63e9 | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L536-L557 | train |
anklimsk/cakephp-console-installer | Model/InstallerCheck.php | InstallerCheck.checkCronJobsExists | public function checkCronJobsExists() {
if ($this->isOsWindows()) {
return true;
}
$apacheUser = $this->getWebSrvUser();
if (empty($apacheUser)) {
return false;
}
$cronjobsList = $this->_modelConfigInstaller->getListCronJobsCreation();
if (empty($cronjobsList)) {
return true;
}
$output = [];
$exitCode = -1;
$cmd = 'crontab -u ' . $apacheUser . ' -l 2>/dev/null';
exec($cmd, $output, $exitCode);
if ($exitCode !== 0) {
return false;
}
if (empty($output)) {
return false;
}
foreach ($cronjobsList as $cmd => $time) {
if (empty($cmd)) {
continue;
}
if (count(preg_grep('/^[^#]+' . preg_quote($cmd, '/') . '$/', $output)) == 0) {
return false;
}
}
return true;
} | php | public function checkCronJobsExists() {
if ($this->isOsWindows()) {
return true;
}
$apacheUser = $this->getWebSrvUser();
if (empty($apacheUser)) {
return false;
}
$cronjobsList = $this->_modelConfigInstaller->getListCronJobsCreation();
if (empty($cronjobsList)) {
return true;
}
$output = [];
$exitCode = -1;
$cmd = 'crontab -u ' . $apacheUser . ' -l 2>/dev/null';
exec($cmd, $output, $exitCode);
if ($exitCode !== 0) {
return false;
}
if (empty($output)) {
return false;
}
foreach ($cronjobsList as $cmd => $time) {
if (empty($cmd)) {
continue;
}
if (count(preg_grep('/^[^#]+' . preg_quote($cmd, '/') . '$/', $output)) == 0) {
return false;
}
}
return true;
} | [
"public",
"function",
"checkCronJobsExists",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isOsWindows",
"(",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"apacheUser",
"=",
"$",
"this",
"->",
"getWebSrvUser",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"apacheUser",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"cronjobsList",
"=",
"$",
"this",
"->",
"_modelConfigInstaller",
"->",
"getListCronJobsCreation",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"cronjobsList",
")",
")",
"{",
"return",
"true",
";",
"}",
"$",
"output",
"=",
"[",
"]",
";",
"$",
"exitCode",
"=",
"-",
"1",
";",
"$",
"cmd",
"=",
"'crontab -u '",
".",
"$",
"apacheUser",
".",
"' -l 2>/dev/null'",
";",
"exec",
"(",
"$",
"cmd",
",",
"$",
"output",
",",
"$",
"exitCode",
")",
";",
"if",
"(",
"$",
"exitCode",
"!==",
"0",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"output",
")",
")",
"{",
"return",
"false",
";",
"}",
"foreach",
"(",
"$",
"cronjobsList",
"as",
"$",
"cmd",
"=>",
"$",
"time",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"cmd",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"count",
"(",
"preg_grep",
"(",
"'/^[^#]+'",
".",
"preg_quote",
"(",
"$",
"cmd",
",",
"'/'",
")",
".",
"'$/'",
",",
"$",
"output",
")",
")",
"==",
"0",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Check cron jobs exists
@return bool Success | [
"Check",
"cron",
"jobs",
"exists"
] | 76136550e856ff4f8fd3634b77633f86510f63e9 | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L564-L602 | train |
anklimsk/cakephp-console-installer | Model/InstallerCheck.php | InstallerCheck._removeMarkerFile | protected function _removeMarkerFile($path) {
if (empty($path)) {
return false;
}
$oFile = new File($path, false);
if (!$oFile->exists()) {
return false;
}
return $oFile->delete();
} | php | protected function _removeMarkerFile($path) {
if (empty($path)) {
return false;
}
$oFile = new File($path, false);
if (!$oFile->exists()) {
return false;
}
return $oFile->delete();
} | [
"protected",
"function",
"_removeMarkerFile",
"(",
"$",
"path",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"path",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"oFile",
"=",
"new",
"File",
"(",
"$",
"path",
",",
"false",
")",
";",
"if",
"(",
"!",
"$",
"oFile",
"->",
"exists",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"oFile",
"->",
"delete",
"(",
")",
";",
"}"
] | Remove marker file
@param string $path Path to marker file.
@return bool True, if file removed successful. False otherwise. | [
"Remove",
"marker",
"file"
] | 76136550e856ff4f8fd3634b77633f86510f63e9 | https://github.com/anklimsk/cakephp-console-installer/blob/76136550e856ff4f8fd3634b77633f86510f63e9/Model/InstallerCheck.php#L668-L679 | train |
phpextra/event-manager-silex-provider | src/PHPExtra/EventManager/Silex/ProxyMapper.php | ProxyMapper.createProxyEvent | public function createProxyEvent(Event $event)
{
if ($event instanceof GetResponseForControllerResultEvent) {
$silexEvent = new PostDispatchEvent($event);
} elseif ($event instanceof GetResponseEvent) {
$silexEvent = new RequestEvent($event);
} elseif ($event instanceof FilterControllerEvent) {
$silexEvent = new PreDispatchEvent($event);
} elseif ($event instanceof FilterResponseEvent) {
$silexEvent = new ResponseEvent($event);
} elseif ($event instanceof SfPostResponseEvent) {
$silexEvent = new PostResponseEvent($event);
} elseif ($event instanceof FinishRequestEvent) {
$silexEvent = new PostRequestEvent($event);
} elseif ($event instanceof KernelEvent) {
$silexEvent = new SilexKernelEvent($event);
} elseif ($event instanceof Event) {
$silexEvent = new SilexEvent($event);
} else {
$silexEvent = null; // unknown event
}
return $silexEvent;
} | php | public function createProxyEvent(Event $event)
{
if ($event instanceof GetResponseForControllerResultEvent) {
$silexEvent = new PostDispatchEvent($event);
} elseif ($event instanceof GetResponseEvent) {
$silexEvent = new RequestEvent($event);
} elseif ($event instanceof FilterControllerEvent) {
$silexEvent = new PreDispatchEvent($event);
} elseif ($event instanceof FilterResponseEvent) {
$silexEvent = new ResponseEvent($event);
} elseif ($event instanceof SfPostResponseEvent) {
$silexEvent = new PostResponseEvent($event);
} elseif ($event instanceof FinishRequestEvent) {
$silexEvent = new PostRequestEvent($event);
} elseif ($event instanceof KernelEvent) {
$silexEvent = new SilexKernelEvent($event);
} elseif ($event instanceof Event) {
$silexEvent = new SilexEvent($event);
} else {
$silexEvent = null; // unknown event
}
return $silexEvent;
} | [
"public",
"function",
"createProxyEvent",
"(",
"Event",
"$",
"event",
")",
"{",
"if",
"(",
"$",
"event",
"instanceof",
"GetResponseForControllerResultEvent",
")",
"{",
"$",
"silexEvent",
"=",
"new",
"PostDispatchEvent",
"(",
"$",
"event",
")",
";",
"}",
"elseif",
"(",
"$",
"event",
"instanceof",
"GetResponseEvent",
")",
"{",
"$",
"silexEvent",
"=",
"new",
"RequestEvent",
"(",
"$",
"event",
")",
";",
"}",
"elseif",
"(",
"$",
"event",
"instanceof",
"FilterControllerEvent",
")",
"{",
"$",
"silexEvent",
"=",
"new",
"PreDispatchEvent",
"(",
"$",
"event",
")",
";",
"}",
"elseif",
"(",
"$",
"event",
"instanceof",
"FilterResponseEvent",
")",
"{",
"$",
"silexEvent",
"=",
"new",
"ResponseEvent",
"(",
"$",
"event",
")",
";",
"}",
"elseif",
"(",
"$",
"event",
"instanceof",
"SfPostResponseEvent",
")",
"{",
"$",
"silexEvent",
"=",
"new",
"PostResponseEvent",
"(",
"$",
"event",
")",
";",
"}",
"elseif",
"(",
"$",
"event",
"instanceof",
"FinishRequestEvent",
")",
"{",
"$",
"silexEvent",
"=",
"new",
"PostRequestEvent",
"(",
"$",
"event",
")",
";",
"}",
"elseif",
"(",
"$",
"event",
"instanceof",
"KernelEvent",
")",
"{",
"$",
"silexEvent",
"=",
"new",
"SilexKernelEvent",
"(",
"$",
"event",
")",
";",
"}",
"elseif",
"(",
"$",
"event",
"instanceof",
"Event",
")",
"{",
"$",
"silexEvent",
"=",
"new",
"SilexEvent",
"(",
"$",
"event",
")",
";",
"}",
"else",
"{",
"$",
"silexEvent",
"=",
"null",
";",
"// unknown event",
"}",
"return",
"$",
"silexEvent",
";",
"}"
] | Create proxy event for given Symfony dispatcher event
@param Event $event
@return EventInterface | [
"Create",
"proxy",
"event",
"for",
"given",
"Symfony",
"dispatcher",
"event"
] | 9952b237feffa5a469dd2976317736a570526249 | https://github.com/phpextra/event-manager-silex-provider/blob/9952b237feffa5a469dd2976317736a570526249/src/PHPExtra/EventManager/Silex/ProxyMapper.php#L37-L68 | train |
comodojo/extender.framework | src/Comodojo/Extender/Utils/Checks.php | Checks.database | final public static function database(Configuration $configuration) {
try {
$dbh = Database::init($configuration);
$dbh->connect();
$manager = $dbh->getSchemaManager();
$manager->getTable($configuration->get('database-jobs-table'));
$manager->getTable($configuration->get('database-worklogs-table'));
$manager->getTable($configuration->get('database-queue-table'));
} catch (Exception $e) {
return false;
} finally {
$dhb->close();
}
return true;
} | php | final public static function database(Configuration $configuration) {
try {
$dbh = Database::init($configuration);
$dbh->connect();
$manager = $dbh->getSchemaManager();
$manager->getTable($configuration->get('database-jobs-table'));
$manager->getTable($configuration->get('database-worklogs-table'));
$manager->getTable($configuration->get('database-queue-table'));
} catch (Exception $e) {
return false;
} finally {
$dhb->close();
}
return true;
} | [
"final",
"public",
"static",
"function",
"database",
"(",
"Configuration",
"$",
"configuration",
")",
"{",
"try",
"{",
"$",
"dbh",
"=",
"Database",
"::",
"init",
"(",
"$",
"configuration",
")",
";",
"$",
"dbh",
"->",
"connect",
"(",
")",
";",
"$",
"manager",
"=",
"$",
"dbh",
"->",
"getSchemaManager",
"(",
")",
";",
"$",
"manager",
"->",
"getTable",
"(",
"$",
"configuration",
"->",
"get",
"(",
"'database-jobs-table'",
")",
")",
";",
"$",
"manager",
"->",
"getTable",
"(",
"$",
"configuration",
"->",
"get",
"(",
"'database-worklogs-table'",
")",
")",
";",
"$",
"manager",
"->",
"getTable",
"(",
"$",
"configuration",
"->",
"get",
"(",
"'database-queue-table'",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"return",
"false",
";",
"}",
"finally",
"{",
"$",
"dhb",
"->",
"close",
"(",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Check if database is available and initialized correctly
@return bool | [
"Check",
"if",
"database",
"is",
"available",
"and",
"initialized",
"correctly"
] | cc9a4fbd29fe0e80965ce4535091c956aad70b27 | https://github.com/comodojo/extender.framework/blob/cc9a4fbd29fe0e80965ce4535091c956aad70b27/src/Comodojo/Extender/Utils/Checks.php#L63-L89 | train |
matryoshka-model/matryoshka | library/Object/Service/ObjectAbstractServiceFactory.php | ObjectAbstractServiceFactory.getActiveRecordCriteriaByName | protected function getActiveRecordCriteriaByName($serviceLocator, $name)
{
$criteria = $serviceLocator->get($name);
if (!$criteria instanceof AbstractCriteria) {
throw new Exception\ServiceNotCreatedException(sprintf(
'Instance of type %s is invalid; must implement %s',
(is_object($criteria) ? get_class($criteria) : gettype($criteria)),
AbstractCriteria::class
));
}
return $criteria;
} | php | protected function getActiveRecordCriteriaByName($serviceLocator, $name)
{
$criteria = $serviceLocator->get($name);
if (!$criteria instanceof AbstractCriteria) {
throw new Exception\ServiceNotCreatedException(sprintf(
'Instance of type %s is invalid; must implement %s',
(is_object($criteria) ? get_class($criteria) : gettype($criteria)),
AbstractCriteria::class
));
}
return $criteria;
} | [
"protected",
"function",
"getActiveRecordCriteriaByName",
"(",
"$",
"serviceLocator",
",",
"$",
"name",
")",
"{",
"$",
"criteria",
"=",
"$",
"serviceLocator",
"->",
"get",
"(",
"$",
"name",
")",
";",
"if",
"(",
"!",
"$",
"criteria",
"instanceof",
"AbstractCriteria",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"ServiceNotCreatedException",
"(",
"sprintf",
"(",
"'Instance of type %s is invalid; must implement %s'",
",",
"(",
"is_object",
"(",
"$",
"criteria",
")",
"?",
"get_class",
"(",
"$",
"criteria",
")",
":",
"gettype",
"(",
"$",
"criteria",
")",
")",
",",
"AbstractCriteria",
"::",
"class",
")",
")",
";",
"}",
"return",
"$",
"criteria",
";",
"}"
] | Retrieve PaginableCriteriaInterface object from config
@param ServiceLocatorInterface $serviceLocator
@param $name
@return AbstractCriteria
@throws Exception\ServiceNotCreatedException | [
"Retrieve",
"PaginableCriteriaInterface",
"object",
"from",
"config"
] | 51792df00d9897f556d5a3c53193eed0974ff09d | https://github.com/matryoshka-model/matryoshka/blob/51792df00d9897f556d5a3c53193eed0974ff09d/library/Object/Service/ObjectAbstractServiceFactory.php#L137-L148 | train |
andyburton/Sonic-Framework | src/Controller/JSON/Session.php | Session.authFail | protected function authFail ($message = null)
{
$this->error ($message);
$this->view->response['auth_fail'] = TRUE;
return FALSE;
} | php | protected function authFail ($message = null)
{
$this->error ($message);
$this->view->response['auth_fail'] = TRUE;
return FALSE;
} | [
"protected",
"function",
"authFail",
"(",
"$",
"message",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"error",
"(",
"$",
"message",
")",
";",
"$",
"this",
"->",
"view",
"->",
"response",
"[",
"'auth_fail'",
"]",
"=",
"TRUE",
";",
"return",
"FALSE",
";",
"}"
] | Set response for an authentication failure
@param string $message Error message
@return false | [
"Set",
"response",
"for",
"an",
"authentication",
"failure"
] | a5999448a0abab4d542413002a780ede391e7374 | https://github.com/andyburton/Sonic-Framework/blob/a5999448a0abab4d542413002a780ede391e7374/src/Controller/JSON/Session.php#L89-L94 | train |
luismareze/geomanager | src/app/Http/Controllers/Admin/GeoCrudController.php | GeoCrudController.useTemplate | public function useTemplate($template_name = false)
{
$templates = $this->getTemplates();
// set the default template
if ($template_name == false) {
$template_name = $templates[0]->name;
}
// actually use the template
if ($template_name) {
$this->{$template_name}();
}
} | php | public function useTemplate($template_name = false)
{
$templates = $this->getTemplates();
// set the default template
if ($template_name == false) {
$template_name = $templates[0]->name;
}
// actually use the template
if ($template_name) {
$this->{$template_name}();
}
} | [
"public",
"function",
"useTemplate",
"(",
"$",
"template_name",
"=",
"false",
")",
"{",
"$",
"templates",
"=",
"$",
"this",
"->",
"getTemplates",
"(",
")",
";",
"// set the default template\r",
"if",
"(",
"$",
"template_name",
"==",
"false",
")",
"{",
"$",
"template_name",
"=",
"$",
"templates",
"[",
"0",
"]",
"->",
"name",
";",
"}",
"// actually use the template\r",
"if",
"(",
"$",
"template_name",
")",
"{",
"$",
"this",
"->",
"{",
"$",
"template_name",
"}",
"(",
")",
";",
"}",
"}"
] | Add the fields defined for a specific template.
@param string $template_name The name of the template that should be used in the current form. | [
"Add",
"the",
"fields",
"defined",
"for",
"a",
"specific",
"template",
"."
] | 9325c4f0e2917abc2ec3ce99379d2a7fe7368d32 | https://github.com/luismareze/geomanager/blob/9325c4f0e2917abc2ec3ce99379d2a7fe7368d32/src/app/Http/Controllers/Admin/GeoCrudController.php#L150-L163 | train |
luismareze/geomanager | src/app/Http/Controllers/Admin/GeoCrudController.php | GeoCrudController.getTemplates | public function getTemplates()
{
$templates_array = [];
$templates_trait = new \ReflectionClass('App\GeoTemplates');
$templates = $templates_trait->getMethods();
if (! count($templates)) {
abort('403', 'No templates have been found.');
}
return $templates;
} | php | public function getTemplates()
{
$templates_array = [];
$templates_trait = new \ReflectionClass('App\GeoTemplates');
$templates = $templates_trait->getMethods();
if (! count($templates)) {
abort('403', 'No templates have been found.');
}
return $templates;
} | [
"public",
"function",
"getTemplates",
"(",
")",
"{",
"$",
"templates_array",
"=",
"[",
"]",
";",
"$",
"templates_trait",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"'App\\GeoTemplates'",
")",
";",
"$",
"templates",
"=",
"$",
"templates_trait",
"->",
"getMethods",
"(",
")",
";",
"if",
"(",
"!",
"count",
"(",
"$",
"templates",
")",
")",
"{",
"abort",
"(",
"'403'",
",",
"'No templates have been found.'",
")",
";",
"}",
"return",
"$",
"templates",
";",
"}"
] | Get all defined templates. | [
"Get",
"all",
"defined",
"templates",
"."
] | 9325c4f0e2917abc2ec3ce99379d2a7fe7368d32 | https://github.com/luismareze/geomanager/blob/9325c4f0e2917abc2ec3ce99379d2a7fe7368d32/src/app/Http/Controllers/Admin/GeoCrudController.php#L168-L180 | train |
luismareze/geomanager | src/app/Http/Controllers/Admin/GeoCrudController.php | GeoCrudController.getTemplatesArray | public function getTemplatesArray()
{
$templates = $this->getTemplates();
foreach ($templates as $template) {
$templates_array[$template->name] = $this->crud->makeLabel($template->name);
}
return $templates_array;
} | php | public function getTemplatesArray()
{
$templates = $this->getTemplates();
foreach ($templates as $template) {
$templates_array[$template->name] = $this->crud->makeLabel($template->name);
}
return $templates_array;
} | [
"public",
"function",
"getTemplatesArray",
"(",
")",
"{",
"$",
"templates",
"=",
"$",
"this",
"->",
"getTemplates",
"(",
")",
";",
"foreach",
"(",
"$",
"templates",
"as",
"$",
"template",
")",
"{",
"$",
"templates_array",
"[",
"$",
"template",
"->",
"name",
"]",
"=",
"$",
"this",
"->",
"crud",
"->",
"makeLabel",
"(",
"$",
"template",
"->",
"name",
")",
";",
"}",
"return",
"$",
"templates_array",
";",
"}"
] | Get all defined template as an array.
Used to populate the template dropdown in the create/update forms. | [
"Get",
"all",
"defined",
"template",
"as",
"an",
"array",
"."
] | 9325c4f0e2917abc2ec3ce99379d2a7fe7368d32 | https://github.com/luismareze/geomanager/blob/9325c4f0e2917abc2ec3ce99379d2a7fe7368d32/src/app/Http/Controllers/Admin/GeoCrudController.php#L187-L196 | train |
as3io/modlr | src/Metadata/EmbeddedPropMetadata.php | EmbeddedPropMetadata.validateType | protected function validateType($embedType)
{
$valid = ['one', 'many'];
if (!in_array($embedType, $valid)) {
throw MetadataException::invalidRelType($embedType, $valid);
}
return true;
} | php | protected function validateType($embedType)
{
$valid = ['one', 'many'];
if (!in_array($embedType, $valid)) {
throw MetadataException::invalidRelType($embedType, $valid);
}
return true;
} | [
"protected",
"function",
"validateType",
"(",
"$",
"embedType",
")",
"{",
"$",
"valid",
"=",
"[",
"'one'",
",",
"'many'",
"]",
";",
"if",
"(",
"!",
"in_array",
"(",
"$",
"embedType",
",",
"$",
"valid",
")",
")",
"{",
"throw",
"MetadataException",
"::",
"invalidRelType",
"(",
"$",
"embedType",
",",
"$",
"valid",
")",
";",
"}",
"return",
"true",
";",
"}"
] | Validates the embed type.
@param string $embedType
@return bool
@throws MetadataException | [
"Validates",
"the",
"embed",
"type",
"."
] | 7e684b88bb22a2e18397df9402075c6533084b16 | https://github.com/as3io/modlr/blob/7e684b88bb22a2e18397df9402075c6533084b16/src/Metadata/EmbeddedPropMetadata.php#L85-L92 | train |
activecollab/databaseconnection | src/Record/ValueCaster.php | ValueCaster.castRowValues | public function castRowValues(array &$row)
{
foreach ($row as $field_name => $value) {
$row[$field_name] = $this->castValue($field_name, $value);
}
} | php | public function castRowValues(array &$row)
{
foreach ($row as $field_name => $value) {
$row[$field_name] = $this->castValue($field_name, $value);
}
} | [
"public",
"function",
"castRowValues",
"(",
"array",
"&",
"$",
"row",
")",
"{",
"foreach",
"(",
"$",
"row",
"as",
"$",
"field_name",
"=>",
"$",
"value",
")",
"{",
"$",
"row",
"[",
"$",
"field_name",
"]",
"=",
"$",
"this",
"->",
"castValue",
"(",
"$",
"field_name",
",",
"$",
"value",
")",
";",
"}",
"}"
] | Cast row value to native PHP types based on caster settings.
@param array $row | [
"Cast",
"row",
"value",
"to",
"native",
"PHP",
"types",
"based",
"on",
"caster",
"settings",
"."
] | f38accc083863262325858a3d72a5afb6b4513f8 | https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Record/ValueCaster.php#L43-L48 | train |
activecollab/databaseconnection | src/Record/ValueCaster.php | ValueCaster.castValue | public function castValue($field_name, $value)
{
if ($value === null) {
return null; // NULL remains NULL
}
switch ($this->getTypeByFieldName($field_name)) {
case self::CAST_INT:
return (int) $value;
case self::CAST_FLOAT:
return (float) $value;
case self::CAST_STRING:
return (string) $value;
case self::CAST_BOOL:
return (bool) $value;
case self::CAST_DATE:
return new DateValue($value, 'UTC');
case self::CAST_DATETIME:
return new DateTimeValue($value, 'UTC');
case self::CAST_JSON:
if (empty($value)) {
return null;
} else {
$result = json_decode($value, true);
if (empty($result) && json_last_error()) {
throw new RuntimeException('Failed to parse JSON. Reason: ' . json_last_error_msg(), json_last_error());
}
return $result;
}
default:
return (string) $value;
}
} | php | public function castValue($field_name, $value)
{
if ($value === null) {
return null; // NULL remains NULL
}
switch ($this->getTypeByFieldName($field_name)) {
case self::CAST_INT:
return (int) $value;
case self::CAST_FLOAT:
return (float) $value;
case self::CAST_STRING:
return (string) $value;
case self::CAST_BOOL:
return (bool) $value;
case self::CAST_DATE:
return new DateValue($value, 'UTC');
case self::CAST_DATETIME:
return new DateTimeValue($value, 'UTC');
case self::CAST_JSON:
if (empty($value)) {
return null;
} else {
$result = json_decode($value, true);
if (empty($result) && json_last_error()) {
throw new RuntimeException('Failed to parse JSON. Reason: ' . json_last_error_msg(), json_last_error());
}
return $result;
}
default:
return (string) $value;
}
} | [
"public",
"function",
"castValue",
"(",
"$",
"field_name",
",",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"return",
"null",
";",
"// NULL remains NULL",
"}",
"switch",
"(",
"$",
"this",
"->",
"getTypeByFieldName",
"(",
"$",
"field_name",
")",
")",
"{",
"case",
"self",
"::",
"CAST_INT",
":",
"return",
"(",
"int",
")",
"$",
"value",
";",
"case",
"self",
"::",
"CAST_FLOAT",
":",
"return",
"(",
"float",
")",
"$",
"value",
";",
"case",
"self",
"::",
"CAST_STRING",
":",
"return",
"(",
"string",
")",
"$",
"value",
";",
"case",
"self",
"::",
"CAST_BOOL",
":",
"return",
"(",
"bool",
")",
"$",
"value",
";",
"case",
"self",
"::",
"CAST_DATE",
":",
"return",
"new",
"DateValue",
"(",
"$",
"value",
",",
"'UTC'",
")",
";",
"case",
"self",
"::",
"CAST_DATETIME",
":",
"return",
"new",
"DateTimeValue",
"(",
"$",
"value",
",",
"'UTC'",
")",
";",
"case",
"self",
"::",
"CAST_JSON",
":",
"if",
"(",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"return",
"null",
";",
"}",
"else",
"{",
"$",
"result",
"=",
"json_decode",
"(",
"$",
"value",
",",
"true",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"result",
")",
"&&",
"json_last_error",
"(",
")",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"'Failed to parse JSON. Reason: '",
".",
"json_last_error_msg",
"(",
")",
",",
"json_last_error",
"(",
")",
")",
";",
"}",
"return",
"$",
"result",
";",
"}",
"default",
":",
"return",
"(",
"string",
")",
"$",
"value",
";",
"}",
"}"
] | Cast a single value.
@param string $field_name
@param mixed $value
@return mixed | [
"Cast",
"a",
"single",
"value",
"."
] | f38accc083863262325858a3d72a5afb6b4513f8 | https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Record/ValueCaster.php#L58-L92 | train |
activecollab/databaseconnection | src/Record/ValueCaster.php | ValueCaster.getTypeByFieldName | public function getTypeByFieldName($field_name)
{
if (isset($this->dictated[$field_name])) {
return $this->dictated[$field_name];
}
if (substr($field_name, 0, 3) === 'is_' || in_array(substr($field_name, 0, 4), ['has_', 'had_', 'was_']) || in_array(substr($field_name, 0, 5), ['were_', 'have_'])) {
return self::CAST_BOOL;
}
$last_three = substr($field_name, -3);
if ($last_three === '_id') {
return self::CAST_INT;
}
if ($last_three === '_on') {
return self::CAST_DATE;
}
if ($last_three === '_at') {
return self::CAST_DATETIME;
}
return self::CAST_STRING;
} | php | public function getTypeByFieldName($field_name)
{
if (isset($this->dictated[$field_name])) {
return $this->dictated[$field_name];
}
if (substr($field_name, 0, 3) === 'is_' || in_array(substr($field_name, 0, 4), ['has_', 'had_', 'was_']) || in_array(substr($field_name, 0, 5), ['were_', 'have_'])) {
return self::CAST_BOOL;
}
$last_three = substr($field_name, -3);
if ($last_three === '_id') {
return self::CAST_INT;
}
if ($last_three === '_on') {
return self::CAST_DATE;
}
if ($last_three === '_at') {
return self::CAST_DATETIME;
}
return self::CAST_STRING;
} | [
"public",
"function",
"getTypeByFieldName",
"(",
"$",
"field_name",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"dictated",
"[",
"$",
"field_name",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"dictated",
"[",
"$",
"field_name",
"]",
";",
"}",
"if",
"(",
"substr",
"(",
"$",
"field_name",
",",
"0",
",",
"3",
")",
"===",
"'is_'",
"||",
"in_array",
"(",
"substr",
"(",
"$",
"field_name",
",",
"0",
",",
"4",
")",
",",
"[",
"'has_'",
",",
"'had_'",
",",
"'was_'",
"]",
")",
"||",
"in_array",
"(",
"substr",
"(",
"$",
"field_name",
",",
"0",
",",
"5",
")",
",",
"[",
"'were_'",
",",
"'have_'",
"]",
")",
")",
"{",
"return",
"self",
"::",
"CAST_BOOL",
";",
"}",
"$",
"last_three",
"=",
"substr",
"(",
"$",
"field_name",
",",
"-",
"3",
")",
";",
"if",
"(",
"$",
"last_three",
"===",
"'_id'",
")",
"{",
"return",
"self",
"::",
"CAST_INT",
";",
"}",
"if",
"(",
"$",
"last_three",
"===",
"'_on'",
")",
"{",
"return",
"self",
"::",
"CAST_DATE",
";",
"}",
"if",
"(",
"$",
"last_three",
"===",
"'_at'",
")",
"{",
"return",
"self",
"::",
"CAST_DATETIME",
";",
"}",
"return",
"self",
"::",
"CAST_STRING",
";",
"}"
] | Return type by field name.
@param string $field_name
@return string | [
"Return",
"type",
"by",
"field",
"name",
"."
] | f38accc083863262325858a3d72a5afb6b4513f8 | https://github.com/activecollab/databaseconnection/blob/f38accc083863262325858a3d72a5afb6b4513f8/src/Record/ValueCaster.php#L101-L126 | train |
PhoxPHP/Glider | src/Query/Builder/QueryBinder.php | QueryBinder.createBinding | public function createBinding(String $key, $queryPart, $params=[], $expr='', $with='', $addValue=true)
{
if (!array_key_exists($key, $this->bindings)) {
return false;
}
if ($key == 'sql') {
return $queryPart;
}
if ($addValue == true) {
$this->bindings[$key] = $queryPart;
}
return $this->$key($queryPart, $params, $expr, $with, $addValue);
} | php | public function createBinding(String $key, $queryPart, $params=[], $expr='', $with='', $addValue=true)
{
if (!array_key_exists($key, $this->bindings)) {
return false;
}
if ($key == 'sql') {
return $queryPart;
}
if ($addValue == true) {
$this->bindings[$key] = $queryPart;
}
return $this->$key($queryPart, $params, $expr, $with, $addValue);
} | [
"public",
"function",
"createBinding",
"(",
"String",
"$",
"key",
",",
"$",
"queryPart",
",",
"$",
"params",
"=",
"[",
"]",
",",
"$",
"expr",
"=",
"''",
",",
"$",
"with",
"=",
"''",
",",
"$",
"addValue",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"this",
"->",
"bindings",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"$",
"key",
"==",
"'sql'",
")",
"{",
"return",
"$",
"queryPart",
";",
"}",
"if",
"(",
"$",
"addValue",
"==",
"true",
")",
"{",
"$",
"this",
"->",
"bindings",
"[",
"$",
"key",
"]",
"=",
"$",
"queryPart",
";",
"}",
"return",
"$",
"this",
"->",
"$",
"key",
"(",
"$",
"queryPart",
",",
"$",
"params",
",",
"$",
"expr",
",",
"$",
"with",
",",
"$",
"addValue",
")",
";",
"}"
] | This method bindings together queries created with
the query builder.
@param $key <String>
@param $queryPart <Mixed>
@param $params <Mixed>
@param $expr <Mixed>
@param $with <Mixed>
@access public
@return <Mixed> | [
"This",
"method",
"bindings",
"together",
"queries",
"created",
"with",
"the",
"query",
"builder",
"."
] | 17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042 | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Query/Builder/QueryBinder.php#L90-L105 | train |
PhoxPHP/Glider | src/Query/Builder/QueryBinder.php | QueryBinder.alias | public function alias(String $column, String $alias)
{
// if (!$this->getBinding('select') || empty($this->getBinding('select'))) {
// Since this method cannot be used without the SELECT statement,
// we will throw an exception if `SELECT` binding is null or false.
// throw new RuntimeException(sprintf('Cannot call aggregate function on empty select.'));
// }
$alias = str_replace($this->generator->getDisallowedChars(), '', $alias);
return $this->attachSeparator($column . ' AS ' . $alias);
} | php | public function alias(String $column, String $alias)
{
// if (!$this->getBinding('select') || empty($this->getBinding('select'))) {
// Since this method cannot be used without the SELECT statement,
// we will throw an exception if `SELECT` binding is null or false.
// throw new RuntimeException(sprintf('Cannot call aggregate function on empty select.'));
// }
$alias = str_replace($this->generator->getDisallowedChars(), '', $alias);
return $this->attachSeparator($column . ' AS ' . $alias);
} | [
"public",
"function",
"alias",
"(",
"String",
"$",
"column",
",",
"String",
"$",
"alias",
")",
"{",
"// if (!$this->getBinding('select') || empty($this->getBinding('select'))) {",
"// Since this method cannot be used without the SELECT statement,",
"// we will throw an exception if `SELECT` binding is null or false. ",
"// throw new RuntimeException(sprintf('Cannot call aggregate function on empty select.'));",
"// }",
"$",
"alias",
"=",
"str_replace",
"(",
"$",
"this",
"->",
"generator",
"->",
"getDisallowedChars",
"(",
")",
",",
"''",
",",
"$",
"alias",
")",
";",
"return",
"$",
"this",
"->",
"attachSeparator",
"(",
"$",
"column",
".",
"' AS '",
".",
"$",
"alias",
")",
";",
"}"
] | Create and return alias for a column.
@param $column <String>
@param $alias <String>
@access public
@return <String> | [
"Create",
"and",
"return",
"alias",
"for",
"a",
"column",
"."
] | 17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042 | https://github.com/PhoxPHP/Glider/blob/17aaf3b7bb6e70ea3ae1f04e30a7690e884bf042/src/Query/Builder/QueryBinder.php#L125-L134 | train |
infusephp/auth | src/Libs/UserRegistration.php | UserRegistration.getTemporaryUser | public function getTemporaryUser($email)
{
$email = trim(strtolower($email));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
$userClass = $this->auth->getUserClass();
$user = $userClass::where('email', $email)->first();
if (!$user) {
return false;
}
if (!$user->isTemporary()) {
return false;
}
return $user;
} | php | public function getTemporaryUser($email)
{
$email = trim(strtolower($email));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
$userClass = $this->auth->getUserClass();
$user = $userClass::where('email', $email)->first();
if (!$user) {
return false;
}
if (!$user->isTemporary()) {
return false;
}
return $user;
} | [
"public",
"function",
"getTemporaryUser",
"(",
"$",
"email",
")",
"{",
"$",
"email",
"=",
"trim",
"(",
"strtolower",
"(",
"$",
"email",
")",
")",
";",
"if",
"(",
"!",
"filter_var",
"(",
"$",
"email",
",",
"FILTER_VALIDATE_EMAIL",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"userClass",
"=",
"$",
"this",
"->",
"auth",
"->",
"getUserClass",
"(",
")",
";",
"$",
"user",
"=",
"$",
"userClass",
"::",
"where",
"(",
"'email'",
",",
"$",
"email",
")",
"->",
"first",
"(",
")",
";",
"if",
"(",
"!",
"$",
"user",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"$",
"user",
"->",
"isTemporary",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"user",
";",
"}"
] | Gets a temporary user from an email address if one exists.
@param string $email email address
@return UserInterface|false | [
"Gets",
"a",
"temporary",
"user",
"from",
"an",
"email",
"address",
"if",
"one",
"exists",
"."
] | 720280b4b2635572f331afe8d082e3e88cf54eb7 | https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/UserRegistration.php#L72-L91 | train |
infusephp/auth | src/Libs/UserRegistration.php | UserRegistration.createTemporaryUser | public function createTemporaryUser($parameters)
{
$email = trim(strtolower(array_value($parameters, 'email')));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new AuthException('Invalid email address');
}
$insertArray = array_replace($parameters, ['enabled' => false]);
// create the temporary user
$userClass = $this->auth->getUserClass();
$user = new $userClass();
$driver = $userClass::getDriver();
$created = $driver->createModel($user, $insertArray);
if (!$created) {
throw new AuthException('Could not create temporary user');
}
// get the new user ID
$id = [];
foreach ($userClass::getIDProperties() as $k) {
$id[] = $driver->getCreatedID($user, $k);
}
$user = $userClass::find($id);
// create the temporary link
$link = new UserLink();
$link->user_id = $user->id();
$link->type = UserLink::TEMPORARY;
$link->saveOrFail();
$user->setTemporaryLink($link);
return $user;
} | php | public function createTemporaryUser($parameters)
{
$email = trim(strtolower(array_value($parameters, 'email')));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new AuthException('Invalid email address');
}
$insertArray = array_replace($parameters, ['enabled' => false]);
// create the temporary user
$userClass = $this->auth->getUserClass();
$user = new $userClass();
$driver = $userClass::getDriver();
$created = $driver->createModel($user, $insertArray);
if (!$created) {
throw new AuthException('Could not create temporary user');
}
// get the new user ID
$id = [];
foreach ($userClass::getIDProperties() as $k) {
$id[] = $driver->getCreatedID($user, $k);
}
$user = $userClass::find($id);
// create the temporary link
$link = new UserLink();
$link->user_id = $user->id();
$link->type = UserLink::TEMPORARY;
$link->saveOrFail();
$user->setTemporaryLink($link);
return $user;
} | [
"public",
"function",
"createTemporaryUser",
"(",
"$",
"parameters",
")",
"{",
"$",
"email",
"=",
"trim",
"(",
"strtolower",
"(",
"array_value",
"(",
"$",
"parameters",
",",
"'email'",
")",
")",
")",
";",
"if",
"(",
"!",
"filter_var",
"(",
"$",
"email",
",",
"FILTER_VALIDATE_EMAIL",
")",
")",
"{",
"throw",
"new",
"AuthException",
"(",
"'Invalid email address'",
")",
";",
"}",
"$",
"insertArray",
"=",
"array_replace",
"(",
"$",
"parameters",
",",
"[",
"'enabled'",
"=>",
"false",
"]",
")",
";",
"// create the temporary user",
"$",
"userClass",
"=",
"$",
"this",
"->",
"auth",
"->",
"getUserClass",
"(",
")",
";",
"$",
"user",
"=",
"new",
"$",
"userClass",
"(",
")",
";",
"$",
"driver",
"=",
"$",
"userClass",
"::",
"getDriver",
"(",
")",
";",
"$",
"created",
"=",
"$",
"driver",
"->",
"createModel",
"(",
"$",
"user",
",",
"$",
"insertArray",
")",
";",
"if",
"(",
"!",
"$",
"created",
")",
"{",
"throw",
"new",
"AuthException",
"(",
"'Could not create temporary user'",
")",
";",
"}",
"// get the new user ID",
"$",
"id",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"userClass",
"::",
"getIDProperties",
"(",
")",
"as",
"$",
"k",
")",
"{",
"$",
"id",
"[",
"]",
"=",
"$",
"driver",
"->",
"getCreatedID",
"(",
"$",
"user",
",",
"$",
"k",
")",
";",
"}",
"$",
"user",
"=",
"$",
"userClass",
"::",
"find",
"(",
"$",
"id",
")",
";",
"// create the temporary link",
"$",
"link",
"=",
"new",
"UserLink",
"(",
")",
";",
"$",
"link",
"->",
"user_id",
"=",
"$",
"user",
"->",
"id",
"(",
")",
";",
"$",
"link",
"->",
"type",
"=",
"UserLink",
"::",
"TEMPORARY",
";",
"$",
"link",
"->",
"saveOrFail",
"(",
")",
";",
"$",
"user",
"->",
"setTemporaryLink",
"(",
"$",
"link",
")",
";",
"return",
"$",
"user",
";",
"}"
] | Creates a temporary user. Useful for creating invites.
@param array $parameters user data
@throws AuthException when the user cannot be created.
@return UserInterface temporary user | [
"Creates",
"a",
"temporary",
"user",
".",
"Useful",
"for",
"creating",
"invites",
"."
] | 720280b4b2635572f331afe8d082e3e88cf54eb7 | https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/UserRegistration.php#L102-L137 | train |
infusephp/auth | src/Libs/UserRegistration.php | UserRegistration.upgradeTemporaryUser | public function upgradeTemporaryUser(UserInterface $user, $values = [])
{
if (!$user->isTemporary()) {
throw new AuthException('Cannot upgrade a non-temporary account');
}
$values = array_replace($values, [
'created_at' => Utility::unixToDb(time()),
'enabled' => true,
]);
$user->grantAllPermissions();
if (!$user->set($values)) {
$user->enforcePermissions();
throw new AuthException('Could not upgrade temporary account: '.implode($user->getErrors()->all()));
}
// remove temporary and unverified links
$app = $user->getApp();
$app['database']->getDefault()
->delete('UserLinks')
->where('user_id', $user->id())
->where(function ($query) {
return $query->where('type', UserLink::TEMPORARY)
->orWhere('type', UserLink::VERIFY_EMAIL);
})
->execute();
$user->clearTemporaryLink();
// send the user a welcome message
$user->sendEmail('welcome');
$user->enforcePermissions();
return $this;
} | php | public function upgradeTemporaryUser(UserInterface $user, $values = [])
{
if (!$user->isTemporary()) {
throw new AuthException('Cannot upgrade a non-temporary account');
}
$values = array_replace($values, [
'created_at' => Utility::unixToDb(time()),
'enabled' => true,
]);
$user->grantAllPermissions();
if (!$user->set($values)) {
$user->enforcePermissions();
throw new AuthException('Could not upgrade temporary account: '.implode($user->getErrors()->all()));
}
// remove temporary and unverified links
$app = $user->getApp();
$app['database']->getDefault()
->delete('UserLinks')
->where('user_id', $user->id())
->where(function ($query) {
return $query->where('type', UserLink::TEMPORARY)
->orWhere('type', UserLink::VERIFY_EMAIL);
})
->execute();
$user->clearTemporaryLink();
// send the user a welcome message
$user->sendEmail('welcome');
$user->enforcePermissions();
return $this;
} | [
"public",
"function",
"upgradeTemporaryUser",
"(",
"UserInterface",
"$",
"user",
",",
"$",
"values",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"user",
"->",
"isTemporary",
"(",
")",
")",
"{",
"throw",
"new",
"AuthException",
"(",
"'Cannot upgrade a non-temporary account'",
")",
";",
"}",
"$",
"values",
"=",
"array_replace",
"(",
"$",
"values",
",",
"[",
"'created_at'",
"=>",
"Utility",
"::",
"unixToDb",
"(",
"time",
"(",
")",
")",
",",
"'enabled'",
"=>",
"true",
",",
"]",
")",
";",
"$",
"user",
"->",
"grantAllPermissions",
"(",
")",
";",
"if",
"(",
"!",
"$",
"user",
"->",
"set",
"(",
"$",
"values",
")",
")",
"{",
"$",
"user",
"->",
"enforcePermissions",
"(",
")",
";",
"throw",
"new",
"AuthException",
"(",
"'Could not upgrade temporary account: '",
".",
"implode",
"(",
"$",
"user",
"->",
"getErrors",
"(",
")",
"->",
"all",
"(",
")",
")",
")",
";",
"}",
"// remove temporary and unverified links",
"$",
"app",
"=",
"$",
"user",
"->",
"getApp",
"(",
")",
";",
"$",
"app",
"[",
"'database'",
"]",
"->",
"getDefault",
"(",
")",
"->",
"delete",
"(",
"'UserLinks'",
")",
"->",
"where",
"(",
"'user_id'",
",",
"$",
"user",
"->",
"id",
"(",
")",
")",
"->",
"where",
"(",
"function",
"(",
"$",
"query",
")",
"{",
"return",
"$",
"query",
"->",
"where",
"(",
"'type'",
",",
"UserLink",
"::",
"TEMPORARY",
")",
"->",
"orWhere",
"(",
"'type'",
",",
"UserLink",
"::",
"VERIFY_EMAIL",
")",
";",
"}",
")",
"->",
"execute",
"(",
")",
";",
"$",
"user",
"->",
"clearTemporaryLink",
"(",
")",
";",
"// send the user a welcome message",
"$",
"user",
"->",
"sendEmail",
"(",
"'welcome'",
")",
";",
"$",
"user",
"->",
"enforcePermissions",
"(",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Upgrades the user from temporary to a fully registered account.
@param UserInterface $user
@param array $values properties to set on user model
@throws AuthException when the upgrade fails.
@return $this | [
"Upgrades",
"the",
"user",
"from",
"temporary",
"to",
"a",
"fully",
"registered",
"account",
"."
] | 720280b4b2635572f331afe8d082e3e88cf54eb7 | https://github.com/infusephp/auth/blob/720280b4b2635572f331afe8d082e3e88cf54eb7/src/Libs/UserRegistration.php#L149-L186 | train |
atelierdisko/cute_php | src/Worker.php | Worker.dispatch | public function dispatch() {
while (true) {
if ($this->_break) {
break;
}
if ($this->_paused) {
$this->_title('Paused, waiting');
$this->_log->debug('Paused, waiting.');
}
while ($this->_paused) {
pcntl_signal_dispatch();
sleep($this->_interval);
}
$this->_title('Waiting for job');
$this->_log->debug('Waiting for job.');
while (!$this->_job) {
// FIXME Catch exception. but only handler exceptions.
$this->_job = $this->_connection->reserve($this->_queues, 5);
pcntl_signal_dispatch();
}
$this->_title("Performing job {$this->_job}");
$this->_log->debug("Performing job {$this->_job}.");
try {
if ($this->_job->perform()) {
$this->_job->succeed();
} else {
$this->_job->fail();
}
} catch (Exception $e) {
$this->_log->notice(get_class($e) . ' while performing job: ' . $e->getMessage());
$this->_job->fail();
}
$this->_job = null;
}
} | php | public function dispatch() {
while (true) {
if ($this->_break) {
break;
}
if ($this->_paused) {
$this->_title('Paused, waiting');
$this->_log->debug('Paused, waiting.');
}
while ($this->_paused) {
pcntl_signal_dispatch();
sleep($this->_interval);
}
$this->_title('Waiting for job');
$this->_log->debug('Waiting for job.');
while (!$this->_job) {
// FIXME Catch exception. but only handler exceptions.
$this->_job = $this->_connection->reserve($this->_queues, 5);
pcntl_signal_dispatch();
}
$this->_title("Performing job {$this->_job}");
$this->_log->debug("Performing job {$this->_job}.");
try {
if ($this->_job->perform()) {
$this->_job->succeed();
} else {
$this->_job->fail();
}
} catch (Exception $e) {
$this->_log->notice(get_class($e) . ' while performing job: ' . $e->getMessage());
$this->_job->fail();
}
$this->_job = null;
}
} | [
"public",
"function",
"dispatch",
"(",
")",
"{",
"while",
"(",
"true",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_break",
")",
"{",
"break",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"_paused",
")",
"{",
"$",
"this",
"->",
"_title",
"(",
"'Paused, waiting'",
")",
";",
"$",
"this",
"->",
"_log",
"->",
"debug",
"(",
"'Paused, waiting.'",
")",
";",
"}",
"while",
"(",
"$",
"this",
"->",
"_paused",
")",
"{",
"pcntl_signal_dispatch",
"(",
")",
";",
"sleep",
"(",
"$",
"this",
"->",
"_interval",
")",
";",
"}",
"$",
"this",
"->",
"_title",
"(",
"'Waiting for job'",
")",
";",
"$",
"this",
"->",
"_log",
"->",
"debug",
"(",
"'Waiting for job.'",
")",
";",
"while",
"(",
"!",
"$",
"this",
"->",
"_job",
")",
"{",
"// FIXME Catch exception. but only handler exceptions.",
"$",
"this",
"->",
"_job",
"=",
"$",
"this",
"->",
"_connection",
"->",
"reserve",
"(",
"$",
"this",
"->",
"_queues",
",",
"5",
")",
";",
"pcntl_signal_dispatch",
"(",
")",
";",
"}",
"$",
"this",
"->",
"_title",
"(",
"\"Performing job {$this->_job}\"",
")",
";",
"$",
"this",
"->",
"_log",
"->",
"debug",
"(",
"\"Performing job {$this->_job}.\"",
")",
";",
"try",
"{",
"if",
"(",
"$",
"this",
"->",
"_job",
"->",
"perform",
"(",
")",
")",
"{",
"$",
"this",
"->",
"_job",
"->",
"succeed",
"(",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"_job",
"->",
"fail",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"$",
"this",
"->",
"_log",
"->",
"notice",
"(",
"get_class",
"(",
"$",
"e",
")",
".",
"' while performing job: '",
".",
"$",
"e",
"->",
"getMessage",
"(",
")",
")",
";",
"$",
"this",
"->",
"_job",
"->",
"fail",
"(",
")",
";",
"}",
"$",
"this",
"->",
"_job",
"=",
"null",
";",
"}",
"}"
] | Main method to start processing loop and dispatch jobs.
@return boolean | [
"Main",
"method",
"to",
"start",
"processing",
"loop",
"and",
"dispatch",
"jobs",
"."
] | 0302ed6f819794ed57a6663361ae4527aa05e183 | https://github.com/atelierdisko/cute_php/blob/0302ed6f819794ed57a6663361ae4527aa05e183/src/Worker.php#L118-L155 | train |
atelierdisko/cute_php | src/Worker.php | Worker._trapSignals | protected function _trapSignals() {
$this->_log->debug('Trapping signals.');
$handler = function($number) {
switch ($number) {
case SIGQUIT:
$this->_log->debug('Received SIGQUIT, waiting and exiting.');
$this->_break = true;
$this->_connection->disconnect();
exit(0);
case SIGINT:
case SIGTERM:
$this->_log->debug('Received SIGTERM/SIGINT, killing exiting.');
$this->_connection->disconnect();
exit(1);
case SIGUSR2:
$this->_log->debug('Received SIGUSR2, pausing job processing.');
$this->_paused = true;
$this->_interval = 10;
break;
case SIGCONT:
$this->_log->debug('Received SIGCONT, continuing to process jobs.');
$this->_paused = false;
$this->_interval = null;
break;
}
};
pcntl_signal(SIGQUIT, $handler);
pcntl_signal(SIGINT, $handler);
pcntl_signal(SIGTERM, $handler);
pcntl_signal(SIGUSR2, $handler);
pcntl_signal(SIGCONT, $handler);
} | php | protected function _trapSignals() {
$this->_log->debug('Trapping signals.');
$handler = function($number) {
switch ($number) {
case SIGQUIT:
$this->_log->debug('Received SIGQUIT, waiting and exiting.');
$this->_break = true;
$this->_connection->disconnect();
exit(0);
case SIGINT:
case SIGTERM:
$this->_log->debug('Received SIGTERM/SIGINT, killing exiting.');
$this->_connection->disconnect();
exit(1);
case SIGUSR2:
$this->_log->debug('Received SIGUSR2, pausing job processing.');
$this->_paused = true;
$this->_interval = 10;
break;
case SIGCONT:
$this->_log->debug('Received SIGCONT, continuing to process jobs.');
$this->_paused = false;
$this->_interval = null;
break;
}
};
pcntl_signal(SIGQUIT, $handler);
pcntl_signal(SIGINT, $handler);
pcntl_signal(SIGTERM, $handler);
pcntl_signal(SIGUSR2, $handler);
pcntl_signal(SIGCONT, $handler);
} | [
"protected",
"function",
"_trapSignals",
"(",
")",
"{",
"$",
"this",
"->",
"_log",
"->",
"debug",
"(",
"'Trapping signals.'",
")",
";",
"$",
"handler",
"=",
"function",
"(",
"$",
"number",
")",
"{",
"switch",
"(",
"$",
"number",
")",
"{",
"case",
"SIGQUIT",
":",
"$",
"this",
"->",
"_log",
"->",
"debug",
"(",
"'Received SIGQUIT, waiting and exiting.'",
")",
";",
"$",
"this",
"->",
"_break",
"=",
"true",
";",
"$",
"this",
"->",
"_connection",
"->",
"disconnect",
"(",
")",
";",
"exit",
"(",
"0",
")",
";",
"case",
"SIGINT",
":",
"case",
"SIGTERM",
":",
"$",
"this",
"->",
"_log",
"->",
"debug",
"(",
"'Received SIGTERM/SIGINT, killing exiting.'",
")",
";",
"$",
"this",
"->",
"_connection",
"->",
"disconnect",
"(",
")",
";",
"exit",
"(",
"1",
")",
";",
"case",
"SIGUSR2",
":",
"$",
"this",
"->",
"_log",
"->",
"debug",
"(",
"'Received SIGUSR2, pausing job processing.'",
")",
";",
"$",
"this",
"->",
"_paused",
"=",
"true",
";",
"$",
"this",
"->",
"_interval",
"=",
"10",
";",
"break",
";",
"case",
"SIGCONT",
":",
"$",
"this",
"->",
"_log",
"->",
"debug",
"(",
"'Received SIGCONT, continuing to process jobs.'",
")",
";",
"$",
"this",
"->",
"_paused",
"=",
"false",
";",
"$",
"this",
"->",
"_interval",
"=",
"null",
";",
"break",
";",
"}",
"}",
";",
"pcntl_signal",
"(",
"SIGQUIT",
",",
"$",
"handler",
")",
";",
"pcntl_signal",
"(",
"SIGINT",
",",
"$",
"handler",
")",
";",
"pcntl_signal",
"(",
"SIGTERM",
",",
"$",
"handler",
")",
";",
"pcntl_signal",
"(",
"SIGUSR2",
",",
"$",
"handler",
")",
";",
"pcntl_signal",
"(",
"SIGCONT",
",",
"$",
"handler",
")",
";",
"}"
] | Registers signal handlers and handles signals once received.
Controls the current processing loop by setting object properties
and using the process manager.
@return void | [
"Registers",
"signal",
"handlers",
"and",
"handles",
"signals",
"once",
"received",
".",
"Controls",
"the",
"current",
"processing",
"loop",
"by",
"setting",
"object",
"properties",
"and",
"using",
"the",
"process",
"manager",
"."
] | 0302ed6f819794ed57a6663361ae4527aa05e183 | https://github.com/atelierdisko/cute_php/blob/0302ed6f819794ed57a6663361ae4527aa05e183/src/Worker.php#L164-L199 | train |
SpoonX/SxCore | library/SxCore/Html/HtmlElement.php | HtmlElement.getAttribute | public function getAttribute($attribute)
{
return !empty($this->attributes[$attribute]) ? $this->attributes[$attribute] : null;
} | php | public function getAttribute($attribute)
{
return !empty($this->attributes[$attribute]) ? $this->attributes[$attribute] : null;
} | [
"public",
"function",
"getAttribute",
"(",
"$",
"attribute",
")",
"{",
"return",
"!",
"empty",
"(",
"$",
"this",
"->",
"attributes",
"[",
"$",
"attribute",
"]",
")",
"?",
"$",
"this",
"->",
"attributes",
"[",
"$",
"attribute",
"]",
":",
"null",
";",
"}"
] | Get a specific attribute for this tag.
@param string @attribute
@return string|null | [
"Get",
"a",
"specific",
"attribute",
"for",
"this",
"tag",
"."
] | 8f914e3737826c408443d6d458dd9a169c82c940 | https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L243-L246 | train |
SpoonX/SxCore | library/SxCore/Html/HtmlElement.php | HtmlElement.appendContent | public function appendContent($content)
{
if ($this->isVoid) {
throw new Exception\RuntimeException(
'Void elements can\'t contain content.'
);
}
$this->content .= $content;
return $this;
} | php | public function appendContent($content)
{
if ($this->isVoid) {
throw new Exception\RuntimeException(
'Void elements can\'t contain content.'
);
}
$this->content .= $content;
return $this;
} | [
"public",
"function",
"appendContent",
"(",
"$",
"content",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isVoid",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"RuntimeException",
"(",
"'Void elements can\\'t contain content.'",
")",
";",
"}",
"$",
"this",
"->",
"content",
".=",
"$",
"content",
";",
"return",
"$",
"this",
";",
"}"
] | Append content before other content
@param string $content
@throws Exception\RuntimeException
@return \SxCore\Html\HtmlElement | [
"Append",
"content",
"before",
"other",
"content"
] | 8f914e3737826c408443d6d458dd9a169c82c940 | https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L293-L304 | train |
SpoonX/SxCore | library/SxCore/Html/HtmlElement.php | HtmlElement.prependContent | public function prependContent($content)
{
if ($this->isVoid) {
throw new Exception\RuntimeException(
'Void elements can\'t contain content.'
);
}
$this->content = $content . $this->content;
return $this;
} | php | public function prependContent($content)
{
if ($this->isVoid) {
throw new Exception\RuntimeException(
'Void elements can\'t contain content.'
);
}
$this->content = $content . $this->content;
return $this;
} | [
"public",
"function",
"prependContent",
"(",
"$",
"content",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isVoid",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"RuntimeException",
"(",
"'Void elements can\\'t contain content.'",
")",
";",
"}",
"$",
"this",
"->",
"content",
"=",
"$",
"content",
".",
"$",
"this",
"->",
"content",
";",
"return",
"$",
"this",
";",
"}"
] | Prepend content before other content
@param string $content
@throws Exception\RuntimeException
@return \SxCore\Html\HtmlElement | [
"Prepend",
"content",
"before",
"other",
"content"
] | 8f914e3737826c408443d6d458dd9a169c82c940 | https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L314-L325 | train |
SpoonX/SxCore | library/SxCore/Html/HtmlElement.php | HtmlElement.addChild | public function addChild(self $child)
{
if ($this->isVoid) {
throw new Exception\RuntimeException(
'Void elements can\'t have child elements.'
);
}
$this->children[] = $child;
return $this;
} | php | public function addChild(self $child)
{
if ($this->isVoid) {
throw new Exception\RuntimeException(
'Void elements can\'t have child elements.'
);
}
$this->children[] = $child;
return $this;
} | [
"public",
"function",
"addChild",
"(",
"self",
"$",
"child",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isVoid",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"RuntimeException",
"(",
"'Void elements can\\'t have child elements.'",
")",
";",
"}",
"$",
"this",
"->",
"children",
"[",
"]",
"=",
"$",
"child",
";",
"return",
"$",
"this",
";",
"}"
] | Add child to tag
@param \SxCore\Html\HtmlElement $child
@throws Exception\RuntimeException
@return \SxCore\Html\HtmlElement | [
"Add",
"child",
"to",
"tag"
] | 8f914e3737826c408443d6d458dd9a169c82c940 | https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L376-L387 | train |
SpoonX/SxCore | library/SxCore/Html/HtmlElement.php | HtmlElement.addChildren | public function addChildren(array $children)
{
if ($this->isVoid) {
throw new Exception\RuntimeException(
'Void elements can\'t have child elements.'
);
}
foreach ($children as $child) {
$this->addChild($child);
}
return $this;
} | php | public function addChildren(array $children)
{
if ($this->isVoid) {
throw new Exception\RuntimeException(
'Void elements can\'t have child elements.'
);
}
foreach ($children as $child) {
$this->addChild($child);
}
return $this;
} | [
"public",
"function",
"addChildren",
"(",
"array",
"$",
"children",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isVoid",
")",
"{",
"throw",
"new",
"Exception",
"\\",
"RuntimeException",
"(",
"'Void elements can\\'t have child elements.'",
")",
";",
"}",
"foreach",
"(",
"$",
"children",
"as",
"$",
"child",
")",
"{",
"$",
"this",
"->",
"addChild",
"(",
"$",
"child",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Add children to tag
@param array $children
@throws Exception\RuntimeException
@return \SxCore\Html\HtmlElement | [
"Add",
"children",
"to",
"tag"
] | 8f914e3737826c408443d6d458dd9a169c82c940 | https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L397-L410 | train |
SpoonX/SxCore | library/SxCore/Html/HtmlElement.php | HtmlElement.renderAttributes | protected function renderAttributes()
{
$attributes = '';
foreach ($this->attributes as $key => $value) {
$attributes .= " $key" . (null !== $value ? "=\"$value\"" : '');
}
return $attributes;
} | php | protected function renderAttributes()
{
$attributes = '';
foreach ($this->attributes as $key => $value) {
$attributes .= " $key" . (null !== $value ? "=\"$value\"" : '');
}
return $attributes;
} | [
"protected",
"function",
"renderAttributes",
"(",
")",
"{",
"$",
"attributes",
"=",
"''",
";",
"foreach",
"(",
"$",
"this",
"->",
"attributes",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"attributes",
".=",
"\" $key\"",
".",
"(",
"null",
"!==",
"$",
"value",
"?",
"\"=\\\"$value\\\"\"",
":",
"''",
")",
";",
"}",
"return",
"$",
"attributes",
";",
"}"
] | Render tag attributes
@return string | [
"Render",
"tag",
"attributes"
] | 8f914e3737826c408443d6d458dd9a169c82c940 | https://github.com/SpoonX/SxCore/blob/8f914e3737826c408443d6d458dd9a169c82c940/library/SxCore/Html/HtmlElement.php#L515-L524 | train |
ekyna/AdminBundle | Menu/MenuGroup.php | MenuGroup.addEntry | public function addEntry(MenuEntry $entry)
{
if ($this->prepared) {
throw new \RuntimeException('MenuGroup has been prepared and can\'t receive new entries.');
}
$this->entries[] = $entry;
return $this;
} | php | public function addEntry(MenuEntry $entry)
{
if ($this->prepared) {
throw new \RuntimeException('MenuGroup has been prepared and can\'t receive new entries.');
}
$this->entries[] = $entry;
return $this;
} | [
"public",
"function",
"addEntry",
"(",
"MenuEntry",
"$",
"entry",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"prepared",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'MenuGroup has been prepared and can\\'t receive new entries.'",
")",
";",
"}",
"$",
"this",
"->",
"entries",
"[",
"]",
"=",
"$",
"entry",
";",
"return",
"$",
"this",
";",
"}"
] | Adds an entry.
@param MenuEntry $entry
@throws \RuntimeException
@return MenuGroup | [
"Adds",
"an",
"entry",
"."
] | 3f58e253ae9cf651add7f3d587caec80eaea459a | https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Menu/MenuGroup.php#L236-L244 | train |
ekyna/AdminBundle | Menu/MenuGroup.php | MenuGroup.prepare | public function prepare()
{
if ($this->prepared) {
return;
}
usort($this->entries, function(MenuEntry $a, MenuEntry $b) {
if ($a->getPosition() == $b->getPosition()) {
return 0;
}
return $a->getPosition() > $b->getPosition() ? 1 : -1;
});
$this->prepared = true;
} | php | public function prepare()
{
if ($this->prepared) {
return;
}
usort($this->entries, function(MenuEntry $a, MenuEntry $b) {
if ($a->getPosition() == $b->getPosition()) {
return 0;
}
return $a->getPosition() > $b->getPosition() ? 1 : -1;
});
$this->prepared = true;
} | [
"public",
"function",
"prepare",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"prepared",
")",
"{",
"return",
";",
"}",
"usort",
"(",
"$",
"this",
"->",
"entries",
",",
"function",
"(",
"MenuEntry",
"$",
"a",
",",
"MenuEntry",
"$",
"b",
")",
"{",
"if",
"(",
"$",
"a",
"->",
"getPosition",
"(",
")",
"==",
"$",
"b",
"->",
"getPosition",
"(",
")",
")",
"{",
"return",
"0",
";",
"}",
"return",
"$",
"a",
"->",
"getPosition",
"(",
")",
">",
"$",
"b",
"->",
"getPosition",
"(",
")",
"?",
"1",
":",
"-",
"1",
";",
"}",
")",
";",
"$",
"this",
"->",
"prepared",
"=",
"true",
";",
"}"
] | Prepares the group for rendering. | [
"Prepares",
"the",
"group",
"for",
"rendering",
"."
] | 3f58e253ae9cf651add7f3d587caec80eaea459a | https://github.com/ekyna/AdminBundle/blob/3f58e253ae9cf651add7f3d587caec80eaea459a/Menu/MenuGroup.php#L259-L271 | train |
armazon/armazon | src/Armazon/Sesion/Manejador.php | Manejador.generarId | private function generarId()
{
if (function_exists('random_bytes')) {
$semilla = random_bytes(32);
} elseif (function_exists('mcrypt_create_iv')) {
$semilla = mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
$semilla = openssl_random_pseudo_bytes(32);
} else {
$semilla = uniqid('armazon', true);
}
return hash('sha256', $semilla);
} | php | private function generarId()
{
if (function_exists('random_bytes')) {
$semilla = random_bytes(32);
} elseif (function_exists('mcrypt_create_iv')) {
$semilla = mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
$semilla = openssl_random_pseudo_bytes(32);
} else {
$semilla = uniqid('armazon', true);
}
return hash('sha256', $semilla);
} | [
"private",
"function",
"generarId",
"(",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'random_bytes'",
")",
")",
"{",
"$",
"semilla",
"=",
"random_bytes",
"(",
"32",
")",
";",
"}",
"elseif",
"(",
"function_exists",
"(",
"'mcrypt_create_iv'",
")",
")",
"{",
"$",
"semilla",
"=",
"mcrypt_create_iv",
"(",
"32",
",",
"MCRYPT_DEV_URANDOM",
")",
";",
"}",
"elseif",
"(",
"function_exists",
"(",
"'openssl_random_pseudo_bytes'",
")",
")",
"{",
"$",
"semilla",
"=",
"openssl_random_pseudo_bytes",
"(",
"32",
")",
";",
"}",
"else",
"{",
"$",
"semilla",
"=",
"uniqid",
"(",
"'armazon'",
",",
"true",
")",
";",
"}",
"return",
"hash",
"(",
"'sha256'",
",",
"$",
"semilla",
")",
";",
"}"
] | Genera un identificador nuevo usando una semilla aleatoria
@return string | [
"Genera",
"un",
"identificador",
"nuevo",
"usando",
"una",
"semilla",
"aleatoria"
] | ec76385ff80ce1659d81bc4050ef9483ab0ebe52 | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Sesion/Manejador.php#L34-L47 | train |
armazon/armazon | src/Armazon/Sesion/Manejador.php | Manejador.anunciar | public function anunciar($mensaje, $tipo = 'error')
{
$this->requerirInicio();
$this->datos['__anuncio']['mensaje'] = $mensaje;
$this->datos['__anuncio']['tipo'] = $tipo;
} | php | public function anunciar($mensaje, $tipo = 'error')
{
$this->requerirInicio();
$this->datos['__anuncio']['mensaje'] = $mensaje;
$this->datos['__anuncio']['tipo'] = $tipo;
} | [
"public",
"function",
"anunciar",
"(",
"$",
"mensaje",
",",
"$",
"tipo",
"=",
"'error'",
")",
"{",
"$",
"this",
"->",
"requerirInicio",
"(",
")",
";",
"$",
"this",
"->",
"datos",
"[",
"'__anuncio'",
"]",
"[",
"'mensaje'",
"]",
"=",
"$",
"mensaje",
";",
"$",
"this",
"->",
"datos",
"[",
"'__anuncio'",
"]",
"[",
"'tipo'",
"]",
"=",
"$",
"tipo",
";",
"}"
] | Define anuncio importante para el usuario.
@param string $mensaje
@param string $tipo | [
"Define",
"anuncio",
"importante",
"para",
"el",
"usuario",
"."
] | ec76385ff80ce1659d81bc4050ef9483ab0ebe52 | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Sesion/Manejador.php#L126-L132 | train |
armazon/armazon | src/Armazon/Sesion/Manejador.php | Manejador.obtener | public function obtener($llave, $valorAlterno = null)
{
$this->requerirInicio();
return isset($this->datos[$llave]) ? $this->datos[$llave] : $valorAlterno;
} | php | public function obtener($llave, $valorAlterno = null)
{
$this->requerirInicio();
return isset($this->datos[$llave]) ? $this->datos[$llave] : $valorAlterno;
} | [
"public",
"function",
"obtener",
"(",
"$",
"llave",
",",
"$",
"valorAlterno",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"requerirInicio",
"(",
")",
";",
"return",
"isset",
"(",
"$",
"this",
"->",
"datos",
"[",
"$",
"llave",
"]",
")",
"?",
"$",
"this",
"->",
"datos",
"[",
"$",
"llave",
"]",
":",
"$",
"valorAlterno",
";",
"}"
] | Obtiene una variable de la sesion.
@param string $llave
@param mixed $valorAlterno
@return mixed | [
"Obtiene",
"una",
"variable",
"de",
"la",
"sesion",
"."
] | ec76385ff80ce1659d81bc4050ef9483ab0ebe52 | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Sesion/Manejador.php#L167-L172 | train |
armazon/armazon | src/Armazon/Sesion/Manejador.php | Manejador.eliminar | public function eliminar($llave)
{
$this->requerirInicio();
if (isset($this->datos[$llave])) {
$valor = $this->datos[$llave];
unset($this->datos[$llave]);
return $valor;
} else {
return null;
}
} | php | public function eliminar($llave)
{
$this->requerirInicio();
if (isset($this->datos[$llave])) {
$valor = $this->datos[$llave];
unset($this->datos[$llave]);
return $valor;
} else {
return null;
}
} | [
"public",
"function",
"eliminar",
"(",
"$",
"llave",
")",
"{",
"$",
"this",
"->",
"requerirInicio",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"datos",
"[",
"$",
"llave",
"]",
")",
")",
"{",
"$",
"valor",
"=",
"$",
"this",
"->",
"datos",
"[",
"$",
"llave",
"]",
";",
"unset",
"(",
"$",
"this",
"->",
"datos",
"[",
"$",
"llave",
"]",
")",
";",
"return",
"$",
"valor",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] | Elimina una variable en la sesion.
@param string $llave
@return mixed el valor de la variable eliminada o nulo si no existe variable | [
"Elimina",
"una",
"variable",
"en",
"la",
"sesion",
"."
] | ec76385ff80ce1659d81bc4050ef9483ab0ebe52 | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Sesion/Manejador.php#L194-L205 | train |
chilimatic/chilimatic-framework | lib/route/parser/UrlParser.php | UrlParser.parse | public function parse($content)
{
// if there is no path it's not needed to try to get a clean one
if (empty($content)) return [];
$path = $this->getCleanPath($content);
$pathParts = [$this->delimiter];
// check if there is even a need for further checks
if (mb_strpos($path, $this->delimiter) === false) {
if (!$path) {
return [$this->delimiter];
}
// set the root and the path
$tmpPathParts = [
$this->delimiter,
$path
];
return $tmpPathParts;
}
// if there's a deeper path it's time to walk through it and clean the empty parts etc
$tmpPathParts = explode($this->delimiter, $path);
// walk through the array and remove the empty entries
for ($i = 0, $c = count($tmpPathParts); $i < $c; $i++) {
if (!$tmpPathParts[$i]) unset($tmpPathParts[$i]);
}
// prepend the default delimiter
$pathParts = array_merge($pathParts, $tmpPathParts);
// path parts
return $pathParts;
} | php | public function parse($content)
{
// if there is no path it's not needed to try to get a clean one
if (empty($content)) return [];
$path = $this->getCleanPath($content);
$pathParts = [$this->delimiter];
// check if there is even a need for further checks
if (mb_strpos($path, $this->delimiter) === false) {
if (!$path) {
return [$this->delimiter];
}
// set the root and the path
$tmpPathParts = [
$this->delimiter,
$path
];
return $tmpPathParts;
}
// if there's a deeper path it's time to walk through it and clean the empty parts etc
$tmpPathParts = explode($this->delimiter, $path);
// walk through the array and remove the empty entries
for ($i = 0, $c = count($tmpPathParts); $i < $c; $i++) {
if (!$tmpPathParts[$i]) unset($tmpPathParts[$i]);
}
// prepend the default delimiter
$pathParts = array_merge($pathParts, $tmpPathParts);
// path parts
return $pathParts;
} | [
"public",
"function",
"parse",
"(",
"$",
"content",
")",
"{",
"// if there is no path it's not needed to try to get a clean one",
"if",
"(",
"empty",
"(",
"$",
"content",
")",
")",
"return",
"[",
"]",
";",
"$",
"path",
"=",
"$",
"this",
"->",
"getCleanPath",
"(",
"$",
"content",
")",
";",
"$",
"pathParts",
"=",
"[",
"$",
"this",
"->",
"delimiter",
"]",
";",
"// check if there is even a need for further checks",
"if",
"(",
"mb_strpos",
"(",
"$",
"path",
",",
"$",
"this",
"->",
"delimiter",
")",
"===",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"path",
")",
"{",
"return",
"[",
"$",
"this",
"->",
"delimiter",
"]",
";",
"}",
"// set the root and the path",
"$",
"tmpPathParts",
"=",
"[",
"$",
"this",
"->",
"delimiter",
",",
"$",
"path",
"]",
";",
"return",
"$",
"tmpPathParts",
";",
"}",
"// if there's a deeper path it's time to walk through it and clean the empty parts etc",
"$",
"tmpPathParts",
"=",
"explode",
"(",
"$",
"this",
"->",
"delimiter",
",",
"$",
"path",
")",
";",
"// walk through the array and remove the empty entries",
"for",
"(",
"$",
"i",
"=",
"0",
",",
"$",
"c",
"=",
"count",
"(",
"$",
"tmpPathParts",
")",
";",
"$",
"i",
"<",
"$",
"c",
";",
"$",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"$",
"tmpPathParts",
"[",
"$",
"i",
"]",
")",
"unset",
"(",
"$",
"tmpPathParts",
"[",
"$",
"i",
"]",
")",
";",
"}",
"// prepend the default delimiter",
"$",
"pathParts",
"=",
"array_merge",
"(",
"$",
"pathParts",
",",
"$",
"tmpPathParts",
")",
";",
"// path parts",
"return",
"$",
"pathParts",
";",
"}"
] | parse method that fills the collection
@param string $content
@return array | [
"parse",
"method",
"that",
"fills",
"the",
"collection"
] | 8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12 | https://github.com/chilimatic/chilimatic-framework/blob/8df7f12e75d75d3fd2197a58c80d39cbb4b9ff12/lib/route/parser/UrlParser.php#L62-L98 | train |
makinacorpus/drupal-umenu | src/ItemStorage.php | ItemStorage.getMenuIdFor | public function getMenuIdFor(int $itemId): int
{
// Find parent identifier
$menuId = (int)$this
->database
->query(
"SELECT menu_id FROM {umenu_item} WHERE id = ?",
[$itemId]
)
->fetchField()
;
if (!$menuId) {
throw new \InvalidArgumentException(sprintf("Item %d does not exist", $itemId));
}
return $menuId;
} | php | public function getMenuIdFor(int $itemId): int
{
// Find parent identifier
$menuId = (int)$this
->database
->query(
"SELECT menu_id FROM {umenu_item} WHERE id = ?",
[$itemId]
)
->fetchField()
;
if (!$menuId) {
throw new \InvalidArgumentException(sprintf("Item %d does not exist", $itemId));
}
return $menuId;
} | [
"public",
"function",
"getMenuIdFor",
"(",
"int",
"$",
"itemId",
")",
":",
"int",
"{",
"// Find parent identifier",
"$",
"menuId",
"=",
"(",
"int",
")",
"$",
"this",
"->",
"database",
"->",
"query",
"(",
"\"SELECT menu_id FROM {umenu_item} WHERE id = ?\"",
",",
"[",
"$",
"itemId",
"]",
")",
"->",
"fetchField",
"(",
")",
";",
"if",
"(",
"!",
"$",
"menuId",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"\"Item %d does not exist\"",
",",
"$",
"itemId",
")",
")",
";",
"}",
"return",
"$",
"menuId",
";",
"}"
] | Get menu identifier for item
@param int $itemId
@return int | [
"Get",
"menu",
"identifier",
"for",
"item"
] | 346574eb0f5982857c64144e99ad2eacc8c52c5b | https://github.com/makinacorpus/drupal-umenu/blob/346574eb0f5982857c64144e99ad2eacc8c52c5b/src/ItemStorage.php#L115-L132 | train |
ElMijo/php-html-dom | src/PHPHtmlDom/Core/PHPHtmlDomElement.php | PHPHtmlDomElement.get_attrs | private function get_attrs()
{
$this->attrs = new \stdClass;
foreach($this->dom_element->attributes as $name => $node)
{
$this->attrs->{strtolower($name)} = $node->nodeValue;
}
return $this;
} | php | private function get_attrs()
{
$this->attrs = new \stdClass;
foreach($this->dom_element->attributes as $name => $node)
{
$this->attrs->{strtolower($name)} = $node->nodeValue;
}
return $this;
} | [
"private",
"function",
"get_attrs",
"(",
")",
"{",
"$",
"this",
"->",
"attrs",
"=",
"new",
"\\",
"stdClass",
";",
"foreach",
"(",
"$",
"this",
"->",
"dom_element",
"->",
"attributes",
"as",
"$",
"name",
"=>",
"$",
"node",
")",
"{",
"$",
"this",
"->",
"attrs",
"->",
"{",
"strtolower",
"(",
"$",
"name",
")",
"}",
"=",
"$",
"node",
"->",
"nodeValue",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Metodo que permite obtener todos atributos del elementos y convertirlos en un objeto stdClass.
@return self | [
"Metodo",
"que",
"permite",
"obtener",
"todos",
"atributos",
"del",
"elementos",
"y",
"convertirlos",
"en",
"un",
"objeto",
"stdClass",
"."
] | 6f294e26f37571e100b885e32b76245c144da6e2 | https://github.com/ElMijo/php-html-dom/blob/6f294e26f37571e100b885e32b76245c144da6e2/src/PHPHtmlDom/Core/PHPHtmlDomElement.php#L64-L73 | train |
ElMijo/php-html-dom | src/PHPHtmlDom/Core/PHPHtmlDomElement.php | PHPHtmlDomElement.get_childs | private function get_childs()
{
$this->childs = new \PHPTools\PHPHtmlDom\Core\PHPHtmlDomList($this->dom_element->childNodes);
return $this;
} | php | private function get_childs()
{
$this->childs = new \PHPTools\PHPHtmlDom\Core\PHPHtmlDomList($this->dom_element->childNodes);
return $this;
} | [
"private",
"function",
"get_childs",
"(",
")",
"{",
"$",
"this",
"->",
"childs",
"=",
"new",
"\\",
"PHPTools",
"\\",
"PHPHtmlDom",
"\\",
"Core",
"\\",
"PHPHtmlDomList",
"(",
"$",
"this",
"->",
"dom_element",
"->",
"childNodes",
")",
";",
"return",
"$",
"this",
";",
"}"
] | Metodo que permite obtener los elementos hijos y convertirlos en un objeto lista PHPHtmlDomList.
@return self | [
"Metodo",
"que",
"permite",
"obtener",
"los",
"elementos",
"hijos",
"y",
"convertirlos",
"en",
"un",
"objeto",
"lista",
"PHPHtmlDomList",
"."
] | 6f294e26f37571e100b885e32b76245c144da6e2 | https://github.com/ElMijo/php-html-dom/blob/6f294e26f37571e100b885e32b76245c144da6e2/src/PHPHtmlDom/Core/PHPHtmlDomElement.php#L79-L84 | train |
ElMijo/php-html-dom | src/PHPHtmlDom/Core/PHPHtmlDomElement.php | PHPHtmlDomElement.get_Text | private function get_Text()
{
$text_formatting = array('b','strong','em','i','small','strong','sub','sup','ins','del','mark','br','hr');
foreach ($this->dom_element->childNodes as $node)
{
if($node->nodeType == 3)
{
$this->set_text(trim($node->textContent));
$this->textFormatting.=$node->textContent;
}
else if($node->nodeType == 1 && !!in_array($node->tagName, $text_formatting))
{
if(!!in_array($node->tagName, ['br','hr']))
{
$this->textFormatting.= sprintf('<%s>',$node->tagName);
}
else
{
$tag = $node->tagName;
$attrs = $this->attrs_to_string($node->attributes);
$text = $node->textContent;
$this->textFormatting.= sprintf('<%1$s%2$s>%3$s</%1$s>',$tag,$attrs,$text);
}
}
}
return $this;
} | php | private function get_Text()
{
$text_formatting = array('b','strong','em','i','small','strong','sub','sup','ins','del','mark','br','hr');
foreach ($this->dom_element->childNodes as $node)
{
if($node->nodeType == 3)
{
$this->set_text(trim($node->textContent));
$this->textFormatting.=$node->textContent;
}
else if($node->nodeType == 1 && !!in_array($node->tagName, $text_formatting))
{
if(!!in_array($node->tagName, ['br','hr']))
{
$this->textFormatting.= sprintf('<%s>',$node->tagName);
}
else
{
$tag = $node->tagName;
$attrs = $this->attrs_to_string($node->attributes);
$text = $node->textContent;
$this->textFormatting.= sprintf('<%1$s%2$s>%3$s</%1$s>',$tag,$attrs,$text);
}
}
}
return $this;
} | [
"private",
"function",
"get_Text",
"(",
")",
"{",
"$",
"text_formatting",
"=",
"array",
"(",
"'b'",
",",
"'strong'",
",",
"'em'",
",",
"'i'",
",",
"'small'",
",",
"'strong'",
",",
"'sub'",
",",
"'sup'",
",",
"'ins'",
",",
"'del'",
",",
"'mark'",
",",
"'br'",
",",
"'hr'",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"dom_element",
"->",
"childNodes",
"as",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"->",
"nodeType",
"==",
"3",
")",
"{",
"$",
"this",
"->",
"set_text",
"(",
"trim",
"(",
"$",
"node",
"->",
"textContent",
")",
")",
";",
"$",
"this",
"->",
"textFormatting",
".=",
"$",
"node",
"->",
"textContent",
";",
"}",
"else",
"if",
"(",
"$",
"node",
"->",
"nodeType",
"==",
"1",
"&&",
"!",
"!",
"in_array",
"(",
"$",
"node",
"->",
"tagName",
",",
"$",
"text_formatting",
")",
")",
"{",
"if",
"(",
"!",
"!",
"in_array",
"(",
"$",
"node",
"->",
"tagName",
",",
"[",
"'br'",
",",
"'hr'",
"]",
")",
")",
"{",
"$",
"this",
"->",
"textFormatting",
".=",
"sprintf",
"(",
"'<%s>'",
",",
"$",
"node",
"->",
"tagName",
")",
";",
"}",
"else",
"{",
"$",
"tag",
"=",
"$",
"node",
"->",
"tagName",
";",
"$",
"attrs",
"=",
"$",
"this",
"->",
"attrs_to_string",
"(",
"$",
"node",
"->",
"attributes",
")",
";",
"$",
"text",
"=",
"$",
"node",
"->",
"textContent",
";",
"$",
"this",
"->",
"textFormatting",
".=",
"sprintf",
"(",
"'<%1$s%2$s>%3$s</%1$s>'",
",",
"$",
"tag",
",",
"$",
"attrs",
",",
"$",
"text",
")",
";",
"}",
"}",
"}",
"return",
"$",
"this",
";",
"}"
] | Metodo que permite obtener el texto que se encuentra dentro del elemento.
@return self | [
"Metodo",
"que",
"permite",
"obtener",
"el",
"texto",
"que",
"se",
"encuentra",
"dentro",
"del",
"elemento",
"."
] | 6f294e26f37571e100b885e32b76245c144da6e2 | https://github.com/ElMijo/php-html-dom/blob/6f294e26f37571e100b885e32b76245c144da6e2/src/PHPHtmlDom/Core/PHPHtmlDomElement.php#L90-L119 | train |
ElMijo/php-html-dom | src/PHPHtmlDom/Core/PHPHtmlDomElement.php | PHPHtmlDomElement.set_text | private function set_text($text)
{
if(!!$text)
{
if(!!$this->text)
{
if(!!is_array($this->text))
{
$this->text[] = $text;
}
else
{
$this->text = array($this->text,$text);
}
}
else
{
$this->text = $text;
}
}
return $this;
} | php | private function set_text($text)
{
if(!!$text)
{
if(!!$this->text)
{
if(!!is_array($this->text))
{
$this->text[] = $text;
}
else
{
$this->text = array($this->text,$text);
}
}
else
{
$this->text = $text;
}
}
return $this;
} | [
"private",
"function",
"set_text",
"(",
"$",
"text",
")",
"{",
"if",
"(",
"!",
"!",
"$",
"text",
")",
"{",
"if",
"(",
"!",
"!",
"$",
"this",
"->",
"text",
")",
"{",
"if",
"(",
"!",
"!",
"is_array",
"(",
"$",
"this",
"->",
"text",
")",
")",
"{",
"$",
"this",
"->",
"text",
"[",
"]",
"=",
"$",
"text",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"text",
"=",
"array",
"(",
"$",
"this",
"->",
"text",
",",
"$",
"text",
")",
";",
"}",
"}",
"else",
"{",
"$",
"this",
"->",
"text",
"=",
"$",
"text",
";",
"}",
"}",
"return",
"$",
"this",
";",
"}"
] | Metodo que permite definir e texto del elemento.
@param string $text Cden de texto a definirse.
@return self | [
"Metodo",
"que",
"permite",
"definir",
"e",
"texto",
"del",
"elemento",
"."
] | 6f294e26f37571e100b885e32b76245c144da6e2 | https://github.com/ElMijo/php-html-dom/blob/6f294e26f37571e100b885e32b76245c144da6e2/src/PHPHtmlDom/Core/PHPHtmlDomElement.php#L126-L148 | train |
ElMijo/php-html-dom | src/PHPHtmlDom/Core/PHPHtmlDomElement.php | PHPHtmlDomElement.attrs_to_string | private function attrs_to_string($attrs)
{
$attrs_string ='';
foreach($attrs as $name => $node)
{
$attrs_string.= sprintf(' %s="%s"',$name,$node->nodeValue);
}
return $attrs_string;
} | php | private function attrs_to_string($attrs)
{
$attrs_string ='';
foreach($attrs as $name => $node)
{
$attrs_string.= sprintf(' %s="%s"',$name,$node->nodeValue);
}
return $attrs_string;
} | [
"private",
"function",
"attrs_to_string",
"(",
"$",
"attrs",
")",
"{",
"$",
"attrs_string",
"=",
"''",
";",
"foreach",
"(",
"$",
"attrs",
"as",
"$",
"name",
"=>",
"$",
"node",
")",
"{",
"$",
"attrs_string",
".=",
"sprintf",
"(",
"' %s=\"%s\"'",
",",
"$",
"name",
",",
"$",
"node",
"->",
"nodeValue",
")",
";",
"}",
"return",
"$",
"attrs_string",
";",
"}"
] | Este metodo permite concatenar un objeto de atributos en una sola cadena.
@param attay $attrs Arreglo de atributos.
@return string | [
"Este",
"metodo",
"permite",
"concatenar",
"un",
"objeto",
"de",
"atributos",
"en",
"una",
"sola",
"cadena",
"."
] | 6f294e26f37571e100b885e32b76245c144da6e2 | https://github.com/ElMijo/php-html-dom/blob/6f294e26f37571e100b885e32b76245c144da6e2/src/PHPHtmlDom/Core/PHPHtmlDomElement.php#L155-L165 | train |
courtney-miles/schnoop-schema | src/MySQL/Routine/RoutineFunction.php | RoutineFunction.makeParametersDDL | protected function makeParametersDDL($separator = " ")
{
$params = [];
foreach ($this->parameters as $parameter) {
$params[] = $parameter->getDDL();
}
return implode(',' . $separator, $params);
} | php | protected function makeParametersDDL($separator = " ")
{
$params = [];
foreach ($this->parameters as $parameter) {
$params[] = $parameter->getDDL();
}
return implode(',' . $separator, $params);
} | [
"protected",
"function",
"makeParametersDDL",
"(",
"$",
"separator",
"=",
"\" \"",
")",
"{",
"$",
"params",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"parameters",
"as",
"$",
"parameter",
")",
"{",
"$",
"params",
"[",
"]",
"=",
"$",
"parameter",
"->",
"getDDL",
"(",
")",
";",
"}",
"return",
"implode",
"(",
"','",
".",
"$",
"separator",
",",
"$",
"params",
")",
";",
"}"
] | Make the portion of DDL for describing the parameters.
@param string $separator String to apply between parameters.
@return string Parameters DDL. | [
"Make",
"the",
"portion",
"of",
"DDL",
"for",
"describing",
"the",
"parameters",
"."
] | f96e9922257860171ecdcdbb6b78182276e2f60d | https://github.com/courtney-miles/schnoop-schema/blob/f96e9922257860171ecdcdbb6b78182276e2f60d/src/MySQL/Routine/RoutineFunction.php#L161-L170 | train |
yii2lab/yii2-rbac | src/domain/repositories/disc/AssignmentRepository.php | AssignmentRepository.saveAssignments | protected function saveAssignments()
{
$assignmentData = [];
foreach ($this->assignments as $userId => $assignments) {
foreach ($assignments as $name => $assignment) {
/* @var $assignment Assignment */
$assignmentData[$userId][] = $assignment->roleName;
}
}
DiscHelper::saveToFile($assignmentData, $this->assignmentFile);
$this->domain->const->generateAll();
} | php | protected function saveAssignments()
{
$assignmentData = [];
foreach ($this->assignments as $userId => $assignments) {
foreach ($assignments as $name => $assignment) {
/* @var $assignment Assignment */
$assignmentData[$userId][] = $assignment->roleName;
}
}
DiscHelper::saveToFile($assignmentData, $this->assignmentFile);
$this->domain->const->generateAll();
} | [
"protected",
"function",
"saveAssignments",
"(",
")",
"{",
"$",
"assignmentData",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"assignments",
"as",
"$",
"userId",
"=>",
"$",
"assignments",
")",
"{",
"foreach",
"(",
"$",
"assignments",
"as",
"$",
"name",
"=>",
"$",
"assignment",
")",
"{",
"/* @var $assignment Assignment */",
"$",
"assignmentData",
"[",
"$",
"userId",
"]",
"[",
"]",
"=",
"$",
"assignment",
"->",
"roleName",
";",
"}",
"}",
"DiscHelper",
"::",
"saveToFile",
"(",
"$",
"assignmentData",
",",
"$",
"this",
"->",
"assignmentFile",
")",
";",
"$",
"this",
"->",
"domain",
"->",
"const",
"->",
"generateAll",
"(",
")",
";",
"}"
] | Saves assignments data into persistent storage. | [
"Saves",
"assignments",
"data",
"into",
"persistent",
"storage",
"."
] | e72ac0359af660690c161451f864208b2d20919d | https://github.com/yii2lab/yii2-rbac/blob/e72ac0359af660690c161451f864208b2d20919d/src/domain/repositories/disc/AssignmentRepository.php#L197-L209 | train |
yii2lab/yii2-rbac | src/domain/repositories/disc/AssignmentRepository.php | AssignmentRepository.load | protected function load()
{
$this->assignments = [];
$assignments = DiscHelper::loadFromFile($this->assignmentFile);
$assignmentsMtime = @filemtime($this->assignmentFile);
foreach ($assignments as $userId => $roles) {
foreach ($roles as $role) {
$this->assignments[$userId][$role] = new Assignment([
'userId' => $userId,
'roleName' => $role,
'createdAt' => $assignmentsMtime,
]);
}
}
} | php | protected function load()
{
$this->assignments = [];
$assignments = DiscHelper::loadFromFile($this->assignmentFile);
$assignmentsMtime = @filemtime($this->assignmentFile);
foreach ($assignments as $userId => $roles) {
foreach ($roles as $role) {
$this->assignments[$userId][$role] = new Assignment([
'userId' => $userId,
'roleName' => $role,
'createdAt' => $assignmentsMtime,
]);
}
}
} | [
"protected",
"function",
"load",
"(",
")",
"{",
"$",
"this",
"->",
"assignments",
"=",
"[",
"]",
";",
"$",
"assignments",
"=",
"DiscHelper",
"::",
"loadFromFile",
"(",
"$",
"this",
"->",
"assignmentFile",
")",
";",
"$",
"assignmentsMtime",
"=",
"@",
"filemtime",
"(",
"$",
"this",
"->",
"assignmentFile",
")",
";",
"foreach",
"(",
"$",
"assignments",
"as",
"$",
"userId",
"=>",
"$",
"roles",
")",
"{",
"foreach",
"(",
"$",
"roles",
"as",
"$",
"role",
")",
"{",
"$",
"this",
"->",
"assignments",
"[",
"$",
"userId",
"]",
"[",
"$",
"role",
"]",
"=",
"new",
"Assignment",
"(",
"[",
"'userId'",
"=>",
"$",
"userId",
",",
"'roleName'",
"=>",
"$",
"role",
",",
"'createdAt'",
"=>",
"$",
"assignmentsMtime",
",",
"]",
")",
";",
"}",
"}",
"}"
] | Loads authorization data from persistent storage. | [
"Loads",
"authorization",
"data",
"from",
"persistent",
"storage",
"."
] | e72ac0359af660690c161451f864208b2d20919d | https://github.com/yii2lab/yii2-rbac/blob/e72ac0359af660690c161451f864208b2d20919d/src/domain/repositories/disc/AssignmentRepository.php#L222-L237 | train |
tigron/skeleton-migrate | console/create.php | Migrate_Create.create_package_migration | private function create_package_migration($name) {
list($packagename, $name) = explode('/', $name);
$skeleton_packages = \Skeleton\Core\Skeleton::get_all();
$package = null;
foreach ($skeleton_packages as $skeleton_package) {
if ($skeleton_package->name == $packagename) {
$package = $skeleton_package;
}
}
if ($package === null) {
throw new \Exception('Package ' . $packagename . ' not found');
}
if (!file_exists($package->migration_path)) {
mkdir($package->migration_path);
}
$name = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $name);
$datetime = date('Ymd_His');
$filename = $datetime . '_' . strtolower($name) . '.php';
$classname = 'Migration_' . $datetime . '_' . ucfirst($name);
$namespace_parts = explode('-', $package->name);
foreach ($namespace_parts as $key => $namespace_part) {
$namespace_parts[$key] = ucfirst($namespace_part);
}
$namespace = implode('\\', $namespace_parts);
$template = file_get_contents(__DIR__ . '/../template/migration.php');
$template = str_replace('%%namespace%%', 'namespace ' . $namespace . ';' . "\n", $template);
$template = str_replace('%%classname%%', $classname, $template);
file_put_contents($package->migration_path . '/' . $filename, $template);
return $package->migration_path . '/' . $filename;
} | php | private function create_package_migration($name) {
list($packagename, $name) = explode('/', $name);
$skeleton_packages = \Skeleton\Core\Skeleton::get_all();
$package = null;
foreach ($skeleton_packages as $skeleton_package) {
if ($skeleton_package->name == $packagename) {
$package = $skeleton_package;
}
}
if ($package === null) {
throw new \Exception('Package ' . $packagename . ' not found');
}
if (!file_exists($package->migration_path)) {
mkdir($package->migration_path);
}
$name = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $name);
$datetime = date('Ymd_His');
$filename = $datetime . '_' . strtolower($name) . '.php';
$classname = 'Migration_' . $datetime . '_' . ucfirst($name);
$namespace_parts = explode('-', $package->name);
foreach ($namespace_parts as $key => $namespace_part) {
$namespace_parts[$key] = ucfirst($namespace_part);
}
$namespace = implode('\\', $namespace_parts);
$template = file_get_contents(__DIR__ . '/../template/migration.php');
$template = str_replace('%%namespace%%', 'namespace ' . $namespace . ';' . "\n", $template);
$template = str_replace('%%classname%%', $classname, $template);
file_put_contents($package->migration_path . '/' . $filename, $template);
return $package->migration_path . '/' . $filename;
} | [
"private",
"function",
"create_package_migration",
"(",
"$",
"name",
")",
"{",
"list",
"(",
"$",
"packagename",
",",
"$",
"name",
")",
"=",
"explode",
"(",
"'/'",
",",
"$",
"name",
")",
";",
"$",
"skeleton_packages",
"=",
"\\",
"Skeleton",
"\\",
"Core",
"\\",
"Skeleton",
"::",
"get_all",
"(",
")",
";",
"$",
"package",
"=",
"null",
";",
"foreach",
"(",
"$",
"skeleton_packages",
"as",
"$",
"skeleton_package",
")",
"{",
"if",
"(",
"$",
"skeleton_package",
"->",
"name",
"==",
"$",
"packagename",
")",
"{",
"$",
"package",
"=",
"$",
"skeleton_package",
";",
"}",
"}",
"if",
"(",
"$",
"package",
"===",
"null",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Package '",
".",
"$",
"packagename",
".",
"' not found'",
")",
";",
"}",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"package",
"->",
"migration_path",
")",
")",
"{",
"mkdir",
"(",
"$",
"package",
"->",
"migration_path",
")",
";",
"}",
"$",
"name",
"=",
"preg_replace",
"(",
"array",
"(",
"'/\\s/'",
",",
"'/\\.[\\.]+/'",
",",
"'/[^\\w_\\.\\-]/'",
")",
",",
"array",
"(",
"'_'",
",",
"'.'",
",",
"''",
")",
",",
"$",
"name",
")",
";",
"$",
"datetime",
"=",
"date",
"(",
"'Ymd_His'",
")",
";",
"$",
"filename",
"=",
"$",
"datetime",
".",
"'_'",
".",
"strtolower",
"(",
"$",
"name",
")",
".",
"'.php'",
";",
"$",
"classname",
"=",
"'Migration_'",
".",
"$",
"datetime",
".",
"'_'",
".",
"ucfirst",
"(",
"$",
"name",
")",
";",
"$",
"namespace_parts",
"=",
"explode",
"(",
"'-'",
",",
"$",
"package",
"->",
"name",
")",
";",
"foreach",
"(",
"$",
"namespace_parts",
"as",
"$",
"key",
"=>",
"$",
"namespace_part",
")",
"{",
"$",
"namespace_parts",
"[",
"$",
"key",
"]",
"=",
"ucfirst",
"(",
"$",
"namespace_part",
")",
";",
"}",
"$",
"namespace",
"=",
"implode",
"(",
"'\\\\'",
",",
"$",
"namespace_parts",
")",
";",
"$",
"template",
"=",
"file_get_contents",
"(",
"__DIR__",
".",
"'/../template/migration.php'",
")",
";",
"$",
"template",
"=",
"str_replace",
"(",
"'%%namespace%%'",
",",
"'namespace '",
".",
"$",
"namespace",
".",
"';'",
".",
"\"\\n\"",
",",
"$",
"template",
")",
";",
"$",
"template",
"=",
"str_replace",
"(",
"'%%classname%%'",
",",
"$",
"classname",
",",
"$",
"template",
")",
";",
"file_put_contents",
"(",
"$",
"package",
"->",
"migration_path",
".",
"'/'",
".",
"$",
"filename",
",",
"$",
"template",
")",
";",
"return",
"$",
"package",
"->",
"migration_path",
".",
"'/'",
".",
"$",
"filename",
";",
"}"
] | Create package migration
@access private
@param string $name
@return string $path | [
"Create",
"package",
"migration"
] | 53b6ea56e928d4f925257949e59467d2d9cbafd4 | https://github.com/tigron/skeleton-migrate/blob/53b6ea56e928d4f925257949e59467d2d9cbafd4/console/create.php#L64-L100 | train |
tigron/skeleton-migrate | console/create.php | Migrate_Create.create_project_migration | private function create_project_migration($name) {
$name = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $name);
$datetime = date('Ymd_His');
$filename = $datetime . '_' . strtolower($name) . '.php';
$classname = 'Migration_' . $datetime . '_' . ucfirst($name);
$template = file_get_contents(__DIR__ . '/../template/migration.php');
$template = str_replace('%%namespace%%', '', $template);
$template = str_replace('%%classname%%', $classname, $template);
file_put_contents(\Skeleton\Database\Migration\Config::$migration_directory . '/' . $filename, $template);
return \Skeleton\Database\Migration\Config::$migration_directory . '/' . $filename;
} | php | private function create_project_migration($name) {
$name = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $name);
$datetime = date('Ymd_His');
$filename = $datetime . '_' . strtolower($name) . '.php';
$classname = 'Migration_' . $datetime . '_' . ucfirst($name);
$template = file_get_contents(__DIR__ . '/../template/migration.php');
$template = str_replace('%%namespace%%', '', $template);
$template = str_replace('%%classname%%', $classname, $template);
file_put_contents(\Skeleton\Database\Migration\Config::$migration_directory . '/' . $filename, $template);
return \Skeleton\Database\Migration\Config::$migration_directory . '/' . $filename;
} | [
"private",
"function",
"create_project_migration",
"(",
"$",
"name",
")",
"{",
"$",
"name",
"=",
"preg_replace",
"(",
"array",
"(",
"'/\\s/'",
",",
"'/\\.[\\.]+/'",
",",
"'/[^\\w_\\.\\-]/'",
")",
",",
"array",
"(",
"'_'",
",",
"'.'",
",",
"''",
")",
",",
"$",
"name",
")",
";",
"$",
"datetime",
"=",
"date",
"(",
"'Ymd_His'",
")",
";",
"$",
"filename",
"=",
"$",
"datetime",
".",
"'_'",
".",
"strtolower",
"(",
"$",
"name",
")",
".",
"'.php'",
";",
"$",
"classname",
"=",
"'Migration_'",
".",
"$",
"datetime",
".",
"'_'",
".",
"ucfirst",
"(",
"$",
"name",
")",
";",
"$",
"template",
"=",
"file_get_contents",
"(",
"__DIR__",
".",
"'/../template/migration.php'",
")",
";",
"$",
"template",
"=",
"str_replace",
"(",
"'%%namespace%%'",
",",
"''",
",",
"$",
"template",
")",
";",
"$",
"template",
"=",
"str_replace",
"(",
"'%%classname%%'",
",",
"$",
"classname",
",",
"$",
"template",
")",
";",
"file_put_contents",
"(",
"\\",
"Skeleton",
"\\",
"Database",
"\\",
"Migration",
"\\",
"Config",
"::",
"$",
"migration_directory",
".",
"'/'",
".",
"$",
"filename",
",",
"$",
"template",
")",
";",
"return",
"\\",
"Skeleton",
"\\",
"Database",
"\\",
"Migration",
"\\",
"Config",
"::",
"$",
"migration_directory",
".",
"'/'",
".",
"$",
"filename",
";",
"}"
] | Create project migration
@access private
@param string $name
@return string $path | [
"Create",
"project",
"migration"
] | 53b6ea56e928d4f925257949e59467d2d9cbafd4 | https://github.com/tigron/skeleton-migrate/blob/53b6ea56e928d4f925257949e59467d2d9cbafd4/console/create.php#L109-L121 | train |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.table | public static function table($table)
{
//as all calls will start with this function, first check if database connection has being established
if(Connect::getConn()==null){
//lets just return the object of the class in-case of connection error (developer will handle the rest)
return new static ;
}
self::$table = self::sanitize($table);
return new static;
} | php | public static function table($table)
{
//as all calls will start with this function, first check if database connection has being established
if(Connect::getConn()==null){
//lets just return the object of the class in-case of connection error (developer will handle the rest)
return new static ;
}
self::$table = self::sanitize($table);
return new static;
} | [
"public",
"static",
"function",
"table",
"(",
"$",
"table",
")",
"{",
"//as all calls will start with this function, first check if database connection has being established",
"if",
"(",
"Connect",
"::",
"getConn",
"(",
")",
"==",
"null",
")",
"{",
"//lets just return the object of the class in-case of connection error (developer will handle the rest)",
"return",
"new",
"static",
";",
"}",
"self",
"::",
"$",
"table",
"=",
"self",
"::",
"sanitize",
"(",
"$",
"table",
")",
";",
"return",
"new",
"static",
";",
"}"
] | Sets the table on to which the various statements are executed.
@param $table
@return string | $this | [
"Sets",
"the",
"table",
"on",
"to",
"which",
"the",
"various",
"statements",
"are",
"executed",
"."
] | a9339b6dea5be52b79095b9c001684c162a09bf6 | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L34-L44 | train |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.sanitize | private static function sanitize($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
} | php | private static function sanitize($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
} | [
"private",
"static",
"function",
"sanitize",
"(",
"$",
"data",
")",
"{",
"$",
"data",
"=",
"trim",
"(",
"$",
"data",
")",
";",
"$",
"data",
"=",
"stripslashes",
"(",
"$",
"data",
")",
";",
"$",
"data",
"=",
"htmlspecialchars",
"(",
"$",
"data",
")",
";",
"return",
"$",
"data",
";",
"}"
] | Sanitizes the data input values
@param $data
@return string | [
"Sanitizes",
"the",
"data",
"input",
"values"
] | a9339b6dea5be52b79095b9c001684c162a09bf6 | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L51-L57 | train |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.orWhere | public function orWhere($param){
if (func_num_args() == 3) {
$operator =strtolower(func_get_arg(1));
if (is_numeric(array_search($operator, $this->condition))) {
$this->whereby .=' or '.self::sanitize(func_get_arg(0))
.' '. $operator . ' \''
. self::sanitize(func_get_arg(2)) . '\'';
} else {
static::$response["status"] = "error";
static::$response["response"] = "Invalid condition provided in where function";
static::$response["code"] = 7000;
}
} else if (func_num_args() == 2) {
$this->whereby .= ' or '.self::sanitize(func_get_arg(0)) . ' = \''
. self::sanitize(func_get_arg(1)) . '\'';
} else {
static::$response["status"] = "error";
static::$response["response"] = "Invalid parameters provided in where function";
static::$response["code"] = 7001;
}
return $this;
} | php | public function orWhere($param){
if (func_num_args() == 3) {
$operator =strtolower(func_get_arg(1));
if (is_numeric(array_search($operator, $this->condition))) {
$this->whereby .=' or '.self::sanitize(func_get_arg(0))
.' '. $operator . ' \''
. self::sanitize(func_get_arg(2)) . '\'';
} else {
static::$response["status"] = "error";
static::$response["response"] = "Invalid condition provided in where function";
static::$response["code"] = 7000;
}
} else if (func_num_args() == 2) {
$this->whereby .= ' or '.self::sanitize(func_get_arg(0)) . ' = \''
. self::sanitize(func_get_arg(1)) . '\'';
} else {
static::$response["status"] = "error";
static::$response["response"] = "Invalid parameters provided in where function";
static::$response["code"] = 7001;
}
return $this;
} | [
"public",
"function",
"orWhere",
"(",
"$",
"param",
")",
"{",
"if",
"(",
"func_num_args",
"(",
")",
"==",
"3",
")",
"{",
"$",
"operator",
"=",
"strtolower",
"(",
"func_get_arg",
"(",
"1",
")",
")",
";",
"if",
"(",
"is_numeric",
"(",
"array_search",
"(",
"$",
"operator",
",",
"$",
"this",
"->",
"condition",
")",
")",
")",
"{",
"$",
"this",
"->",
"whereby",
".=",
"' or '",
".",
"self",
"::",
"sanitize",
"(",
"func_get_arg",
"(",
"0",
")",
")",
".",
"' '",
".",
"$",
"operator",
".",
"' \\''",
".",
"self",
"::",
"sanitize",
"(",
"func_get_arg",
"(",
"2",
")",
")",
".",
"'\\''",
";",
"}",
"else",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"\"Invalid condition provided in where function\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"code\"",
"]",
"=",
"7000",
";",
"}",
"}",
"else",
"if",
"(",
"func_num_args",
"(",
")",
"==",
"2",
")",
"{",
"$",
"this",
"->",
"whereby",
".=",
"' or '",
".",
"self",
"::",
"sanitize",
"(",
"func_get_arg",
"(",
"0",
")",
")",
".",
"' = \\''",
".",
"self",
"::",
"sanitize",
"(",
"func_get_arg",
"(",
"1",
")",
")",
".",
"'\\''",
";",
"}",
"else",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"\"Invalid parameters provided in where function\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"code\"",
"]",
"=",
"7001",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Adds condition for or in where clause
@see where
@param $param
@return $this | [
"Adds",
"condition",
"for",
"or",
"in",
"where",
"clause"
] | a9339b6dea5be52b79095b9c001684c162a09bf6 | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L172-L195 | train |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.orderBy | public function orderBy($column = '', $sort = 'desc')
{
$column=self::sanitize($column);
$sort=strtoupper(self::sanitize($sort));
/*check if the sort method passed is valid */
if (!(hash_equals('DESC',$sort) || hash_equals('ASC',$sort))){
static::$response["status"] = "error";
static::$response["response"] = "The sort order in order by clause is invalid";
static::$response['code'] = 6050;
return static::terminate(static::$response);
}
if ($this->order == null) {
$this->order = " ORDER BY $column $sort";
} else {
$this->order .= ", $column $sort";
}
return $this;
} | php | public function orderBy($column = '', $sort = 'desc')
{
$column=self::sanitize($column);
$sort=strtoupper(self::sanitize($sort));
/*check if the sort method passed is valid */
if (!(hash_equals('DESC',$sort) || hash_equals('ASC',$sort))){
static::$response["status"] = "error";
static::$response["response"] = "The sort order in order by clause is invalid";
static::$response['code'] = 6050;
return static::terminate(static::$response);
}
if ($this->order == null) {
$this->order = " ORDER BY $column $sort";
} else {
$this->order .= ", $column $sort";
}
return $this;
} | [
"public",
"function",
"orderBy",
"(",
"$",
"column",
"=",
"''",
",",
"$",
"sort",
"=",
"'desc'",
")",
"{",
"$",
"column",
"=",
"self",
"::",
"sanitize",
"(",
"$",
"column",
")",
";",
"$",
"sort",
"=",
"strtoupper",
"(",
"self",
"::",
"sanitize",
"(",
"$",
"sort",
")",
")",
";",
"/*check if the sort method passed is valid */",
"if",
"(",
"!",
"(",
"hash_equals",
"(",
"'DESC'",
",",
"$",
"sort",
")",
"||",
"hash_equals",
"(",
"'ASC'",
",",
"$",
"sort",
")",
")",
")",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"\"The sort order in order by clause is invalid\"",
";",
"static",
"::",
"$",
"response",
"[",
"'code'",
"]",
"=",
"6050",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"order",
"==",
"null",
")",
"{",
"$",
"this",
"->",
"order",
"=",
"\" ORDER BY $column $sort\"",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"order",
".=",
"\", $column $sort\"",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Set order in which the return results will be return
@param string $column :column to base the order on
@param string $sort :asc or desc
@return $this|mixed | [
"Set",
"order",
"in",
"which",
"the",
"return",
"results",
"will",
"be",
"return"
] | a9339b6dea5be52b79095b9c001684c162a09bf6 | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L203-L222 | train |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.get | public function get($limit = 0, $offset = 0)
{
//check if there is an error
if (static::$response['status'] == "error") {
return static::terminate(static::$response);
}
//check if the limit is a number
if (!is_numeric($limit)) {
static::$response["status"] = "error";
static::$response["response"] = "Parameter limit should be numeric at function get()";
static::$response["code"] = 6000;
return static::terminate(static::$response);
}
//check if the offset is a number
if (!is_numeric($offset)) {
static::$response["status"] = "error";
static::$response["response"] = "Parameter offset should be numeric at function get()";
static::$response["code"] = 6001;
return static::terminate(static::$response);
}
$table_name = self::$table;
/* if no column passed as param, select all */
$columns = empty($this->columns) ? "*" : $this->columns;
$query = /** @lang text */
"SELECT {$columns} FROM {$table_name}";
if (!empty($this->whereby)) {
$query = $query . ' WHERE ' . $this->whereby;
}
if(!empty($this->groupby)){
$query.=' GROUP BY '.$this->groupby;
}
if (!empty($this->order)) {
$query .= $this->order;
}
if (!empty($limit)) {
$query = $query . ' LIMIT ' . $limit;
}
if (!empty($offset)) {
$query = $query . ' OFFSET ' . $offset;
}
return $this->fetch($query);
} | php | public function get($limit = 0, $offset = 0)
{
//check if there is an error
if (static::$response['status'] == "error") {
return static::terminate(static::$response);
}
//check if the limit is a number
if (!is_numeric($limit)) {
static::$response["status"] = "error";
static::$response["response"] = "Parameter limit should be numeric at function get()";
static::$response["code"] = 6000;
return static::terminate(static::$response);
}
//check if the offset is a number
if (!is_numeric($offset)) {
static::$response["status"] = "error";
static::$response["response"] = "Parameter offset should be numeric at function get()";
static::$response["code"] = 6001;
return static::terminate(static::$response);
}
$table_name = self::$table;
/* if no column passed as param, select all */
$columns = empty($this->columns) ? "*" : $this->columns;
$query = /** @lang text */
"SELECT {$columns} FROM {$table_name}";
if (!empty($this->whereby)) {
$query = $query . ' WHERE ' . $this->whereby;
}
if(!empty($this->groupby)){
$query.=' GROUP BY '.$this->groupby;
}
if (!empty($this->order)) {
$query .= $this->order;
}
if (!empty($limit)) {
$query = $query . ' LIMIT ' . $limit;
}
if (!empty($offset)) {
$query = $query . ' OFFSET ' . $offset;
}
return $this->fetch($query);
} | [
"public",
"function",
"get",
"(",
"$",
"limit",
"=",
"0",
",",
"$",
"offset",
"=",
"0",
")",
"{",
"//check if there is an error",
"if",
"(",
"static",
"::",
"$",
"response",
"[",
"'status'",
"]",
"==",
"\"error\"",
")",
"{",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"//check if the limit is a number",
"if",
"(",
"!",
"is_numeric",
"(",
"$",
"limit",
")",
")",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"\"Parameter limit should be numeric at function get()\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"code\"",
"]",
"=",
"6000",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"//check if the offset is a number",
"if",
"(",
"!",
"is_numeric",
"(",
"$",
"offset",
")",
")",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"\"Parameter offset should be numeric at function get()\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"code\"",
"]",
"=",
"6001",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"$",
"table_name",
"=",
"self",
"::",
"$",
"table",
";",
"/* if no column passed as param, select all\t */",
"$",
"columns",
"=",
"empty",
"(",
"$",
"this",
"->",
"columns",
")",
"?",
"\"*\"",
":",
"$",
"this",
"->",
"columns",
";",
"$",
"query",
"=",
"/** @lang text */",
"\"SELECT {$columns} FROM {$table_name}\"",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"whereby",
")",
")",
"{",
"$",
"query",
"=",
"$",
"query",
".",
"' WHERE '",
".",
"$",
"this",
"->",
"whereby",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"groupby",
")",
")",
"{",
"$",
"query",
".=",
"' GROUP BY '",
".",
"$",
"this",
"->",
"groupby",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"order",
")",
")",
"{",
"$",
"query",
".=",
"$",
"this",
"->",
"order",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"limit",
")",
")",
"{",
"$",
"query",
"=",
"$",
"query",
".",
"' LIMIT '",
".",
"$",
"limit",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"offset",
")",
")",
"{",
"$",
"query",
"=",
"$",
"query",
".",
"' OFFSET '",
".",
"$",
"offset",
";",
"}",
"return",
"$",
"this",
"->",
"fetch",
"(",
"$",
"query",
")",
";",
"}"
] | Fetch records form database
@param int $limit :optional limit of records to be retrieved
@param int $offset :the index which the record should be retrieved from
@return array|string | [
"Fetch",
"records",
"form",
"database"
] | a9339b6dea5be52b79095b9c001684c162a09bf6 | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L245-L302 | train |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.fetch | protected function fetch($sql)
{
try {
try {
$stm = Connect::getConn()->prepare($sql);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response['code'] = $e->getCode();
return static::terminate(static::$response);
}
try {
$stm->execute();
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response['code'] = $e->getCode();
return static::terminate(static::$response);
}
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response['code'] = $e->getCode();
return static::terminate(static::$response);
}
try {
$data = null;
// set the resulting array to associative
$stm->setFetchMode(PDO::FETCH_ASSOC);
foreach (new RecursiveArrayIterator($stm->fetchAll()) as $k => $v) {
$data[] = $v;
}
if ($data == null) {
static::$response["status"] = "success";
static::$response["response"] = Null;
static::$response['code'] = 300;
return static::terminate(static::$response);
}
static::$response["status"] = "success";
static::$response["response"] = $data;
static::$response['code'] = 200;
return static::terminate(static::$response);
} catch (PDOException $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
} | php | protected function fetch($sql)
{
try {
try {
$stm = Connect::getConn()->prepare($sql);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response['code'] = $e->getCode();
return static::terminate(static::$response);
}
try {
$stm->execute();
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response['code'] = $e->getCode();
return static::terminate(static::$response);
}
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response['code'] = $e->getCode();
return static::terminate(static::$response);
}
try {
$data = null;
// set the resulting array to associative
$stm->setFetchMode(PDO::FETCH_ASSOC);
foreach (new RecursiveArrayIterator($stm->fetchAll()) as $k => $v) {
$data[] = $v;
}
if ($data == null) {
static::$response["status"] = "success";
static::$response["response"] = Null;
static::$response['code'] = 300;
return static::terminate(static::$response);
}
static::$response["status"] = "success";
static::$response["response"] = $data;
static::$response['code'] = 200;
return static::terminate(static::$response);
} catch (PDOException $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
} | [
"protected",
"function",
"fetch",
"(",
"$",
"sql",
")",
"{",
"try",
"{",
"try",
"{",
"$",
"stm",
"=",
"Connect",
"::",
"getConn",
"(",
")",
"->",
"prepare",
"(",
"$",
"sql",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"$",
"e",
"->",
"getMessage",
"(",
")",
";",
"static",
"::",
"$",
"response",
"[",
"'code'",
"]",
"=",
"$",
"e",
"->",
"getCode",
"(",
")",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"try",
"{",
"$",
"stm",
"->",
"execute",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"$",
"e",
"->",
"getMessage",
"(",
")",
";",
"static",
"::",
"$",
"response",
"[",
"'code'",
"]",
"=",
"$",
"e",
"->",
"getCode",
"(",
")",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"$",
"e",
"->",
"getMessage",
"(",
")",
";",
"static",
"::",
"$",
"response",
"[",
"'code'",
"]",
"=",
"$",
"e",
"->",
"getCode",
"(",
")",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"try",
"{",
"$",
"data",
"=",
"null",
";",
"// set the resulting array to associative",
"$",
"stm",
"->",
"setFetchMode",
"(",
"PDO",
"::",
"FETCH_ASSOC",
")",
";",
"foreach",
"(",
"new",
"RecursiveArrayIterator",
"(",
"$",
"stm",
"->",
"fetchAll",
"(",
")",
")",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",
"$",
"data",
"[",
"]",
"=",
"$",
"v",
";",
"}",
"if",
"(",
"$",
"data",
"==",
"null",
")",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"success\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"Null",
";",
"static",
"::",
"$",
"response",
"[",
"'code'",
"]",
"=",
"300",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"success\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"$",
"data",
";",
"static",
"::",
"$",
"response",
"[",
"'code'",
"]",
"=",
"200",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"catch",
"(",
"PDOException",
"$",
"e",
")",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"$",
"e",
"->",
"getMessage",
"(",
")",
";",
"static",
"::",
"$",
"response",
"[",
"\"code\"",
"]",
"=",
"$",
"e",
"->",
"getCode",
"(",
")",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"}"
] | Executes a query that returns data
@param $sql
@return array|string | [
"Executes",
"a",
"query",
"that",
"returns",
"data"
] | a9339b6dea5be52b79095b9c001684c162a09bf6 | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L310-L365 | train |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.all | public function all()
{
$table = trim(self::$table);
if (!empty($table)) {
$query = /** @lang text */
"SELECT * FROM {$table}";
if(!empty($this->groupby)){
$query.=' GROUP BY '.$this->groupby;
}
if (!empty($this->order)) {
$query .= $this->order;
}
//execute the query and return the data or error message
return $this->fetch($query);
} else {
static::$response["status"] = "error";
static::$response["response"] = "Table name cannot be empty";
static::$response["code"] = 5000;
return static::terminate(static::$response);
}
} | php | public function all()
{
$table = trim(self::$table);
if (!empty($table)) {
$query = /** @lang text */
"SELECT * FROM {$table}";
if(!empty($this->groupby)){
$query.=' GROUP BY '.$this->groupby;
}
if (!empty($this->order)) {
$query .= $this->order;
}
//execute the query and return the data or error message
return $this->fetch($query);
} else {
static::$response["status"] = "error";
static::$response["response"] = "Table name cannot be empty";
static::$response["code"] = 5000;
return static::terminate(static::$response);
}
} | [
"public",
"function",
"all",
"(",
")",
"{",
"$",
"table",
"=",
"trim",
"(",
"self",
"::",
"$",
"table",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"table",
")",
")",
"{",
"$",
"query",
"=",
"/** @lang text */",
"\"SELECT * FROM {$table}\"",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"groupby",
")",
")",
"{",
"$",
"query",
".=",
"' GROUP BY '",
".",
"$",
"this",
"->",
"groupby",
";",
"}",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"order",
")",
")",
"{",
"$",
"query",
".=",
"$",
"this",
"->",
"order",
";",
"}",
"//execute the query and return the data or error message",
"return",
"$",
"this",
"->",
"fetch",
"(",
"$",
"query",
")",
";",
"}",
"else",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"\"Table name cannot be empty\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"code\"",
"]",
"=",
"5000",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"}"
] | Fetch all data without limits or offset | [
"Fetch",
"all",
"data",
"without",
"limits",
"or",
"offset"
] | a9339b6dea5be52b79095b9c001684c162a09bf6 | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L370-L397 | train |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.insert | public function insert($values)
{
try {
if (func_num_args() > 0 && !is_array($values)) {
$this->values = array_merge($this->values, self::sanitizeAV(func_get_args()));
} else if (is_array($values)) {
$this->values = self::sanitize($values);
} else {
static::$response["status"] = "error";
static::$response["response"] = "unrecognized parameter options in the insert values";
static::$response["code"] = 7004;
return static::terminate(static::$response);
}
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
return $this;
} | php | public function insert($values)
{
try {
if (func_num_args() > 0 && !is_array($values)) {
$this->values = array_merge($this->values, self::sanitizeAV(func_get_args()));
} else if (is_array($values)) {
$this->values = self::sanitize($values);
} else {
static::$response["status"] = "error";
static::$response["response"] = "unrecognized parameter options in the insert values";
static::$response["code"] = 7004;
return static::terminate(static::$response);
}
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
return $this;
} | [
"public",
"function",
"insert",
"(",
"$",
"values",
")",
"{",
"try",
"{",
"if",
"(",
"func_num_args",
"(",
")",
">",
"0",
"&&",
"!",
"is_array",
"(",
"$",
"values",
")",
")",
"{",
"$",
"this",
"->",
"values",
"=",
"array_merge",
"(",
"$",
"this",
"->",
"values",
",",
"self",
"::",
"sanitizeAV",
"(",
"func_get_args",
"(",
")",
")",
")",
";",
"}",
"else",
"if",
"(",
"is_array",
"(",
"$",
"values",
")",
")",
"{",
"$",
"this",
"->",
"values",
"=",
"self",
"::",
"sanitize",
"(",
"$",
"values",
")",
";",
"}",
"else",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"\"unrecognized parameter options in the insert values\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"code\"",
"]",
"=",
"7004",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"$",
"e",
"->",
"getMessage",
"(",
")",
";",
"static",
"::",
"$",
"response",
"[",
"\"code\"",
"]",
"=",
"$",
"e",
"->",
"getCode",
"(",
")",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] | Sets the values to be inserted
@param $values
@return $this|string | [
"Sets",
"the",
"values",
"to",
"be",
"inserted"
] | a9339b6dea5be52b79095b9c001684c162a09bf6 | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L413-L434 | train |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.into | public function into($columns)
{
//if columns count does not match values count, throw an error.
$valuesCount = count($this->values);
$colStringCount = 0;
if (is_string($columns)) {
try {
$colStringCount = count(
explode(',', $columns)
);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = "Unrecognized characters. Please refer to documentation on how to insert a record";
static::$response["code"] = 4001;
return static::terminate(static::$response);
}
}
if (func_num_args() > 1 && func_num_args() == $valuesCount) {
$this->columns = $this->columnize(func_get_args());
} else if (is_array($columns) && count($columns) == $valuesCount) {
$this->columns = $this->columnize($columns);
} else if ($colStringCount == $valuesCount) {
$this->columns = $columns;
} else {
static::$response["status"] = "error";
static::$response["response"] = "Columns count does not equal the values count";
static::$response['code'] = 4005;
return static::terminate(static::$response);
}
return $this->doInsert();
} | php | public function into($columns)
{
//if columns count does not match values count, throw an error.
$valuesCount = count($this->values);
$colStringCount = 0;
if (is_string($columns)) {
try {
$colStringCount = count(
explode(',', $columns)
);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = "Unrecognized characters. Please refer to documentation on how to insert a record";
static::$response["code"] = 4001;
return static::terminate(static::$response);
}
}
if (func_num_args() > 1 && func_num_args() == $valuesCount) {
$this->columns = $this->columnize(func_get_args());
} else if (is_array($columns) && count($columns) == $valuesCount) {
$this->columns = $this->columnize($columns);
} else if ($colStringCount == $valuesCount) {
$this->columns = $columns;
} else {
static::$response["status"] = "error";
static::$response["response"] = "Columns count does not equal the values count";
static::$response['code'] = 4005;
return static::terminate(static::$response);
}
return $this->doInsert();
} | [
"public",
"function",
"into",
"(",
"$",
"columns",
")",
"{",
"//if columns count does not match values count, throw an error.",
"$",
"valuesCount",
"=",
"count",
"(",
"$",
"this",
"->",
"values",
")",
";",
"$",
"colStringCount",
"=",
"0",
";",
"if",
"(",
"is_string",
"(",
"$",
"columns",
")",
")",
"{",
"try",
"{",
"$",
"colStringCount",
"=",
"count",
"(",
"explode",
"(",
"','",
",",
"$",
"columns",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"\"Unrecognized characters. Please refer to documentation on how to insert a record\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"code\"",
"]",
"=",
"4001",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"}",
"if",
"(",
"func_num_args",
"(",
")",
">",
"1",
"&&",
"func_num_args",
"(",
")",
"==",
"$",
"valuesCount",
")",
"{",
"$",
"this",
"->",
"columns",
"=",
"$",
"this",
"->",
"columnize",
"(",
"func_get_args",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"is_array",
"(",
"$",
"columns",
")",
"&&",
"count",
"(",
"$",
"columns",
")",
"==",
"$",
"valuesCount",
")",
"{",
"$",
"this",
"->",
"columns",
"=",
"$",
"this",
"->",
"columnize",
"(",
"$",
"columns",
")",
";",
"}",
"else",
"if",
"(",
"$",
"colStringCount",
"==",
"$",
"valuesCount",
")",
"{",
"$",
"this",
"->",
"columns",
"=",
"$",
"columns",
";",
"}",
"else",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"\"Columns count does not equal the values count\"",
";",
"static",
"::",
"$",
"response",
"[",
"'code'",
"]",
"=",
"4005",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"return",
"$",
"this",
"->",
"doInsert",
"(",
")",
";",
"}"
] | Sets the column to which the values will be inserted
@param $columns
@return string | [
"Sets",
"the",
"column",
"to",
"which",
"the",
"values",
"will",
"be",
"inserted"
] | a9339b6dea5be52b79095b9c001684c162a09bf6 | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L441-L477 | train |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.doInsert | protected function doInsert()
{
//check if there is an error from previous function execution
if (static::$response["status"] == "error") {
return static::terminate(static::$response);
}
//convert each columns to ? parameter
$columnParam = array_map(function () {
return '?';
}, $this->values);
$sql = /** @lang sql */
'INSERT INTO ' . self::$table .
' (' . $this->columns .
') VALUES(' . implode(',', $columnParam) . ')';
$ext=array_map(function ($column){
return $column.'=VALUES('.$column.')';
},explode(',',$this->columns));
if($this->updateOrInsert){ //if update when duplicate is found is set to true
$sql.=' ON DUPLICATE KEY UPDATE '.implode(',',$ext);
}
try {
$stm = Connect::getConn()->prepare($sql);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
try {
$stm->execute($this->values);
static::$response["status"] = "success";
static::$response["response"] = "success";
static::$response["code"] = 200;
return static::terminate(static::$response);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
} | php | protected function doInsert()
{
//check if there is an error from previous function execution
if (static::$response["status"] == "error") {
return static::terminate(static::$response);
}
//convert each columns to ? parameter
$columnParam = array_map(function () {
return '?';
}, $this->values);
$sql = /** @lang sql */
'INSERT INTO ' . self::$table .
' (' . $this->columns .
') VALUES(' . implode(',', $columnParam) . ')';
$ext=array_map(function ($column){
return $column.'=VALUES('.$column.')';
},explode(',',$this->columns));
if($this->updateOrInsert){ //if update when duplicate is found is set to true
$sql.=' ON DUPLICATE KEY UPDATE '.implode(',',$ext);
}
try {
$stm = Connect::getConn()->prepare($sql);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
try {
$stm->execute($this->values);
static::$response["status"] = "success";
static::$response["response"] = "success";
static::$response["code"] = 200;
return static::terminate(static::$response);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
} | [
"protected",
"function",
"doInsert",
"(",
")",
"{",
"//check if there is an error from previous function execution",
"if",
"(",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"==",
"\"error\"",
")",
"{",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"//convert each columns to ? parameter",
"$",
"columnParam",
"=",
"array_map",
"(",
"function",
"(",
")",
"{",
"return",
"'?'",
";",
"}",
",",
"$",
"this",
"->",
"values",
")",
";",
"$",
"sql",
"=",
"/** @lang sql */",
"'INSERT INTO '",
".",
"self",
"::",
"$",
"table",
".",
"' ('",
".",
"$",
"this",
"->",
"columns",
".",
"') VALUES('",
".",
"implode",
"(",
"','",
",",
"$",
"columnParam",
")",
".",
"')'",
";",
"$",
"ext",
"=",
"array_map",
"(",
"function",
"(",
"$",
"column",
")",
"{",
"return",
"$",
"column",
".",
"'=VALUES('",
".",
"$",
"column",
".",
"')'",
";",
"}",
",",
"explode",
"(",
"','",
",",
"$",
"this",
"->",
"columns",
")",
")",
";",
"if",
"(",
"$",
"this",
"->",
"updateOrInsert",
")",
"{",
"//if update when duplicate is found is set to true",
"$",
"sql",
".=",
"' ON DUPLICATE KEY UPDATE '",
".",
"implode",
"(",
"','",
",",
"$",
"ext",
")",
";",
"}",
"try",
"{",
"$",
"stm",
"=",
"Connect",
"::",
"getConn",
"(",
")",
"->",
"prepare",
"(",
"$",
"sql",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"$",
"e",
"->",
"getMessage",
"(",
")",
";",
"static",
"::",
"$",
"response",
"[",
"\"code\"",
"]",
"=",
"$",
"e",
"->",
"getCode",
"(",
")",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"try",
"{",
"$",
"stm",
"->",
"execute",
"(",
"$",
"this",
"->",
"values",
")",
";",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"success\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"\"success\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"code\"",
"]",
"=",
"200",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"$",
"e",
"->",
"getMessage",
"(",
")",
";",
"static",
"::",
"$",
"response",
"[",
"\"code\"",
"]",
"=",
"$",
"e",
"->",
"getCode",
"(",
")",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"}"
] | Performs the actual database insert
@return string | [
"Performs",
"the",
"actual",
"database",
"insert"
] | a9339b6dea5be52b79095b9c001684c162a09bf6 | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L483-L530 | train |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.isAssocStr | private function isAssocStr($array)
{
if(!is_array($array)){
return false;
}
for (reset($array); is_int(key($array));
next($array)) {
if (is_null(key($array)))
return false;
}
return true;
} | php | private function isAssocStr($array)
{
if(!is_array($array)){
return false;
}
for (reset($array); is_int(key($array));
next($array)) {
if (is_null(key($array)))
return false;
}
return true;
} | [
"private",
"function",
"isAssocStr",
"(",
"$",
"array",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"array",
")",
")",
"{",
"return",
"false",
";",
"}",
"for",
"(",
"reset",
"(",
"$",
"array",
")",
";",
"is_int",
"(",
"key",
"(",
"$",
"array",
")",
")",
";",
"next",
"(",
"$",
"array",
")",
")",
"{",
"if",
"(",
"is_null",
"(",
"key",
"(",
"$",
"array",
")",
")",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Function to check if an array is association or sequential
@param $array
@return bool | [
"Function",
"to",
"check",
"if",
"an",
"array",
"is",
"association",
"or",
"sequential"
] | a9339b6dea5be52b79095b9c001684c162a09bf6 | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L607-L618 | train |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.exec | protected function exec($query)
{
try {
Connect::getConn()->exec($query);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
return null;
} | php | protected function exec($query)
{
try {
Connect::getConn()->exec($query);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
return null;
} | [
"protected",
"function",
"exec",
"(",
"$",
"query",
")",
"{",
"try",
"{",
"Connect",
"::",
"getConn",
"(",
")",
"->",
"exec",
"(",
"$",
"query",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"$",
"e",
"->",
"getMessage",
"(",
")",
";",
"static",
"::",
"$",
"response",
"[",
"\"code\"",
"]",
"=",
"$",
"e",
"->",
"getCode",
"(",
")",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"return",
"null",
";",
"}"
] | Executes a query that does not return any results
@param $query
@return null|string | [
"Executes",
"a",
"query",
"that",
"does",
"not",
"return",
"any",
"results"
] | a9339b6dea5be52b79095b9c001684c162a09bf6 | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L657-L669 | train |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.valTable | private static function valTable(){
if(static::$table==null || ! is_string(static::$table)){
static::$response["status"] = "error";
static::$response["response"] = "check the table name provided";
static::$response["code"]=5000;
return self::terminate(static::$response);
}else{
static::$table=self::sanitize(static::$table);
}
return static::$table; //no effect
} | php | private static function valTable(){
if(static::$table==null || ! is_string(static::$table)){
static::$response["status"] = "error";
static::$response["response"] = "check the table name provided";
static::$response["code"]=5000;
return self::terminate(static::$response);
}else{
static::$table=self::sanitize(static::$table);
}
return static::$table; //no effect
} | [
"private",
"static",
"function",
"valTable",
"(",
")",
"{",
"if",
"(",
"static",
"::",
"$",
"table",
"==",
"null",
"||",
"!",
"is_string",
"(",
"static",
"::",
"$",
"table",
")",
")",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"\"check the table name provided\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"code\"",
"]",
"=",
"5000",
";",
"return",
"self",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"else",
"{",
"static",
"::",
"$",
"table",
"=",
"self",
"::",
"sanitize",
"(",
"static",
"::",
"$",
"table",
")",
";",
"}",
"return",
"static",
"::",
"$",
"table",
";",
"//no effect",
"}"
] | Validate that the table name has been provided and is a string | [
"Validate",
"that",
"the",
"table",
"name",
"has",
"been",
"provided",
"and",
"is",
"a",
"string"
] | a9339b6dea5be52b79095b9c001684c162a09bf6 | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L700-L711 | train |
mimidotsuser/sqlQueryuilder | src/Builder.php | Builder.drop | public function drop()
{
static::valTable();
$sql = /** @lang text */
"DROP TABLE " . self::$table;
try {
$this->exec($sql);
static::$response["status"] = "success";
static::$response["response"] = "success";
return self::terminate(static::$response);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
} | php | public function drop()
{
static::valTable();
$sql = /** @lang text */
"DROP TABLE " . self::$table;
try {
$this->exec($sql);
static::$response["status"] = "success";
static::$response["response"] = "success";
return self::terminate(static::$response);
} catch (Exception $e) {
static::$response["status"] = "error";
static::$response["response"] = $e->getMessage();
static::$response["code"] = $e->getCode();
return static::terminate(static::$response);
}
} | [
"public",
"function",
"drop",
"(",
")",
"{",
"static",
"::",
"valTable",
"(",
")",
";",
"$",
"sql",
"=",
"/** @lang text */",
"\"DROP TABLE \"",
".",
"self",
"::",
"$",
"table",
";",
"try",
"{",
"$",
"this",
"->",
"exec",
"(",
"$",
"sql",
")",
";",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"success\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"\"success\"",
";",
"return",
"self",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"catch",
"(",
"Exception",
"$",
"e",
")",
"{",
"static",
"::",
"$",
"response",
"[",
"\"status\"",
"]",
"=",
"\"error\"",
";",
"static",
"::",
"$",
"response",
"[",
"\"response\"",
"]",
"=",
"$",
"e",
"->",
"getMessage",
"(",
")",
";",
"static",
"::",
"$",
"response",
"[",
"\"code\"",
"]",
"=",
"$",
"e",
"->",
"getCode",
"(",
")",
";",
"return",
"static",
"::",
"terminate",
"(",
"static",
"::",
"$",
"response",
")",
";",
"}",
"}"
] | Function to drop a table
@return string | [
"Function",
"to",
"drop",
"a",
"table"
] | a9339b6dea5be52b79095b9c001684c162a09bf6 | https://github.com/mimidotsuser/sqlQueryuilder/blob/a9339b6dea5be52b79095b9c001684c162a09bf6/src/Builder.php#L717-L736 | train |
Etenil/assegai | src/assegai/modules/Module.php | Module.setDependencies | function setDependencies(\assegai\Server $server, ModuleContainer $modules)
{
$this->server = $server;
$this->modules = $modules;
} | php | function setDependencies(\assegai\Server $server, ModuleContainer $modules)
{
$this->server = $server;
$this->modules = $modules;
} | [
"function",
"setDependencies",
"(",
"\\",
"assegai",
"\\",
"Server",
"$",
"server",
",",
"ModuleContainer",
"$",
"modules",
")",
"{",
"$",
"this",
"->",
"server",
"=",
"$",
"server",
";",
"$",
"this",
"->",
"modules",
"=",
"$",
"modules",
";",
"}"
] | Default module constructor. Loads options into properties.
@param array $options is an associative array whose keys will
be mapped to properties for speed populating of the object. | [
"Default",
"module",
"constructor",
".",
"Loads",
"options",
"into",
"properties",
"."
] | d43cce1a88f1c332f60dd0a4374b17764852af9e | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/Module.php#L41-L45 | train |
Etenil/assegai | src/assegai/modules/Module.php | Module.getOption | protected function getOption($option, $default = false)
{
return isset($this->options[$option])? $this->options[$option] : $default;
} | php | protected function getOption($option, $default = false)
{
return isset($this->options[$option])? $this->options[$option] : $default;
} | [
"protected",
"function",
"getOption",
"(",
"$",
"option",
",",
"$",
"default",
"=",
"false",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"options",
"[",
"$",
"option",
"]",
")",
"?",
"$",
"this",
"->",
"options",
"[",
"$",
"option",
"]",
":",
"$",
"default",
";",
"}"
] | Just a convenient wrapper to retrieve an option.
@param string $option is the option's name to retrieve.
@param mixed $default default value returned if option doesn't
exist. Default is false.
@return the value or default value. | [
"Just",
"a",
"convenient",
"wrapper",
"to",
"retrieve",
"an",
"option",
"."
] | d43cce1a88f1c332f60dd0a4374b17764852af9e | https://github.com/Etenil/assegai/blob/d43cce1a88f1c332f60dd0a4374b17764852af9e/src/assegai/modules/Module.php#L76-L79 | train |
3ev/wordpress-core | src/Tev/Field/Model/PostField.php | PostField.getValue | public function getValue()
{
$val = $this->base['value'];
if (is_array($val)) {
$posts = array();
foreach ($val as $p) {
$posts[] = $this->postFactory->create($this->getPostObject($p));
}
return $posts;
} elseif (strlen($val)) {
return $this->postFactory->create($this->getPostObject($val));
} else {
if (isset($this->base['multiple']) && $this->base['multiple']) {
return array();
} else {
return null;
}
}
} | php | public function getValue()
{
$val = $this->base['value'];
if (is_array($val)) {
$posts = array();
foreach ($val as $p) {
$posts[] = $this->postFactory->create($this->getPostObject($p));
}
return $posts;
} elseif (strlen($val)) {
return $this->postFactory->create($this->getPostObject($val));
} else {
if (isset($this->base['multiple']) && $this->base['multiple']) {
return array();
} else {
return null;
}
}
} | [
"public",
"function",
"getValue",
"(",
")",
"{",
"$",
"val",
"=",
"$",
"this",
"->",
"base",
"[",
"'value'",
"]",
";",
"if",
"(",
"is_array",
"(",
"$",
"val",
")",
")",
"{",
"$",
"posts",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"val",
"as",
"$",
"p",
")",
"{",
"$",
"posts",
"[",
"]",
"=",
"$",
"this",
"->",
"postFactory",
"->",
"create",
"(",
"$",
"this",
"->",
"getPostObject",
"(",
"$",
"p",
")",
")",
";",
"}",
"return",
"$",
"posts",
";",
"}",
"elseif",
"(",
"strlen",
"(",
"$",
"val",
")",
")",
"{",
"return",
"$",
"this",
"->",
"postFactory",
"->",
"create",
"(",
"$",
"this",
"->",
"getPostObject",
"(",
"$",
"val",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"base",
"[",
"'multiple'",
"]",
")",
"&&",
"$",
"this",
"->",
"base",
"[",
"'multiple'",
"]",
")",
"{",
"return",
"array",
"(",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"}"
] | Get a single post object or array of post objects.
If no posts are configured, returned will result will be an empty array
if this is a mutli-select, or null if not.
@return \Tev\Post\Model\Post|\Tev\Post\Model\Post[]|null | [
"Get",
"a",
"single",
"post",
"object",
"or",
"array",
"of",
"post",
"objects",
"."
] | da674fbec5bf3d5bd2a2141680a4c141113eb6b0 | https://github.com/3ev/wordpress-core/blob/da674fbec5bf3d5bd2a2141680a4c141113eb6b0/src/Tev/Field/Model/PostField.php#L43-L64 | train |
armazon/armazon | src/Armazon/Servidor/Swoole.php | Swoole.detectarNucleosCPU | private function detectarNucleosCPU()
{
$cantidad_cpu = 1;
if (is_file('/proc/cpuinfo')) {
$cpu_info = file_get_contents('/proc/cpuinfo');
preg_match_all('/^processor/m', $cpu_info, $matches);
$cantidad_cpu = count($matches[0]);
} else if ('WIN' == strtoupper(substr(PHP_OS, 0, 3))) {
$process = @popen('wmic cpu get NumberOfCores', 'rb');
if (false !== $process) {
fgets($process);
$cantidad_cpu = intval(fgets($process));
pclose($process);
}
} else {
$process = @popen('sysctl -a', 'rb');
if (false !== $process) {
$output = stream_get_contents($process);
preg_match('/hw.ncpu: (\d+)/', $output, $matches);
if ($matches) {
$cantidad_cpu = intval($matches[1][0]);
}
pclose($process);
}
}
return $cantidad_cpu;
} | php | private function detectarNucleosCPU()
{
$cantidad_cpu = 1;
if (is_file('/proc/cpuinfo')) {
$cpu_info = file_get_contents('/proc/cpuinfo');
preg_match_all('/^processor/m', $cpu_info, $matches);
$cantidad_cpu = count($matches[0]);
} else if ('WIN' == strtoupper(substr(PHP_OS, 0, 3))) {
$process = @popen('wmic cpu get NumberOfCores', 'rb');
if (false !== $process) {
fgets($process);
$cantidad_cpu = intval(fgets($process));
pclose($process);
}
} else {
$process = @popen('sysctl -a', 'rb');
if (false !== $process) {
$output = stream_get_contents($process);
preg_match('/hw.ncpu: (\d+)/', $output, $matches);
if ($matches) {
$cantidad_cpu = intval($matches[1][0]);
}
pclose($process);
}
}
return $cantidad_cpu;
} | [
"private",
"function",
"detectarNucleosCPU",
"(",
")",
"{",
"$",
"cantidad_cpu",
"=",
"1",
";",
"if",
"(",
"is_file",
"(",
"'/proc/cpuinfo'",
")",
")",
"{",
"$",
"cpu_info",
"=",
"file_get_contents",
"(",
"'/proc/cpuinfo'",
")",
";",
"preg_match_all",
"(",
"'/^processor/m'",
",",
"$",
"cpu_info",
",",
"$",
"matches",
")",
";",
"$",
"cantidad_cpu",
"=",
"count",
"(",
"$",
"matches",
"[",
"0",
"]",
")",
";",
"}",
"else",
"if",
"(",
"'WIN'",
"==",
"strtoupper",
"(",
"substr",
"(",
"PHP_OS",
",",
"0",
",",
"3",
")",
")",
")",
"{",
"$",
"process",
"=",
"@",
"popen",
"(",
"'wmic cpu get NumberOfCores'",
",",
"'rb'",
")",
";",
"if",
"(",
"false",
"!==",
"$",
"process",
")",
"{",
"fgets",
"(",
"$",
"process",
")",
";",
"$",
"cantidad_cpu",
"=",
"intval",
"(",
"fgets",
"(",
"$",
"process",
")",
")",
";",
"pclose",
"(",
"$",
"process",
")",
";",
"}",
"}",
"else",
"{",
"$",
"process",
"=",
"@",
"popen",
"(",
"'sysctl -a'",
",",
"'rb'",
")",
";",
"if",
"(",
"false",
"!==",
"$",
"process",
")",
"{",
"$",
"output",
"=",
"stream_get_contents",
"(",
"$",
"process",
")",
";",
"preg_match",
"(",
"'/hw.ncpu: (\\d+)/'",
",",
"$",
"output",
",",
"$",
"matches",
")",
";",
"if",
"(",
"$",
"matches",
")",
"{",
"$",
"cantidad_cpu",
"=",
"intval",
"(",
"$",
"matches",
"[",
"1",
"]",
"[",
"0",
"]",
")",
";",
"}",
"pclose",
"(",
"$",
"process",
")",
";",
"}",
"}",
"return",
"$",
"cantidad_cpu",
";",
"}"
] | Devuelve la cantidad de nucleos del CPU
@return int | [
"Devuelve",
"la",
"cantidad",
"de",
"nucleos",
"del",
"CPU"
] | ec76385ff80ce1659d81bc4050ef9483ab0ebe52 | https://github.com/armazon/armazon/blob/ec76385ff80ce1659d81bc4050ef9483ab0ebe52/src/Armazon/Servidor/Swoole.php#L17-L44 | train |
akumar2-velsof/guzzlehttp | src/Utils.php | Utils.getPath | public static function getPath($data, $path)
{
$path = explode('/', $path);
while (null !== ($part = array_shift($path))) {
if (!is_array($data) || !isset($data[$part])) {
return null;
}
$data = $data[$part];
}
return $data;
} | php | public static function getPath($data, $path)
{
$path = explode('/', $path);
while (null !== ($part = array_shift($path))) {
if (!is_array($data) || !isset($data[$part])) {
return null;
}
$data = $data[$part];
}
return $data;
} | [
"public",
"static",
"function",
"getPath",
"(",
"$",
"data",
",",
"$",
"path",
")",
"{",
"$",
"path",
"=",
"explode",
"(",
"'/'",
",",
"$",
"path",
")",
";",
"while",
"(",
"null",
"!==",
"(",
"$",
"part",
"=",
"array_shift",
"(",
"$",
"path",
")",
")",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"data",
")",
"||",
"!",
"isset",
"(",
"$",
"data",
"[",
"$",
"part",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"data",
"=",
"$",
"data",
"[",
"$",
"part",
"]",
";",
"}",
"return",
"$",
"data",
";",
"}"
] | Gets a value from an array using a path syntax to retrieve nested data.
This method does not allow for keys that contain "/". You must traverse
the array manually or using something more advanced like JMESPath to
work with keys that contain "/".
// Get the bar key of a set of nested arrays.
// This is equivalent to $collection['foo']['baz']['bar'] but won't
// throw warnings for missing keys.
GuzzleHttp1\get_path($data, 'foo/baz/bar');
@param array $data Data to retrieve values from
@param string $path Path to traverse and retrieve a value from
@return mixed|null | [
"Gets",
"a",
"value",
"from",
"an",
"array",
"using",
"a",
"path",
"syntax",
"to",
"retrieve",
"nested",
"data",
"."
] | 9588a489c52b27e2d4047f146ddacffc3e111b7e | https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/Utils.php#L31-L43 | train |
akumar2-velsof/guzzlehttp | src/Utils.php | Utils.setPath | public static function setPath(&$data, $path, $value)
{
$queue = explode('/', $path);
// Optimization for simple sets.
if (count($queue) === 1) {
$data[$path] = $value;
return;
}
$current =& $data;
while (null !== ($key = array_shift($queue))) {
if (!is_array($current)) {
throw new \RuntimeException("Trying to setPath {$path}, but "
. "{$key} is set and is not an array");
} elseif (!$queue) {
if ($key == '[]') {
$current[] = $value;
} else {
$current[$key] = $value;
}
} elseif (isset($current[$key])) {
$current =& $current[$key];
} else {
$current[$key] = [];
$current =& $current[$key];
}
}
} | php | public static function setPath(&$data, $path, $value)
{
$queue = explode('/', $path);
// Optimization for simple sets.
if (count($queue) === 1) {
$data[$path] = $value;
return;
}
$current =& $data;
while (null !== ($key = array_shift($queue))) {
if (!is_array($current)) {
throw new \RuntimeException("Trying to setPath {$path}, but "
. "{$key} is set and is not an array");
} elseif (!$queue) {
if ($key == '[]') {
$current[] = $value;
} else {
$current[$key] = $value;
}
} elseif (isset($current[$key])) {
$current =& $current[$key];
} else {
$current[$key] = [];
$current =& $current[$key];
}
}
} | [
"public",
"static",
"function",
"setPath",
"(",
"&",
"$",
"data",
",",
"$",
"path",
",",
"$",
"value",
")",
"{",
"$",
"queue",
"=",
"explode",
"(",
"'/'",
",",
"$",
"path",
")",
";",
"// Optimization for simple sets.",
"if",
"(",
"count",
"(",
"$",
"queue",
")",
"===",
"1",
")",
"{",
"$",
"data",
"[",
"$",
"path",
"]",
"=",
"$",
"value",
";",
"return",
";",
"}",
"$",
"current",
"=",
"&",
"$",
"data",
";",
"while",
"(",
"null",
"!==",
"(",
"$",
"key",
"=",
"array_shift",
"(",
"$",
"queue",
")",
")",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"current",
")",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"Trying to setPath {$path}, but \"",
".",
"\"{$key} is set and is not an array\"",
")",
";",
"}",
"elseif",
"(",
"!",
"$",
"queue",
")",
"{",
"if",
"(",
"$",
"key",
"==",
"'[]'",
")",
"{",
"$",
"current",
"[",
"]",
"=",
"$",
"value",
";",
"}",
"else",
"{",
"$",
"current",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"}",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"current",
"[",
"$",
"key",
"]",
")",
")",
"{",
"$",
"current",
"=",
"&",
"$",
"current",
"[",
"$",
"key",
"]",
";",
"}",
"else",
"{",
"$",
"current",
"[",
"$",
"key",
"]",
"=",
"[",
"]",
";",
"$",
"current",
"=",
"&",
"$",
"current",
"[",
"$",
"key",
"]",
";",
"}",
"}",
"}"
] | Set a value in a nested array key. Keys will be created as needed to set
the value.
This function does not support keys that contain "/" or "[]" characters
because these are special tokens used when traversing the data structure.
A value may be prepended to an existing array by using "[]" as the final
key of a path.
GuzzleHttp1\get_path($data, 'foo/baz'); // null
GuzzleHttp1\set_path($data, 'foo/baz/[]', 'a');
GuzzleHttp1\set_path($data, 'foo/baz/[]', 'b');
GuzzleHttp1\get_path($data, 'foo/baz');
// Returns ['a', 'b']
@param array $data Data to modify by reference
@param string $path Path to set
@param mixed $value Value to set at the key
@throws \RuntimeException when trying to setPath using a nested path
that travels through a scalar value. | [
"Set",
"a",
"value",
"in",
"a",
"nested",
"array",
"key",
".",
"Keys",
"will",
"be",
"created",
"as",
"needed",
"to",
"set",
"the",
"value",
"."
] | 9588a489c52b27e2d4047f146ddacffc3e111b7e | https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/Utils.php#L67-L94 | train |
akumar2-velsof/guzzlehttp | src/Utils.php | Utils.uriTemplate | public static function uriTemplate($template, array $variables)
{
if (function_exists('\\uri_template')) {
return \uri_template($template, $variables);
}
static $uriTemplate;
if (!$uriTemplate) {
$uriTemplate = new UriTemplate();
}
return $uriTemplate->expand($template, $variables);
} | php | public static function uriTemplate($template, array $variables)
{
if (function_exists('\\uri_template')) {
return \uri_template($template, $variables);
}
static $uriTemplate;
if (!$uriTemplate) {
$uriTemplate = new UriTemplate();
}
return $uriTemplate->expand($template, $variables);
} | [
"public",
"static",
"function",
"uriTemplate",
"(",
"$",
"template",
",",
"array",
"$",
"variables",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'\\\\uri_template'",
")",
")",
"{",
"return",
"\\",
"uri_template",
"(",
"$",
"template",
",",
"$",
"variables",
")",
";",
"}",
"static",
"$",
"uriTemplate",
";",
"if",
"(",
"!",
"$",
"uriTemplate",
")",
"{",
"$",
"uriTemplate",
"=",
"new",
"UriTemplate",
"(",
")",
";",
"}",
"return",
"$",
"uriTemplate",
"->",
"expand",
"(",
"$",
"template",
",",
"$",
"variables",
")",
";",
"}"
] | Expands a URI template
@param string $template URI template
@param array $variables Template variables
@return string | [
"Expands",
"a",
"URI",
"template"
] | 9588a489c52b27e2d4047f146ddacffc3e111b7e | https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/Utils.php#L104-L116 | train |
akumar2-velsof/guzzlehttp | src/Utils.php | Utils.jsonDecode | public static function jsonDecode($json, $assoc = false, $depth = 512, $options = 0)
{
if ($json === '' || $json === null) {
return null;
}
static $jsonErrors = [
JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch',
JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found',
JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON',
JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded'
];
$data = \json_decode($json, $assoc, $depth, $options);
if (JSON_ERROR_NONE !== json_last_error()) {
$last = json_last_error();
throw new \InvalidArgumentException(
'Unable to parse JSON data: '
. (isset($jsonErrors[$last])
? $jsonErrors[$last]
: 'Unknown error')
);
}
return $data;
} | php | public static function jsonDecode($json, $assoc = false, $depth = 512, $options = 0)
{
if ($json === '' || $json === null) {
return null;
}
static $jsonErrors = [
JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch',
JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found',
JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON',
JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded'
];
$data = \json_decode($json, $assoc, $depth, $options);
if (JSON_ERROR_NONE !== json_last_error()) {
$last = json_last_error();
throw new \InvalidArgumentException(
'Unable to parse JSON data: '
. (isset($jsonErrors[$last])
? $jsonErrors[$last]
: 'Unknown error')
);
}
return $data;
} | [
"public",
"static",
"function",
"jsonDecode",
"(",
"$",
"json",
",",
"$",
"assoc",
"=",
"false",
",",
"$",
"depth",
"=",
"512",
",",
"$",
"options",
"=",
"0",
")",
"{",
"if",
"(",
"$",
"json",
"===",
"''",
"||",
"$",
"json",
"===",
"null",
")",
"{",
"return",
"null",
";",
"}",
"static",
"$",
"jsonErrors",
"=",
"[",
"JSON_ERROR_DEPTH",
"=>",
"'JSON_ERROR_DEPTH - Maximum stack depth exceeded'",
",",
"JSON_ERROR_STATE_MISMATCH",
"=>",
"'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch'",
",",
"JSON_ERROR_CTRL_CHAR",
"=>",
"'JSON_ERROR_CTRL_CHAR - Unexpected control character found'",
",",
"JSON_ERROR_SYNTAX",
"=>",
"'JSON_ERROR_SYNTAX - Syntax error, malformed JSON'",
",",
"JSON_ERROR_UTF8",
"=>",
"'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded'",
"]",
";",
"$",
"data",
"=",
"\\",
"json_decode",
"(",
"$",
"json",
",",
"$",
"assoc",
",",
"$",
"depth",
",",
"$",
"options",
")",
";",
"if",
"(",
"JSON_ERROR_NONE",
"!==",
"json_last_error",
"(",
")",
")",
"{",
"$",
"last",
"=",
"json_last_error",
"(",
")",
";",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Unable to parse JSON data: '",
".",
"(",
"isset",
"(",
"$",
"jsonErrors",
"[",
"$",
"last",
"]",
")",
"?",
"$",
"jsonErrors",
"[",
"$",
"last",
"]",
":",
"'Unknown error'",
")",
")",
";",
"}",
"return",
"$",
"data",
";",
"}"
] | Wrapper for JSON decode that implements error detection with helpful
error messages.
@param string $json JSON data to parse
@param bool $assoc When true, returned objects will be converted
into associative arrays.
@param int $depth User specified recursion depth.
@param int $options Bitmask of JSON decode options.
@return mixed
@throws \InvalidArgumentException if the JSON cannot be parsed.
@link http://www.php.net/manual/en/function.json-decode.php | [
"Wrapper",
"for",
"JSON",
"decode",
"that",
"implements",
"error",
"detection",
"with",
"helpful",
"error",
"messages",
"."
] | 9588a489c52b27e2d4047f146ddacffc3e111b7e | https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/Utils.php#L132-L159 | train |
akumar2-velsof/guzzlehttp | src/Utils.php | Utils.getDefaultHandler | public static function getDefaultHandler()
{
$default = $future = null;
if (extension_loaded('curl')) {
$config = [
'select_timeout' => getenv('GUZZLE_CURL_SELECT_TIMEOUT') ?: 1
];
if ($maxHandles = getenv('GUZZLE_CURL_MAX_HANDLES')) {
$config['max_handles'] = $maxHandles;
}
if (function_exists('curl_reset')) {
$default = new CurlHandler();
$future = new CurlMultiHandler($config);
} else {
$default = new CurlMultiHandler($config);
}
}
if (ini_get('allow_url_fopen')) {
$default = !$default
? new StreamHandler()
: Middleware::wrapStreaming($default, new StreamHandler());
} elseif (!$default) {
throw new \RuntimeException('Guzzle requires cURL, the '
. 'allow_url_fopen ini setting, or a custom HTTP handler.');
}
return $future ? Middleware::wrapFuture($default, $future) : $default;
} | php | public static function getDefaultHandler()
{
$default = $future = null;
if (extension_loaded('curl')) {
$config = [
'select_timeout' => getenv('GUZZLE_CURL_SELECT_TIMEOUT') ?: 1
];
if ($maxHandles = getenv('GUZZLE_CURL_MAX_HANDLES')) {
$config['max_handles'] = $maxHandles;
}
if (function_exists('curl_reset')) {
$default = new CurlHandler();
$future = new CurlMultiHandler($config);
} else {
$default = new CurlMultiHandler($config);
}
}
if (ini_get('allow_url_fopen')) {
$default = !$default
? new StreamHandler()
: Middleware::wrapStreaming($default, new StreamHandler());
} elseif (!$default) {
throw new \RuntimeException('Guzzle requires cURL, the '
. 'allow_url_fopen ini setting, or a custom HTTP handler.');
}
return $future ? Middleware::wrapFuture($default, $future) : $default;
} | [
"public",
"static",
"function",
"getDefaultHandler",
"(",
")",
"{",
"$",
"default",
"=",
"$",
"future",
"=",
"null",
";",
"if",
"(",
"extension_loaded",
"(",
"'curl'",
")",
")",
"{",
"$",
"config",
"=",
"[",
"'select_timeout'",
"=>",
"getenv",
"(",
"'GUZZLE_CURL_SELECT_TIMEOUT'",
")",
"?",
":",
"1",
"]",
";",
"if",
"(",
"$",
"maxHandles",
"=",
"getenv",
"(",
"'GUZZLE_CURL_MAX_HANDLES'",
")",
")",
"{",
"$",
"config",
"[",
"'max_handles'",
"]",
"=",
"$",
"maxHandles",
";",
"}",
"if",
"(",
"function_exists",
"(",
"'curl_reset'",
")",
")",
"{",
"$",
"default",
"=",
"new",
"CurlHandler",
"(",
")",
";",
"$",
"future",
"=",
"new",
"CurlMultiHandler",
"(",
"$",
"config",
")",
";",
"}",
"else",
"{",
"$",
"default",
"=",
"new",
"CurlMultiHandler",
"(",
"$",
"config",
")",
";",
"}",
"}",
"if",
"(",
"ini_get",
"(",
"'allow_url_fopen'",
")",
")",
"{",
"$",
"default",
"=",
"!",
"$",
"default",
"?",
"new",
"StreamHandler",
"(",
")",
":",
"Middleware",
"::",
"wrapStreaming",
"(",
"$",
"default",
",",
"new",
"StreamHandler",
"(",
")",
")",
";",
"}",
"elseif",
"(",
"!",
"$",
"default",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"'Guzzle requires cURL, the '",
".",
"'allow_url_fopen ini setting, or a custom HTTP handler.'",
")",
";",
"}",
"return",
"$",
"future",
"?",
"Middleware",
"::",
"wrapFuture",
"(",
"$",
"default",
",",
"$",
"future",
")",
":",
"$",
"default",
";",
"}"
] | Create a default handler to use based on the environment
@throws \RuntimeException if no viable Handler is available. | [
"Create",
"a",
"default",
"handler",
"to",
"use",
"based",
"on",
"the",
"environment"
] | 9588a489c52b27e2d4047f146ddacffc3e111b7e | https://github.com/akumar2-velsof/guzzlehttp/blob/9588a489c52b27e2d4047f146ddacffc3e111b7e/src/Utils.php#L185-L214 | train |
mlocati/concrete5-translation-library | src/Parser.php | Parser.parseDirectory | final public function parseDirectory($rootDirectory, $relativePath, $translations = null, $subParsersFilter = false, $exclude3rdParty = true)
{
if (!is_object($translations)) {
$translations = new \Gettext\Translations();
}
$dir = (string) $rootDirectory;
if ($dir !== '') {
$dir = @realpath($rootDirectory);
if (($dir === false) || (!is_dir($dir))) {
$dir = '';
} else {
$dir = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $dir), '/');
}
}
if ($dir === '') {
throw new \Exception("Unable to find the directory $rootDirectory");
}
if (!@is_readable($dir)) {
throw new \Exception("Directory not readable: $dir");
}
$dirRel = is_string($relativePath) ? trim(str_replace(DIRECTORY_SEPARATOR, '/', $relativePath), '/') : '';
$this->parseDirectoryDo($translations, $dir, $dirRel, $subParsersFilter, $exclude3rdParty);
return $translations;
} | php | final public function parseDirectory($rootDirectory, $relativePath, $translations = null, $subParsersFilter = false, $exclude3rdParty = true)
{
if (!is_object($translations)) {
$translations = new \Gettext\Translations();
}
$dir = (string) $rootDirectory;
if ($dir !== '') {
$dir = @realpath($rootDirectory);
if (($dir === false) || (!is_dir($dir))) {
$dir = '';
} else {
$dir = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $dir), '/');
}
}
if ($dir === '') {
throw new \Exception("Unable to find the directory $rootDirectory");
}
if (!@is_readable($dir)) {
throw new \Exception("Directory not readable: $dir");
}
$dirRel = is_string($relativePath) ? trim(str_replace(DIRECTORY_SEPARATOR, '/', $relativePath), '/') : '';
$this->parseDirectoryDo($translations, $dir, $dirRel, $subParsersFilter, $exclude3rdParty);
return $translations;
} | [
"final",
"public",
"function",
"parseDirectory",
"(",
"$",
"rootDirectory",
",",
"$",
"relativePath",
",",
"$",
"translations",
"=",
"null",
",",
"$",
"subParsersFilter",
"=",
"false",
",",
"$",
"exclude3rdParty",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"is_object",
"(",
"$",
"translations",
")",
")",
"{",
"$",
"translations",
"=",
"new",
"\\",
"Gettext",
"\\",
"Translations",
"(",
")",
";",
"}",
"$",
"dir",
"=",
"(",
"string",
")",
"$",
"rootDirectory",
";",
"if",
"(",
"$",
"dir",
"!==",
"''",
")",
"{",
"$",
"dir",
"=",
"@",
"realpath",
"(",
"$",
"rootDirectory",
")",
";",
"if",
"(",
"(",
"$",
"dir",
"===",
"false",
")",
"||",
"(",
"!",
"is_dir",
"(",
"$",
"dir",
")",
")",
")",
"{",
"$",
"dir",
"=",
"''",
";",
"}",
"else",
"{",
"$",
"dir",
"=",
"rtrim",
"(",
"str_replace",
"(",
"DIRECTORY_SEPARATOR",
",",
"'/'",
",",
"$",
"dir",
")",
",",
"'/'",
")",
";",
"}",
"}",
"if",
"(",
"$",
"dir",
"===",
"''",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"Unable to find the directory $rootDirectory\"",
")",
";",
"}",
"if",
"(",
"!",
"@",
"is_readable",
"(",
"$",
"dir",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"Directory not readable: $dir\"",
")",
";",
"}",
"$",
"dirRel",
"=",
"is_string",
"(",
"$",
"relativePath",
")",
"?",
"trim",
"(",
"str_replace",
"(",
"DIRECTORY_SEPARATOR",
",",
"'/'",
",",
"$",
"relativePath",
")",
",",
"'/'",
")",
":",
"''",
";",
"$",
"this",
"->",
"parseDirectoryDo",
"(",
"$",
"translations",
",",
"$",
"dir",
",",
"$",
"dirRel",
",",
"$",
"subParsersFilter",
",",
"$",
"exclude3rdParty",
")",
";",
"return",
"$",
"translations",
";",
"}"
] | Extracts translations from a directory.
@param string $rootDirectory The base directory where we start looking translations from
@param string $relativePath The relative path (translations references will be prepended with this path)
@param \Gettext\Translations|null=null $translations The translations object where the translatable strings will be added (if null we'll create a new Translations instance)
@param array|false $subParsersFilter A list of sub-parsers handles (set to false to use all the sub-parsers)
@param bool $exclude3rdParty Exclude concrete5 3rd party directories (namely directories called 'vendor' and '3rdparty')
@throws \Exception Throws an \Exception in case of errors
@return \Gettext\Translations
@example If you want to parse the concrete5 core directory, you should call `parseDirectory('PathToTheWebroot/concrete', 'concrete')`
@example If you want to parse a concrete5 package, you should call `parseDirectory('PathToThePackageFolder', 'packages/YourPackageHandle')` | [
"Extracts",
"translations",
"from",
"a",
"directory",
"."
] | 26f806c8c1ecb6ce63115a4058ab396303622e00 | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser.php#L74-L98 | train |
mlocati/concrete5-translation-library | src/Parser.php | Parser.parseRunningConcrete5 | final public function parseRunningConcrete5($translations = null, $subParsersFilter = false)
{
if (!is_object($translations)) {
$translations = new \Gettext\Translations();
}
$runningVersion = '';
if (defined('\C5_EXECUTE') && defined('\APP_VERSION') && is_string(\APP_VERSION)) {
$runningVersion = \APP_VERSION;
}
if ($runningVersion === '') {
throw new \Exception('Unable to determine the current working directory');
}
$this->parseRunningConcrete5Do($translations, $runningVersion, $subParsersFilter);
return $translations;
} | php | final public function parseRunningConcrete5($translations = null, $subParsersFilter = false)
{
if (!is_object($translations)) {
$translations = new \Gettext\Translations();
}
$runningVersion = '';
if (defined('\C5_EXECUTE') && defined('\APP_VERSION') && is_string(\APP_VERSION)) {
$runningVersion = \APP_VERSION;
}
if ($runningVersion === '') {
throw new \Exception('Unable to determine the current working directory');
}
$this->parseRunningConcrete5Do($translations, $runningVersion, $subParsersFilter);
return $translations;
} | [
"final",
"public",
"function",
"parseRunningConcrete5",
"(",
"$",
"translations",
"=",
"null",
",",
"$",
"subParsersFilter",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"is_object",
"(",
"$",
"translations",
")",
")",
"{",
"$",
"translations",
"=",
"new",
"\\",
"Gettext",
"\\",
"Translations",
"(",
")",
";",
"}",
"$",
"runningVersion",
"=",
"''",
";",
"if",
"(",
"defined",
"(",
"'\\C5_EXECUTE'",
")",
"&&",
"defined",
"(",
"'\\APP_VERSION'",
")",
"&&",
"is_string",
"(",
"\\",
"APP_VERSION",
")",
")",
"{",
"$",
"runningVersion",
"=",
"\\",
"APP_VERSION",
";",
"}",
"if",
"(",
"$",
"runningVersion",
"===",
"''",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Unable to determine the current working directory'",
")",
";",
"}",
"$",
"this",
"->",
"parseRunningConcrete5Do",
"(",
"$",
"translations",
",",
"$",
"runningVersion",
",",
"$",
"subParsersFilter",
")",
";",
"return",
"$",
"translations",
";",
"}"
] | Extracts translations from a running concrete5 instance.
@param \Gettext\Translations|null=null $translations The translations object where the translatable strings will be added (if null we'll create a new Translations instance)
@param array|false $subParsersFilter A list of sub-parsers handles (set to false to use all the sub-parsers)
@throws \Exception Throws an \Exception in case of errors
@return \Gettext\Translations | [
"Extracts",
"translations",
"from",
"a",
"running",
"concrete5",
"instance",
"."
] | 26f806c8c1ecb6ce63115a4058ab396303622e00 | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser.php#L134-L149 | train |
mlocati/concrete5-translation-library | src/Parser.php | Parser.getDirectoryStructure | final protected static function getDirectoryStructure($rootDirectory, $exclude3rdParty = true)
{
$rootDirectory = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $rootDirectory), '/');
if (!isset(self::$cache[__FUNCTION__])) {
self::$cache[__FUNCTION__] = array();
}
$cacheKey = $rootDirectory.'*'.($exclude3rdParty ? '1' : '0');
if (!isset(self::$cache[__FUNCTION__][$cacheKey])) {
self::$cache[__FUNCTION__][$cacheKey] = static::getDirectoryStructureDo('', $rootDirectory, $exclude3rdParty);
}
return self::$cache[__FUNCTION__][$cacheKey];
} | php | final protected static function getDirectoryStructure($rootDirectory, $exclude3rdParty = true)
{
$rootDirectory = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $rootDirectory), '/');
if (!isset(self::$cache[__FUNCTION__])) {
self::$cache[__FUNCTION__] = array();
}
$cacheKey = $rootDirectory.'*'.($exclude3rdParty ? '1' : '0');
if (!isset(self::$cache[__FUNCTION__][$cacheKey])) {
self::$cache[__FUNCTION__][$cacheKey] = static::getDirectoryStructureDo('', $rootDirectory, $exclude3rdParty);
}
return self::$cache[__FUNCTION__][$cacheKey];
} | [
"final",
"protected",
"static",
"function",
"getDirectoryStructure",
"(",
"$",
"rootDirectory",
",",
"$",
"exclude3rdParty",
"=",
"true",
")",
"{",
"$",
"rootDirectory",
"=",
"rtrim",
"(",
"str_replace",
"(",
"DIRECTORY_SEPARATOR",
",",
"'/'",
",",
"$",
"rootDirectory",
")",
",",
"'/'",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"cache",
"[",
"__FUNCTION__",
"]",
")",
")",
"{",
"self",
"::",
"$",
"cache",
"[",
"__FUNCTION__",
"]",
"=",
"array",
"(",
")",
";",
"}",
"$",
"cacheKey",
"=",
"$",
"rootDirectory",
".",
"'*'",
".",
"(",
"$",
"exclude3rdParty",
"?",
"'1'",
":",
"'0'",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"self",
"::",
"$",
"cache",
"[",
"__FUNCTION__",
"]",
"[",
"$",
"cacheKey",
"]",
")",
")",
"{",
"self",
"::",
"$",
"cache",
"[",
"__FUNCTION__",
"]",
"[",
"$",
"cacheKey",
"]",
"=",
"static",
"::",
"getDirectoryStructureDo",
"(",
"''",
",",
"$",
"rootDirectory",
",",
"$",
"exclude3rdParty",
")",
";",
"}",
"return",
"self",
"::",
"$",
"cache",
"[",
"__FUNCTION__",
"]",
"[",
"$",
"cacheKey",
"]",
";",
"}"
] | Returns the directory structure underneath a given directory.
@param string $rootDirectory The root directory
@param bool $exclude3rdParty=true Exclude concrete5 3rd party directories (namely directories called 'vendor' and '3rdparty')
@return array | [
"Returns",
"the",
"directory",
"structure",
"underneath",
"a",
"given",
"directory",
"."
] | 26f806c8c1ecb6ce63115a4058ab396303622e00 | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser.php#L189-L201 | train |
mlocati/concrete5-translation-library | src/Parser.php | Parser.getAllParsers | final public static function getAllParsers()
{
$result = array();
$dir = __DIR__.'/Parser';
if (is_dir($dir) && is_readable($dir)) {
$matches = null;
foreach (scandir($dir) as $item) {
if (($item[0] !== '.') && preg_match('/^(.+)\.php$/i', $item, $matches)) {
$fqClassName = '\\'.__NAMESPACE__.'\\Parser\\'.$matches[1];
$result[] = new $fqClassName();
}
}
}
return $result;
} | php | final public static function getAllParsers()
{
$result = array();
$dir = __DIR__.'/Parser';
if (is_dir($dir) && is_readable($dir)) {
$matches = null;
foreach (scandir($dir) as $item) {
if (($item[0] !== '.') && preg_match('/^(.+)\.php$/i', $item, $matches)) {
$fqClassName = '\\'.__NAMESPACE__.'\\Parser\\'.$matches[1];
$result[] = new $fqClassName();
}
}
}
return $result;
} | [
"final",
"public",
"static",
"function",
"getAllParsers",
"(",
")",
"{",
"$",
"result",
"=",
"array",
"(",
")",
";",
"$",
"dir",
"=",
"__DIR__",
".",
"'/Parser'",
";",
"if",
"(",
"is_dir",
"(",
"$",
"dir",
")",
"&&",
"is_readable",
"(",
"$",
"dir",
")",
")",
"{",
"$",
"matches",
"=",
"null",
";",
"foreach",
"(",
"scandir",
"(",
"$",
"dir",
")",
"as",
"$",
"item",
")",
"{",
"if",
"(",
"(",
"$",
"item",
"[",
"0",
"]",
"!==",
"'.'",
")",
"&&",
"preg_match",
"(",
"'/^(.+)\\.php$/i'",
",",
"$",
"item",
",",
"$",
"matches",
")",
")",
"{",
"$",
"fqClassName",
"=",
"'\\\\'",
".",
"__NAMESPACE__",
".",
"'\\\\Parser\\\\'",
".",
"$",
"matches",
"[",
"1",
"]",
";",
"$",
"result",
"[",
"]",
"=",
"new",
"$",
"fqClassName",
"(",
")",
";",
"}",
"}",
"}",
"return",
"$",
"result",
";",
"}"
] | Retrieves all the available parsers.
@return array[\C5TL\Parser] | [
"Retrieves",
"all",
"the",
"available",
"parsers",
"."
] | 26f806c8c1ecb6ce63115a4058ab396303622e00 | https://github.com/mlocati/concrete5-translation-library/blob/26f806c8c1ecb6ce63115a4058ab396303622e00/src/Parser.php#L256-L271 | train |
CodeCollab/Http | src/Cookie/Cookie.php | Cookie.send | public function send()
{
setcookie(
$this->name,
$this->value,
(int) $this->expire->format('U'),
$this->path,
$this->domain,
$this->secure,
$this->httpOnly
);
} | php | public function send()
{
setcookie(
$this->name,
$this->value,
(int) $this->expire->format('U'),
$this->path,
$this->domain,
$this->secure,
$this->httpOnly
);
} | [
"public",
"function",
"send",
"(",
")",
"{",
"setcookie",
"(",
"$",
"this",
"->",
"name",
",",
"$",
"this",
"->",
"value",
",",
"(",
"int",
")",
"$",
"this",
"->",
"expire",
"->",
"format",
"(",
"'U'",
")",
",",
"$",
"this",
"->",
"path",
",",
"$",
"this",
"->",
"domain",
",",
"$",
"this",
"->",
"secure",
",",
"$",
"this",
"->",
"httpOnly",
")",
";",
"}"
] | Sends the cookie header | [
"Sends",
"the",
"cookie",
"header"
] | b1f8306b20daebcf26ed4b13c032c5bc008a0861 | https://github.com/CodeCollab/Http/blob/b1f8306b20daebcf26ed4b13c032c5bc008a0861/src/Cookie/Cookie.php#L85-L96 | train |
luoxiaojun1992/lb_framework | components/Route.php | Route.triggerAopEvent | protected static function triggerAopEvent(
$controller_id,
$action_name,
$request = null,
$response = null
) {
$context = [
'controller_id' => $controller_id,
'action_id' => $action_name,
];
if ($request) {
$context['request'] = $request;
}
if ($response) {
$context['response'] = $response;
}
Lb::app()->trigger(
Event::AOP_EVENT . '_' . implode('@', [$controller_id, $action_name]),
new AopEvent($context)
);
Lb::app()->trigger(
Event::REQUEST_EVENT,
new RequestEvent($context)
);
} | php | protected static function triggerAopEvent(
$controller_id,
$action_name,
$request = null,
$response = null
) {
$context = [
'controller_id' => $controller_id,
'action_id' => $action_name,
];
if ($request) {
$context['request'] = $request;
}
if ($response) {
$context['response'] = $response;
}
Lb::app()->trigger(
Event::AOP_EVENT . '_' . implode('@', [$controller_id, $action_name]),
new AopEvent($context)
);
Lb::app()->trigger(
Event::REQUEST_EVENT,
new RequestEvent($context)
);
} | [
"protected",
"static",
"function",
"triggerAopEvent",
"(",
"$",
"controller_id",
",",
"$",
"action_name",
",",
"$",
"request",
"=",
"null",
",",
"$",
"response",
"=",
"null",
")",
"{",
"$",
"context",
"=",
"[",
"'controller_id'",
"=>",
"$",
"controller_id",
",",
"'action_id'",
"=>",
"$",
"action_name",
",",
"]",
";",
"if",
"(",
"$",
"request",
")",
"{",
"$",
"context",
"[",
"'request'",
"]",
"=",
"$",
"request",
";",
"}",
"if",
"(",
"$",
"response",
")",
"{",
"$",
"context",
"[",
"'response'",
"]",
"=",
"$",
"response",
";",
"}",
"Lb",
"::",
"app",
"(",
")",
"->",
"trigger",
"(",
"Event",
"::",
"AOP_EVENT",
".",
"'_'",
".",
"implode",
"(",
"'@'",
",",
"[",
"$",
"controller_id",
",",
"$",
"action_name",
"]",
")",
",",
"new",
"AopEvent",
"(",
"$",
"context",
")",
")",
";",
"Lb",
"::",
"app",
"(",
")",
"->",
"trigger",
"(",
"Event",
"::",
"REQUEST_EVENT",
",",
"new",
"RequestEvent",
"(",
"$",
"context",
")",
")",
";",
"}"
] | Trigger AOP Event
@param $controller_id
@param $action_name
@param null $request
@param null $response | [
"Trigger",
"AOP",
"Event"
] | 12a865729e7738d7d1e07371ad7203243c4571fa | https://github.com/luoxiaojun1992/lb_framework/blob/12a865729e7738d7d1e07371ad7203243c4571fa/components/Route.php#L295-L320 | train |
vincenttouzet/BootstrapFormBundle | Form/DataTransformer/DateRangeToStringTransformer.php | DateRangeToStringTransformer.transform | public function transform($value)
{
if ( $value ) {
$from = '';
if ( $value->getFrom() ) {
$from = $value->getFrom()->format('Y-m-d');
}
$to = '';
if ( $value->getTo() ) {
$to = $value->getTo()->format('Y-m-d');
}
return sprintf(
'%s%s%s',
$from,
$this->dateSeparator,
$to
);
}
} | php | public function transform($value)
{
if ( $value ) {
$from = '';
if ( $value->getFrom() ) {
$from = $value->getFrom()->format('Y-m-d');
}
$to = '';
if ( $value->getTo() ) {
$to = $value->getTo()->format('Y-m-d');
}
return sprintf(
'%s%s%s',
$from,
$this->dateSeparator,
$to
);
}
} | [
"public",
"function",
"transform",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
")",
"{",
"$",
"from",
"=",
"''",
";",
"if",
"(",
"$",
"value",
"->",
"getFrom",
"(",
")",
")",
"{",
"$",
"from",
"=",
"$",
"value",
"->",
"getFrom",
"(",
")",
"->",
"format",
"(",
"'Y-m-d'",
")",
";",
"}",
"$",
"to",
"=",
"''",
";",
"if",
"(",
"$",
"value",
"->",
"getTo",
"(",
")",
")",
"{",
"$",
"to",
"=",
"$",
"value",
"->",
"getTo",
"(",
")",
"->",
"format",
"(",
"'Y-m-d'",
")",
";",
"}",
"return",
"sprintf",
"(",
"'%s%s%s'",
",",
"$",
"from",
",",
"$",
"this",
"->",
"dateSeparator",
",",
"$",
"to",
")",
";",
"}",
"}"
] | Transforms a DateRange into a string.
@param DateRange $value DateRange value.
@return string string value. | [
"Transforms",
"a",
"DateRange",
"into",
"a",
"string",
"."
] | d648c825ca9f7020336023e82a1059fc070727ac | https://github.com/vincenttouzet/BootstrapFormBundle/blob/d648c825ca9f7020336023e82a1059fc070727ac/Form/DataTransformer/DateRangeToStringTransformer.php#L48-L66 | train |
vincenttouzet/BootstrapFormBundle | Form/DataTransformer/DateRangeToStringTransformer.php | DateRangeToStringTransformer.reverseTransform | public function reverseTransform($value)
{
$parts = explode($this->dateSeparator, $value);
$from = isset($parts[0]) ? $parts[0] : null;
$to = isset($parts[1]) ? $parts[1] : null;
return new DAteRange($from, $to);
} | php | public function reverseTransform($value)
{
$parts = explode($this->dateSeparator, $value);
$from = isset($parts[0]) ? $parts[0] : null;
$to = isset($parts[1]) ? $parts[1] : null;
return new DAteRange($from, $to);
} | [
"public",
"function",
"reverseTransform",
"(",
"$",
"value",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"$",
"this",
"->",
"dateSeparator",
",",
"$",
"value",
")",
";",
"$",
"from",
"=",
"isset",
"(",
"$",
"parts",
"[",
"0",
"]",
")",
"?",
"$",
"parts",
"[",
"0",
"]",
":",
"null",
";",
"$",
"to",
"=",
"isset",
"(",
"$",
"parts",
"[",
"1",
"]",
")",
"?",
"$",
"parts",
"[",
"1",
"]",
":",
"null",
";",
"return",
"new",
"DAteRange",
"(",
"$",
"from",
",",
"$",
"to",
")",
";",
"}"
] | Transforms a string into a DateRange.
@param string $value String value.
@return DateRange DateRange value. | [
"Transforms",
"a",
"string",
"into",
"a",
"DateRange",
"."
] | d648c825ca9f7020336023e82a1059fc070727ac | https://github.com/vincenttouzet/BootstrapFormBundle/blob/d648c825ca9f7020336023e82a1059fc070727ac/Form/DataTransformer/DateRangeToStringTransformer.php#L75-L81 | train |
cyberspectrum/i18n-contao | src/Extractor/TableExtractor.php | TableExtractor.decode | private function decode(array $row): ?array
{
if (null === ($encoded = $row[$this->name()])) {
return null;
}
if (false === ($decoded = unserialize($encoded, ['allowed_classes' => false]))) {
return null;
}
if (!\is_array($decoded)) {
return null;
}
return $decoded;
} | php | private function decode(array $row): ?array
{
if (null === ($encoded = $row[$this->name()])) {
return null;
}
if (false === ($decoded = unserialize($encoded, ['allowed_classes' => false]))) {
return null;
}
if (!\is_array($decoded)) {
return null;
}
return $decoded;
} | [
"private",
"function",
"decode",
"(",
"array",
"$",
"row",
")",
":",
"?",
"array",
"{",
"if",
"(",
"null",
"===",
"(",
"$",
"encoded",
"=",
"$",
"row",
"[",
"$",
"this",
"->",
"name",
"(",
")",
"]",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"false",
"===",
"(",
"$",
"decoded",
"=",
"unserialize",
"(",
"$",
"encoded",
",",
"[",
"'allowed_classes'",
"=>",
"false",
"]",
")",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"!",
"\\",
"is_array",
"(",
"$",
"decoded",
")",
")",
"{",
"return",
"null",
";",
"}",
"return",
"$",
"decoded",
";",
"}"
] | Decode the row value.
@param array $row The row.
@return array|null | [
"Decode",
"the",
"row",
"value",
"."
] | 038cf6ea9c609a734d7476fba256bc4b0db236b7 | https://github.com/cyberspectrum/i18n-contao/blob/038cf6ea9c609a734d7476fba256bc4b0db236b7/src/Extractor/TableExtractor.php#L144-L158 | train |
ARCANEDEV/Markup | src/Entities/Tag/ElementCollection.php | ElementCollection.render | public function render()
{
$output = $this->each(function($tag) {
/** @var Tag $tag */
return $tag->render();
});
return implode('', $output->toArray());
} | php | public function render()
{
$output = $this->each(function($tag) {
/** @var Tag $tag */
return $tag->render();
});
return implode('', $output->toArray());
} | [
"public",
"function",
"render",
"(",
")",
"{",
"$",
"output",
"=",
"$",
"this",
"->",
"each",
"(",
"function",
"(",
"$",
"tag",
")",
"{",
"/** @var Tag $tag */",
"return",
"$",
"tag",
"->",
"render",
"(",
")",
";",
"}",
")",
";",
"return",
"implode",
"(",
"''",
",",
"$",
"output",
"->",
"toArray",
"(",
")",
")",
";",
"}"
] | Render tag elements
@return string | [
"Render",
"tag",
"elements"
] | 881331df74b27614d025c365daacbae6aa865612 | https://github.com/ARCANEDEV/Markup/blob/881331df74b27614d025c365daacbae6aa865612/src/Entities/Tag/ElementCollection.php#L56-L64 | train |
ARCANEDEV/Markup | src/Entities/Tag/ElementCollection.php | ElementCollection.getNextItem | private function getNextItem(Tag $item, $items)
{
$currentItem = $items[0];
while ($currentItem !== null and $currentItem !== $item) {
$currentItem = next($items);
}
$next = next($items);
return $next !== false ? $next : null;
} | php | private function getNextItem(Tag $item, $items)
{
$currentItem = $items[0];
while ($currentItem !== null and $currentItem !== $item) {
$currentItem = next($items);
}
$next = next($items);
return $next !== false ? $next : null;
} | [
"private",
"function",
"getNextItem",
"(",
"Tag",
"$",
"item",
",",
"$",
"items",
")",
"{",
"$",
"currentItem",
"=",
"$",
"items",
"[",
"0",
"]",
";",
"while",
"(",
"$",
"currentItem",
"!==",
"null",
"and",
"$",
"currentItem",
"!==",
"$",
"item",
")",
"{",
"$",
"currentItem",
"=",
"next",
"(",
"$",
"items",
")",
";",
"}",
"$",
"next",
"=",
"next",
"(",
"$",
"items",
")",
";",
"return",
"$",
"next",
"!==",
"false",
"?",
"$",
"next",
":",
"null",
";",
"}"
] | Get next item from items array
@param Tag $item
@param array $items
@return Tag|null | [
"Get",
"next",
"item",
"from",
"items",
"array"
] | 881331df74b27614d025c365daacbae6aa865612 | https://github.com/ARCANEDEV/Markup/blob/881331df74b27614d025c365daacbae6aa865612/src/Entities/Tag/ElementCollection.php#L78-L89 | train |
ARCANEDEV/Markup | src/Entities/Tag/ElementCollection.php | ElementCollection.remove | public function remove($tag)
{
if ($this->count() == 0) {
return [$this, null];
}
$deleted = null;
foreach ($this->items as $key => $element) {
if ($element === $tag) {
$this->forget($key);
$deleted = $tag;
break;
}
}
return [$this, $deleted];
} | php | public function remove($tag)
{
if ($this->count() == 0) {
return [$this, null];
}
$deleted = null;
foreach ($this->items as $key => $element) {
if ($element === $tag) {
$this->forget($key);
$deleted = $tag;
break;
}
}
return [$this, $deleted];
} | [
"public",
"function",
"remove",
"(",
"$",
"tag",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"count",
"(",
")",
"==",
"0",
")",
"{",
"return",
"[",
"$",
"this",
",",
"null",
"]",
";",
"}",
"$",
"deleted",
"=",
"null",
";",
"foreach",
"(",
"$",
"this",
"->",
"items",
"as",
"$",
"key",
"=>",
"$",
"element",
")",
"{",
"if",
"(",
"$",
"element",
"===",
"$",
"tag",
")",
"{",
"$",
"this",
"->",
"forget",
"(",
"$",
"key",
")",
";",
"$",
"deleted",
"=",
"$",
"tag",
";",
"break",
";",
"}",
"}",
"return",
"[",
"$",
"this",
",",
"$",
"deleted",
"]",
";",
"}"
] | Remove tag element from collection
@param Tag $tag
@return array | [
"Remove",
"tag",
"element",
"from",
"collection"
] | 881331df74b27614d025c365daacbae6aa865612 | https://github.com/ARCANEDEV/Markup/blob/881331df74b27614d025c365daacbae6aa865612/src/Entities/Tag/ElementCollection.php#L98-L117 | train |
sellerlabs/php-standard | src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php | Chroma_Sniffs_Commenting_FunctionCommentSniff.findUseStatements | protected function findUseStatements(File $file)
{
if (array_key_exists($file->getFilename(), static::$useCache)) {
return static::$useCache[$file->getFilename()];
}
$tokens = $file->getTokens();
$usePosition = $file->findNext(T_USE, 0);
$useStatements = [];
while ($usePosition !== false) {
if ($this->shouldIgnoreUse($file, $usePosition)) {
$usePosition = $file->findNext(T_USE, $usePosition + 1);
continue;
}
$fullPath = '';
$lastString = '';
$alias = '';
$useEnd = $file->findNext(
[T_SEMICOLON, T_COMMA],
$usePosition
);
$useFullPathEnd = $file->findNext(
[T_SEMICOLON, T_COMMA, T_WHITESPACE],
$usePosition + 2
);
$afterUse = $file->findNext(
[T_STRING, T_NS_SEPARATOR],
$usePosition
);
while ($afterUse !== false) {
$fullPath .= $tokens[$afterUse]['content'];
if ($tokens[$afterUse]['code'] == T_STRING) {
$lastString = $tokens[$afterUse]['content'];
}
$afterUse = $file->findNext(
[T_STRING, T_NS_SEPARATOR],
$afterUse + 1,
$useFullPathEnd
);
}
if ($useFullPathEnd != $useEnd) {
if ($tokens[$useFullPathEnd + 1]['code'] !== T_AS) {
continue;
}
if ($tokens[$useFullPathEnd + 3]['code'] === T_STRING) {
$alias = $tokens[$useFullPathEnd + 3]['content'];
}
} else {
$alias = $lastString;
}
$useStatements[$fullPath] = $alias;
$usePosition = $file->findNext(T_USE, $usePosition + 1);
}
static::$useCache[$file->getFilename()] = $useStatements;
return $useStatements;
} | php | protected function findUseStatements(File $file)
{
if (array_key_exists($file->getFilename(), static::$useCache)) {
return static::$useCache[$file->getFilename()];
}
$tokens = $file->getTokens();
$usePosition = $file->findNext(T_USE, 0);
$useStatements = [];
while ($usePosition !== false) {
if ($this->shouldIgnoreUse($file, $usePosition)) {
$usePosition = $file->findNext(T_USE, $usePosition + 1);
continue;
}
$fullPath = '';
$lastString = '';
$alias = '';
$useEnd = $file->findNext(
[T_SEMICOLON, T_COMMA],
$usePosition
);
$useFullPathEnd = $file->findNext(
[T_SEMICOLON, T_COMMA, T_WHITESPACE],
$usePosition + 2
);
$afterUse = $file->findNext(
[T_STRING, T_NS_SEPARATOR],
$usePosition
);
while ($afterUse !== false) {
$fullPath .= $tokens[$afterUse]['content'];
if ($tokens[$afterUse]['code'] == T_STRING) {
$lastString = $tokens[$afterUse]['content'];
}
$afterUse = $file->findNext(
[T_STRING, T_NS_SEPARATOR],
$afterUse + 1,
$useFullPathEnd
);
}
if ($useFullPathEnd != $useEnd) {
if ($tokens[$useFullPathEnd + 1]['code'] !== T_AS) {
continue;
}
if ($tokens[$useFullPathEnd + 3]['code'] === T_STRING) {
$alias = $tokens[$useFullPathEnd + 3]['content'];
}
} else {
$alias = $lastString;
}
$useStatements[$fullPath] = $alias;
$usePosition = $file->findNext(T_USE, $usePosition + 1);
}
static::$useCache[$file->getFilename()] = $useStatements;
return $useStatements;
} | [
"protected",
"function",
"findUseStatements",
"(",
"File",
"$",
"file",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"file",
"->",
"getFilename",
"(",
")",
",",
"static",
"::",
"$",
"useCache",
")",
")",
"{",
"return",
"static",
"::",
"$",
"useCache",
"[",
"$",
"file",
"->",
"getFilename",
"(",
")",
"]",
";",
"}",
"$",
"tokens",
"=",
"$",
"file",
"->",
"getTokens",
"(",
")",
";",
"$",
"usePosition",
"=",
"$",
"file",
"->",
"findNext",
"(",
"T_USE",
",",
"0",
")",
";",
"$",
"useStatements",
"=",
"[",
"]",
";",
"while",
"(",
"$",
"usePosition",
"!==",
"false",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"shouldIgnoreUse",
"(",
"$",
"file",
",",
"$",
"usePosition",
")",
")",
"{",
"$",
"usePosition",
"=",
"$",
"file",
"->",
"findNext",
"(",
"T_USE",
",",
"$",
"usePosition",
"+",
"1",
")",
";",
"continue",
";",
"}",
"$",
"fullPath",
"=",
"''",
";",
"$",
"lastString",
"=",
"''",
";",
"$",
"alias",
"=",
"''",
";",
"$",
"useEnd",
"=",
"$",
"file",
"->",
"findNext",
"(",
"[",
"T_SEMICOLON",
",",
"T_COMMA",
"]",
",",
"$",
"usePosition",
")",
";",
"$",
"useFullPathEnd",
"=",
"$",
"file",
"->",
"findNext",
"(",
"[",
"T_SEMICOLON",
",",
"T_COMMA",
",",
"T_WHITESPACE",
"]",
",",
"$",
"usePosition",
"+",
"2",
")",
";",
"$",
"afterUse",
"=",
"$",
"file",
"->",
"findNext",
"(",
"[",
"T_STRING",
",",
"T_NS_SEPARATOR",
"]",
",",
"$",
"usePosition",
")",
";",
"while",
"(",
"$",
"afterUse",
"!==",
"false",
")",
"{",
"$",
"fullPath",
".=",
"$",
"tokens",
"[",
"$",
"afterUse",
"]",
"[",
"'content'",
"]",
";",
"if",
"(",
"$",
"tokens",
"[",
"$",
"afterUse",
"]",
"[",
"'code'",
"]",
"==",
"T_STRING",
")",
"{",
"$",
"lastString",
"=",
"$",
"tokens",
"[",
"$",
"afterUse",
"]",
"[",
"'content'",
"]",
";",
"}",
"$",
"afterUse",
"=",
"$",
"file",
"->",
"findNext",
"(",
"[",
"T_STRING",
",",
"T_NS_SEPARATOR",
"]",
",",
"$",
"afterUse",
"+",
"1",
",",
"$",
"useFullPathEnd",
")",
";",
"}",
"if",
"(",
"$",
"useFullPathEnd",
"!=",
"$",
"useEnd",
")",
"{",
"if",
"(",
"$",
"tokens",
"[",
"$",
"useFullPathEnd",
"+",
"1",
"]",
"[",
"'code'",
"]",
"!==",
"T_AS",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"$",
"tokens",
"[",
"$",
"useFullPathEnd",
"+",
"3",
"]",
"[",
"'code'",
"]",
"===",
"T_STRING",
")",
"{",
"$",
"alias",
"=",
"$",
"tokens",
"[",
"$",
"useFullPathEnd",
"+",
"3",
"]",
"[",
"'content'",
"]",
";",
"}",
"}",
"else",
"{",
"$",
"alias",
"=",
"$",
"lastString",
";",
"}",
"$",
"useStatements",
"[",
"$",
"fullPath",
"]",
"=",
"$",
"alias",
";",
"$",
"usePosition",
"=",
"$",
"file",
"->",
"findNext",
"(",
"T_USE",
",",
"$",
"usePosition",
"+",
"1",
")",
";",
"}",
"static",
"::",
"$",
"useCache",
"[",
"$",
"file",
"->",
"getFilename",
"(",
")",
"]",
"=",
"$",
"useStatements",
";",
"return",
"$",
"useStatements",
";",
"}"
] | Find all use statements.
@param PHP_CodeSniffer_File $file
@return array | [
"Find",
"all",
"use",
"statements",
"."
] | cd5c919c5aad1aba6f2486a81867172d0eb167f7 | https://github.com/sellerlabs/php-standard/blob/cd5c919c5aad1aba6f2486a81867172d0eb167f7/src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php#L323-L391 | train |
sellerlabs/php-standard | src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php | Chroma_Sniffs_Commenting_FunctionCommentSniff.shouldIgnoreUse | protected function shouldIgnoreUse(File $file, $stackPtr)
{
$tokens = $file->getTokens();
// Ignore USE keywords inside closures.
$next = $file->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
if ($tokens[$next]['code'] === T_OPEN_PARENTHESIS) {
return true;
}
// Ignore USE keywords for traits.
if ($file->hasCondition($stackPtr, [T_CLASS, T_TRAIT]) === true) {
return true;
}
return false;
} | php | protected function shouldIgnoreUse(File $file, $stackPtr)
{
$tokens = $file->getTokens();
// Ignore USE keywords inside closures.
$next = $file->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
if ($tokens[$next]['code'] === T_OPEN_PARENTHESIS) {
return true;
}
// Ignore USE keywords for traits.
if ($file->hasCondition($stackPtr, [T_CLASS, T_TRAIT]) === true) {
return true;
}
return false;
} | [
"protected",
"function",
"shouldIgnoreUse",
"(",
"File",
"$",
"file",
",",
"$",
"stackPtr",
")",
"{",
"$",
"tokens",
"=",
"$",
"file",
"->",
"getTokens",
"(",
")",
";",
"// Ignore USE keywords inside closures.",
"$",
"next",
"=",
"$",
"file",
"->",
"findNext",
"(",
"T_WHITESPACE",
",",
"(",
"$",
"stackPtr",
"+",
"1",
")",
",",
"null",
",",
"true",
")",
";",
"if",
"(",
"$",
"tokens",
"[",
"$",
"next",
"]",
"[",
"'code'",
"]",
"===",
"T_OPEN_PARENTHESIS",
")",
"{",
"return",
"true",
";",
"}",
"// Ignore USE keywords for traits.",
"if",
"(",
"$",
"file",
"->",
"hasCondition",
"(",
"$",
"stackPtr",
",",
"[",
"T_CLASS",
",",
"T_TRAIT",
"]",
")",
"===",
"true",
")",
"{",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Check whether or not a USE statement should be ignored.
@param PHP_CodeSniffer_File $file
@param $stackPtr
@return bool | [
"Check",
"whether",
"or",
"not",
"a",
"USE",
"statement",
"should",
"be",
"ignored",
"."
] | cd5c919c5aad1aba6f2486a81867172d0eb167f7 | https://github.com/sellerlabs/php-standard/blob/cd5c919c5aad1aba6f2486a81867172d0eb167f7/src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php#L401-L417 | train |
sellerlabs/php-standard | src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php | Chroma_Sniffs_Commenting_FunctionCommentSniff.resolveArrayType | protected function resolveArrayType($type)
{
if (strrpos($type, '[]', -2) !== false) {
return substr($type, 0, strlen($type) - 2);
}
return $type;
} | php | protected function resolveArrayType($type)
{
if (strrpos($type, '[]', -2) !== false) {
return substr($type, 0, strlen($type) - 2);
}
return $type;
} | [
"protected",
"function",
"resolveArrayType",
"(",
"$",
"type",
")",
"{",
"if",
"(",
"strrpos",
"(",
"$",
"type",
",",
"'[]'",
",",
"-",
"2",
")",
"!==",
"false",
")",
"{",
"return",
"substr",
"(",
"$",
"type",
",",
"0",
",",
"strlen",
"(",
"$",
"type",
")",
"-",
"2",
")",
";",
"}",
"return",
"$",
"type",
";",
"}"
] | Attempt to resolve the type of an array.
@param $type
@return string | [
"Attempt",
"to",
"resolve",
"the",
"type",
"of",
"an",
"array",
"."
] | cd5c919c5aad1aba6f2486a81867172d0eb167f7 | https://github.com/sellerlabs/php-standard/blob/cd5c919c5aad1aba6f2486a81867172d0eb167f7/src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php#L468-L475 | train |
sellerlabs/php-standard | src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php | Chroma_Sniffs_Commenting_FunctionCommentSniff.extractNamespace | protected function extractNamespace(
File $file
) {
$namespace = '';
$tokens = $file->getTokens();
$prev = $file->findNext(T_NAMESPACE, 0);
for ($i = $prev + 2; $i < count($tokens); $i++) {
if (!in_array($tokens[$i]['code'], [T_STRING, T_NS_SEPARATOR])) {
break;
}
$namespace .= $tokens[$i]['content'];
}
return $namespace;
} | php | protected function extractNamespace(
File $file
) {
$namespace = '';
$tokens = $file->getTokens();
$prev = $file->findNext(T_NAMESPACE, 0);
for ($i = $prev + 2; $i < count($tokens); $i++) {
if (!in_array($tokens[$i]['code'], [T_STRING, T_NS_SEPARATOR])) {
break;
}
$namespace .= $tokens[$i]['content'];
}
return $namespace;
} | [
"protected",
"function",
"extractNamespace",
"(",
"File",
"$",
"file",
")",
"{",
"$",
"namespace",
"=",
"''",
";",
"$",
"tokens",
"=",
"$",
"file",
"->",
"getTokens",
"(",
")",
";",
"$",
"prev",
"=",
"$",
"file",
"->",
"findNext",
"(",
"T_NAMESPACE",
",",
"0",
")",
";",
"for",
"(",
"$",
"i",
"=",
"$",
"prev",
"+",
"2",
";",
"$",
"i",
"<",
"count",
"(",
"$",
"tokens",
")",
";",
"$",
"i",
"++",
")",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"tokens",
"[",
"$",
"i",
"]",
"[",
"'code'",
"]",
",",
"[",
"T_STRING",
",",
"T_NS_SEPARATOR",
"]",
")",
")",
"{",
"break",
";",
"}",
"$",
"namespace",
".=",
"$",
"tokens",
"[",
"$",
"i",
"]",
"[",
"'content'",
"]",
";",
"}",
"return",
"$",
"namespace",
";",
"}"
] | Extract the first namespace found in the file.
@param PHP_CodeSniffer_File $file
@return string | [
"Extract",
"the",
"first",
"namespace",
"found",
"in",
"the",
"file",
"."
] | cd5c919c5aad1aba6f2486a81867172d0eb167f7 | https://github.com/sellerlabs/php-standard/blob/cd5c919c5aad1aba6f2486a81867172d0eb167f7/src/SellerLabs/Standards/Chroma/Sniffs/Commenting/FunctionCommentSniff.php#L561-L579 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.