repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
simplepie/simplepie | idn/idna_convert.class.php | idna_convert.decode | function decode($input, $one_time_encoding = false)
{
// Optionally set
if ($one_time_encoding) {
switch ($one_time_encoding) {
case 'utf8':
case 'ucs4_string':
case 'ucs4_array':
break;
default:
$this->_error('Unknown encoding '.$one_time_encoding);
return false;
}
}
// Make sure to drop any newline characters around
$input = trim($input);
// Negotiate input and try to determine, whether it is a plain string,
// an email address or something like a complete URL
if (strpos($input, '@')) { // Maybe it is an email address
// No no in strict mode
if ($this->_strict_mode) {
$this->_error('Only simple domain name parts can be handled in strict mode');
return false;
}
list ($email_pref, $input) = explode('@', $input, 2);
$arr = explode('.', $input);
foreach ($arr as $k => $v) {
if (preg_match('!^'.preg_quote($this->_punycode_prefix, '!').'!', $v)) {
$conv = $this->_decode($v);
if ($conv) $arr[$k] = $conv;
}
}
$input = join('.', $arr);
$arr = explode('.', $email_pref);
foreach ($arr as $k => $v) {
if (preg_match('!^'.preg_quote($this->_punycode_prefix, '!').'!', $v)) {
$conv = $this->_decode($v);
if ($conv) $arr[$k] = $conv;
}
}
$email_pref = join('.', $arr);
$return = $email_pref . '@' . $input;
} elseif (preg_match('![:\./]!', $input)) { // Or a complete domain name (with or without paths / parameters)
// No no in strict mode
if ($this->_strict_mode) {
$this->_error('Only simple domain name parts can be handled in strict mode');
return false;
}
$parsed = parse_url($input);
if (isset($parsed['host'])) {
$arr = explode('.', $parsed['host']);
foreach ($arr as $k => $v) {
$conv = $this->_decode($v);
if ($conv) $arr[$k] = $conv;
}
$parsed['host'] = join('.', $arr);
$return =
(empty($parsed['scheme']) ? '' : $parsed['scheme'].(strtolower($parsed['scheme']) == 'mailto' ? ':' : '://'))
.(empty($parsed['user']) ? '' : $parsed['user'].(empty($parsed['pass']) ? '' : ':'.$parsed['pass']).'@')
.$parsed['host']
.(empty($parsed['port']) ? '' : ':'.$parsed['port'])
.(empty($parsed['path']) ? '' : $parsed['path'])
.(empty($parsed['query']) ? '' : '?'.$parsed['query'])
.(empty($parsed['fragment']) ? '' : '#'.$parsed['fragment']);
} else { // parse_url seems to have failed, try without it
$arr = explode('.', $input);
foreach ($arr as $k => $v) {
$conv = $this->_decode($v);
$arr[$k] = ($conv) ? $conv : $v;
}
$return = join('.', $arr);
}
} else { // Otherwise we consider it being a pure domain name string
$return = $this->_decode($input);
if (!$return) $return = $input;
}
// The output is UTF-8 by default, other output formats need conversion here
// If one time encoding is given, use this, else the objects property
switch (($one_time_encoding) ? $one_time_encoding : $this->_api_encoding) {
case 'utf8':
return $return;
break;
case 'ucs4_string':
return $this->_ucs4_to_ucs4_string($this->_utf8_to_ucs4($return));
break;
case 'ucs4_array':
return $this->_utf8_to_ucs4($return);
break;
default:
$this->_error('Unsupported output format');
return false;
}
} | php | function decode($input, $one_time_encoding = false)
{
// Optionally set
if ($one_time_encoding) {
switch ($one_time_encoding) {
case 'utf8':
case 'ucs4_string':
case 'ucs4_array':
break;
default:
$this->_error('Unknown encoding '.$one_time_encoding);
return false;
}
}
// Make sure to drop any newline characters around
$input = trim($input);
// Negotiate input and try to determine, whether it is a plain string,
// an email address or something like a complete URL
if (strpos($input, '@')) { // Maybe it is an email address
// No no in strict mode
if ($this->_strict_mode) {
$this->_error('Only simple domain name parts can be handled in strict mode');
return false;
}
list ($email_pref, $input) = explode('@', $input, 2);
$arr = explode('.', $input);
foreach ($arr as $k => $v) {
if (preg_match('!^'.preg_quote($this->_punycode_prefix, '!').'!', $v)) {
$conv = $this->_decode($v);
if ($conv) $arr[$k] = $conv;
}
}
$input = join('.', $arr);
$arr = explode('.', $email_pref);
foreach ($arr as $k => $v) {
if (preg_match('!^'.preg_quote($this->_punycode_prefix, '!').'!', $v)) {
$conv = $this->_decode($v);
if ($conv) $arr[$k] = $conv;
}
}
$email_pref = join('.', $arr);
$return = $email_pref . '@' . $input;
} elseif (preg_match('![:\./]!', $input)) { // Or a complete domain name (with or without paths / parameters)
// No no in strict mode
if ($this->_strict_mode) {
$this->_error('Only simple domain name parts can be handled in strict mode');
return false;
}
$parsed = parse_url($input);
if (isset($parsed['host'])) {
$arr = explode('.', $parsed['host']);
foreach ($arr as $k => $v) {
$conv = $this->_decode($v);
if ($conv) $arr[$k] = $conv;
}
$parsed['host'] = join('.', $arr);
$return =
(empty($parsed['scheme']) ? '' : $parsed['scheme'].(strtolower($parsed['scheme']) == 'mailto' ? ':' : '://'))
.(empty($parsed['user']) ? '' : $parsed['user'].(empty($parsed['pass']) ? '' : ':'.$parsed['pass']).'@')
.$parsed['host']
.(empty($parsed['port']) ? '' : ':'.$parsed['port'])
.(empty($parsed['path']) ? '' : $parsed['path'])
.(empty($parsed['query']) ? '' : '?'.$parsed['query'])
.(empty($parsed['fragment']) ? '' : '#'.$parsed['fragment']);
} else { // parse_url seems to have failed, try without it
$arr = explode('.', $input);
foreach ($arr as $k => $v) {
$conv = $this->_decode($v);
$arr[$k] = ($conv) ? $conv : $v;
}
$return = join('.', $arr);
}
} else { // Otherwise we consider it being a pure domain name string
$return = $this->_decode($input);
if (!$return) $return = $input;
}
// The output is UTF-8 by default, other output formats need conversion here
// If one time encoding is given, use this, else the objects property
switch (($one_time_encoding) ? $one_time_encoding : $this->_api_encoding) {
case 'utf8':
return $return;
break;
case 'ucs4_string':
return $this->_ucs4_to_ucs4_string($this->_utf8_to_ucs4($return));
break;
case 'ucs4_array':
return $this->_utf8_to_ucs4($return);
break;
default:
$this->_error('Unsupported output format');
return false;
}
} | [
"function",
"decode",
"(",
"$",
"input",
",",
"$",
"one_time_encoding",
"=",
"false",
")",
"{",
"// Optionally set",
"if",
"(",
"$",
"one_time_encoding",
")",
"{",
"switch",
"(",
"$",
"one_time_encoding",
")",
"{",
"case",
"'utf8'",
":",
"case",
"'ucs4_strin... | Decode a given ACE domain name
@param string Domain name (ACE string)
[@param string Desired output encoding, see {@link set_parameter}]
@return string Decoded Domain name (UTF-8 or UCS-4)
@access public | [
"Decode",
"a",
"given",
"ACE",
"domain",
"name"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/idn/idna_convert.class.php#L165-L258 |
simplepie/simplepie | idn/idna_convert.class.php | idna_convert.encode | function encode($decoded, $one_time_encoding = false)
{
// Forcing conversion of input to UCS4 array
// If one time encoding is given, use this, else the objects property
switch ($one_time_encoding ? $one_time_encoding : $this->_api_encoding) {
case 'utf8':
$decoded = $this->_utf8_to_ucs4($decoded);
break;
case 'ucs4_string':
$decoded = $this->_ucs4_string_to_ucs4($decoded);
case 'ucs4_array':
break;
default:
$this->_error('Unsupported input format: '.($one_time_encoding ? $one_time_encoding : $this->_api_encoding));
return false;
}
// No input, no output, what else did you expect?
if (empty($decoded)) return '';
// Anchors for iteration
$last_begin = 0;
// Output string
$output = '';
foreach ($decoded as $k => $v) {
// Make sure to use just the plain dot
switch($v) {
case 0x3002:
case 0xFF0E:
case 0xFF61:
$decoded[$k] = 0x2E;
// Right, no break here, the above are converted to dots anyway
// Stumbling across an anchoring character
case 0x2E:
case 0x2F:
case 0x3A:
case 0x3F:
case 0x40:
// Neither email addresses nor URLs allowed in strict mode
if ($this->_strict_mode) {
$this->_error('Neither email addresses nor URLs are allowed in strict mode.');
return false;
}
// Skip first char
if ($k) {
$encoded = '';
$encoded = $this->_encode(array_slice($decoded, $last_begin, (($k)-$last_begin)));
if ($encoded) {
$output .= $encoded;
} else {
$output .= $this->_ucs4_to_utf8(array_slice($decoded, $last_begin, (($k)-$last_begin)));
}
$output .= chr($decoded[$k]);
}
$last_begin = $k + 1;
}
}
// Catch the rest of the string
if ($last_begin) {
$inp_len = sizeof($decoded);
$encoded = '';
$encoded = $this->_encode(array_slice($decoded, $last_begin, (($inp_len)-$last_begin)));
if ($encoded) {
$output .= $encoded;
} else {
$output .= $this->_ucs4_to_utf8(array_slice($decoded, $last_begin, (($inp_len)-$last_begin)));
}
return $output;
}
if ($output = $this->_encode($decoded)) {
return $output;
}
return $this->_ucs4_to_utf8($decoded);
} | php | function encode($decoded, $one_time_encoding = false)
{
// Forcing conversion of input to UCS4 array
// If one time encoding is given, use this, else the objects property
switch ($one_time_encoding ? $one_time_encoding : $this->_api_encoding) {
case 'utf8':
$decoded = $this->_utf8_to_ucs4($decoded);
break;
case 'ucs4_string':
$decoded = $this->_ucs4_string_to_ucs4($decoded);
case 'ucs4_array':
break;
default:
$this->_error('Unsupported input format: '.($one_time_encoding ? $one_time_encoding : $this->_api_encoding));
return false;
}
// No input, no output, what else did you expect?
if (empty($decoded)) return '';
// Anchors for iteration
$last_begin = 0;
// Output string
$output = '';
foreach ($decoded as $k => $v) {
// Make sure to use just the plain dot
switch($v) {
case 0x3002:
case 0xFF0E:
case 0xFF61:
$decoded[$k] = 0x2E;
// Right, no break here, the above are converted to dots anyway
// Stumbling across an anchoring character
case 0x2E:
case 0x2F:
case 0x3A:
case 0x3F:
case 0x40:
// Neither email addresses nor URLs allowed in strict mode
if ($this->_strict_mode) {
$this->_error('Neither email addresses nor URLs are allowed in strict mode.');
return false;
}
// Skip first char
if ($k) {
$encoded = '';
$encoded = $this->_encode(array_slice($decoded, $last_begin, (($k)-$last_begin)));
if ($encoded) {
$output .= $encoded;
} else {
$output .= $this->_ucs4_to_utf8(array_slice($decoded, $last_begin, (($k)-$last_begin)));
}
$output .= chr($decoded[$k]);
}
$last_begin = $k + 1;
}
}
// Catch the rest of the string
if ($last_begin) {
$inp_len = sizeof($decoded);
$encoded = '';
$encoded = $this->_encode(array_slice($decoded, $last_begin, (($inp_len)-$last_begin)));
if ($encoded) {
$output .= $encoded;
} else {
$output .= $this->_ucs4_to_utf8(array_slice($decoded, $last_begin, (($inp_len)-$last_begin)));
}
return $output;
}
if ($output = $this->_encode($decoded)) {
return $output;
}
return $this->_ucs4_to_utf8($decoded);
} | [
"function",
"encode",
"(",
"$",
"decoded",
",",
"$",
"one_time_encoding",
"=",
"false",
")",
"{",
"// Forcing conversion of input to UCS4 array",
"// If one time encoding is given, use this, else the objects property",
"switch",
"(",
"$",
"one_time_encoding",
"?",
"$",
"one_t... | Encode a given UTF-8 domain name
@param string Domain name (UTF-8 or UCS-4)
[@param string Desired input encoding, see {@link set_parameter}]
@return string Encoded Domain name (ACE string)
@access public | [
"Encode",
"a",
"given",
"UTF",
"-",
"8",
"domain",
"name"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/idn/idna_convert.class.php#L267-L343 |
simplepie/simplepie | idn/idna_convert.class.php | idna_convert._nameprep | function _nameprep($input)
{
$output = array();
$error = false;
//
// Mapping
// Walking through the input array, performing the required steps on each of
// the input chars and putting the result into the output array
// While mapping required chars we apply the cannonical ordering
foreach ($input as $v) {
// Map to nothing == skip that code point
if (in_array($v, $this->NP['map_nothing'])) continue;
// Try to find prohibited input
if (in_array($v, $this->NP['prohibit']) || in_array($v, $this->NP['general_prohibited'])) {
$this->_error('NAMEPREP: Prohibited input U+'.sprintf('%08X', $v));
return false;
}
foreach ($this->NP['prohibit_ranges'] as $range) {
if ($range[0] <= $v && $v <= $range[1]) {
$this->_error('NAMEPREP: Prohibited input U+'.sprintf('%08X', $v));
return false;
}
}
//
// Hangul syllable decomposition
if (0xAC00 <= $v && $v <= 0xD7AF) {
foreach ($this->_hangul_decompose($v) as $out) {
$output[] = (int) $out;
}
// There's a decomposition mapping for that code point
} elseif (isset($this->NP['replacemaps'][$v])) {
foreach ($this->_apply_cannonical_ordering($this->NP['replacemaps'][$v]) as $out) {
$output[] = (int) $out;
}
} else {
$output[] = (int) $v;
}
}
// Before applying any Combining, try to rearrange any Hangul syllables
$output = $this->_hangul_compose($output);
//
// Combine code points
//
$last_class = 0;
$last_starter = 0;
$out_len = count($output);
for ($i = 0; $i < $out_len; ++$i) {
$class = $this->_get_combining_class($output[$i]);
if ((!$last_class || $last_class > $class) && $class) {
// Try to match
$seq_len = $i - $last_starter;
$out = $this->_combine(array_slice($output, $last_starter, $seq_len));
// On match: Replace the last starter with the composed character and remove
// the now redundant non-starter(s)
if ($out) {
$output[$last_starter] = $out;
if (count($out) != $seq_len) {
for ($j = $i+1; $j < $out_len; ++$j) {
$output[$j-1] = $output[$j];
}
unset($output[$out_len]);
}
// Rewind the for loop by one, since there can be more possible compositions
$i--;
$out_len--;
$last_class = ($i == $last_starter) ? 0 : $this->_get_combining_class($output[$i-1]);
continue;
}
}
// The current class is 0
if (!$class) $last_starter = $i;
$last_class = $class;
}
return $output;
} | php | function _nameprep($input)
{
$output = array();
$error = false;
//
// Mapping
// Walking through the input array, performing the required steps on each of
// the input chars and putting the result into the output array
// While mapping required chars we apply the cannonical ordering
foreach ($input as $v) {
// Map to nothing == skip that code point
if (in_array($v, $this->NP['map_nothing'])) continue;
// Try to find prohibited input
if (in_array($v, $this->NP['prohibit']) || in_array($v, $this->NP['general_prohibited'])) {
$this->_error('NAMEPREP: Prohibited input U+'.sprintf('%08X', $v));
return false;
}
foreach ($this->NP['prohibit_ranges'] as $range) {
if ($range[0] <= $v && $v <= $range[1]) {
$this->_error('NAMEPREP: Prohibited input U+'.sprintf('%08X', $v));
return false;
}
}
//
// Hangul syllable decomposition
if (0xAC00 <= $v && $v <= 0xD7AF) {
foreach ($this->_hangul_decompose($v) as $out) {
$output[] = (int) $out;
}
// There's a decomposition mapping for that code point
} elseif (isset($this->NP['replacemaps'][$v])) {
foreach ($this->_apply_cannonical_ordering($this->NP['replacemaps'][$v]) as $out) {
$output[] = (int) $out;
}
} else {
$output[] = (int) $v;
}
}
// Before applying any Combining, try to rearrange any Hangul syllables
$output = $this->_hangul_compose($output);
//
// Combine code points
//
$last_class = 0;
$last_starter = 0;
$out_len = count($output);
for ($i = 0; $i < $out_len; ++$i) {
$class = $this->_get_combining_class($output[$i]);
if ((!$last_class || $last_class > $class) && $class) {
// Try to match
$seq_len = $i - $last_starter;
$out = $this->_combine(array_slice($output, $last_starter, $seq_len));
// On match: Replace the last starter with the composed character and remove
// the now redundant non-starter(s)
if ($out) {
$output[$last_starter] = $out;
if (count($out) != $seq_len) {
for ($j = $i+1; $j < $out_len; ++$j) {
$output[$j-1] = $output[$j];
}
unset($output[$out_len]);
}
// Rewind the for loop by one, since there can be more possible compositions
$i--;
$out_len--;
$last_class = ($i == $last_starter) ? 0 : $this->_get_combining_class($output[$i-1]);
continue;
}
}
// The current class is 0
if (!$class) $last_starter = $i;
$last_class = $class;
}
return $output;
} | [
"function",
"_nameprep",
"(",
"$",
"input",
")",
"{",
"$",
"output",
"=",
"array",
"(",
")",
";",
"$",
"error",
"=",
"false",
";",
"//",
"// Mapping",
"// Walking through the input array, performing the required steps on each of",
"// the input chars and putting the resul... | Do Nameprep according to RFC3491 and RFC3454
@param array Unicode Characters
@return string Unicode Characters, Nameprep'd
@access private | [
"Do",
"Nameprep",
"according",
"to",
"RFC3491",
"and",
"RFC3454"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/idn/idna_convert.class.php#L561-L636 |
simplepie/simplepie | idn/idna_convert.class.php | idna_convert._hangul_decompose | function _hangul_decompose($char)
{
$sindex = (int) $char - $this->_sbase;
if ($sindex < 0 || $sindex >= $this->_scount) {
return array($char);
}
$result = array();
$result[] = (int) $this->_lbase + $sindex / $this->_ncount;
$result[] = (int) $this->_vbase + ($sindex % $this->_ncount) / $this->_tcount;
$T = intval($this->_tbase + $sindex % $this->_tcount);
if ($T != $this->_tbase) $result[] = $T;
return $result;
} | php | function _hangul_decompose($char)
{
$sindex = (int) $char - $this->_sbase;
if ($sindex < 0 || $sindex >= $this->_scount) {
return array($char);
}
$result = array();
$result[] = (int) $this->_lbase + $sindex / $this->_ncount;
$result[] = (int) $this->_vbase + ($sindex % $this->_ncount) / $this->_tcount;
$T = intval($this->_tbase + $sindex % $this->_tcount);
if ($T != $this->_tbase) $result[] = $T;
return $result;
} | [
"function",
"_hangul_decompose",
"(",
"$",
"char",
")",
"{",
"$",
"sindex",
"=",
"(",
"int",
")",
"$",
"char",
"-",
"$",
"this",
"->",
"_sbase",
";",
"if",
"(",
"$",
"sindex",
"<",
"0",
"||",
"$",
"sindex",
">=",
"$",
"this",
"->",
"_scount",
")"... | Decomposes a Hangul syllable
(see http://www.unicode.org/unicode/reports/tr15/#Hangul
@param integer 32bit UCS4 code point
@return array Either Hangul Syllable decomposed or original 32bit value as one value array
@access private | [
"Decomposes",
"a",
"Hangul",
"syllable",
"(",
"see",
"http",
":",
"//",
"www",
".",
"unicode",
".",
"org",
"/",
"unicode",
"/",
"reports",
"/",
"tr15",
"/",
"#Hangul"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/idn/idna_convert.class.php#L645-L657 |
simplepie/simplepie | idn/idna_convert.class.php | idna_convert._ucs4_to_utf8 | function _ucs4_to_utf8($input)
{
$output = '';
$k = 0;
foreach ($input as $v) {
++$k;
// $v = ord($v);
if ($v < 128) { // 7bit are transferred literally
$output .= chr($v);
} elseif ($v < (1 << 11)) { // 2 bytes
$output .= chr(192 + ($v >> 6)) . chr(128 + ($v & 63));
} elseif ($v < (1 << 16)) { // 3 bytes
$output .= chr(224 + ($v >> 12)) . chr(128 + (($v >> 6) & 63)) . chr(128 + ($v & 63));
} elseif ($v < (1 << 21)) { // 4 bytes
$output .= chr(240 + ($v >> 18)) . chr(128 + (($v >> 12) & 63))
. chr(128 + (($v >> 6) & 63)) . chr(128 + ($v & 63));
} elseif ($v < (1 << 26)) { // 5 bytes
$output .= chr(248 + ($v >> 24)) . chr(128 + (($v >> 18) & 63))
. chr(128 + (($v >> 12) & 63)) . chr(128 + (($v >> 6) & 63))
. chr(128 + ($v & 63));
} elseif ($v < (1 << 31)) { // 6 bytes
$output .= chr(252 + ($v >> 30)) . chr(128 + (($v >> 24) & 63))
. chr(128 + (($v >> 18) & 63)) . chr(128 + (($v >> 12) & 63))
. chr(128 + (($v >> 6) & 63)) . chr(128 + ($v & 63));
} else {
$this->_error('Conversion from UCS-4 to UTF-8 failed: malformed input at byte '.$k);
return false;
}
}
return $output;
} | php | function _ucs4_to_utf8($input)
{
$output = '';
$k = 0;
foreach ($input as $v) {
++$k;
// $v = ord($v);
if ($v < 128) { // 7bit are transferred literally
$output .= chr($v);
} elseif ($v < (1 << 11)) { // 2 bytes
$output .= chr(192 + ($v >> 6)) . chr(128 + ($v & 63));
} elseif ($v < (1 << 16)) { // 3 bytes
$output .= chr(224 + ($v >> 12)) . chr(128 + (($v >> 6) & 63)) . chr(128 + ($v & 63));
} elseif ($v < (1 << 21)) { // 4 bytes
$output .= chr(240 + ($v >> 18)) . chr(128 + (($v >> 12) & 63))
. chr(128 + (($v >> 6) & 63)) . chr(128 + ($v & 63));
} elseif ($v < (1 << 26)) { // 5 bytes
$output .= chr(248 + ($v >> 24)) . chr(128 + (($v >> 18) & 63))
. chr(128 + (($v >> 12) & 63)) . chr(128 + (($v >> 6) & 63))
. chr(128 + ($v & 63));
} elseif ($v < (1 << 31)) { // 6 bytes
$output .= chr(252 + ($v >> 30)) . chr(128 + (($v >> 24) & 63))
. chr(128 + (($v >> 18) & 63)) . chr(128 + (($v >> 12) & 63))
. chr(128 + (($v >> 6) & 63)) . chr(128 + ($v & 63));
} else {
$this->_error('Conversion from UCS-4 to UTF-8 failed: malformed input at byte '.$k);
return false;
}
}
return $output;
} | [
"function",
"_ucs4_to_utf8",
"(",
"$",
"input",
")",
"{",
"$",
"output",
"=",
"''",
";",
"$",
"k",
"=",
"0",
";",
"foreach",
"(",
"$",
"input",
"as",
"$",
"v",
")",
"{",
"++",
"$",
"k",
";",
"// $v = ord($v);",
"if",
"(",
"$",
"v",
"<",
"128",
... | Convert UCS-4 string into UTF-8 string
See _utf8_to_ucs4() for details
@access private | [
"Convert",
"UCS",
"-",
"4",
"string",
"into",
"UTF",
"-",
"8",
"string",
"See",
"_utf8_to_ucs4",
"()",
"for",
"details"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/idn/idna_convert.class.php#L865-L895 |
simplepie/simplepie | idn/idna_convert.class.php | idna_convert._ucs4_to_ucs4_string | function _ucs4_to_ucs4_string($input)
{
$output = '';
// Take array values and split output to 4 bytes per value
// The bit mask is 255, which reads &11111111
foreach ($input as $v) {
$output .= chr(($v >> 24) & 255).chr(($v >> 16) & 255).chr(($v >> 8) & 255).chr($v & 255);
}
return $output;
} | php | function _ucs4_to_ucs4_string($input)
{
$output = '';
// Take array values and split output to 4 bytes per value
// The bit mask is 255, which reads &11111111
foreach ($input as $v) {
$output .= chr(($v >> 24) & 255).chr(($v >> 16) & 255).chr(($v >> 8) & 255).chr($v & 255);
}
return $output;
} | [
"function",
"_ucs4_to_ucs4_string",
"(",
"$",
"input",
")",
"{",
"$",
"output",
"=",
"''",
";",
"// Take array values and split output to 4 bytes per value",
"// The bit mask is 255, which reads &11111111",
"foreach",
"(",
"$",
"input",
"as",
"$",
"v",
")",
"{",
"$",
... | Convert UCS-4 array into UCS-4 string
@access private | [
"Convert",
"UCS",
"-",
"4",
"array",
"into",
"UCS",
"-",
"4",
"string"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/idn/idna_convert.class.php#L902-L911 |
simplepie/simplepie | idn/idna_convert.class.php | idna_convert._ucs4_string_to_ucs4 | function _ucs4_string_to_ucs4($input)
{
$output = array();
$inp_len = strlen($input);
// Input length must be dividable by 4
if ($inp_len % 4) {
$this->_error('Input UCS4 string is broken');
return false;
}
// Empty input - return empty output
if (!$inp_len) return $output;
for ($i = 0, $out_len = -1; $i < $inp_len; ++$i) {
// Increment output position every 4 input bytes
if (!($i % 4)) {
$out_len++;
$output[$out_len] = 0;
}
$output[$out_len] += ord($input{$i}) << (8 * (3 - ($i % 4) ) );
}
return $output;
} | php | function _ucs4_string_to_ucs4($input)
{
$output = array();
$inp_len = strlen($input);
// Input length must be dividable by 4
if ($inp_len % 4) {
$this->_error('Input UCS4 string is broken');
return false;
}
// Empty input - return empty output
if (!$inp_len) return $output;
for ($i = 0, $out_len = -1; $i < $inp_len; ++$i) {
// Increment output position every 4 input bytes
if (!($i % 4)) {
$out_len++;
$output[$out_len] = 0;
}
$output[$out_len] += ord($input{$i}) << (8 * (3 - ($i % 4) ) );
}
return $output;
} | [
"function",
"_ucs4_string_to_ucs4",
"(",
"$",
"input",
")",
"{",
"$",
"output",
"=",
"array",
"(",
")",
";",
"$",
"inp_len",
"=",
"strlen",
"(",
"$",
"input",
")",
";",
"// Input length must be dividable by 4",
"if",
"(",
"$",
"inp_len",
"%",
"4",
")",
"... | Convert UCS-4 strin into UCS-4 garray
@access private | [
"Convert",
"UCS",
"-",
"4",
"strin",
"into",
"UCS",
"-",
"4",
"garray"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/idn/idna_convert.class.php#L918-L938 |
simplepie/simplepie | library/SimplePie/HTTP/Parser.php | SimplePie_HTTP_Parser.parse | public function parse()
{
while ($this->state && $this->state !== 'emit' && $this->has_data())
{
$state = $this->state;
$this->$state();
}
$this->data = '';
if ($this->state === 'emit' || $this->state === 'body')
{
return true;
}
$this->http_version = '';
$this->status_code = '';
$this->reason = '';
$this->headers = array();
$this->body = '';
return false;
} | php | public function parse()
{
while ($this->state && $this->state !== 'emit' && $this->has_data())
{
$state = $this->state;
$this->$state();
}
$this->data = '';
if ($this->state === 'emit' || $this->state === 'body')
{
return true;
}
$this->http_version = '';
$this->status_code = '';
$this->reason = '';
$this->headers = array();
$this->body = '';
return false;
} | [
"public",
"function",
"parse",
"(",
")",
"{",
"while",
"(",
"$",
"this",
"->",
"state",
"&&",
"$",
"this",
"->",
"state",
"!==",
"'emit'",
"&&",
"$",
"this",
"->",
"has_data",
"(",
")",
")",
"{",
"$",
"state",
"=",
"$",
"this",
"->",
"state",
";"... | Parse the input data
@return bool true on success, false on failure | [
"Parse",
"the",
"input",
"data"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/library/SimplePie/HTTP/Parser.php#L146-L165 |
simplepie/simplepie | library/SimplePie/HTTP/Parser.php | SimplePie_HTTP_Parser.prepareHeaders | static public function prepareHeaders($headers, $count = 1)
{
$data = explode("\r\n\r\n", $headers, $count);
$data = array_pop($data);
if (false !== stripos($data, "HTTP/1.0 200 Connection established\r\n\r\n")) {
$data = str_ireplace("HTTP/1.0 200 Connection established\r\n\r\n", '', $data);
}
if (false !== stripos($data, "HTTP/1.1 200 Connection established\r\n\r\n")) {
$data = str_ireplace("HTTP/1.1 200 Connection established\r\n\r\n", '', $data);
}
return $data;
} | php | static public function prepareHeaders($headers, $count = 1)
{
$data = explode("\r\n\r\n", $headers, $count);
$data = array_pop($data);
if (false !== stripos($data, "HTTP/1.0 200 Connection established\r\n\r\n")) {
$data = str_ireplace("HTTP/1.0 200 Connection established\r\n\r\n", '', $data);
}
if (false !== stripos($data, "HTTP/1.1 200 Connection established\r\n\r\n")) {
$data = str_ireplace("HTTP/1.1 200 Connection established\r\n\r\n", '', $data);
}
return $data;
} | [
"static",
"public",
"function",
"prepareHeaders",
"(",
"$",
"headers",
",",
"$",
"count",
"=",
"1",
")",
"{",
"$",
"data",
"=",
"explode",
"(",
"\"\\r\\n\\r\\n\"",
",",
"$",
"headers",
",",
"$",
"count",
")",
";",
"$",
"data",
"=",
"array_pop",
"(",
... | Prepare headers (take care of proxies headers)
@param string $headers Raw headers
@param integer $count Redirection count. Default to 1.
@return string | [
"Prepare",
"headers",
"(",
"take",
"care",
"of",
"proxies",
"headers",
")"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/library/SimplePie/HTTP/Parser.php#L506-L517 |
simplepie/simplepie | library/SimplePie/Item.php | SimplePie_Item.get_description | public function get_description($description_only = false)
{
if (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'summary')) &&
($return = $this->sanitize($tags[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($tags[0]['attribs'])), $this->get_base($tags[0]))))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'summary')) &&
($return = $this->sanitize($tags[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($tags[0]['attribs'])), $this->get_base($tags[0]))))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'description')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($tags[0]))))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'description')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($tags[0]))))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'description')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'description')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'summary')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($tags[0]))))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'subtitle')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'description')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_HTML)))
{
return $return;
}
elseif (!$description_only)
{
return $this->get_content(true);
}
return null;
} | php | public function get_description($description_only = false)
{
if (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'summary')) &&
($return = $this->sanitize($tags[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($tags[0]['attribs'])), $this->get_base($tags[0]))))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'summary')) &&
($return = $this->sanitize($tags[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($tags[0]['attribs'])), $this->get_base($tags[0]))))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'description')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($tags[0]))))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'description')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($tags[0]))))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'description')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'description')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'summary')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($tags[0]))))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'subtitle')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'description')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_HTML)))
{
return $return;
}
elseif (!$description_only)
{
return $this->get_content(true);
}
return null;
} | [
"public",
"function",
"get_description",
"(",
"$",
"description_only",
"=",
"false",
")",
"{",
"if",
"(",
"(",
"$",
"tags",
"=",
"$",
"this",
"->",
"get_item_tags",
"(",
"SIMPLEPIE_NAMESPACE_ATOM_10",
",",
"'summary'",
")",
")",
"&&",
"(",
"$",
"return",
"... | Get the content for the item
Prefers summaries over full content , but will return full content if a
summary does not exist.
To prefer full content instead, use {@see get_content}
Uses `<atom:summary>`, `<description>`, `<dc:description>` or
`<itunes:subtitle>`
@since 0.8
@param boolean $description_only Should we avoid falling back to the content?
@return string|null | [
"Get",
"the",
"content",
"for",
"the",
"item"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/library/SimplePie/Item.php#L315-L369 |
simplepie/simplepie | library/SimplePie/Item.php | SimplePie_Item.get_content | public function get_content($content_only = false)
{
if (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'content')) &&
($return = $this->sanitize($tags[0]['data'], $this->registry->call('Misc', 'atom_10_content_construct_type', array($tags[0]['attribs'])), $this->get_base($tags[0]))))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'content')) &&
($return = $this->sanitize($tags[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($tags[0]['attribs'])), $this->get_base($tags[0]))))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_10_MODULES_CONTENT, 'encoded')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($tags[0]))))
{
return $return;
}
elseif (!$content_only)
{
return $this->get_description(true);
}
return null;
} | php | public function get_content($content_only = false)
{
if (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'content')) &&
($return = $this->sanitize($tags[0]['data'], $this->registry->call('Misc', 'atom_10_content_construct_type', array($tags[0]['attribs'])), $this->get_base($tags[0]))))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'content')) &&
($return = $this->sanitize($tags[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($tags[0]['attribs'])), $this->get_base($tags[0]))))
{
return $return;
}
elseif (($tags = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_10_MODULES_CONTENT, 'encoded')) &&
($return = $this->sanitize($tags[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($tags[0]))))
{
return $return;
}
elseif (!$content_only)
{
return $this->get_description(true);
}
return null;
} | [
"public",
"function",
"get_content",
"(",
"$",
"content_only",
"=",
"false",
")",
"{",
"if",
"(",
"(",
"$",
"tags",
"=",
"$",
"this",
"->",
"get_item_tags",
"(",
"SIMPLEPIE_NAMESPACE_ATOM_10",
",",
"'content'",
")",
")",
"&&",
"(",
"$",
"return",
"=",
"$... | Get the content for the item
Prefers full content over summaries, but will return a summary if full
content does not exist.
To prefer summaries instead, use {@see get_description}
Uses `<atom:content>` or `<content:encoded>` (RSS 1.0 Content Module)
@since 1.0
@param boolean $content_only Should we avoid falling back to the description?
@return string|null | [
"Get",
"the",
"content",
"for",
"the",
"item"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/library/SimplePie/Item.php#L385-L408 |
simplepie/simplepie | library/SimplePie/Item.php | SimplePie_Item.get_copyright | public function get_copyright()
{
if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'rights'))
{
return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0]));
}
elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'rights'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'rights'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
return null;
} | php | public function get_copyright()
{
if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'rights'))
{
return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0]));
}
elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'rights'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'rights'))
{
return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT);
}
return null;
} | [
"public",
"function",
"get_copyright",
"(",
")",
"{",
"if",
"(",
"$",
"return",
"=",
"$",
"this",
"->",
"get_item_tags",
"(",
"SIMPLEPIE_NAMESPACE_ATOM_10",
",",
"'rights'",
")",
")",
"{",
"return",
"$",
"this",
"->",
"sanitize",
"(",
"$",
"return",
"[",
... | Get the copyright info for the item
Uses `<atom:rights>` or `<dc:rights>`
@since 1.1
@return string | [
"Get",
"the",
"copyright",
"info",
"for",
"the",
"item"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/library/SimplePie/Item.php#L714-L730 |
simplepie/simplepie | library/SimplePie/Item.php | SimplePie_Item.get_local_date | public function get_local_date($date_format = '%c')
{
if (!$date_format)
{
return $this->sanitize($this->get_date(''), SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif (($date = $this->get_date('U')) !== null && $date !== false)
{
return strftime($date_format, $date);
}
return null;
} | php | public function get_local_date($date_format = '%c')
{
if (!$date_format)
{
return $this->sanitize($this->get_date(''), SIMPLEPIE_CONSTRUCT_TEXT);
}
elseif (($date = $this->get_date('U')) !== null && $date !== false)
{
return strftime($date_format, $date);
}
return null;
} | [
"public",
"function",
"get_local_date",
"(",
"$",
"date_format",
"=",
"'%c'",
")",
"{",
"if",
"(",
"!",
"$",
"date_format",
")",
"{",
"return",
"$",
"this",
"->",
"sanitize",
"(",
"$",
"this",
"->",
"get_date",
"(",
"''",
")",
",",
"SIMPLEPIE_CONSTRUCT_T... | Get the localized posting date/time for the item
Returns the date formatted in the localized language. To display in
languages other than the server's default, you need to change the locale
with {@link http://php.net/setlocale setlocale()}. The available
localizations depend on which ones are installed on your web server.
@since 1.0
@param string $date_format Supports any PHP date format from {@see http://php.net/strftime} (empty for the raw data)
@return int|string|null | [
"Get",
"the",
"localized",
"posting",
"date",
"/",
"time",
"for",
"the",
"item"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/library/SimplePie/Item.php#L874-L886 |
simplepie/simplepie | library/SimplePie/Item.php | SimplePie_Item.get_permalink | public function get_permalink()
{
$link = $this->get_link();
$enclosure = $this->get_enclosure(0);
if ($link !== null)
{
return $link;
}
elseif ($enclosure !== null)
{
return $enclosure->get_link();
}
return null;
} | php | public function get_permalink()
{
$link = $this->get_link();
$enclosure = $this->get_enclosure(0);
if ($link !== null)
{
return $link;
}
elseif ($enclosure !== null)
{
return $enclosure->get_link();
}
return null;
} | [
"public",
"function",
"get_permalink",
"(",
")",
"{",
"$",
"link",
"=",
"$",
"this",
"->",
"get_link",
"(",
")",
";",
"$",
"enclosure",
"=",
"$",
"this",
"->",
"get_enclosure",
"(",
"0",
")",
";",
"if",
"(",
"$",
"link",
"!==",
"null",
")",
"{",
... | Get the permalink for the item
Returns the first link available with a relationship of "alternate".
Identical to {@see get_link()} with key 0
@see get_link
@since 0.8
@return string|null Permalink URL | [
"Get",
"the",
"permalink",
"for",
"the",
"item"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/library/SimplePie/Item.php#L934-L948 |
simplepie/simplepie | library/SimplePie/Misc.php | SimplePie_Misc.get_build | public static function get_build()
{
$root = dirname(dirname(__FILE__));
if (file_exists($root . '/.git/index'))
{
return filemtime($root . '/.git/index');
}
elseif (file_exists($root . '/SimplePie'))
{
$time = 0;
foreach (glob($root . '/SimplePie/*.php') as $file)
{
if (($mtime = filemtime($file)) > $time)
{
$time = $mtime;
}
}
return $time;
}
elseif (file_exists(dirname(__FILE__) . '/Core.php'))
{
return filemtime(dirname(__FILE__) . '/Core.php');
}
return filemtime(__FILE__);
} | php | public static function get_build()
{
$root = dirname(dirname(__FILE__));
if (file_exists($root . '/.git/index'))
{
return filemtime($root . '/.git/index');
}
elseif (file_exists($root . '/SimplePie'))
{
$time = 0;
foreach (glob($root . '/SimplePie/*.php') as $file)
{
if (($mtime = filemtime($file)) > $time)
{
$time = $mtime;
}
}
return $time;
}
elseif (file_exists(dirname(__FILE__) . '/Core.php'))
{
return filemtime(dirname(__FILE__) . '/Core.php');
}
return filemtime(__FILE__);
} | [
"public",
"static",
"function",
"get_build",
"(",
")",
"{",
"$",
"root",
"=",
"dirname",
"(",
"dirname",
"(",
"__FILE__",
")",
")",
";",
"if",
"(",
"file_exists",
"(",
"$",
"root",
".",
"'/.git/index'",
")",
")",
"{",
"return",
"filemtime",
"(",
"$",
... | Get the SimplePie build timestamp
Uses the git index if it exists, otherwise uses the modification time
of the newest file. | [
"Get",
"the",
"SimplePie",
"build",
"timestamp"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/library/SimplePie/Misc.php#L2181-L2206 |
simplepie/simplepie | library/SimplePie/Content/Type/Sniffer.php | SimplePie_Content_Type_Sniffer.unknown | public function unknown()
{
$ws = strspn($this->file->body, "\x09\x0A\x0B\x0C\x0D\x20");
if (strtolower(substr($this->file->body, $ws, 14)) === '<!doctype html'
|| strtolower(substr($this->file->body, $ws, 5)) === '<html'
|| strtolower(substr($this->file->body, $ws, 7)) === '<script')
{
return 'text/html';
}
elseif (substr($this->file->body, 0, 5) === '%PDF-')
{
return 'application/pdf';
}
elseif (substr($this->file->body, 0, 11) === '%!PS-Adobe-')
{
return 'application/postscript';
}
elseif (substr($this->file->body, 0, 6) === 'GIF87a'
|| substr($this->file->body, 0, 6) === 'GIF89a')
{
return 'image/gif';
}
elseif (substr($this->file->body, 0, 8) === "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A")
{
return 'image/png';
}
elseif (substr($this->file->body, 0, 3) === "\xFF\xD8\xFF")
{
return 'image/jpeg';
}
elseif (substr($this->file->body, 0, 2) === "\x42\x4D")
{
return 'image/bmp';
}
elseif (substr($this->file->body, 0, 4) === "\x00\x00\x01\x00")
{
return 'image/vnd.microsoft.icon';
}
return $this->text_or_binary();
} | php | public function unknown()
{
$ws = strspn($this->file->body, "\x09\x0A\x0B\x0C\x0D\x20");
if (strtolower(substr($this->file->body, $ws, 14)) === '<!doctype html'
|| strtolower(substr($this->file->body, $ws, 5)) === '<html'
|| strtolower(substr($this->file->body, $ws, 7)) === '<script')
{
return 'text/html';
}
elseif (substr($this->file->body, 0, 5) === '%PDF-')
{
return 'application/pdf';
}
elseif (substr($this->file->body, 0, 11) === '%!PS-Adobe-')
{
return 'application/postscript';
}
elseif (substr($this->file->body, 0, 6) === 'GIF87a'
|| substr($this->file->body, 0, 6) === 'GIF89a')
{
return 'image/gif';
}
elseif (substr($this->file->body, 0, 8) === "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A")
{
return 'image/png';
}
elseif (substr($this->file->body, 0, 3) === "\xFF\xD8\xFF")
{
return 'image/jpeg';
}
elseif (substr($this->file->body, 0, 2) === "\x42\x4D")
{
return 'image/bmp';
}
elseif (substr($this->file->body, 0, 4) === "\x00\x00\x01\x00")
{
return 'image/vnd.microsoft.icon';
}
return $this->text_or_binary();
} | [
"public",
"function",
"unknown",
"(",
")",
"{",
"$",
"ws",
"=",
"strspn",
"(",
"$",
"this",
"->",
"file",
"->",
"body",
",",
"\"\\x09\\x0A\\x0B\\x0C\\x0D\\x20\"",
")",
";",
"if",
"(",
"strtolower",
"(",
"substr",
"(",
"$",
"this",
"->",
"file",
"->",
"... | Sniff unknown
@return string Actual Content-Type | [
"Sniff",
"unknown"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/library/SimplePie/Content/Type/Sniffer.php#L164-L204 |
simplepie/simplepie | library/SimplePie/Net/IPv6.php | SimplePie_Net_IPv6.compress | public static function compress($ip)
{
// Prepare the IP to be compressed
$ip = self::uncompress($ip);
$ip_parts = self::split_v6_v4($ip);
// Replace all leading zeros
$ip_parts[0] = preg_replace('/(^|:)0+([0-9])/', '\1\2', $ip_parts[0]);
// Find bunches of zeros
if (preg_match_all('/(?:^|:)(?:0(?::|$))+/', $ip_parts[0], $matches, PREG_OFFSET_CAPTURE))
{
$max = 0;
$pos = null;
foreach ($matches[0] as $match)
{
if (strlen($match[0]) > $max)
{
$max = strlen($match[0]);
$pos = $match[1];
}
}
$ip_parts[0] = substr_replace($ip_parts[0], '::', $pos, $max);
}
if ($ip_parts[1] !== '')
{
return implode(':', $ip_parts);
}
return $ip_parts[0];
} | php | public static function compress($ip)
{
// Prepare the IP to be compressed
$ip = self::uncompress($ip);
$ip_parts = self::split_v6_v4($ip);
// Replace all leading zeros
$ip_parts[0] = preg_replace('/(^|:)0+([0-9])/', '\1\2', $ip_parts[0]);
// Find bunches of zeros
if (preg_match_all('/(?:^|:)(?:0(?::|$))+/', $ip_parts[0], $matches, PREG_OFFSET_CAPTURE))
{
$max = 0;
$pos = null;
foreach ($matches[0] as $match)
{
if (strlen($match[0]) > $max)
{
$max = strlen($match[0]);
$pos = $match[1];
}
}
$ip_parts[0] = substr_replace($ip_parts[0], '::', $pos, $max);
}
if ($ip_parts[1] !== '')
{
return implode(':', $ip_parts);
}
return $ip_parts[0];
} | [
"public",
"static",
"function",
"compress",
"(",
"$",
"ip",
")",
"{",
"// Prepare the IP to be compressed",
"$",
"ip",
"=",
"self",
"::",
"uncompress",
"(",
"$",
"ip",
")",
";",
"$",
"ip_parts",
"=",
"self",
"::",
"split_v6_v4",
"(",
"$",
"ip",
")",
";",... | Compresses an IPv6 address
RFC 4291 allows you to compress concecutive zero pieces in an address to
'::'. This method expects a valid IPv6 address and compresses consecutive
zero pieces to '::'.
Example: FF01:0:0:0:0:0:0:101 -> FF01::101
0:0:0:0:0:0:0:1 -> ::1
@see uncompress()
@param string $ip An IPv6 address
@return string The compressed IPv6 address | [
"Compresses",
"an",
"IPv6",
"address"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/library/SimplePie/Net/IPv6.php#L146-L178 |
simplepie/simplepie | library/SimplePie/IRI.php | SimplePie_IRI.absolutize | public static function absolutize($base, $relative)
{
if (!($relative instanceof SimplePie_IRI))
{
$relative = new SimplePie_IRI($relative);
}
if (!$relative->is_valid())
{
return false;
}
elseif ($relative->scheme !== null)
{
return clone $relative;
}
else
{
if (!($base instanceof SimplePie_IRI))
{
$base = new SimplePie_IRI($base);
}
if ($base->scheme !== null && $base->is_valid())
{
if ($relative->get_iri() !== '')
{
if ($relative->iuserinfo !== null || $relative->ihost !== null || $relative->port !== null)
{
$target = clone $relative;
$target->scheme = $base->scheme;
}
else
{
$target = new SimplePie_IRI;
$target->scheme = $base->scheme;
$target->iuserinfo = $base->iuserinfo;
$target->ihost = $base->ihost;
$target->port = $base->port;
if ($relative->ipath !== '')
{
if ($relative->ipath[0] === '/')
{
$target->ipath = $relative->ipath;
}
elseif (($base->iuserinfo !== null || $base->ihost !== null || $base->port !== null) && $base->ipath === '')
{
$target->ipath = '/' . $relative->ipath;
}
elseif (($last_segment = strrpos($base->ipath, '/')) !== false)
{
$target->ipath = substr($base->ipath, 0, $last_segment + 1) . $relative->ipath;
}
else
{
$target->ipath = $relative->ipath;
}
$target->ipath = $target->remove_dot_segments($target->ipath);
$target->iquery = $relative->iquery;
}
else
{
$target->ipath = $base->ipath;
if ($relative->iquery !== null)
{
$target->iquery = $relative->iquery;
}
elseif ($base->iquery !== null)
{
$target->iquery = $base->iquery;
}
}
$target->ifragment = $relative->ifragment;
}
}
else
{
$target = clone $base;
$target->ifragment = null;
}
$target->scheme_normalization();
return $target;
}
return false;
}
} | php | public static function absolutize($base, $relative)
{
if (!($relative instanceof SimplePie_IRI))
{
$relative = new SimplePie_IRI($relative);
}
if (!$relative->is_valid())
{
return false;
}
elseif ($relative->scheme !== null)
{
return clone $relative;
}
else
{
if (!($base instanceof SimplePie_IRI))
{
$base = new SimplePie_IRI($base);
}
if ($base->scheme !== null && $base->is_valid())
{
if ($relative->get_iri() !== '')
{
if ($relative->iuserinfo !== null || $relative->ihost !== null || $relative->port !== null)
{
$target = clone $relative;
$target->scheme = $base->scheme;
}
else
{
$target = new SimplePie_IRI;
$target->scheme = $base->scheme;
$target->iuserinfo = $base->iuserinfo;
$target->ihost = $base->ihost;
$target->port = $base->port;
if ($relative->ipath !== '')
{
if ($relative->ipath[0] === '/')
{
$target->ipath = $relative->ipath;
}
elseif (($base->iuserinfo !== null || $base->ihost !== null || $base->port !== null) && $base->ipath === '')
{
$target->ipath = '/' . $relative->ipath;
}
elseif (($last_segment = strrpos($base->ipath, '/')) !== false)
{
$target->ipath = substr($base->ipath, 0, $last_segment + 1) . $relative->ipath;
}
else
{
$target->ipath = $relative->ipath;
}
$target->ipath = $target->remove_dot_segments($target->ipath);
$target->iquery = $relative->iquery;
}
else
{
$target->ipath = $base->ipath;
if ($relative->iquery !== null)
{
$target->iquery = $relative->iquery;
}
elseif ($base->iquery !== null)
{
$target->iquery = $base->iquery;
}
}
$target->ifragment = $relative->ifragment;
}
}
else
{
$target = clone $base;
$target->ifragment = null;
}
$target->scheme_normalization();
return $target;
}
return false;
}
} | [
"public",
"static",
"function",
"absolutize",
"(",
"$",
"base",
",",
"$",
"relative",
")",
"{",
"if",
"(",
"!",
"(",
"$",
"relative",
"instanceof",
"SimplePie_IRI",
")",
")",
"{",
"$",
"relative",
"=",
"new",
"SimplePie_IRI",
"(",
"$",
"relative",
")",
... | Create a new IRI object by resolving a relative IRI
Returns false if $base is not absolute, otherwise an IRI.
@param IRI|string $base (Absolute) Base IRI
@param IRI|string $relative Relative IRI
@return IRI|false | [
"Create",
"a",
"new",
"IRI",
"object",
"by",
"resolving",
"a",
"relative",
"IRI"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/library/SimplePie/IRI.php#L270-L353 |
simplepie/simplepie | library/SimplePie/IRI.php | SimplePie_IRI.parse_iri | protected function parse_iri($iri)
{
$iri = trim($iri, "\x20\x09\x0A\x0C\x0D");
if (preg_match('/^((?P<scheme>[^:\/?#]+):)?(\/\/(?P<authority>[^\/?#]*))?(?P<path>[^?#]*)(\?(?P<query>[^#]*))?(#(?P<fragment>.*))?$/', $iri, $match))
{
if ($match[1] === '')
{
$match['scheme'] = null;
}
if (!isset($match[3]) || $match[3] === '')
{
$match['authority'] = null;
}
if (!isset($match[5]))
{
$match['path'] = '';
}
if (!isset($match[6]) || $match[6] === '')
{
$match['query'] = null;
}
if (!isset($match[8]) || $match[8] === '')
{
$match['fragment'] = null;
}
return $match;
}
// This can occur when a paragraph is accidentally parsed as a URI
return false;
} | php | protected function parse_iri($iri)
{
$iri = trim($iri, "\x20\x09\x0A\x0C\x0D");
if (preg_match('/^((?P<scheme>[^:\/?#]+):)?(\/\/(?P<authority>[^\/?#]*))?(?P<path>[^?#]*)(\?(?P<query>[^#]*))?(#(?P<fragment>.*))?$/', $iri, $match))
{
if ($match[1] === '')
{
$match['scheme'] = null;
}
if (!isset($match[3]) || $match[3] === '')
{
$match['authority'] = null;
}
if (!isset($match[5]))
{
$match['path'] = '';
}
if (!isset($match[6]) || $match[6] === '')
{
$match['query'] = null;
}
if (!isset($match[8]) || $match[8] === '')
{
$match['fragment'] = null;
}
return $match;
}
// This can occur when a paragraph is accidentally parsed as a URI
return false;
} | [
"protected",
"function",
"parse_iri",
"(",
"$",
"iri",
")",
"{",
"$",
"iri",
"=",
"trim",
"(",
"$",
"iri",
",",
"\"\\x20\\x09\\x0A\\x0C\\x0D\"",
")",
";",
"if",
"(",
"preg_match",
"(",
"'/^((?P<scheme>[^:\\/?#]+):)?(\\/\\/(?P<authority>[^\\/?#]*))?(?P<path>[^?#]*)(\\?(?... | Parse an IRI into scheme/authority/path/query/fragment segments
@param string $iri
@return array | [
"Parse",
"an",
"IRI",
"into",
"scheme",
"/",
"authority",
"/",
"path",
"/",
"query",
"/",
"fragment",
"segments"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/library/SimplePie/IRI.php#L361-L391 |
simplepie/simplepie | library/SimplePie/IRI.php | SimplePie_IRI.set_authority | public function set_authority($authority, $clear_cache = false)
{
static $cache;
if ($clear_cache)
{
$cache = null;
return;
}
if (!$cache)
$cache = array();
if ($authority === null)
{
$this->iuserinfo = null;
$this->ihost = null;
$this->port = null;
return true;
}
elseif (isset($cache[$authority]))
{
list($this->iuserinfo,
$this->ihost,
$this->port,
$return) = $cache[$authority];
return $return;
}
$remaining = $authority;
if (($iuserinfo_end = strrpos($remaining, '@')) !== false)
{
$iuserinfo = substr($remaining, 0, $iuserinfo_end);
$remaining = substr($remaining, $iuserinfo_end + 1);
}
else
{
$iuserinfo = null;
}
if (($port_start = strpos($remaining, ':', strpos($remaining, ']'))) !== false)
{
if (($port = substr($remaining, $port_start + 1)) === false)
{
$port = null;
}
$remaining = substr($remaining, 0, $port_start);
}
else
{
$port = null;
}
$return = $this->set_userinfo($iuserinfo) &&
$this->set_host($remaining) &&
$this->set_port($port);
$cache[$authority] = array($this->iuserinfo,
$this->ihost,
$this->port,
$return);
return $return;
} | php | public function set_authority($authority, $clear_cache = false)
{
static $cache;
if ($clear_cache)
{
$cache = null;
return;
}
if (!$cache)
$cache = array();
if ($authority === null)
{
$this->iuserinfo = null;
$this->ihost = null;
$this->port = null;
return true;
}
elseif (isset($cache[$authority]))
{
list($this->iuserinfo,
$this->ihost,
$this->port,
$return) = $cache[$authority];
return $return;
}
$remaining = $authority;
if (($iuserinfo_end = strrpos($remaining, '@')) !== false)
{
$iuserinfo = substr($remaining, 0, $iuserinfo_end);
$remaining = substr($remaining, $iuserinfo_end + 1);
}
else
{
$iuserinfo = null;
}
if (($port_start = strpos($remaining, ':', strpos($remaining, ']'))) !== false)
{
if (($port = substr($remaining, $port_start + 1)) === false)
{
$port = null;
}
$remaining = substr($remaining, 0, $port_start);
}
else
{
$port = null;
}
$return = $this->set_userinfo($iuserinfo) &&
$this->set_host($remaining) &&
$this->set_port($port);
$cache[$authority] = array($this->iuserinfo,
$this->ihost,
$this->port,
$return);
return $return;
} | [
"public",
"function",
"set_authority",
"(",
"$",
"authority",
",",
"$",
"clear_cache",
"=",
"false",
")",
"{",
"static",
"$",
"cache",
";",
"if",
"(",
"$",
"clear_cache",
")",
"{",
"$",
"cache",
"=",
"null",
";",
"return",
";",
"}",
"if",
"(",
"!",
... | Set the authority. Returns true on success, false on failure (if there are
any invalid characters).
@param string $authority
@return bool | [
"Set",
"the",
"authority",
".",
"Returns",
"true",
"on",
"success",
"false",
"on",
"failure",
"(",
"if",
"there",
"are",
"any",
"invalid",
"characters",
")",
"."
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/library/SimplePie/IRI.php#L876-L937 |
simplepie/simplepie | library/SimplePie/IRI.php | SimplePie_IRI.get_authority | protected function get_authority()
{
$iauthority = $this->get_iauthority();
if (is_string($iauthority))
return $this->to_uri($iauthority);
return $iauthority;
} | php | protected function get_authority()
{
$iauthority = $this->get_iauthority();
if (is_string($iauthority))
return $this->to_uri($iauthority);
return $iauthority;
} | [
"protected",
"function",
"get_authority",
"(",
")",
"{",
"$",
"iauthority",
"=",
"$",
"this",
"->",
"get_iauthority",
"(",
")",
";",
"if",
"(",
"is_string",
"(",
"$",
"iauthority",
")",
")",
"return",
"$",
"this",
"->",
"to_uri",
"(",
"$",
"iauthority",
... | Get the complete authority
@return string | [
"Get",
"the",
"complete",
"authority"
] | train | https://github.com/simplepie/simplepie/blob/11ddaed291ccd1b2628eef433a6bef58a1e4f920/library/SimplePie/IRI.php#L1228-L1235 |
ircmaxell/RandomLib | lib/RandomLib/Source/MTRand.php | MTRand.generate | public function generate($size)
{
$result = '';
for ($i = 0; $i < $size; $i++) {
$result .= chr((mt_rand() ^ mt_rand()) % 256);
}
return $result;
} | php | public function generate($size)
{
$result = '';
for ($i = 0; $i < $size; $i++) {
$result .= chr((mt_rand() ^ mt_rand()) % 256);
}
return $result;
} | [
"public",
"function",
"generate",
"(",
"$",
"size",
")",
"{",
"$",
"result",
"=",
"''",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"size",
";",
"$",
"i",
"++",
")",
"{",
"$",
"result",
".=",
"chr",
"(",
"(",
"mt_rand",
"(... | Generate a random string of the specified size
@param int $size The size of the requested random string
@return string A string of the requested size | [
"Generate",
"a",
"random",
"string",
"of",
"the",
"specified",
"size"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/Source/MTRand.php#L74-L82 |
ircmaxell/RandomLib | lib/RandomLib/Source/URandom.php | URandom.generate | public function generate($size)
{
if ($size == 0) {
return static::emptyValue($size);
}
$file = fopen(static::$file, 'rb');
if (!$file) {
return static::emptyValue($size);
}
if (function_exists('stream_set_read_buffer')) {
stream_set_read_buffer($file, 0);
}
$result = fread($file, $size);
fclose($file);
return $result;
} | php | public function generate($size)
{
if ($size == 0) {
return static::emptyValue($size);
}
$file = fopen(static::$file, 'rb');
if (!$file) {
return static::emptyValue($size);
}
if (function_exists('stream_set_read_buffer')) {
stream_set_read_buffer($file, 0);
}
$result = fread($file, $size);
fclose($file);
return $result;
} | [
"public",
"function",
"generate",
"(",
"$",
"size",
")",
"{",
"if",
"(",
"$",
"size",
"==",
"0",
")",
"{",
"return",
"static",
"::",
"emptyValue",
"(",
"$",
"size",
")",
";",
"}",
"$",
"file",
"=",
"fopen",
"(",
"static",
"::",
"$",
"file",
",",
... | Generate a random string of the specified size
@param int $size The size of the requested random string
@return string A string of the requested size | [
"Generate",
"a",
"random",
"string",
"of",
"the",
"specified",
"size"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/Source/URandom.php#L81-L97 |
ircmaxell/RandomLib | lib/RandomLib/Source/MicroTime.php | MicroTime.generate | public function generate($size)
{
$result = '';
$seed = microtime() . memory_get_usage();
self::$state = hash('sha512', self::$state . $seed, true);
/**
* Make the generated randomness a bit better by forcing a GC run which
* should complete in a indeterminate amount of time, hence improving
* the strength of the randomness a bit. It's still not crypto-safe,
* but at least it's more difficult to predict.
*/
gc_collect_cycles();
for ($i = 0; $i < $size; $i += 8) {
$seed = self::$state .
microtime() .
pack('Ni', $i, self::counter());
self::$state = hash('sha512', $seed, true);
/**
* We only use the first 8 bytes here to prevent exposing the state
* in its entirety, which could potentially expose other random
* generations in the future (in the same process)...
*/
$result .= Util::safeSubstr(self::$state, 0, 8);
}
return Util::safeSubstr($result, 0, $size);
} | php | public function generate($size)
{
$result = '';
$seed = microtime() . memory_get_usage();
self::$state = hash('sha512', self::$state . $seed, true);
/**
* Make the generated randomness a bit better by forcing a GC run which
* should complete in a indeterminate amount of time, hence improving
* the strength of the randomness a bit. It's still not crypto-safe,
* but at least it's more difficult to predict.
*/
gc_collect_cycles();
for ($i = 0; $i < $size; $i += 8) {
$seed = self::$state .
microtime() .
pack('Ni', $i, self::counter());
self::$state = hash('sha512', $seed, true);
/**
* We only use the first 8 bytes here to prevent exposing the state
* in its entirety, which could potentially expose other random
* generations in the future (in the same process)...
*/
$result .= Util::safeSubstr(self::$state, 0, 8);
}
return Util::safeSubstr($result, 0, $size);
} | [
"public",
"function",
"generate",
"(",
"$",
"size",
")",
"{",
"$",
"result",
"=",
"''",
";",
"$",
"seed",
"=",
"microtime",
"(",
")",
".",
"memory_get_usage",
"(",
")",
";",
"self",
"::",
"$",
"state",
"=",
"hash",
"(",
"'sha512'",
",",
"self",
"::... | Generate a random string of the specified size
@param int $size The size of the requested random string
@return string A string of the requested size | [
"Generate",
"a",
"random",
"string",
"of",
"the",
"specified",
"size"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/Source/MicroTime.php#L98-L124 |
ircmaxell/RandomLib | lib/RandomLib/AbstractMcryptMixer.php | AbstractMcryptMixer.encryptBlock | private function encryptBlock($input, $key)
{
if (!$input && !$key) {
return '';
}
$this->prepareCipher($key);
$result = mcrypt_generic($this->mcrypt, $input);
mcrypt_generic_deinit($this->mcrypt);
return $result;
} | php | private function encryptBlock($input, $key)
{
if (!$input && !$key) {
return '';
}
$this->prepareCipher($key);
$result = mcrypt_generic($this->mcrypt, $input);
mcrypt_generic_deinit($this->mcrypt);
return $result;
} | [
"private",
"function",
"encryptBlock",
"(",
"$",
"input",
",",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"$",
"input",
"&&",
"!",
"$",
"key",
")",
"{",
"return",
"''",
";",
"}",
"$",
"this",
"->",
"prepareCipher",
"(",
"$",
"key",
")",
";",
"$",
"r... | Encrypts a block using the suppied key
@param string $input Plaintext to encrypt
@param string $key Encryption key
@return string Resulting ciphertext | [
"Encrypts",
"a",
"block",
"using",
"the",
"suppied",
"key"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/AbstractMcryptMixer.php#L129-L140 |
ircmaxell/RandomLib | lib/RandomLib/AbstractMcryptMixer.php | AbstractMcryptMixer.decryptBlock | private function decryptBlock($input, $key)
{
if (!$input && !$key) {
return '';
}
$this->prepareCipher($key);
$result = mdecrypt_generic($this->mcrypt, $input);
mcrypt_generic_deinit($this->mcrypt);
return $result;
} | php | private function decryptBlock($input, $key)
{
if (!$input && !$key) {
return '';
}
$this->prepareCipher($key);
$result = mdecrypt_generic($this->mcrypt, $input);
mcrypt_generic_deinit($this->mcrypt);
return $result;
} | [
"private",
"function",
"decryptBlock",
"(",
"$",
"input",
",",
"$",
"key",
")",
"{",
"if",
"(",
"!",
"$",
"input",
"&&",
"!",
"$",
"key",
")",
"{",
"return",
"''",
";",
"}",
"$",
"this",
"->",
"prepareCipher",
"(",
"$",
"key",
")",
";",
"$",
"r... | Derypts a block using the suppied key
@param string $input Ciphertext to decrypt
@param string $key Encryption key
@return string Resulting plaintext | [
"Derypts",
"a",
"block",
"using",
"the",
"suppied",
"key"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/AbstractMcryptMixer.php#L150-L161 |
ircmaxell/RandomLib | lib/RandomLib/Source/Sodium.php | Sodium.generate | public function generate($size)
{
if (!$this->hasLibsodium || $size < 1) {
return str_repeat(chr(0), $size);
}
return \Sodium\randombytes_buf($size);
} | php | public function generate($size)
{
if (!$this->hasLibsodium || $size < 1) {
return str_repeat(chr(0), $size);
}
return \Sodium\randombytes_buf($size);
} | [
"public",
"function",
"generate",
"(",
"$",
"size",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasLibsodium",
"||",
"$",
"size",
"<",
"1",
")",
"{",
"return",
"str_repeat",
"(",
"chr",
"(",
"0",
")",
",",
"$",
"size",
")",
";",
"}",
"return",
... | Generate a random string of the specified size
@param int $size The size of the requested random string
@return string A string of the requested size | [
"Generate",
"a",
"random",
"string",
"of",
"the",
"specified",
"size"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/Source/Sodium.php#L101-L108 |
ircmaxell/RandomLib | lib/RandomLib/AbstractMixer.php | AbstractMixer.mix | public function mix(array $parts)
{
if (empty($parts)) {
return '';
}
$len = Util::safeStrlen($parts[0]);
$parts = $this->normalizeParts($parts);
$stringSize = count($parts[0]);
$partsSize = count($parts);
$result = '';
$offset = 0;
for ($i = 0; $i < $stringSize; $i++) {
$stub = $parts[$offset][$i];
for ($j = 1; $j < $partsSize; $j++) {
$newKey = $parts[($j + $offset) % $partsSize][$i];
//Alternately mix the output for each source
if ($j % 2 == 1) {
$stub ^= $this->mixParts1($stub, $newKey);
} else {
$stub ^= $this->mixParts2($stub, $newKey);
}
}
$result .= $stub;
$offset = ($offset + 1) % $partsSize;
}
return Util::safeSubstr($result, 0, $len);
} | php | public function mix(array $parts)
{
if (empty($parts)) {
return '';
}
$len = Util::safeStrlen($parts[0]);
$parts = $this->normalizeParts($parts);
$stringSize = count($parts[0]);
$partsSize = count($parts);
$result = '';
$offset = 0;
for ($i = 0; $i < $stringSize; $i++) {
$stub = $parts[$offset][$i];
for ($j = 1; $j < $partsSize; $j++) {
$newKey = $parts[($j + $offset) % $partsSize][$i];
//Alternately mix the output for each source
if ($j % 2 == 1) {
$stub ^= $this->mixParts1($stub, $newKey);
} else {
$stub ^= $this->mixParts2($stub, $newKey);
}
}
$result .= $stub;
$offset = ($offset + 1) % $partsSize;
}
return Util::safeSubstr($result, 0, $len);
} | [
"public",
"function",
"mix",
"(",
"array",
"$",
"parts",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"parts",
")",
")",
"{",
"return",
"''",
";",
"}",
"$",
"len",
"=",
"Util",
"::",
"safeStrlen",
"(",
"$",
"parts",
"[",
"0",
"]",
")",
";",
"$",
"... | Mix the provided array of strings into a single output of the same size
All elements of the array should be the same size.
@param array $parts The parts to be mixed
@return string The mixed result | [
"Mix",
"the",
"provided",
"array",
"of",
"strings",
"into",
"a",
"single",
"output",
"of",
"the",
"same",
"size"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/AbstractMixer.php#L79-L106 |
ircmaxell/RandomLib | lib/RandomLib/AbstractMixer.php | AbstractMixer.normalizeParts | protected function normalizeParts(array $parts)
{
$blockSize = $this->getPartSize();
$callback = function ($value) {
return Util::safeStrlen($value);
};
$maxSize = max(array_map($callback, $parts));
if ($maxSize % $blockSize != 0) {
$maxSize += $blockSize - ($maxSize % $blockSize);
}
foreach ($parts as &$part) {
$part = $this->str_pad($part, $maxSize, chr(0));
$part = str_split($part, $blockSize);
}
return $parts;
} | php | protected function normalizeParts(array $parts)
{
$blockSize = $this->getPartSize();
$callback = function ($value) {
return Util::safeStrlen($value);
};
$maxSize = max(array_map($callback, $parts));
if ($maxSize % $blockSize != 0) {
$maxSize += $blockSize - ($maxSize % $blockSize);
}
foreach ($parts as &$part) {
$part = $this->str_pad($part, $maxSize, chr(0));
$part = str_split($part, $blockSize);
}
return $parts;
} | [
"protected",
"function",
"normalizeParts",
"(",
"array",
"$",
"parts",
")",
"{",
"$",
"blockSize",
"=",
"$",
"this",
"->",
"getPartSize",
"(",
")",
";",
"$",
"callback",
"=",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"Util",
"::",
"safeStrlen",
... | Normalize the part array and split it block part size.
This will make all parts the same length and a multiple
of the part size
@param array $parts The parts to normalize
@return array The normalized and split parts | [
"Normalize",
"the",
"part",
"array",
"and",
"split",
"it",
"block",
"part",
"size",
"."
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/AbstractMixer.php#L118-L134 |
ircmaxell/RandomLib | lib/RandomLib/Generator.php | Generator.generate | public function generate($size)
{
$seeds = array();
foreach ($this->sources as $source) {
$seeds[] = $source->generate($size);
}
return $this->mixer->mix($seeds);
} | php | public function generate($size)
{
$seeds = array();
foreach ($this->sources as $source) {
$seeds[] = $source->generate($size);
}
return $this->mixer->mix($seeds);
} | [
"public",
"function",
"generate",
"(",
"$",
"size",
")",
"{",
"$",
"seeds",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"sources",
"as",
"$",
"source",
")",
"{",
"$",
"seeds",
"[",
"]",
"=",
"$",
"source",
"->",
"generate",
"(... | Generate a random number (string) of the requested size
@param int $size The size of the requested random number
@return string The generated random number (string) | [
"Generate",
"a",
"random",
"number",
"(",
"string",
")",
"of",
"the",
"requested",
"size"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/Generator.php#L172-L180 |
ircmaxell/RandomLib | lib/RandomLib/Generator.php | Generator.generateInt | public function generateInt($min = 0, $max = PHP_INT_MAX)
{
$tmp = (int) max($max, $min);
$min = (int) min($max, $min);
$max = $tmp;
$range = $max - $min;
if ($range == 0) {
return $max;
} elseif ($range > PHP_INT_MAX || is_float($range) || $range < 0) {
/**
* This works, because PHP will auto-convert it to a float at this point,
* But on 64 bit systems, the float won't have enough precision to
* actually store the difference, so we need to check if it's a float
* and hence auto-converted...
*/
throw new \RangeException(
'The supplied range is too great to generate'
);
}
$bits = $this->countBits($range) + 1;
$bytes = (int) max(ceil($bits / 8), 1);
if ($bits == 63) {
/**
* Fixes issue #22
*
* @see https://github.com/ircmaxell/RandomLib/issues/22
*/
$mask = 0x7fffffffffffffff;
} else {
$mask = (int) (pow(2, $bits) - 1);
}
/**
* The mask is a better way of dropping unused bits. Basically what it does
* is to set all the bits in the mask to 1 that we may need. Since the max
* range is PHP_INT_MAX, we will never need negative numbers (which would
* have the MSB set on the max int possible to generate). Therefore we
* can just mask that away. Since pow returns a float, we need to cast
* it back to an int so the mask will work.
*
* On a 64 bit platform, that means that PHP_INT_MAX is 2^63 - 1. Which
* is also the mask if 63 bits are needed (by the log(range, 2) call).
* So if the computed result is negative (meaning the 64th bit is set), the
* mask will correct that.
*
* This turns out to be slightly better than the shift as we don't need to
* worry about "fixing" negative values.
*/
do {
$test = $this->generate($bytes);
$result = hexdec(bin2hex($test)) & $mask;
} while ($result > $range);
return $result + $min;
} | php | public function generateInt($min = 0, $max = PHP_INT_MAX)
{
$tmp = (int) max($max, $min);
$min = (int) min($max, $min);
$max = $tmp;
$range = $max - $min;
if ($range == 0) {
return $max;
} elseif ($range > PHP_INT_MAX || is_float($range) || $range < 0) {
/**
* This works, because PHP will auto-convert it to a float at this point,
* But on 64 bit systems, the float won't have enough precision to
* actually store the difference, so we need to check if it's a float
* and hence auto-converted...
*/
throw new \RangeException(
'The supplied range is too great to generate'
);
}
$bits = $this->countBits($range) + 1;
$bytes = (int) max(ceil($bits / 8), 1);
if ($bits == 63) {
/**
* Fixes issue #22
*
* @see https://github.com/ircmaxell/RandomLib/issues/22
*/
$mask = 0x7fffffffffffffff;
} else {
$mask = (int) (pow(2, $bits) - 1);
}
/**
* The mask is a better way of dropping unused bits. Basically what it does
* is to set all the bits in the mask to 1 that we may need. Since the max
* range is PHP_INT_MAX, we will never need negative numbers (which would
* have the MSB set on the max int possible to generate). Therefore we
* can just mask that away. Since pow returns a float, we need to cast
* it back to an int so the mask will work.
*
* On a 64 bit platform, that means that PHP_INT_MAX is 2^63 - 1. Which
* is also the mask if 63 bits are needed (by the log(range, 2) call).
* So if the computed result is negative (meaning the 64th bit is set), the
* mask will correct that.
*
* This turns out to be slightly better than the shift as we don't need to
* worry about "fixing" negative values.
*/
do {
$test = $this->generate($bytes);
$result = hexdec(bin2hex($test)) & $mask;
} while ($result > $range);
return $result + $min;
} | [
"public",
"function",
"generateInt",
"(",
"$",
"min",
"=",
"0",
",",
"$",
"max",
"=",
"PHP_INT_MAX",
")",
"{",
"$",
"tmp",
"=",
"(",
"int",
")",
"max",
"(",
"$",
"max",
",",
"$",
"min",
")",
";",
"$",
"min",
"=",
"(",
"int",
")",
"min",
"(",
... | Generate a random integer with the given range
@param int $min The lower bound of the range to generate
@param int $max The upper bound of the range to generate
@return int The generated random number within the range | [
"Generate",
"a",
"random",
"integer",
"with",
"the",
"given",
"range"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/Generator.php#L190-L245 |
ircmaxell/RandomLib | lib/RandomLib/Generator.php | Generator.generateString | public function generateString($length, $characters = '')
{
if (is_int($characters)) {
// Combine character sets
$characters = $this->expandCharacterSets($characters);
}
if ($length == 0 || strlen($characters) == 1) {
return '';
} elseif (empty($characters)) {
// Default to base 64
$characters = $this->expandCharacterSets(self::CHAR_BASE64);
}
// determine how many bytes to generate
// This is basically doing floor(log(strlen($characters)))
// But it's fixed to work properly for all numbers
$len = strlen($characters);
// The max call here fixes an issue where we under-generate in cases
// where less than 8 bits are needed to represent $len
$bytes = $length * ceil(($this->countBits($len)) / 8);
// determine mask for valid characters
$mask = 256 - (256 % $len);
$result = '';
do {
$rand = $this->generate($bytes);
for ($i = 0; $i < $bytes; $i++) {
if (ord($rand[$i]) >= $mask) {
continue;
}
$result .= $characters[ord($rand[$i]) % $len];
}
} while (strlen($result) < $length);
// We may over-generate, since we always use the entire buffer
return substr($result, 0, $length);
} | php | public function generateString($length, $characters = '')
{
if (is_int($characters)) {
// Combine character sets
$characters = $this->expandCharacterSets($characters);
}
if ($length == 0 || strlen($characters) == 1) {
return '';
} elseif (empty($characters)) {
// Default to base 64
$characters = $this->expandCharacterSets(self::CHAR_BASE64);
}
// determine how many bytes to generate
// This is basically doing floor(log(strlen($characters)))
// But it's fixed to work properly for all numbers
$len = strlen($characters);
// The max call here fixes an issue where we under-generate in cases
// where less than 8 bits are needed to represent $len
$bytes = $length * ceil(($this->countBits($len)) / 8);
// determine mask for valid characters
$mask = 256 - (256 % $len);
$result = '';
do {
$rand = $this->generate($bytes);
for ($i = 0; $i < $bytes; $i++) {
if (ord($rand[$i]) >= $mask) {
continue;
}
$result .= $characters[ord($rand[$i]) % $len];
}
} while (strlen($result) < $length);
// We may over-generate, since we always use the entire buffer
return substr($result, 0, $length);
} | [
"public",
"function",
"generateString",
"(",
"$",
"length",
",",
"$",
"characters",
"=",
"''",
")",
"{",
"if",
"(",
"is_int",
"(",
"$",
"characters",
")",
")",
"{",
"// Combine character sets",
"$",
"characters",
"=",
"$",
"this",
"->",
"expandCharacterSets"... | Generate a random string of specified length.
This uses the supplied character list for generating the new result
string.
@param int $length The length of the generated string
@param mixed $characters String: An optional list of characters to use
Integer: Character flags
@return string The generated random string | [
"Generate",
"a",
"random",
"string",
"of",
"specified",
"length",
"."
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/Generator.php#L259-L296 |
ircmaxell/RandomLib | lib/RandomLib/Generator.php | Generator.expandCharacterSets | protected function expandCharacterSets($spec)
{
$combined = '';
if ($spec == self::EASY_TO_READ) {
$spec |= self::CHAR_ALNUM;
}
foreach ($this->charArrays as $flag => $chars) {
if ($flag == self::EASY_TO_READ) {
// handle this later
continue;
}
if (($spec & $flag) === $flag) {
$combined .= $chars;
}
}
if ($spec & self::EASY_TO_READ) {
// remove ambiguous characters
$combined = str_replace(str_split(self::AMBIGUOUS_CHARS), '', $combined);
}
return count_chars($combined, 3);
} | php | protected function expandCharacterSets($spec)
{
$combined = '';
if ($spec == self::EASY_TO_READ) {
$spec |= self::CHAR_ALNUM;
}
foreach ($this->charArrays as $flag => $chars) {
if ($flag == self::EASY_TO_READ) {
// handle this later
continue;
}
if (($spec & $flag) === $flag) {
$combined .= $chars;
}
}
if ($spec & self::EASY_TO_READ) {
// remove ambiguous characters
$combined = str_replace(str_split(self::AMBIGUOUS_CHARS), '', $combined);
}
return count_chars($combined, 3);
} | [
"protected",
"function",
"expandCharacterSets",
"(",
"$",
"spec",
")",
"{",
"$",
"combined",
"=",
"''",
";",
"if",
"(",
"$",
"spec",
"==",
"self",
"::",
"EASY_TO_READ",
")",
"{",
"$",
"spec",
"|=",
"self",
"::",
"CHAR_ALNUM",
";",
"}",
"foreach",
"(",
... | Expand a character set bitwise spec into a string character set
This will also replace EASY_TO_READ characters if the flag is set
@param int $spec The spec to expand (bitwise combination of flags)
@return string The expanded string | [
"Expand",
"a",
"character",
"set",
"bitwise",
"spec",
"into",
"a",
"string",
"character",
"set"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/Generator.php#L347-L368 |
ircmaxell/RandomLib | lib/RandomLib/Source/CAPICOM.php | CAPICOM.generate | public function generate($size)
{
try {
$util = new \COM('CAPICOM.Utilities.1');
$data = base64_decode($util->GetRandom($size, 0));
return str_pad($data, $size, chr(0));
} catch (\Exception $e) {
unset($e);
return static::emptyValue($size);
}
} | php | public function generate($size)
{
try {
$util = new \COM('CAPICOM.Utilities.1');
$data = base64_decode($util->GetRandom($size, 0));
return str_pad($data, $size, chr(0));
} catch (\Exception $e) {
unset($e);
return static::emptyValue($size);
}
} | [
"public",
"function",
"generate",
"(",
"$",
"size",
")",
"{",
"try",
"{",
"$",
"util",
"=",
"new",
"\\",
"COM",
"(",
"'CAPICOM.Utilities.1'",
")",
";",
"$",
"data",
"=",
"base64_decode",
"(",
"$",
"util",
"->",
"GetRandom",
"(",
"$",
"size",
",",
"0"... | Generate a random string of the specified size
@param int $size The size of the requested random string
@return string A string of the requested size | [
"Generate",
"a",
"random",
"string",
"of",
"the",
"specified",
"size"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/Source/CAPICOM.php#L76-L88 |
ircmaxell/RandomLib | lib/RandomLib/Factory.php | Factory.getGenerator | public function getGenerator(\SecurityLib\Strength $strength)
{
$sources = $this->findSources($strength);
$mixer = $this->findMixer($strength);
return new Generator($sources, $mixer);
} | php | public function getGenerator(\SecurityLib\Strength $strength)
{
$sources = $this->findSources($strength);
$mixer = $this->findMixer($strength);
return new Generator($sources, $mixer);
} | [
"public",
"function",
"getGenerator",
"(",
"\\",
"SecurityLib",
"\\",
"Strength",
"$",
"strength",
")",
"{",
"$",
"sources",
"=",
"$",
"this",
"->",
"findSources",
"(",
"$",
"strength",
")",
";",
"$",
"mixer",
"=",
"$",
"this",
"->",
"findMixer",
"(",
... | Get a generator for the requested strength
@param Strength $strength The requested strength of the random number
@throws RuntimeException If an appropriate mixing strategy isn't found
@return Generator The instantiated generator | [
"Get",
"a",
"generator",
"for",
"the",
"requested",
"strength"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/Factory.php#L75-L81 |
ircmaxell/RandomLib | lib/RandomLib/Factory.php | Factory.findSources | protected function findSources(\SecurityLib\Strength $strength)
{
$sources = array();
foreach ($this->getSources() as $source) {
if ($strength->compare($source::getStrength()) <= 0 && $source::isSupported()) {
$sources[] = new $source();
}
}
if (0 === count($sources)) {
throw new \RuntimeException('Could not find sources');
}
return $sources;
} | php | protected function findSources(\SecurityLib\Strength $strength)
{
$sources = array();
foreach ($this->getSources() as $source) {
if ($strength->compare($source::getStrength()) <= 0 && $source::isSupported()) {
$sources[] = new $source();
}
}
if (0 === count($sources)) {
throw new \RuntimeException('Could not find sources');
}
return $sources;
} | [
"protected",
"function",
"findSources",
"(",
"\\",
"SecurityLib",
"\\",
"Strength",
"$",
"strength",
")",
"{",
"$",
"sources",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getSources",
"(",
")",
"as",
"$",
"source",
")",
"{",
"if",
... | Find a sources based upon the requested strength
@param Strength $strength The strength mixer to find
@throws RuntimeException if a valid source cannot be found
@return Source The found source | [
"Find",
"a",
"sources",
"based",
"upon",
"the",
"requested",
"strength"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/Factory.php#L196-L210 |
ircmaxell/RandomLib | lib/RandomLib/Factory.php | Factory.findMixer | protected function findMixer(\SecurityLib\Strength $strength)
{
$newMixer = null;
$fallback = null;
foreach ($this->getMixers() as $mixer) {
if (!$mixer::test()) {
continue;
}
if ($strength->compare($mixer::getStrength()) == 0) {
$newMixer = new $mixer();
} elseif ($strength->compare($mixer::getStrength()) == 1) {
$fallback = new $mixer();
}
}
if (is_null($newMixer)) {
if (is_null($fallback)) {
throw new \RuntimeException('Could not find mixer');
}
return $fallback;
}
return $newMixer;
} | php | protected function findMixer(\SecurityLib\Strength $strength)
{
$newMixer = null;
$fallback = null;
foreach ($this->getMixers() as $mixer) {
if (!$mixer::test()) {
continue;
}
if ($strength->compare($mixer::getStrength()) == 0) {
$newMixer = new $mixer();
} elseif ($strength->compare($mixer::getStrength()) == 1) {
$fallback = new $mixer();
}
}
if (is_null($newMixer)) {
if (is_null($fallback)) {
throw new \RuntimeException('Could not find mixer');
}
return $fallback;
}
return $newMixer;
} | [
"protected",
"function",
"findMixer",
"(",
"\\",
"SecurityLib",
"\\",
"Strength",
"$",
"strength",
")",
"{",
"$",
"newMixer",
"=",
"null",
";",
"$",
"fallback",
"=",
"null",
";",
"foreach",
"(",
"$",
"this",
"->",
"getMixers",
"(",
")",
"as",
"$",
"mix... | Find a mixer based upon the requested strength
@param Strength $strength The strength mixer to find
@throws RuntimeException if a valid mixer cannot be found
@return Mixer The found mixer | [
"Find",
"a",
"mixer",
"based",
"upon",
"the",
"requested",
"strength"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/Factory.php#L221-L244 |
ircmaxell/RandomLib | lib/RandomLib/Source/UniqID.php | UniqID.generate | public function generate($size)
{
$result = '';
while (Util::safeStrlen($result) < $size) {
$result = uniqid($result, true);
}
return Util::safeSubstr($result, 0, $size);
} | php | public function generate($size)
{
$result = '';
while (Util::safeStrlen($result) < $size) {
$result = uniqid($result, true);
}
return Util::safeSubstr($result, 0, $size);
} | [
"public",
"function",
"generate",
"(",
"$",
"size",
")",
"{",
"$",
"result",
"=",
"''",
";",
"while",
"(",
"Util",
"::",
"safeStrlen",
"(",
"$",
"result",
")",
"<",
"$",
"size",
")",
"{",
"$",
"result",
"=",
"uniqid",
"(",
"$",
"result",
",",
"tr... | Generate a random string of the specified size
@param int $size The size of the requested random string
@return string A string of the requested size | [
"Generate",
"a",
"random",
"string",
"of",
"the",
"specified",
"size"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/Source/UniqID.php#L68-L76 |
ircmaxell/RandomLib | lib/RandomLib/Source/OpenSSL.php | OpenSSL.getStrength | public static function getStrength()
{
/**
* Prior to PHP 5.6.12 (see https://bugs.php.net/bug.php?id=70014) the "openssl_random_pseudo_bytes"
* was using "RAND_pseudo_bytes" (predictable) instead of "RAND_bytes" (unpredictable).
* Release notes: http://php.net/ChangeLog-5.php#5.6.12
*/
if (PHP_VERSION_ID >= 50612) {
return new Strength(Strength::HIGH);
}
/**
* Prior to PHP 5.5.28 (see https://bugs.php.net/bug.php?id=70014) the "openssl_random_pseudo_bytes"
* was using "RAND_pseudo_bytes" (predictable) instead of "RAND_bytes" (unpredictable).
* Release notes: http://php.net/ChangeLog-5.php#5.5.28
*/
if (PHP_VERSION_ID >= 50528 && PHP_VERSION_ID < 50600) {
return new Strength(Strength::HIGH);
}
/**
* Prior to PHP 5.4.44 (see https://bugs.php.net/bug.php?id=70014) the "openssl_random_pseudo_bytes"
* was using "RAND_pseudo_bytes" (predictable) instead of "RAND_bytes" (unpredictable).
* Release notes: http://php.net/ChangeLog-5.php#5.4.44
*/
if (PHP_VERSION_ID >= 50444 && PHP_VERSION_ID < 50500) {
return new Strength(Strength::HIGH);
}
return new Strength(Strength::MEDIUM);
} | php | public static function getStrength()
{
/**
* Prior to PHP 5.6.12 (see https://bugs.php.net/bug.php?id=70014) the "openssl_random_pseudo_bytes"
* was using "RAND_pseudo_bytes" (predictable) instead of "RAND_bytes" (unpredictable).
* Release notes: http://php.net/ChangeLog-5.php#5.6.12
*/
if (PHP_VERSION_ID >= 50612) {
return new Strength(Strength::HIGH);
}
/**
* Prior to PHP 5.5.28 (see https://bugs.php.net/bug.php?id=70014) the "openssl_random_pseudo_bytes"
* was using "RAND_pseudo_bytes" (predictable) instead of "RAND_bytes" (unpredictable).
* Release notes: http://php.net/ChangeLog-5.php#5.5.28
*/
if (PHP_VERSION_ID >= 50528 && PHP_VERSION_ID < 50600) {
return new Strength(Strength::HIGH);
}
/**
* Prior to PHP 5.4.44 (see https://bugs.php.net/bug.php?id=70014) the "openssl_random_pseudo_bytes"
* was using "RAND_pseudo_bytes" (predictable) instead of "RAND_bytes" (unpredictable).
* Release notes: http://php.net/ChangeLog-5.php#5.4.44
*/
if (PHP_VERSION_ID >= 50444 && PHP_VERSION_ID < 50500) {
return new Strength(Strength::HIGH);
}
return new Strength(Strength::MEDIUM);
} | [
"public",
"static",
"function",
"getStrength",
"(",
")",
"{",
"/**\n * Prior to PHP 5.6.12 (see https://bugs.php.net/bug.php?id=70014) the \"openssl_random_pseudo_bytes\"\n * was using \"RAND_pseudo_bytes\" (predictable) instead of \"RAND_bytes\" (unpredictable).\n * Release no... | Return an instance of Strength indicating the strength of the source
@return \SecurityLib\Strength An instance of one of the strength classes | [
"Return",
"an",
"instance",
"of",
"Strength",
"indicating",
"the",
"strength",
"of",
"the",
"source"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/Source/OpenSSL.php#L53-L83 |
ircmaxell/RandomLib | lib/RandomLib/Source/Rand.php | Rand.generate | public function generate($size)
{
$result = '';
for ($i = 0; $i < $size; $i++) {
$result .= chr((rand() ^ rand()) % 256);
}
return $result;
} | php | public function generate($size)
{
$result = '';
for ($i = 0; $i < $size; $i++) {
$result .= chr((rand() ^ rand()) % 256);
}
return $result;
} | [
"public",
"function",
"generate",
"(",
"$",
"size",
")",
"{",
"$",
"result",
"=",
"''",
";",
"for",
"(",
"$",
"i",
"=",
"0",
";",
"$",
"i",
"<",
"$",
"size",
";",
"$",
"i",
"++",
")",
"{",
"$",
"result",
".=",
"chr",
"(",
"(",
"rand",
"(",
... | Generate a random string of the specified size
@param int $size The size of the requested random string
@return string A string of the requested size | [
"Generate",
"a",
"random",
"string",
"of",
"the",
"specified",
"size"
] | train | https://github.com/ircmaxell/RandomLib/blob/e9e0204f40e49fa4419946c677eccd3fa25b8cf4/lib/RandomLib/Source/Rand.php#L74-L82 |
goaop/framework | src/Aop/Pointcut/PointcutReference.php | PointcutReference.matches | public function matches($point, $context = null, $instance = null, array $arguments = null): bool
{
return $this->getPointcut()->matches($point, $context, $instance, $arguments);
} | php | public function matches($point, $context = null, $instance = null, array $arguments = null): bool
{
return $this->getPointcut()->matches($point, $context, $instance, $arguments);
} | [
"public",
"function",
"matches",
"(",
"$",
"point",
",",
"$",
"context",
"=",
"null",
",",
"$",
"instance",
"=",
"null",
",",
"array",
"$",
"arguments",
"=",
"null",
")",
":",
"bool",
"{",
"return",
"$",
"this",
"->",
"getPointcut",
"(",
")",
"->",
... | Performs matching of point of code
@param mixed $point Specific part of code, can be any Reflection class
@param null|mixed $context Related context, can be class or namespace
@param null|string|object $instance Invocation instance or string for static calls
@param null|array $arguments Dynamic arguments for method | [
"Performs",
"matching",
"of",
"point",
"of",
"code"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Pointcut/PointcutReference.php#L56-L59 |
goaop/framework | src/Aop/Pointcut/PointcutReference.php | PointcutReference.getPointcut | private function getPointcut(): Pointcut
{
if (!$this->pointcut) {
$this->pointcut = $this->container->getPointcut($this->pointcutId);
}
return $this->pointcut;
} | php | private function getPointcut(): Pointcut
{
if (!$this->pointcut) {
$this->pointcut = $this->container->getPointcut($this->pointcutId);
}
return $this->pointcut;
} | [
"private",
"function",
"getPointcut",
"(",
")",
":",
"Pointcut",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"pointcut",
")",
"{",
"$",
"this",
"->",
"pointcut",
"=",
"$",
"this",
"->",
"container",
"->",
"getPointcut",
"(",
"$",
"this",
"->",
"pointcutId"... | Returns a real pointcut from the container | [
"Returns",
"a",
"real",
"pointcut",
"from",
"the",
"container"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Pointcut/PointcutReference.php#L96-L103 |
goaop/framework | src/Proxy/TraitProxyGenerator.php | TraitProxyGenerator.getJoinPoint | public static function getJoinPoint(
string $className,
string $joinPointType,
string $methodName,
array $advices
): MethodInvocation {
static $accessor;
if ($accessor === null) {
$aspectKernel = AspectKernel::getInstance();
$accessor = $aspectKernel->getContainer()->get('aspect.advisor.accessor');
}
$filledAdvices = [];
foreach ($advices as $advisorName) {
$filledAdvices[] = $accessor->$advisorName;
}
$joinPoint = new self::$invocationClassMap[$joinPointType]($className, $methodName . '➩', $filledAdvices);
return $joinPoint;
} | php | public static function getJoinPoint(
string $className,
string $joinPointType,
string $methodName,
array $advices
): MethodInvocation {
static $accessor;
if ($accessor === null) {
$aspectKernel = AspectKernel::getInstance();
$accessor = $aspectKernel->getContainer()->get('aspect.advisor.accessor');
}
$filledAdvices = [];
foreach ($advices as $advisorName) {
$filledAdvices[] = $accessor->$advisorName;
}
$joinPoint = new self::$invocationClassMap[$joinPointType]($className, $methodName . '➩', $filledAdvices);
return $joinPoint;
} | [
"public",
"static",
"function",
"getJoinPoint",
"(",
"string",
"$",
"className",
",",
"string",
"$",
"joinPointType",
",",
"string",
"$",
"methodName",
",",
"array",
"$",
"advices",
")",
":",
"MethodInvocation",
"{",
"static",
"$",
"accessor",
";",
"if",
"("... | Returns a method invocation for the specific trait method
@param array $advices List of advices for this trait method | [
"Returns",
"a",
"method",
"invocation",
"for",
"the",
"specific",
"trait",
"method"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Proxy/TraitProxyGenerator.php#L78-L99 |
goaop/framework | src/Proxy/TraitProxyGenerator.php | TraitProxyGenerator.getJoinpointInvocationBody | protected function getJoinpointInvocationBody(ReflectionMethod $method): string
{
$isStatic = $method->isStatic();
$class = '\\' . __CLASS__;
$scope = $isStatic ? 'static::class' : '$this';
$prefix = $isStatic ? AspectContainer::STATIC_METHOD_PREFIX : AspectContainer::METHOD_PREFIX;
$argumentList = new FunctionCallArgumentListGenerator($method);
$argumentCode = $argumentList->generate();
$argumentCode = $scope . ($argumentCode ? ", $argumentCode" : '');
$return = 'return ';
if ($method->hasReturnType()) {
$returnType = (string) $method->getReturnType();
if ($returnType === 'void') {
// void return types should not return anything
$return = '';
}
}
$advicesArray = new ValueGenerator($this->advices[$prefix][$method->name], ValueGenerator::TYPE_ARRAY_SHORT);
$advicesArray->setArrayDepth(1);
$advicesCode = $advicesArray->generate();
return <<<BODY
static \$__joinPoint;
if (\$__joinPoint === null) {
\$__joinPoint = {$class}::getJoinPoint(__CLASS__, '{$prefix}', '{$method->name}', {$advicesCode});
}
{$return}\$__joinPoint->__invoke($argumentCode);
BODY;
} | php | protected function getJoinpointInvocationBody(ReflectionMethod $method): string
{
$isStatic = $method->isStatic();
$class = '\\' . __CLASS__;
$scope = $isStatic ? 'static::class' : '$this';
$prefix = $isStatic ? AspectContainer::STATIC_METHOD_PREFIX : AspectContainer::METHOD_PREFIX;
$argumentList = new FunctionCallArgumentListGenerator($method);
$argumentCode = $argumentList->generate();
$argumentCode = $scope . ($argumentCode ? ", $argumentCode" : '');
$return = 'return ';
if ($method->hasReturnType()) {
$returnType = (string) $method->getReturnType();
if ($returnType === 'void') {
// void return types should not return anything
$return = '';
}
}
$advicesArray = new ValueGenerator($this->advices[$prefix][$method->name], ValueGenerator::TYPE_ARRAY_SHORT);
$advicesArray->setArrayDepth(1);
$advicesCode = $advicesArray->generate();
return <<<BODY
static \$__joinPoint;
if (\$__joinPoint === null) {
\$__joinPoint = {$class}::getJoinPoint(__CLASS__, '{$prefix}', '{$method->name}', {$advicesCode});
}
{$return}\$__joinPoint->__invoke($argumentCode);
BODY;
} | [
"protected",
"function",
"getJoinpointInvocationBody",
"(",
"ReflectionMethod",
"$",
"method",
")",
":",
"string",
"{",
"$",
"isStatic",
"=",
"$",
"method",
"->",
"isStatic",
"(",
")",
";",
"$",
"class",
"=",
"'\\\\'",
".",
"__CLASS__",
";",
"$",
"scope",
... | Creates string definition for trait method body by method reflection | [
"Creates",
"string",
"definition",
"for",
"trait",
"method",
"body",
"by",
"method",
"reflection"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Proxy/TraitProxyGenerator.php#L104-L135 |
goaop/framework | demos/Demo/Aspect/AwesomeAspectKernel.php | AwesomeAspectKernel.configureAop | protected function configureAop(AspectContainer $container)
{
$container->registerAspect(new DeclareErrorAspect());
$container->registerAspect(new CachingAspect());
$container->registerAspect(new LoggingAspect());
$container->registerAspect(new IntroductionAspect());
$container->registerAspect(new PropertyInterceptorAspect());
$container->registerAspect(new FunctionInterceptorAspect());
$container->registerAspect(new FluentInterfaceAspect());
$container->registerAspect(new HealthyLiveAspect());
$container->registerAspect(new DynamicMethodsAspect());
} | php | protected function configureAop(AspectContainer $container)
{
$container->registerAspect(new DeclareErrorAspect());
$container->registerAspect(new CachingAspect());
$container->registerAspect(new LoggingAspect());
$container->registerAspect(new IntroductionAspect());
$container->registerAspect(new PropertyInterceptorAspect());
$container->registerAspect(new FunctionInterceptorAspect());
$container->registerAspect(new FluentInterfaceAspect());
$container->registerAspect(new HealthyLiveAspect());
$container->registerAspect(new DynamicMethodsAspect());
} | [
"protected",
"function",
"configureAop",
"(",
"AspectContainer",
"$",
"container",
")",
"{",
"$",
"container",
"->",
"registerAspect",
"(",
"new",
"DeclareErrorAspect",
"(",
")",
")",
";",
"$",
"container",
"->",
"registerAspect",
"(",
"new",
"CachingAspect",
"(... | Configure an AspectContainer with advisors, aspects and pointcuts
@param AspectContainer $container | [
"Configure",
"an",
"AspectContainer",
"with",
"advisors",
"aspects",
"and",
"pointcuts"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/demos/Demo/Aspect/AwesomeAspectKernel.php#L27-L38 |
goaop/framework | src/Aop/Pointcut/AnnotationPointcut.php | AnnotationPointcut.matches | public function matches($point, $context = null, $instance = null, array $arguments = null): bool
{
$expectedClass = $this->expectedClass;
if (!$point instanceof $expectedClass) {
return false;
}
$annotation = $this->annotationReader->{$this->annotationMethod}($point, $this->annotationName);
return (bool) $annotation;
} | php | public function matches($point, $context = null, $instance = null, array $arguments = null): bool
{
$expectedClass = $this->expectedClass;
if (!$point instanceof $expectedClass) {
return false;
}
$annotation = $this->annotationReader->{$this->annotationMethod}($point, $this->annotationName);
return (bool) $annotation;
} | [
"public",
"function",
"matches",
"(",
"$",
"point",
",",
"$",
"context",
"=",
"null",
",",
"$",
"instance",
"=",
"null",
",",
"array",
"$",
"arguments",
"=",
"null",
")",
":",
"bool",
"{",
"$",
"expectedClass",
"=",
"$",
"this",
"->",
"expectedClass",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Pointcut/AnnotationPointcut.php#L91-L101 |
goaop/framework | src/Core/Container.php | Container.set | public function set(string $id, $value, array $tags = []): void
{
$this->values[$id] = $value;
foreach ($tags as $tag) {
$this->tags[$tag][] = $id;
}
} | php | public function set(string $id, $value, array $tags = []): void
{
$this->values[$id] = $value;
foreach ($tags as $tag) {
$this->tags[$tag][] = $id;
}
} | [
"public",
"function",
"set",
"(",
"string",
"$",
"id",
",",
"$",
"value",
",",
"array",
"$",
"tags",
"=",
"[",
"]",
")",
":",
"void",
"{",
"$",
"this",
"->",
"values",
"[",
"$",
"id",
"]",
"=",
"$",
"value",
";",
"foreach",
"(",
"$",
"tags",
... | Set a service into the container
@param mixed $value Value to store | [
"Set",
"a",
"service",
"into",
"the",
"container"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/Container.php#L37-L43 |
goaop/framework | src/Core/Container.php | Container.share | public function share(string $id, Closure $value, array $tags = []): void
{
$value = function ($container) use ($value) {
static $sharedValue;
if ($sharedValue === null) {
$sharedValue = $value($container);
}
return $sharedValue;
};
$this->set($id, $value, $tags);
} | php | public function share(string $id, Closure $value, array $tags = []): void
{
$value = function ($container) use ($value) {
static $sharedValue;
if ($sharedValue === null) {
$sharedValue = $value($container);
}
return $sharedValue;
};
$this->set($id, $value, $tags);
} | [
"public",
"function",
"share",
"(",
"string",
"$",
"id",
",",
"Closure",
"$",
"value",
",",
"array",
"$",
"tags",
"=",
"[",
"]",
")",
":",
"void",
"{",
"$",
"value",
"=",
"function",
"(",
"$",
"container",
")",
"use",
"(",
"$",
"value",
")",
"{",... | Set a shared value in the container | [
"Set",
"a",
"shared",
"value",
"in",
"the",
"container"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/Container.php#L48-L60 |
goaop/framework | src/Core/Container.php | Container.get | public function get(string $id)
{
if (!isset($this->values[$id])) {
throw new OutOfBoundsException("Value {$id} is not defined in the container");
}
if ($this->values[$id] instanceof Closure) {
return $this->values[$id]($this);
}
return $this->values[$id];
} | php | public function get(string $id)
{
if (!isset($this->values[$id])) {
throw new OutOfBoundsException("Value {$id} is not defined in the container");
}
if ($this->values[$id] instanceof Closure) {
return $this->values[$id]($this);
}
return $this->values[$id];
} | [
"public",
"function",
"get",
"(",
"string",
"$",
"id",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"values",
"[",
"$",
"id",
"]",
")",
")",
"{",
"throw",
"new",
"OutOfBoundsException",
"(",
"\"Value {$id} is not defined in the container\"",
... | Return a service or value from the container
@return mixed
@throws OutOfBoundsException if service was not found | [
"Return",
"a",
"service",
"or",
"value",
"from",
"the",
"container"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/Container.php#L68-L78 |
goaop/framework | src/Core/Container.php | Container.getByTag | public function getByTag(string $tag): array
{
$result = [];
if (isset($this->tags[$tag])) {
foreach ($this->tags[$tag] as $id) {
$result[$id] = $this->get($id);
}
}
return $result;
} | php | public function getByTag(string $tag): array
{
$result = [];
if (isset($this->tags[$tag])) {
foreach ($this->tags[$tag] as $id) {
$result[$id] = $this->get($id);
}
}
return $result;
} | [
"public",
"function",
"getByTag",
"(",
"string",
"$",
"tag",
")",
":",
"array",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"tags",
"[",
"$",
"tag",
"]",
")",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
... | Return list of service tagged with marker | [
"Return",
"list",
"of",
"service",
"tagged",
"with",
"marker"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/Container.php#L91-L101 |
goaop/framework | src/Aop/Pointcut/FunctionPointcut.php | FunctionPointcut.matches | public function matches($function, $context = null, $instance = null, array $arguments = null): bool
{
if (!$function instanceof ReflectionFunction) {
return false;
}
if (($this->returnTypeFilter !== null) && !$this->returnTypeFilter->matches($function, $context)) {
return false;
}
return ($function->name === $this->functionName) || (bool) preg_match("/^{$this->regexp}$/", $function->name);
} | php | public function matches($function, $context = null, $instance = null, array $arguments = null): bool
{
if (!$function instanceof ReflectionFunction) {
return false;
}
if (($this->returnTypeFilter !== null) && !$this->returnTypeFilter->matches($function, $context)) {
return false;
}
return ($function->name === $this->functionName) || (bool) preg_match("/^{$this->regexp}$/", $function->name);
} | [
"public",
"function",
"matches",
"(",
"$",
"function",
",",
"$",
"context",
"=",
"null",
",",
"$",
"instance",
"=",
"null",
",",
"array",
"$",
"arguments",
"=",
"null",
")",
":",
"bool",
"{",
"if",
"(",
"!",
"$",
"function",
"instanceof",
"ReflectionFu... | Performs matching of point of code
@param mixed $function Specific part of code, can be any Reflection class
@param mixed $context Related context, can be class or namespace
@param null|string|object $instance Invocation instance or string for static calls
@param null|array $arguments Dynamic arguments for method | [
"Performs",
"matching",
"of",
"point",
"of",
"code"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Pointcut/FunctionPointcut.php#L64-L75 |
goaop/framework | src/Core/GoAspectContainer.php | GoAspectContainer.registerAspect | public function registerAspect(Aspect $aspect): void
{
$refAspect = new ReflectionClass($aspect);
$this->set("aspect.{$refAspect->name}", $aspect, ['aspect']);
$this->addResource($refAspect->getFileName());
} | php | public function registerAspect(Aspect $aspect): void
{
$refAspect = new ReflectionClass($aspect);
$this->set("aspect.{$refAspect->name}", $aspect, ['aspect']);
$this->addResource($refAspect->getFileName());
} | [
"public",
"function",
"registerAspect",
"(",
"Aspect",
"$",
"aspect",
")",
":",
"void",
"{",
"$",
"refAspect",
"=",
"new",
"ReflectionClass",
"(",
"$",
"aspect",
")",
";",
"$",
"this",
"->",
"set",
"(",
"\"aspect.{$refAspect->name}\"",
",",
"$",
"aspect",
... | Register an aspect in the container | [
"Register",
"an",
"aspect",
"in",
"the",
"container"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/GoAspectContainer.php#L183-L188 |
goaop/framework | src/Core/GoAspectContainer.php | GoAspectContainer.isFresh | public function isFresh(int $timestamp): bool
{
if (!$this->maxTimestamp && !empty($this->resources)) {
$this->maxTimestamp = max(array_map('filemtime', $this->resources));
}
return $this->maxTimestamp <= $timestamp;
} | php | public function isFresh(int $timestamp): bool
{
if (!$this->maxTimestamp && !empty($this->resources)) {
$this->maxTimestamp = max(array_map('filemtime', $this->resources));
}
return $this->maxTimestamp <= $timestamp;
} | [
"public",
"function",
"isFresh",
"(",
"int",
"$",
"timestamp",
")",
":",
"bool",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"maxTimestamp",
"&&",
"!",
"empty",
"(",
"$",
"this",
"->",
"resources",
")",
")",
"{",
"$",
"this",
"->",
"maxTimestamp",
"=",
... | Checks the freshness of AOP cache
@return bool Whether or not concrete file is fresh | [
"Checks",
"the",
"freshness",
"of",
"AOP",
"cache"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/GoAspectContainer.php#L215-L222 |
goaop/framework | src/Proxy/ClassProxyGenerator.php | ClassProxyGenerator.addUse | public function addUse(string $use, string $useAlias = null): void
{
$this->generator->addUse($use, $useAlias);
} | php | public function addUse(string $use, string $useAlias = null): void
{
$this->generator->addUse($use, $useAlias);
} | [
"public",
"function",
"addUse",
"(",
"string",
"$",
"use",
",",
"string",
"$",
"useAlias",
"=",
"null",
")",
":",
"void",
"{",
"$",
"this",
"->",
"generator",
"->",
"addUse",
"(",
"$",
"use",
",",
"$",
"useAlias",
")",
";",
"}"
] | Adds use alias for this class | [
"Adds",
"use",
"alias",
"for",
"this",
"class"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Proxy/ClassProxyGenerator.php#L120-L123 |
goaop/framework | src/Proxy/ClassProxyGenerator.php | ClassProxyGenerator.injectJoinPoints | public static function injectJoinPoints(string $targetClassName): void
{
$reflectionClass = new ReflectionClass($targetClassName);
$joinPointsProperty = $reflectionClass->getProperty(JoinPointPropertyGenerator::NAME);
$joinPointsProperty->setAccessible(true);
$advices = $joinPointsProperty->getValue();
$joinPoints = static::wrapWithJoinPoints($advices, $reflectionClass->getParentClass()->name);
$joinPointsProperty->setValue($joinPoints);
$staticInit = AspectContainer::STATIC_INIT_PREFIX . ':root';
if (isset($joinPoints[$staticInit])) {
$joinPoints[$staticInit]->__invoke();
}
} | php | public static function injectJoinPoints(string $targetClassName): void
{
$reflectionClass = new ReflectionClass($targetClassName);
$joinPointsProperty = $reflectionClass->getProperty(JoinPointPropertyGenerator::NAME);
$joinPointsProperty->setAccessible(true);
$advices = $joinPointsProperty->getValue();
$joinPoints = static::wrapWithJoinPoints($advices, $reflectionClass->getParentClass()->name);
$joinPointsProperty->setValue($joinPoints);
$staticInit = AspectContainer::STATIC_INIT_PREFIX . ':root';
if (isset($joinPoints[$staticInit])) {
$joinPoints[$staticInit]->__invoke();
}
} | [
"public",
"static",
"function",
"injectJoinPoints",
"(",
"string",
"$",
"targetClassName",
")",
":",
"void",
"{",
"$",
"reflectionClass",
"=",
"new",
"ReflectionClass",
"(",
"$",
"targetClassName",
")",
";",
"$",
"joinPointsProperty",
"=",
"$",
"reflectionClass",
... | Inject advices into given class
NB This method will be used as a callback during source code evaluation to inject joinpoints | [
"Inject",
"advices",
"into",
"given",
"class"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Proxy/ClassProxyGenerator.php#L130-L144 |
goaop/framework | src/Proxy/ClassProxyGenerator.php | ClassProxyGenerator.generate | public function generate(): string
{
$classCode = $this->generator->generate();
return $classCode
// Inject advices on call
. '\\' . __CLASS__ . '::injectJoinPoints(' . $this->generator->getName() . '::class);';
} | php | public function generate(): string
{
$classCode = $this->generator->generate();
return $classCode
// Inject advices on call
. '\\' . __CLASS__ . '::injectJoinPoints(' . $this->generator->getName() . '::class);';
} | [
"public",
"function",
"generate",
"(",
")",
":",
"string",
"{",
"$",
"classCode",
"=",
"$",
"this",
"->",
"generator",
"->",
"generate",
"(",
")",
";",
"return",
"$",
"classCode",
"// Inject advices on call",
".",
"'\\\\'",
".",
"__CLASS__",
".",
"'::injectJ... | Generates the source code of child class | [
"Generates",
"the",
"source",
"code",
"of",
"child",
"class"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Proxy/ClassProxyGenerator.php#L149-L156 |
goaop/framework | src/Proxy/ClassProxyGenerator.php | ClassProxyGenerator.wrapWithJoinPoints | protected static function wrapWithJoinPoints(array $classAdvices, string $className): array
{
/** @var LazyAdvisorAccessor $accessor */
static $accessor;
if (!isset($accessor)) {
$aspectKernel = AspectKernel::getInstance();
$accessor = $aspectKernel->getContainer()->get('aspect.advisor.accessor');
}
$joinPoints = [];
foreach ($classAdvices as $joinPointType => $typedAdvices) {
// if not isset then we don't want to create such invocation for class
if (!isset(self::$invocationClassMap[$joinPointType])) {
continue;
}
foreach ($typedAdvices as $joinPointName => $advices) {
$filledAdvices = [];
foreach ($advices as $advisorName) {
$filledAdvices[] = $accessor->$advisorName;
}
$joinpoint = new self::$invocationClassMap[$joinPointType]($className, $joinPointName, $filledAdvices);
$joinPoints["$joinPointType:$joinPointName"] = $joinpoint;
}
}
return $joinPoints;
} | php | protected static function wrapWithJoinPoints(array $classAdvices, string $className): array
{
/** @var LazyAdvisorAccessor $accessor */
static $accessor;
if (!isset($accessor)) {
$aspectKernel = AspectKernel::getInstance();
$accessor = $aspectKernel->getContainer()->get('aspect.advisor.accessor');
}
$joinPoints = [];
foreach ($classAdvices as $joinPointType => $typedAdvices) {
// if not isset then we don't want to create such invocation for class
if (!isset(self::$invocationClassMap[$joinPointType])) {
continue;
}
foreach ($typedAdvices as $joinPointName => $advices) {
$filledAdvices = [];
foreach ($advices as $advisorName) {
$filledAdvices[] = $accessor->$advisorName;
}
$joinpoint = new self::$invocationClassMap[$joinPointType]($className, $joinPointName, $filledAdvices);
$joinPoints["$joinPointType:$joinPointName"] = $joinpoint;
}
}
return $joinPoints;
} | [
"protected",
"static",
"function",
"wrapWithJoinPoints",
"(",
"array",
"$",
"classAdvices",
",",
"string",
"$",
"className",
")",
":",
"array",
"{",
"/** @var LazyAdvisorAccessor $accessor */",
"static",
"$",
"accessor",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"... | Wrap advices with joinpoint object
@param array|Advice[][][] $classAdvices Advices for specific class
@throws \UnexpectedValueException If joinPoint type is unknown
NB: Extension should be responsible for wrapping advice with join point.
@return Joinpoint[] returns list of joinpoint ready to use | [
"Wrap",
"advices",
"with",
"joinpoint",
"object"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Proxy/ClassProxyGenerator.php#L169-L198 |
goaop/framework | src/Proxy/ClassProxyGenerator.php | ClassProxyGenerator.interceptMethods | protected function interceptMethods(ReflectionClass $originalClass, array $methodNames): array
{
$interceptedMethods = [];
foreach ($methodNames as $methodName) {
$reflectionMethod = $originalClass->getMethod($methodName);
$methodBody = $this->getJoinpointInvocationBody($reflectionMethod);
$interceptedMethods[$methodName] = new InterceptedMethodGenerator($reflectionMethod, $methodBody);
}
return $interceptedMethods;
} | php | protected function interceptMethods(ReflectionClass $originalClass, array $methodNames): array
{
$interceptedMethods = [];
foreach ($methodNames as $methodName) {
$reflectionMethod = $originalClass->getMethod($methodName);
$methodBody = $this->getJoinpointInvocationBody($reflectionMethod);
$interceptedMethods[$methodName] = new InterceptedMethodGenerator($reflectionMethod, $methodBody);
}
return $interceptedMethods;
} | [
"protected",
"function",
"interceptMethods",
"(",
"ReflectionClass",
"$",
"originalClass",
",",
"array",
"$",
"methodNames",
")",
":",
"array",
"{",
"$",
"interceptedMethods",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"methodNames",
"as",
"$",
"methodName",
")"... | Returns list of intercepted method generators for class by method names
@param string[] $methodNames List of methods to intercept
@return InterceptedMethodGenerator[] | [
"Returns",
"list",
"of",
"intercepted",
"method",
"generators",
"for",
"class",
"by",
"method",
"names"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Proxy/ClassProxyGenerator.php#L207-L218 |
goaop/framework | src/Proxy/ClassProxyGenerator.php | ClassProxyGenerator.getJoinpointInvocationBody | protected function getJoinpointInvocationBody(ReflectionMethod $method): string
{
$isStatic = $method->isStatic();
$scope = $isStatic ? 'static::class' : '$this';
$prefix = $isStatic ? AspectContainer::STATIC_METHOD_PREFIX : AspectContainer::METHOD_PREFIX;
$argumentList = new FunctionCallArgumentListGenerator($method);
$argumentCode = $argumentList->generate();
$return = 'return ';
if ($method->hasReturnType()) {
$returnType = (string) $method->getReturnType();
if ($returnType === 'void') {
// void return types should not return anything
$return = '';
}
}
if (!empty($argumentCode)) {
$scope = "$scope, $argumentCode";
}
$body = "{$return}self::\$__joinPoints['{$prefix}:{$method->name}']->__invoke($scope);";
return $body;
} | php | protected function getJoinpointInvocationBody(ReflectionMethod $method): string
{
$isStatic = $method->isStatic();
$scope = $isStatic ? 'static::class' : '$this';
$prefix = $isStatic ? AspectContainer::STATIC_METHOD_PREFIX : AspectContainer::METHOD_PREFIX;
$argumentList = new FunctionCallArgumentListGenerator($method);
$argumentCode = $argumentList->generate();
$return = 'return ';
if ($method->hasReturnType()) {
$returnType = (string) $method->getReturnType();
if ($returnType === 'void') {
// void return types should not return anything
$return = '';
}
}
if (!empty($argumentCode)) {
$scope = "$scope, $argumentCode";
}
$body = "{$return}self::\$__joinPoints['{$prefix}:{$method->name}']->__invoke($scope);";
return $body;
} | [
"protected",
"function",
"getJoinpointInvocationBody",
"(",
"ReflectionMethod",
"$",
"method",
")",
":",
"string",
"{",
"$",
"isStatic",
"=",
"$",
"method",
"->",
"isStatic",
"(",
")",
";",
"$",
"scope",
"=",
"$",
"isStatic",
"?",
"'static::class'",
":",
"'$... | Creates string definition for method body by method reflection | [
"Creates",
"string",
"definition",
"for",
"method",
"body",
"by",
"method",
"reflection"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Proxy/ClassProxyGenerator.php#L223-L247 |
goaop/framework | src/Aop/Support/ModifierMatcherFilter.php | ModifierMatcherFilter.matches | public function matches($point, $context = null, $instance = null, array $arguments = null): bool
{
$modifiers = $point->getModifiers();
return !($this->notMask & $modifiers) &&
(($this->andMask === ($this->andMask & $modifiers)) || ($this->orMask & $modifiers));
} | php | public function matches($point, $context = null, $instance = null, array $arguments = null): bool
{
$modifiers = $point->getModifiers();
return !($this->notMask & $modifiers) &&
(($this->andMask === ($this->andMask & $modifiers)) || ($this->orMask & $modifiers));
} | [
"public",
"function",
"matches",
"(",
"$",
"point",
",",
"$",
"context",
"=",
"null",
",",
"$",
"instance",
"=",
"null",
",",
"array",
"$",
"arguments",
"=",
"null",
")",
":",
"bool",
"{",
"$",
"modifiers",
"=",
"$",
"point",
"->",
"getModifiers",
"(... | Performs matching of point of code
@param mixed $point Specific part of code, can be any Reflection class
@param null|mixed $context Related context, can be class or namespace
@param null|string|object $instance Invocation instance or string for static calls
@param null|array $arguments Dynamic arguments for method | [
"Performs",
"matching",
"of",
"point",
"of",
"code"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Support/ModifierMatcherFilter.php#L54-L60 |
goaop/framework | demos/Demo/Aspect/PropertyInterceptorAspect.php | PropertyInterceptorAspect.aroundFieldAccess | public function aroundFieldAccess(FieldAccess $fieldAccess)
{
$isRead = $fieldAccess->getAccessType() == FieldAccess::READ;
// proceed all internal advices
$fieldAccess->proceed();
if ($isRead) {
// if you want to change original property value, then return it by reference
$value = /* & */$fieldAccess->getValue();
} else {
// if you want to change value to set, then return it by reference
$value = /* & */$fieldAccess->getValueToSet();
}
echo "Calling After Interceptor for ", $fieldAccess, ", value: ", json_encode($value), PHP_EOL;
} | php | public function aroundFieldAccess(FieldAccess $fieldAccess)
{
$isRead = $fieldAccess->getAccessType() == FieldAccess::READ;
// proceed all internal advices
$fieldAccess->proceed();
if ($isRead) {
// if you want to change original property value, then return it by reference
$value = /* & */$fieldAccess->getValue();
} else {
// if you want to change value to set, then return it by reference
$value = /* & */$fieldAccess->getValueToSet();
}
echo "Calling After Interceptor for ", $fieldAccess, ", value: ", json_encode($value), PHP_EOL;
} | [
"public",
"function",
"aroundFieldAccess",
"(",
"FieldAccess",
"$",
"fieldAccess",
")",
"{",
"$",
"isRead",
"=",
"$",
"fieldAccess",
"->",
"getAccessType",
"(",
")",
"==",
"FieldAccess",
"::",
"READ",
";",
"// proceed all internal advices",
"$",
"fieldAccess",
"->... | Advice that controls an access to the properties
@param FieldAccess $fieldAccess Joinpoint
@Around("access(public|protected|private Demo\Example\PropertyDemo->*)")
@return mixed | [
"Advice",
"that",
"controls",
"an",
"access",
"to",
"the",
"properties"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/demos/Demo/Aspect/PropertyInterceptorAspect.php#L34-L49 |
goaop/framework | demos/Demo/Aspect/DynamicMethodsAspect.php | DynamicMethodsAspect.beforeMagicMethodExecution | public function beforeMagicMethodExecution(MethodInvocation $invocation)
{
$obj = $invocation->getThis();
// we need to unpack args from invocation args
list($methodName, $args) = $invocation->getArguments();
echo 'Calling Magic Interceptor for method: ',
is_object($obj) ? get_class($obj) : $obj,
$invocation->getMethod()->isStatic() ? '::' : '->',
$methodName,
'()',
' with arguments: ',
json_encode($args),
PHP_EOL;
} | php | public function beforeMagicMethodExecution(MethodInvocation $invocation)
{
$obj = $invocation->getThis();
// we need to unpack args from invocation args
list($methodName, $args) = $invocation->getArguments();
echo 'Calling Magic Interceptor for method: ',
is_object($obj) ? get_class($obj) : $obj,
$invocation->getMethod()->isStatic() ? '::' : '->',
$methodName,
'()',
' with arguments: ',
json_encode($args),
PHP_EOL;
} | [
"public",
"function",
"beforeMagicMethodExecution",
"(",
"MethodInvocation",
"$",
"invocation",
")",
"{",
"$",
"obj",
"=",
"$",
"invocation",
"->",
"getThis",
"(",
")",
";",
"// we need to unpack args from invocation args",
"list",
"(",
"$",
"methodName",
",",
"$",
... | This advice intercepts an execution of __call methods
Unlike traditional "execution" pointcut, "dynamic" is checking the name of method in
the runtime, allowing to write interceptors for __call more transparently.
@param MethodInvocation $invocation Invocation
@Before("dynamic(public Demo\Example\DynamicMethodsDemo->save*(*))") | [
"This",
"advice",
"intercepts",
"an",
"execution",
"of",
"__call",
"methods"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/demos/Demo/Aspect/DynamicMethodsAspect.php#L34-L48 |
goaop/framework | demos/Demo/Aspect/CachingAspect.php | CachingAspect.aroundCacheable | public function aroundCacheable(MethodInvocation $invocation)
{
static $memoryCache = [];
$time = microtime(true);
$obj = $invocation->getThis();
$class = is_object($obj) ? get_class($obj) : $obj;
$key = $class . ':' . $invocation->getMethod()->name;
if (!isset($memoryCache[$key])) {
// We can use ttl value from annotation, but Doctrine annotations doesn't work under GAE
if (!isset($_SERVER['APPENGINE_RUNTIME'])) {
echo "Ttl is: ", $invocation->getMethod()->getAnnotation('Demo\Annotation\Cacheable')->time, PHP_EOL;
}
$memoryCache[$key] = $invocation->proceed();
}
echo "Take ", sprintf("%0.3f", (microtime(true) - $time) * 1e3), "ms to call method $key", PHP_EOL;
return $memoryCache[$key];
} | php | public function aroundCacheable(MethodInvocation $invocation)
{
static $memoryCache = [];
$time = microtime(true);
$obj = $invocation->getThis();
$class = is_object($obj) ? get_class($obj) : $obj;
$key = $class . ':' . $invocation->getMethod()->name;
if (!isset($memoryCache[$key])) {
// We can use ttl value from annotation, but Doctrine annotations doesn't work under GAE
if (!isset($_SERVER['APPENGINE_RUNTIME'])) {
echo "Ttl is: ", $invocation->getMethod()->getAnnotation('Demo\Annotation\Cacheable')->time, PHP_EOL;
}
$memoryCache[$key] = $invocation->proceed();
}
echo "Take ", sprintf("%0.3f", (microtime(true) - $time) * 1e3), "ms to call method $key", PHP_EOL;
return $memoryCache[$key];
} | [
"public",
"function",
"aroundCacheable",
"(",
"MethodInvocation",
"$",
"invocation",
")",
"{",
"static",
"$",
"memoryCache",
"=",
"[",
"]",
";",
"$",
"time",
"=",
"microtime",
"(",
"true",
")",
";",
"$",
"obj",
"=",
"$",
"invocation",
"->",
"getThis",
"(... | This advice intercepts an execution of cacheable methods
Logic is pretty simple: we look for the value in the cache and if it's not present here
then invoke original method and store it's result in the cache.
Real-life examples will use APC or Memcache to store value in the cache
@param MethodInvocation $invocation Invocation
@Around("@execution(Demo\Annotation\Cacheable)") | [
"This",
"advice",
"intercepts",
"an",
"execution",
"of",
"cacheable",
"methods"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/demos/Demo/Aspect/CachingAspect.php#L35-L56 |
goaop/framework | src/Instrument/ClassLoading/CachePathManager.php | CachePathManager.getCachePathForResource | public function getCachePathForResource(string $resource)
{
if (!$this->cacheDir) {
return false;
}
return str_replace($this->appDir, $this->cacheDir, $resource);
} | php | public function getCachePathForResource(string $resource)
{
if (!$this->cacheDir) {
return false;
}
return str_replace($this->appDir, $this->cacheDir, $resource);
} | [
"public",
"function",
"getCachePathForResource",
"(",
"string",
"$",
"resource",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"cacheDir",
")",
"{",
"return",
"false",
";",
"}",
"return",
"str_replace",
"(",
"$",
"this",
"->",
"appDir",
",",
"$",
"this",
... | Returns cache path for requested file name
@return bool|string | [
"Returns",
"cache",
"path",
"for",
"requested",
"file",
"name"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/ClassLoading/CachePathManager.php#L119-L126 |
goaop/framework | src/Instrument/ClassLoading/CachePathManager.php | CachePathManager.queryCacheState | public function queryCacheState(string $resource = null): ?array
{
if ($resource === null) {
return $this->cacheState;
}
if (isset($this->newCacheState[$resource])) {
return $this->newCacheState[$resource];
}
if (isset($this->cacheState[$resource])) {
return $this->cacheState[$resource];
}
return null;
} | php | public function queryCacheState(string $resource = null): ?array
{
if ($resource === null) {
return $this->cacheState;
}
if (isset($this->newCacheState[$resource])) {
return $this->newCacheState[$resource];
}
if (isset($this->cacheState[$resource])) {
return $this->cacheState[$resource];
}
return null;
} | [
"public",
"function",
"queryCacheState",
"(",
"string",
"$",
"resource",
"=",
"null",
")",
":",
"?",
"array",
"{",
"if",
"(",
"$",
"resource",
"===",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"cacheState",
";",
"}",
"if",
"(",
"isset",
"(",
"$",... | Tries to return an information for queried resource
@param string|null $resource Name of the file or null to get all information
@return array|null Information or null if no record in the cache | [
"Tries",
"to",
"return",
"an",
"information",
"for",
"queried",
"resource"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/ClassLoading/CachePathManager.php#L135-L150 |
goaop/framework | src/Instrument/ClassLoading/CachePathManager.php | CachePathManager.flushCacheState | public function flushCacheState(bool $force = false): void
{
if ((!empty($this->newCacheState) && is_writable($this->cacheDir)) || $force) {
$fullCacheMap = $this->newCacheState + $this->cacheState;
$cachePath = substr(var_export($this->cacheDir, true), 1, -1);
$rootPath = substr(var_export($this->appDir, true), 1, -1);
$cacheData = '<?php return ' . var_export($fullCacheMap, true) . ';';
$cacheData = strtr($cacheData, [
'\'' . $cachePath => 'AOP_CACHE_DIR . \'',
'\'' . $rootPath => 'AOP_ROOT_DIR . \''
]);
$fullCacheFileName = $this->cacheDir . self::CACHE_FILE_NAME;
file_put_contents($fullCacheFileName, $cacheData, LOCK_EX);
// For cache files we don't want executable bits by default
chmod($fullCacheFileName, $this->fileMode & (~0111));
if (function_exists('opcache_invalidate')) {
opcache_invalidate($fullCacheFileName, true);
}
$this->cacheState = $this->newCacheState + $this->cacheState;
$this->newCacheState = [];
}
} | php | public function flushCacheState(bool $force = false): void
{
if ((!empty($this->newCacheState) && is_writable($this->cacheDir)) || $force) {
$fullCacheMap = $this->newCacheState + $this->cacheState;
$cachePath = substr(var_export($this->cacheDir, true), 1, -1);
$rootPath = substr(var_export($this->appDir, true), 1, -1);
$cacheData = '<?php return ' . var_export($fullCacheMap, true) . ';';
$cacheData = strtr($cacheData, [
'\'' . $cachePath => 'AOP_CACHE_DIR . \'',
'\'' . $rootPath => 'AOP_ROOT_DIR . \''
]);
$fullCacheFileName = $this->cacheDir . self::CACHE_FILE_NAME;
file_put_contents($fullCacheFileName, $cacheData, LOCK_EX);
// For cache files we don't want executable bits by default
chmod($fullCacheFileName, $this->fileMode & (~0111));
if (function_exists('opcache_invalidate')) {
opcache_invalidate($fullCacheFileName, true);
}
$this->cacheState = $this->newCacheState + $this->cacheState;
$this->newCacheState = [];
}
} | [
"public",
"function",
"flushCacheState",
"(",
"bool",
"$",
"force",
"=",
"false",
")",
":",
"void",
"{",
"if",
"(",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"newCacheState",
")",
"&&",
"is_writable",
"(",
"$",
"this",
"->",
"cacheDir",
")",
")",
"|... | Flushes the cache state into the file | [
"Flushes",
"the",
"cache",
"state",
"into",
"the",
"file"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/ClassLoading/CachePathManager.php#L177-L199 |
goaop/framework | src/Proxy/FunctionProxyGenerator.php | FunctionProxyGenerator.getJoinPoint | public static function getJoinPoint(string $functionName, array $advices): FunctionInvocation
{
static $accessor;
if ($accessor === null) {
$accessor = AspectKernel::getInstance()->getContainer()->get('aspect.advisor.accessor');
}
$filledAdvices = [];
foreach ($advices as $advisorName) {
$filledAdvices[] = $accessor->$advisorName;
}
return new ReflectionFunctionInvocation($functionName, $filledAdvices);
} | php | public static function getJoinPoint(string $functionName, array $advices): FunctionInvocation
{
static $accessor;
if ($accessor === null) {
$accessor = AspectKernel::getInstance()->getContainer()->get('aspect.advisor.accessor');
}
$filledAdvices = [];
foreach ($advices as $advisorName) {
$filledAdvices[] = $accessor->$advisorName;
}
return new ReflectionFunctionInvocation($functionName, $filledAdvices);
} | [
"public",
"static",
"function",
"getJoinPoint",
"(",
"string",
"$",
"functionName",
",",
"array",
"$",
"advices",
")",
":",
"FunctionInvocation",
"{",
"static",
"$",
"accessor",
";",
"if",
"(",
"$",
"accessor",
"===",
"null",
")",
"{",
"$",
"accessor",
"="... | Returns a joinpoint for specific function in the namespace
@param array $advices List of advices | [
"Returns",
"a",
"joinpoint",
"for",
"specific",
"function",
"in",
"the",
"namespace"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Proxy/FunctionProxyGenerator.php#L75-L89 |
goaop/framework | src/Proxy/FunctionProxyGenerator.php | FunctionProxyGenerator.getJoinpointInvocationBody | protected function getJoinpointInvocationBody(ReflectionFunction $function): string
{
$class = '\\' . __CLASS__;
$argumentList = new FunctionCallArgumentListGenerator($function);
$argumentCode = $argumentList->generate();
$return = 'return ';
if ($function->hasReturnType()) {
$returnType = (string) $function->getReturnType();
if ($returnType === 'void') {
// void return types should not return anything
$return = '';
}
}
$functionAdvices = $this->advices[AspectContainer::FUNCTION_PREFIX][$function->name];
$advicesArray = new ValueGenerator($functionAdvices, ValueGenerator::TYPE_ARRAY_SHORT);
$advicesArray->setArrayDepth(1);
$advicesCode = $advicesArray->generate();
return <<<BODY
static \$__joinPoint;
if (\$__joinPoint === null) {
\$__joinPoint = {$class}::getJoinPoint('{$function->name}', {$advicesCode});
}
{$return}\$__joinPoint->__invoke($argumentCode);
BODY;
} | php | protected function getJoinpointInvocationBody(ReflectionFunction $function): string
{
$class = '\\' . __CLASS__;
$argumentList = new FunctionCallArgumentListGenerator($function);
$argumentCode = $argumentList->generate();
$return = 'return ';
if ($function->hasReturnType()) {
$returnType = (string) $function->getReturnType();
if ($returnType === 'void') {
// void return types should not return anything
$return = '';
}
}
$functionAdvices = $this->advices[AspectContainer::FUNCTION_PREFIX][$function->name];
$advicesArray = new ValueGenerator($functionAdvices, ValueGenerator::TYPE_ARRAY_SHORT);
$advicesArray->setArrayDepth(1);
$advicesCode = $advicesArray->generate();
return <<<BODY
static \$__joinPoint;
if (\$__joinPoint === null) {
\$__joinPoint = {$class}::getJoinPoint('{$function->name}', {$advicesCode});
}
{$return}\$__joinPoint->__invoke($argumentCode);
BODY;
} | [
"protected",
"function",
"getJoinpointInvocationBody",
"(",
"ReflectionFunction",
"$",
"function",
")",
":",
"string",
"{",
"$",
"class",
"=",
"'\\\\'",
".",
"__CLASS__",
";",
"$",
"argumentList",
"=",
"new",
"FunctionCallArgumentListGenerator",
"(",
"$",
"function"... | Creates string definition for function method body by function reflection | [
"Creates",
"string",
"definition",
"for",
"function",
"method",
"body",
"by",
"function",
"reflection"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Proxy/FunctionProxyGenerator.php#L102-L130 |
goaop/framework | src/Instrument/FileSystem/Enumerator.php | Enumerator.enumerate | public function enumerate(): Iterator
{
$finder = new Finder();
$finder->files()
->name('*.php')
->in($this->getInPaths());
foreach ($this->getExcludePaths() as $path) {
$finder->notPath($path);
}
$iterator = $finder->getIterator();
// on Windows platform the default iterator is unable to rewind, not sure why
if (strpos(PHP_OS, 'WIN') === 0) {
$iterator = new ArrayIterator(iterator_to_array($iterator));
}
return $iterator;
} | php | public function enumerate(): Iterator
{
$finder = new Finder();
$finder->files()
->name('*.php')
->in($this->getInPaths());
foreach ($this->getExcludePaths() as $path) {
$finder->notPath($path);
}
$iterator = $finder->getIterator();
// on Windows platform the default iterator is unable to rewind, not sure why
if (strpos(PHP_OS, 'WIN') === 0) {
$iterator = new ArrayIterator(iterator_to_array($iterator));
}
return $iterator;
} | [
"public",
"function",
"enumerate",
"(",
")",
":",
"Iterator",
"{",
"$",
"finder",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"finder",
"->",
"files",
"(",
")",
"->",
"name",
"(",
"'*.php'",
")",
"->",
"in",
"(",
"$",
"this",
"->",
"getInPaths",
"(",... | Returns an enumerator for files
@return Iterator|SplFileInfo[]
@throws UnexpectedValueException
@throws InvalidArgumentException
@throws LogicException | [
"Returns",
"an",
"enumerator",
"for",
"files"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/FileSystem/Enumerator.php#L65-L84 |
goaop/framework | src/Instrument/FileSystem/Enumerator.php | Enumerator.getFilter | public function getFilter(): Closure
{
$rootDirectory = $this->rootDirectory;
$includePaths = $this->includePaths;
$excludePaths = $this->excludePaths;
return function (SplFileInfo $file) use ($rootDirectory, $includePaths, $excludePaths) {
if ($file->getExtension() !== 'php') {
return false;
}
$fullPath = $this->getFileFullPath($file);
// Do not touch files that not under rootDirectory
if (strpos($fullPath, $rootDirectory) !== 0) {
return false;
}
if (!empty($includePaths)) {
$found = false;
foreach ($includePaths as $includePattern) {
if (fnmatch("{$includePattern}*", $fullPath, FNM_NOESCAPE)) {
$found = true;
break;
}
}
if (!$found) {
return false;
}
}
foreach ($excludePaths as $excludePattern) {
if (fnmatch("{$excludePattern}*", $fullPath, FNM_NOESCAPE)) {
return false;
}
}
return true;
};
} | php | public function getFilter(): Closure
{
$rootDirectory = $this->rootDirectory;
$includePaths = $this->includePaths;
$excludePaths = $this->excludePaths;
return function (SplFileInfo $file) use ($rootDirectory, $includePaths, $excludePaths) {
if ($file->getExtension() !== 'php') {
return false;
}
$fullPath = $this->getFileFullPath($file);
// Do not touch files that not under rootDirectory
if (strpos($fullPath, $rootDirectory) !== 0) {
return false;
}
if (!empty($includePaths)) {
$found = false;
foreach ($includePaths as $includePattern) {
if (fnmatch("{$includePattern}*", $fullPath, FNM_NOESCAPE)) {
$found = true;
break;
}
}
if (!$found) {
return false;
}
}
foreach ($excludePaths as $excludePattern) {
if (fnmatch("{$excludePattern}*", $fullPath, FNM_NOESCAPE)) {
return false;
}
}
return true;
};
} | [
"public",
"function",
"getFilter",
"(",
")",
":",
"Closure",
"{",
"$",
"rootDirectory",
"=",
"$",
"this",
"->",
"rootDirectory",
";",
"$",
"includePaths",
"=",
"$",
"this",
"->",
"includePaths",
";",
"$",
"excludePaths",
"=",
"$",
"this",
"->",
"excludePat... | Returns a filter callback for enumerating files | [
"Returns",
"a",
"filter",
"callback",
"for",
"enumerating",
"files"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/FileSystem/Enumerator.php#L89-L128 |
goaop/framework | src/Instrument/FileSystem/Enumerator.php | Enumerator.getInPaths | private function getInPaths(): array
{
$inPaths = [];
foreach ($this->includePaths as $path) {
if (strpos($path, $this->rootDirectory, 0) === false) {
throw new UnexpectedValueException(sprintf('Path %s is not in %s', $path, $this->rootDirectory));
}
$path = str_replace('*', '', $path);
$inPaths[] = $path;
}
if (empty($inPaths)) {
$inPaths[] = $this->rootDirectory;
}
return $inPaths;
} | php | private function getInPaths(): array
{
$inPaths = [];
foreach ($this->includePaths as $path) {
if (strpos($path, $this->rootDirectory, 0) === false) {
throw new UnexpectedValueException(sprintf('Path %s is not in %s', $path, $this->rootDirectory));
}
$path = str_replace('*', '', $path);
$inPaths[] = $path;
}
if (empty($inPaths)) {
$inPaths[] = $this->rootDirectory;
}
return $inPaths;
} | [
"private",
"function",
"getInPaths",
"(",
")",
":",
"array",
"{",
"$",
"inPaths",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"includePaths",
"as",
"$",
"path",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"path",
",",
"$",
"this",
"->",
"... | Returns collection of directories to look at
@throws UnexpectedValueException if directory not under the root | [
"Returns",
"collection",
"of",
"directories",
"to",
"look",
"at"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/FileSystem/Enumerator.php#L147-L165 |
goaop/framework | src/Instrument/FileSystem/Enumerator.php | Enumerator.getExcludePaths | private function getExcludePaths(): array
{
$excludePaths = [];
foreach ($this->excludePaths as $path) {
$path = str_replace('*', '.*', $path);
$excludePaths[] = '#' . str_replace($this->rootDirectory . '/', '', $path) . '#';
}
return $excludePaths;
} | php | private function getExcludePaths(): array
{
$excludePaths = [];
foreach ($this->excludePaths as $path) {
$path = str_replace('*', '.*', $path);
$excludePaths[] = '#' . str_replace($this->rootDirectory . '/', '', $path) . '#';
}
return $excludePaths;
} | [
"private",
"function",
"getExcludePaths",
"(",
")",
":",
"array",
"{",
"$",
"excludePaths",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"excludePaths",
"as",
"$",
"path",
")",
"{",
"$",
"path",
"=",
"str_replace",
"(",
"'*'",
",",
"'.*'",
... | Returns the list of excluded paths | [
"Returns",
"the",
"list",
"of",
"excluded",
"paths"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/FileSystem/Enumerator.php#L170-L180 |
goaop/framework | demos/Demo/Highlighter.php | Highlighter.highlight | public static function highlight($file)
{
$highlightFileFunc = new \ReflectionFunction('highlight_file');
if (!$highlightFileFunc->isDisabled()) {
highlight_file($file);
} else {
echo '<pre>' . htmlspecialchars(file_get_contents($file)) . '</pre>';
}
} | php | public static function highlight($file)
{
$highlightFileFunc = new \ReflectionFunction('highlight_file');
if (!$highlightFileFunc->isDisabled()) {
highlight_file($file);
} else {
echo '<pre>' . htmlspecialchars(file_get_contents($file)) . '</pre>';
}
} | [
"public",
"static",
"function",
"highlight",
"(",
"$",
"file",
")",
"{",
"$",
"highlightFileFunc",
"=",
"new",
"\\",
"ReflectionFunction",
"(",
"'highlight_file'",
")",
";",
"if",
"(",
"!",
"$",
"highlightFileFunc",
"->",
"isDisabled",
"(",
")",
")",
"{",
... | Highlighter with built-in check for list of disabled function (Google AppEngine)
@param string $file Name of the file | [
"Highlighter",
"with",
"built",
"-",
"in",
"check",
"for",
"list",
"of",
"disabled",
"function",
"(",
"Google",
"AppEngine",
")"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/demos/Demo/Highlighter.php#L24-L32 |
goaop/framework | src/Instrument/Transformer/SelfValueVisitor.php | SelfValueVisitor.resolveClassName | protected function resolveClassName(Name $name): Name
{
// Skip all names except special `self`
if (strtolower($name->toString()) !== 'self') {
return $name;
}
// Save the original name
$originalName = $name;
$name = clone $originalName;
$name->setAttribute('originalName', $originalName);
$fullClassName = Name::concat($this->namespace, $this->className);
$resolvedSelfName = new FullyQualified('\\' . ltrim($fullClassName->toString(), '\\'), $name->getAttributes());
$this->replacedNodes[] = $resolvedSelfName;
return $resolvedSelfName;
} | php | protected function resolveClassName(Name $name): Name
{
// Skip all names except special `self`
if (strtolower($name->toString()) !== 'self') {
return $name;
}
// Save the original name
$originalName = $name;
$name = clone $originalName;
$name->setAttribute('originalName', $originalName);
$fullClassName = Name::concat($this->namespace, $this->className);
$resolvedSelfName = new FullyQualified('\\' . ltrim($fullClassName->toString(), '\\'), $name->getAttributes());
$this->replacedNodes[] = $resolvedSelfName;
return $resolvedSelfName;
} | [
"protected",
"function",
"resolveClassName",
"(",
"Name",
"$",
"name",
")",
":",
"Name",
"{",
"// Skip all names except special `self`",
"if",
"(",
"strtolower",
"(",
"$",
"name",
"->",
"toString",
"(",
")",
")",
"!==",
"'self'",
")",
"{",
"return",
"$",
"na... | Resolves `self` class name with value
@param Name $name Instance of original node
@return Name|FullyQualified | [
"Resolves",
"self",
"class",
"name",
"with",
"value"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/SelfValueVisitor.php#L105-L123 |
goaop/framework | src/Instrument/Transformer/SelfValueVisitor.php | SelfValueVisitor.resolveType | private function resolveType($node)
{
if ($node instanceof Node\NullableType) {
$node->type = $this->resolveType($node->type);
return $node;
}
if ($node instanceof Name) {
return $this->resolveClassName($node);
}
return $node;
} | php | private function resolveType($node)
{
if ($node instanceof Node\NullableType) {
$node->type = $this->resolveType($node->type);
return $node;
}
if ($node instanceof Name) {
return $this->resolveClassName($node);
}
return $node;
} | [
"private",
"function",
"resolveType",
"(",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"instanceof",
"Node",
"\\",
"NullableType",
")",
"{",
"$",
"node",
"->",
"type",
"=",
"$",
"this",
"->",
"resolveType",
"(",
"$",
"node",
"->",
"type",
")",
";"... | Helper method for resolving type nodes
@param Node|string|null $node Instance of node
@return Node|Name|FullyQualified | [
"Helper",
"method",
"for",
"resolving",
"type",
"nodes"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/SelfValueVisitor.php#L132-L143 |
goaop/framework | src/Aop/Framework/DynamicClosureMethodInvocation.php | DynamicClosureMethodInvocation.proceed | public function proceed()
{
if (isset($this->advices[$this->current])) {
$currentInterceptor = $this->advices[$this->current++];
return $currentInterceptor->invoke($this);
}
// Fill the closure only once if it's empty
if ($this->closureToCall === null) {
$this->closureToCall = $this->reflectionMethod->getClosure($this->instance);
$this->previousInstance = $this->instance;
}
// Rebind the closure if instance was changed since last time
if ($this->previousInstance !== $this->instance) {
$this->closureToCall = $this->closureToCall->bindTo($this->instance, $this->reflectionMethod->class);
$this->previousInstance = $this->instance;
}
return ($this->closureToCall)(...$this->arguments);
} | php | public function proceed()
{
if (isset($this->advices[$this->current])) {
$currentInterceptor = $this->advices[$this->current++];
return $currentInterceptor->invoke($this);
}
// Fill the closure only once if it's empty
if ($this->closureToCall === null) {
$this->closureToCall = $this->reflectionMethod->getClosure($this->instance);
$this->previousInstance = $this->instance;
}
// Rebind the closure if instance was changed since last time
if ($this->previousInstance !== $this->instance) {
$this->closureToCall = $this->closureToCall->bindTo($this->instance, $this->reflectionMethod->class);
$this->previousInstance = $this->instance;
}
return ($this->closureToCall)(...$this->arguments);
} | [
"public",
"function",
"proceed",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"advices",
"[",
"$",
"this",
"->",
"current",
"]",
")",
")",
"{",
"$",
"currentInterceptor",
"=",
"$",
"this",
"->",
"advices",
"[",
"$",
"this",
"->",
"cur... | Invokes original method and return result from it
@return mixed | [
"Invokes",
"original",
"method",
"and",
"return",
"result",
"from",
"it"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Framework/DynamicClosureMethodInvocation.php#L38-L59 |
goaop/framework | src/Bridge/Doctrine/MetadataLoadInterceptor.php | MetadataLoadInterceptor.loadClassMetadata | public function loadClassMetadata(LoadClassMetadataEventArgs $args): void
{
/**
* @var ClassMetadata $metadata
*/
$metadata = $args->getClassMetadata();
if (1 === preg_match(sprintf('/.+(%s)$/', AspectContainer::AOP_PROXIED_SUFFIX), $metadata->name)) {
$metadata->isMappedSuperclass = true;
$metadata->isEmbeddedClass = false;
$metadata->table = [];
$metadata->customRepositoryClassName = null;
$this->removeMappingsFromTraits($metadata);
}
} | php | public function loadClassMetadata(LoadClassMetadataEventArgs $args): void
{
/**
* @var ClassMetadata $metadata
*/
$metadata = $args->getClassMetadata();
if (1 === preg_match(sprintf('/.+(%s)$/', AspectContainer::AOP_PROXIED_SUFFIX), $metadata->name)) {
$metadata->isMappedSuperclass = true;
$metadata->isEmbeddedClass = false;
$metadata->table = [];
$metadata->customRepositoryClassName = null;
$this->removeMappingsFromTraits($metadata);
}
} | [
"public",
"function",
"loadClassMetadata",
"(",
"LoadClassMetadataEventArgs",
"$",
"args",
")",
":",
"void",
"{",
"/**\n * @var ClassMetadata $metadata\n */",
"$",
"metadata",
"=",
"$",
"args",
"->",
"getClassMetadata",
"(",
")",
";",
"if",
"(",
"1",
... | Handles \Doctrine\ORM\Events::loadClassMetadata event by modifying metadata of Go! AOP proxied classes.
This method intercepts loaded metadata of Doctrine's entities which are weaved by Go! AOP,
and denotes them as mapped superclass. If weaved entities uses mappings from traits
(such as Timestampable, Blameable, etc... from https://github.com/Atlantic18/DoctrineExtensions),
it will remove all mappings from proxied class for fields inherited from traits in order to prevent
collision with concrete subclass of weaved entity. Fields from trait will be present in concrete subclass
of weaved entitites.
@see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/inheritance-mapping.html#mapped-superclasses
@see https://github.com/Atlantic18/DoctrineExtensions | [
"Handles",
"\\",
"Doctrine",
"\\",
"ORM",
"\\",
"Events",
"::",
"loadClassMetadata",
"event",
"by",
"modifying",
"metadata",
"of",
"Go!",
"AOP",
"proxied",
"classes",
"."
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Bridge/Doctrine/MetadataLoadInterceptor.php#L49-L64 |
goaop/framework | src/Bridge/Doctrine/MetadataLoadInterceptor.php | MetadataLoadInterceptor.removeMappingsFromTraits | private function removeMappingsFromTraits(ClassMetadata $metadata): void
{
$traits = $this->getTraits($metadata->name);
foreach ($traits as $trait) {
$trait = new \ReflectionClass($trait);
/**
* @var \ReflectionProperty $property
*/
foreach ($trait->getProperties() as $property) {
$name = $property->getName();
if (isset($metadata->fieldMappings[$name])) {
$mapping = $metadata->fieldMappings[$name];
unset(
$metadata->fieldMappings[$name],
$metadata->fieldNames[$mapping['columnName']],
$metadata->columnNames[$name]
);
}
}
}
} | php | private function removeMappingsFromTraits(ClassMetadata $metadata): void
{
$traits = $this->getTraits($metadata->name);
foreach ($traits as $trait) {
$trait = new \ReflectionClass($trait);
/**
* @var \ReflectionProperty $property
*/
foreach ($trait->getProperties() as $property) {
$name = $property->getName();
if (isset($metadata->fieldMappings[$name])) {
$mapping = $metadata->fieldMappings[$name];
unset(
$metadata->fieldMappings[$name],
$metadata->fieldNames[$mapping['columnName']],
$metadata->columnNames[$name]
);
}
}
}
} | [
"private",
"function",
"removeMappingsFromTraits",
"(",
"ClassMetadata",
"$",
"metadata",
")",
":",
"void",
"{",
"$",
"traits",
"=",
"$",
"this",
"->",
"getTraits",
"(",
"$",
"metadata",
"->",
"name",
")",
";",
"foreach",
"(",
"$",
"traits",
"as",
"$",
"... | Remove fields in Go! AOP proxied class metadata that are inherited
from traits. | [
"Remove",
"fields",
"in",
"Go!",
"AOP",
"proxied",
"class",
"metadata",
"that",
"are",
"inherited",
"from",
"traits",
"."
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Bridge/Doctrine/MetadataLoadInterceptor.php#L70-L94 |
goaop/framework | src/Bridge/Doctrine/MetadataLoadInterceptor.php | MetadataLoadInterceptor.getTraits | private function getTraits($objectOrClass, $autoload = true): array
{
if (is_object($objectOrClass)) {
$objectOrClass = get_class($objectOrClass);
}
if (!is_string($objectOrClass)) {
throw new \InvalidArgumentException(sprintf('Full qualified class name expected, got: "%s".', gettype($objectOrClass)));
}
if (!class_exists($objectOrClass)) {
throw new \RuntimeException(sprintf('Class "%s" does not exists or it can not be autoloaded.', $objectOrClass));
}
$traits = [];
// Get traits of all parent classes
do {
$traits = array_merge(class_uses($objectOrClass, $autoload), $traits);
} while ($objectOrClass = get_parent_class($objectOrClass));
$traitsToSearch = $traits;
while (count($traitsToSearch) > 0) {
$newTraits = class_uses(array_pop($traitsToSearch), $autoload);
$traits = array_merge($newTraits, $traits);
$traitsToSearch = array_merge($newTraits, $traitsToSearch);
}
foreach ($traits as $trait => $same) {
$traits = array_merge(class_uses($trait, $autoload), $traits);
}
return array_unique(array_map(function ($fqcn) {
return ltrim($fqcn, '\\');
}, $traits));
} | php | private function getTraits($objectOrClass, $autoload = true): array
{
if (is_object($objectOrClass)) {
$objectOrClass = get_class($objectOrClass);
}
if (!is_string($objectOrClass)) {
throw new \InvalidArgumentException(sprintf('Full qualified class name expected, got: "%s".', gettype($objectOrClass)));
}
if (!class_exists($objectOrClass)) {
throw new \RuntimeException(sprintf('Class "%s" does not exists or it can not be autoloaded.', $objectOrClass));
}
$traits = [];
// Get traits of all parent classes
do {
$traits = array_merge(class_uses($objectOrClass, $autoload), $traits);
} while ($objectOrClass = get_parent_class($objectOrClass));
$traitsToSearch = $traits;
while (count($traitsToSearch) > 0) {
$newTraits = class_uses(array_pop($traitsToSearch), $autoload);
$traits = array_merge($newTraits, $traits);
$traitsToSearch = array_merge($newTraits, $traitsToSearch);
}
foreach ($traits as $trait => $same) {
$traits = array_merge(class_uses($trait, $autoload), $traits);
}
return array_unique(array_map(function ($fqcn) {
return ltrim($fqcn, '\\');
}, $traits));
} | [
"private",
"function",
"getTraits",
"(",
"$",
"objectOrClass",
",",
"$",
"autoload",
"=",
"true",
")",
":",
"array",
"{",
"if",
"(",
"is_object",
"(",
"$",
"objectOrClass",
")",
")",
"{",
"$",
"objectOrClass",
"=",
"get_class",
"(",
"$",
"objectOrClass",
... | Get ALL traits used by one class.
This method is copied from https://github.com/RunOpenCode/traitor-bundle/blob/master/src/RunOpenCode/Bundle/Traitor/Utils/ClassUtils.php
@param object|string $objectOrClass Instance of class or FQCN
@param bool $autoload Weather to autoload class.
@throws \InvalidArgumentException
@throws \RuntimeException | [
"Get",
"ALL",
"traits",
"used",
"by",
"one",
"class",
"."
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Bridge/Doctrine/MetadataLoadInterceptor.php#L107-L142 |
goaop/framework | src/Proxy/Part/InterceptedConstructorGenerator.php | InterceptedConstructorGenerator.getConstructorBody | private function getConstructorBody(array $interceptedProperties): string
{
$assocProperties = [];
$listProperties = [];
foreach ($interceptedProperties as $propertyName) {
$assocProperties[] = " '{$propertyName}' => &\$target->{$propertyName}";
$listProperties[] = " \$target->{$propertyName}";
}
$lines = [
'$accessor = function(array &$propertyStorage, object $target) {',
' $propertyStorage = [',
implode(',' . PHP_EOL, $assocProperties),
' ];',
' unset(',
implode(',' . PHP_EOL, $listProperties),
' );',
'};',
'($accessor->bindTo($this, parent::class))($this->__properties, $this);'
];
return implode(PHP_EOL, $lines);
} | php | private function getConstructorBody(array $interceptedProperties): string
{
$assocProperties = [];
$listProperties = [];
foreach ($interceptedProperties as $propertyName) {
$assocProperties[] = " '{$propertyName}' => &\$target->{$propertyName}";
$listProperties[] = " \$target->{$propertyName}";
}
$lines = [
'$accessor = function(array &$propertyStorage, object $target) {',
' $propertyStorage = [',
implode(',' . PHP_EOL, $assocProperties),
' ];',
' unset(',
implode(',' . PHP_EOL, $listProperties),
' );',
'};',
'($accessor->bindTo($this, parent::class))($this->__properties, $this);'
];
return implode(PHP_EOL, $lines);
} | [
"private",
"function",
"getConstructorBody",
"(",
"array",
"$",
"interceptedProperties",
")",
":",
"string",
"{",
"$",
"assocProperties",
"=",
"[",
"]",
";",
"$",
"listProperties",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"interceptedProperties",
"as",
"$",
... | Returns constructor code
@param array $interceptedProperties List of properties to intercept | [
"Returns",
"constructor",
"code"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Proxy/Part/InterceptedConstructorGenerator.php#L83-L104 |
goaop/framework | src/Core/AdviceMatcher.php | AdviceMatcher.getAdvicesForFunctions | public function getAdvicesForFunctions(ReflectionFileNamespace $namespace, array $advisors): array
{
if (!$this->isInterceptFunctions) {
return [];
}
$advices = [];
foreach ($advisors as $advisorId => $advisor) {
if ($advisor instanceof Aop\PointcutAdvisor) {
$pointcut = $advisor->getPointcut();
$isFunctionAdvisor = $pointcut->getKind() & Aop\PointFilter::KIND_FUNCTION;
if ($isFunctionAdvisor && $pointcut->getClassFilter()->matches($namespace)) {
$advices[] = $this->getFunctionAdvicesFromAdvisor($namespace, $advisor, $advisorId, $pointcut);
}
}
}
if (count($advices) > 0) {
$advices = array_merge_recursive(...$advices);
}
return $advices;
} | php | public function getAdvicesForFunctions(ReflectionFileNamespace $namespace, array $advisors): array
{
if (!$this->isInterceptFunctions) {
return [];
}
$advices = [];
foreach ($advisors as $advisorId => $advisor) {
if ($advisor instanceof Aop\PointcutAdvisor) {
$pointcut = $advisor->getPointcut();
$isFunctionAdvisor = $pointcut->getKind() & Aop\PointFilter::KIND_FUNCTION;
if ($isFunctionAdvisor && $pointcut->getClassFilter()->matches($namespace)) {
$advices[] = $this->getFunctionAdvicesFromAdvisor($namespace, $advisor, $advisorId, $pointcut);
}
}
}
if (count($advices) > 0) {
$advices = array_merge_recursive(...$advices);
}
return $advices;
} | [
"public",
"function",
"getAdvicesForFunctions",
"(",
"ReflectionFileNamespace",
"$",
"namespace",
",",
"array",
"$",
"advisors",
")",
":",
"array",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isInterceptFunctions",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
... | Returns list of function advices for namespace
@param Aop\Advisor[] $advisors List of advisor to match
@return Aop\Advice[] List of advices for class | [
"Returns",
"list",
"of",
"function",
"advices",
"for",
"namespace"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AdviceMatcher.php#L51-L74 |
goaop/framework | src/Core/AdviceMatcher.php | AdviceMatcher.getAdvicesForClass | public function getAdvicesForClass(ReflectionClass $class, array $advisors): array
{
$classAdvices = [];
$parentClass = $class->getParentClass();
$originalClass = $class;
if ($parentClass && strpos($parentClass->name, AspectContainer::AOP_PROXIED_SUFFIX) !== false) {
$originalClass = $parentClass;
}
foreach ($advisors as $advisorId => $advisor) {
if ($advisor instanceof Aop\PointcutAdvisor) {
$pointcut = $advisor->getPointcut();
if ($pointcut->getClassFilter()->matches($class)) {
$classAdvices[] = $this->getAdvicesFromAdvisor($originalClass, $advisor, $advisorId, $pointcut);
}
}
if ($advisor instanceof Aop\IntroductionAdvisor) {
if ($advisor->getClassFilter()->matches($class)) {
$classAdvices[] = $this->getIntroductionFromAdvisor($originalClass, $advisor, $advisorId);
}
}
}
if (count($classAdvices) > 0) {
$classAdvices = array_merge_recursive(...$classAdvices);
}
return $classAdvices;
} | php | public function getAdvicesForClass(ReflectionClass $class, array $advisors): array
{
$classAdvices = [];
$parentClass = $class->getParentClass();
$originalClass = $class;
if ($parentClass && strpos($parentClass->name, AspectContainer::AOP_PROXIED_SUFFIX) !== false) {
$originalClass = $parentClass;
}
foreach ($advisors as $advisorId => $advisor) {
if ($advisor instanceof Aop\PointcutAdvisor) {
$pointcut = $advisor->getPointcut();
if ($pointcut->getClassFilter()->matches($class)) {
$classAdvices[] = $this->getAdvicesFromAdvisor($originalClass, $advisor, $advisorId, $pointcut);
}
}
if ($advisor instanceof Aop\IntroductionAdvisor) {
if ($advisor->getClassFilter()->matches($class)) {
$classAdvices[] = $this->getIntroductionFromAdvisor($originalClass, $advisor, $advisorId);
}
}
}
if (count($classAdvices) > 0) {
$classAdvices = array_merge_recursive(...$classAdvices);
}
return $classAdvices;
} | [
"public",
"function",
"getAdvicesForClass",
"(",
"ReflectionClass",
"$",
"class",
",",
"array",
"$",
"advisors",
")",
":",
"array",
"{",
"$",
"classAdvices",
"=",
"[",
"]",
";",
"$",
"parentClass",
"=",
"$",
"class",
"->",
"getParentClass",
"(",
")",
";",
... | Return list of advices for class
@param array|Aop\Advisor[] $advisors List of advisor to match
@return Aop\Advice[] List of advices for class | [
"Return",
"list",
"of",
"advices",
"for",
"class"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AdviceMatcher.php#L83-L112 |
goaop/framework | src/Core/AdviceMatcher.php | AdviceMatcher.getAdvicesFromAdvisor | private function getAdvicesFromAdvisor(
ReflectionClass $class,
Aop\PointcutAdvisor $advisor,
string $advisorId,
Aop\PointFilter $filter
): array {
$classAdvices = [];
$filterKind = $filter->getKind();
// Check class only for class filters
if ($filterKind & Aop\PointFilter::KIND_CLASS) {
if ($filter->matches($class)) {
// Dynamic initialization
if ($filterKind & Aop\PointFilter::KIND_INIT) {
$classAdvices[AspectContainer::INIT_PREFIX]['root'][$advisorId] = $advisor->getAdvice();
}
// Static initalization
if ($filterKind & Aop\PointFilter::KIND_STATIC_INIT) {
$classAdvices[AspectContainer::STATIC_INIT_PREFIX]['root'][$advisorId] = $advisor->getAdvice();
}
}
}
// Check methods in class only for method filters
if ($filterKind & Aop\PointFilter::KIND_METHOD) {
$mask = ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED;
foreach ($class->getMethods($mask) as $method) {
// abstract and parent final methods could not be woven
$isParentFinalMethod = ($method->getDeclaringClass()->name !== $class->name) && $method->isFinal();
if ($isParentFinalMethod || $method->isAbstract()) {
continue;
}
if ($filter->matches($method, $class)) {
$prefix = $method->isStatic() ? AspectContainer::STATIC_METHOD_PREFIX : AspectContainer::METHOD_PREFIX;
$classAdvices[$prefix][$method->name][$advisorId] = $advisor->getAdvice();
}
}
}
// Check properties in class only for property filters
if ($filterKind & Aop\PointFilter::KIND_PROPERTY) {
$mask = ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PRIVATE;
foreach ($class->getProperties($mask) as $property) {
if ($filter->matches($property, $class) && !$property->isStatic()) {
$classAdvices[AspectContainer::PROPERTY_PREFIX][$property->name][$advisorId] = $advisor->getAdvice();
}
}
}
return $classAdvices;
} | php | private function getAdvicesFromAdvisor(
ReflectionClass $class,
Aop\PointcutAdvisor $advisor,
string $advisorId,
Aop\PointFilter $filter
): array {
$classAdvices = [];
$filterKind = $filter->getKind();
// Check class only for class filters
if ($filterKind & Aop\PointFilter::KIND_CLASS) {
if ($filter->matches($class)) {
// Dynamic initialization
if ($filterKind & Aop\PointFilter::KIND_INIT) {
$classAdvices[AspectContainer::INIT_PREFIX]['root'][$advisorId] = $advisor->getAdvice();
}
// Static initalization
if ($filterKind & Aop\PointFilter::KIND_STATIC_INIT) {
$classAdvices[AspectContainer::STATIC_INIT_PREFIX]['root'][$advisorId] = $advisor->getAdvice();
}
}
}
// Check methods in class only for method filters
if ($filterKind & Aop\PointFilter::KIND_METHOD) {
$mask = ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED;
foreach ($class->getMethods($mask) as $method) {
// abstract and parent final methods could not be woven
$isParentFinalMethod = ($method->getDeclaringClass()->name !== $class->name) && $method->isFinal();
if ($isParentFinalMethod || $method->isAbstract()) {
continue;
}
if ($filter->matches($method, $class)) {
$prefix = $method->isStatic() ? AspectContainer::STATIC_METHOD_PREFIX : AspectContainer::METHOD_PREFIX;
$classAdvices[$prefix][$method->name][$advisorId] = $advisor->getAdvice();
}
}
}
// Check properties in class only for property filters
if ($filterKind & Aop\PointFilter::KIND_PROPERTY) {
$mask = ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PRIVATE;
foreach ($class->getProperties($mask) as $property) {
if ($filter->matches($property, $class) && !$property->isStatic()) {
$classAdvices[AspectContainer::PROPERTY_PREFIX][$property->name][$advisorId] = $advisor->getAdvice();
}
}
}
return $classAdvices;
} | [
"private",
"function",
"getAdvicesFromAdvisor",
"(",
"ReflectionClass",
"$",
"class",
",",
"Aop",
"\\",
"PointcutAdvisor",
"$",
"advisor",
",",
"string",
"$",
"advisorId",
",",
"Aop",
"\\",
"PointFilter",
"$",
"filter",
")",
":",
"array",
"{",
"$",
"classAdvic... | Returns list of advices from advisor and point filter | [
"Returns",
"list",
"of",
"advices",
"from",
"advisor",
"and",
"point",
"filter"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AdviceMatcher.php#L117-L168 |
goaop/framework | src/Core/AdviceMatcher.php | AdviceMatcher.getIntroductionFromAdvisor | private function getIntroductionFromAdvisor(
ReflectionClass $class,
Aop\IntroductionAdvisor $advisor,
string $advisorId
): array {
$classAdvices = [];
// Do not make introduction for traits
if ($class->isTrait()) {
return $classAdvices;
}
/** @var Aop\IntroductionInfo $introduction */
$introduction = $advisor->getAdvice();
$introducedTrait = $introduction->getTrait();
if (!empty($introducedTrait)) {
$introducedTrait = '\\' . ltrim($introducedTrait, '\\');
$classAdvices[AspectContainer::INTRODUCTION_TRAIT_PREFIX][$advisorId] = $introducedTrait;
}
$introducedInterface = $introduction->getInterface();
if (!empty($introducedInterface)) {
$introducedInterface = '\\' . ltrim($introducedInterface, '\\');
$classAdvices[AspectContainer::INTRODUCTION_INTERFACE_PREFIX][$advisorId] = $introducedInterface;
}
return $classAdvices;
} | php | private function getIntroductionFromAdvisor(
ReflectionClass $class,
Aop\IntroductionAdvisor $advisor,
string $advisorId
): array {
$classAdvices = [];
// Do not make introduction for traits
if ($class->isTrait()) {
return $classAdvices;
}
/** @var Aop\IntroductionInfo $introduction */
$introduction = $advisor->getAdvice();
$introducedTrait = $introduction->getTrait();
if (!empty($introducedTrait)) {
$introducedTrait = '\\' . ltrim($introducedTrait, '\\');
$classAdvices[AspectContainer::INTRODUCTION_TRAIT_PREFIX][$advisorId] = $introducedTrait;
}
$introducedInterface = $introduction->getInterface();
if (!empty($introducedInterface)) {
$introducedInterface = '\\' . ltrim($introducedInterface, '\\');
$classAdvices[AspectContainer::INTRODUCTION_INTERFACE_PREFIX][$advisorId] = $introducedInterface;
}
return $classAdvices;
} | [
"private",
"function",
"getIntroductionFromAdvisor",
"(",
"ReflectionClass",
"$",
"class",
",",
"Aop",
"\\",
"IntroductionAdvisor",
"$",
"advisor",
",",
"string",
"$",
"advisorId",
")",
":",
"array",
"{",
"$",
"classAdvices",
"=",
"[",
"]",
";",
"// Do not make ... | Returns list of introduction advices from advisor | [
"Returns",
"list",
"of",
"introduction",
"advices",
"from",
"advisor"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AdviceMatcher.php#L173-L200 |
goaop/framework | src/Core/AdviceMatcher.php | AdviceMatcher.getFunctionAdvicesFromAdvisor | private function getFunctionAdvicesFromAdvisor(
ReflectionFileNamespace $namespace,
Aop\PointcutAdvisor $advisor,
string $advisorId,
Aop\PointFilter $pointcut
): array {
$functions = [];
$advices = [];
$listOfGlobalFunctions = get_defined_functions();
foreach ($listOfGlobalFunctions['internal'] as $functionName) {
$functions[$functionName] = new NamespacedReflectionFunction($functionName, $namespace->getName());
}
foreach ($functions as $functionName => $function) {
if ($pointcut->matches($function, $namespace)) {
$advices[AspectContainer::FUNCTION_PREFIX][$functionName][$advisorId] = $advisor->getAdvice();
}
}
return $advices;
} | php | private function getFunctionAdvicesFromAdvisor(
ReflectionFileNamespace $namespace,
Aop\PointcutAdvisor $advisor,
string $advisorId,
Aop\PointFilter $pointcut
): array {
$functions = [];
$advices = [];
$listOfGlobalFunctions = get_defined_functions();
foreach ($listOfGlobalFunctions['internal'] as $functionName) {
$functions[$functionName] = new NamespacedReflectionFunction($functionName, $namespace->getName());
}
foreach ($functions as $functionName => $function) {
if ($pointcut->matches($function, $namespace)) {
$advices[AspectContainer::FUNCTION_PREFIX][$functionName][$advisorId] = $advisor->getAdvice();
}
}
return $advices;
} | [
"private",
"function",
"getFunctionAdvicesFromAdvisor",
"(",
"ReflectionFileNamespace",
"$",
"namespace",
",",
"Aop",
"\\",
"PointcutAdvisor",
"$",
"advisor",
",",
"string",
"$",
"advisorId",
",",
"Aop",
"\\",
"PointFilter",
"$",
"pointcut",
")",
":",
"array",
"{"... | Returns list of function advices for specific namespace | [
"Returns",
"list",
"of",
"function",
"advices",
"for",
"specific",
"namespace"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Core/AdviceMatcher.php#L205-L226 |
goaop/framework | src/Instrument/ClassLoading/AopComposerLoader.php | AopComposerLoader.init | public static function init(array $options, AspectContainer $container): bool
{
$loaders = spl_autoload_functions();
foreach ($loaders as &$loader) {
$loaderToUnregister = $loader;
if (is_array($loader) && ($loader[0] instanceof ClassLoader)) {
$originalLoader = $loader[0];
// Configure library loader for doctrine annotation loader
AnnotationRegistry::registerLoader(function($class) use ($originalLoader) {
$originalLoader->loadClass($class);
return class_exists($class, false);
});
$loader[0] = new AopComposerLoader($loader[0], $container, $options);
self::$wasInitialized = true;
}
spl_autoload_unregister($loaderToUnregister);
}
unset($loader);
foreach ($loaders as $loader) {
spl_autoload_register($loader);
}
return self::$wasInitialized;
} | php | public static function init(array $options, AspectContainer $container): bool
{
$loaders = spl_autoload_functions();
foreach ($loaders as &$loader) {
$loaderToUnregister = $loader;
if (is_array($loader) && ($loader[0] instanceof ClassLoader)) {
$originalLoader = $loader[0];
// Configure library loader for doctrine annotation loader
AnnotationRegistry::registerLoader(function($class) use ($originalLoader) {
$originalLoader->loadClass($class);
return class_exists($class, false);
});
$loader[0] = new AopComposerLoader($loader[0], $container, $options);
self::$wasInitialized = true;
}
spl_autoload_unregister($loaderToUnregister);
}
unset($loader);
foreach ($loaders as $loader) {
spl_autoload_register($loader);
}
return self::$wasInitialized;
} | [
"public",
"static",
"function",
"init",
"(",
"array",
"$",
"options",
",",
"AspectContainer",
"$",
"container",
")",
":",
"bool",
"{",
"$",
"loaders",
"=",
"spl_autoload_functions",
"(",
")",
";",
"foreach",
"(",
"$",
"loaders",
"as",
"&",
"$",
"loader",
... | Initialize aspect autoloader and returns status whether initialization was successful or not
Replaces original composer autoloader with wrapper
@param array $options Aspect kernel options | [
"Initialize",
"aspect",
"autoloader",
"and",
"returns",
"status",
"whether",
"initialization",
"was",
"successful",
"or",
"not"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/ClassLoading/AopComposerLoader.php#L88-L114 |
goaop/framework | src/Instrument/ClassLoading/AopComposerLoader.php | AopComposerLoader.findFile | public function findFile(string $class)
{
static $isAllowedFilter = null, $isProduction = false;
if (!$isAllowedFilter) {
$isAllowedFilter = $this->fileEnumerator->getFilter();
$isProduction = !$this->options['debug'];
}
$file = $this->original->findFile($class);
if ($file !== false) {
$file = PathResolver::realpath($file)?:$file;
$cacheState = $this->cacheState[$file] ?? null;
if ($cacheState && $isProduction) {
$file = $cacheState['cacheUri'] ?: $file;
} elseif ($isAllowedFilter(new \SplFileInfo($file))) {
// can be optimized here with $cacheState even for debug mode, but no needed right now
$file = FilterInjectorTransformer::rewrite($file);
}
}
return $file;
} | php | public function findFile(string $class)
{
static $isAllowedFilter = null, $isProduction = false;
if (!$isAllowedFilter) {
$isAllowedFilter = $this->fileEnumerator->getFilter();
$isProduction = !$this->options['debug'];
}
$file = $this->original->findFile($class);
if ($file !== false) {
$file = PathResolver::realpath($file)?:$file;
$cacheState = $this->cacheState[$file] ?? null;
if ($cacheState && $isProduction) {
$file = $cacheState['cacheUri'] ?: $file;
} elseif ($isAllowedFilter(new \SplFileInfo($file))) {
// can be optimized here with $cacheState even for debug mode, but no needed right now
$file = FilterInjectorTransformer::rewrite($file);
}
}
return $file;
} | [
"public",
"function",
"findFile",
"(",
"string",
"$",
"class",
")",
"{",
"static",
"$",
"isAllowedFilter",
"=",
"null",
",",
"$",
"isProduction",
"=",
"false",
";",
"if",
"(",
"!",
"$",
"isAllowedFilter",
")",
"{",
"$",
"isAllowedFilter",
"=",
"$",
"this... | Finds either the path to the file where the class is defined,
or gets the appropriate php://filter stream for the given class.
@return string|false The path/resource if found, false otherwise. | [
"Finds",
"either",
"the",
"path",
"to",
"the",
"file",
"where",
"the",
"class",
"is",
"defined",
"or",
"gets",
"the",
"appropriate",
"php",
":",
"//",
"filter",
"stream",
"for",
"the",
"given",
"class",
"."
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/ClassLoading/AopComposerLoader.php#L134-L156 |
goaop/framework | src/Aop/Framework/StaticClosureMethodInvocation.php | StaticClosureMethodInvocation.proceed | public function proceed()
{
if (isset($this->advices[$this->current])) {
$currentInterceptor = $this->advices[$this->current++];
return $currentInterceptor->invoke($this);
}
// Rebind the closure if scope (class name) was changed since last time
if ($this->previousScope !== $this->instance) {
if ($this->closureToCall === null) {
$this->closureToCall = static::getStaticInvoker($this->className, $this->reflectionMethod->name);
}
$this->closureToCall = $this->closureToCall->bindTo(null, $this->instance);
$this->previousScope = $this->instance;
}
return ($this->closureToCall)($this->arguments);
} | php | public function proceed()
{
if (isset($this->advices[$this->current])) {
$currentInterceptor = $this->advices[$this->current++];
return $currentInterceptor->invoke($this);
}
// Rebind the closure if scope (class name) was changed since last time
if ($this->previousScope !== $this->instance) {
if ($this->closureToCall === null) {
$this->closureToCall = static::getStaticInvoker($this->className, $this->reflectionMethod->name);
}
$this->closureToCall = $this->closureToCall->bindTo(null, $this->instance);
$this->previousScope = $this->instance;
}
return ($this->closureToCall)($this->arguments);
} | [
"public",
"function",
"proceed",
"(",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"advices",
"[",
"$",
"this",
"->",
"current",
"]",
")",
")",
"{",
"$",
"currentInterceptor",
"=",
"$",
"this",
"->",
"advices",
"[",
"$",
"this",
"->",
"cur... | Proceeds all registered advices for the static method and returns an invocation result | [
"Proceeds",
"all",
"registered",
"advices",
"for",
"the",
"static",
"method",
"and",
"returns",
"an",
"invocation",
"result"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Framework/StaticClosureMethodInvocation.php#L38-L57 |
goaop/framework | src/Aop/Framework/StaticClosureMethodInvocation.php | StaticClosureMethodInvocation.getStaticInvoker | protected static function getStaticInvoker(string $className, string $methodName): Closure
{
return function (array $args) use ($className, $methodName) {
return forward_static_call_array([$className, $methodName], $args);
};
} | php | protected static function getStaticInvoker(string $className, string $methodName): Closure
{
return function (array $args) use ($className, $methodName) {
return forward_static_call_array([$className, $methodName], $args);
};
} | [
"protected",
"static",
"function",
"getStaticInvoker",
"(",
"string",
"$",
"className",
",",
"string",
"$",
"methodName",
")",
":",
"Closure",
"{",
"return",
"function",
"(",
"array",
"$",
"args",
")",
"use",
"(",
"$",
"className",
",",
"$",
"methodName",
... | Returns static method invoker for the concrete method in the class | [
"Returns",
"static",
"method",
"invoker",
"for",
"the",
"concrete",
"method",
"in",
"the",
"class"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Framework/StaticClosureMethodInvocation.php#L62-L67 |
goaop/framework | src/Aop/Support/AndPointFilter.php | AndPointFilter.matches | public function matches($point, $context = null, $instance = null, array $arguments = null): bool
{
foreach ($this->filters as $filter) {
if (!$filter->matches($point, $context)) {
return false;
}
}
return true;
} | php | public function matches($point, $context = null, $instance = null, array $arguments = null): bool
{
foreach ($this->filters as $filter) {
if (!$filter->matches($point, $context)) {
return false;
}
}
return true;
} | [
"public",
"function",
"matches",
"(",
"$",
"point",
",",
"$",
"context",
"=",
"null",
",",
"$",
"instance",
"=",
"null",
",",
"array",
"$",
"arguments",
"=",
"null",
")",
":",
"bool",
"{",
"foreach",
"(",
"$",
"this",
"->",
"filters",
"as",
"$",
"f... | Performs matching of point of code
@param mixed $point Specific part of code, can be any Reflection class
@param null|mixed $context Related context, can be class or namespace
@param null|string|object $instance Invocation instance or string for static calls
@param null|array $arguments Dynamic arguments for method | [
"Performs",
"matching",
"of",
"point",
"of",
"code"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Support/AndPointFilter.php#L50-L59 |
goaop/framework | src/Aop/Pointcut/AndPointcut.php | AndPointcut.matchPart | protected function matchPart(
Pointcut $pointcut,
$point,
$context = null,
$instance = null,
array $arguments = null
): bool {
return $pointcut->matches($point, $context, $instance, $arguments)
&& $pointcut->getClassFilter()->matches($context);
} | php | protected function matchPart(
Pointcut $pointcut,
$point,
$context = null,
$instance = null,
array $arguments = null
): bool {
return $pointcut->matches($point, $context, $instance, $arguments)
&& $pointcut->getClassFilter()->matches($context);
} | [
"protected",
"function",
"matchPart",
"(",
"Pointcut",
"$",
"pointcut",
",",
"$",
"point",
",",
"$",
"context",
"=",
"null",
",",
"$",
"instance",
"=",
"null",
",",
"array",
"$",
"arguments",
"=",
"null",
")",
":",
"bool",
"{",
"return",
"$",
"pointcut... | Checks if point filter matches the point
@param Pointcut $pointcut
@param \ReflectionMethod|\ReflectionProperty $point
@param mixed $context Related context, can be class or namespace
@param object|string|null $instance [Optional] Instance for dynamic matching
@param array $arguments [Optional] Extra arguments for dynamic matching
@return bool | [
"Checks",
"if",
"point",
"filter",
"matches",
"the",
"point"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Pointcut/AndPointcut.php#L84-L93 |
goaop/framework | src/Instrument/Transformer/ConstructorExecutionTransformer.php | ConstructorExecutionTransformer.transform | public function transform(StreamMetaData $metadata): string
{
$newExpressionFinder = new NodeFinderVisitor([Node\Expr\New_::class]);
// TODO: move this logic into walkSyntaxTree(Visitor $nodeVistor) method
$traverser = new NodeTraverser();
$traverser->addVisitor($newExpressionFinder);
$traverser->traverse($metadata->syntaxTree);
/** @var Node\Expr\New_[] $newExpressions */
$newExpressions = $newExpressionFinder->getFoundNodes();
if (empty($newExpressions)) {
return self::RESULT_ABSTAIN;
}
foreach ($newExpressions as $newExpressionNode) {
$startPosition = $newExpressionNode->getAttribute('startTokenPos');
$metadata->tokenStream[$startPosition][1] = '\\' . __CLASS__ . '::getInstance()->{';
if ($metadata->tokenStream[$startPosition+1][0] === T_WHITESPACE) {
unset($metadata->tokenStream[$startPosition+1]);
}
$isExplicitClass = $newExpressionNode->class instanceof Node\Name;
$endClassNamePos = $newExpressionNode->class->getAttribute('endTokenPos');
$expressionSuffix = $isExplicitClass ? '::class}' : '}';
$metadata->tokenStream[$endClassNamePos][1] .= $expressionSuffix;
}
return self::RESULT_TRANSFORMED;
} | php | public function transform(StreamMetaData $metadata): string
{
$newExpressionFinder = new NodeFinderVisitor([Node\Expr\New_::class]);
// TODO: move this logic into walkSyntaxTree(Visitor $nodeVistor) method
$traverser = new NodeTraverser();
$traverser->addVisitor($newExpressionFinder);
$traverser->traverse($metadata->syntaxTree);
/** @var Node\Expr\New_[] $newExpressions */
$newExpressions = $newExpressionFinder->getFoundNodes();
if (empty($newExpressions)) {
return self::RESULT_ABSTAIN;
}
foreach ($newExpressions as $newExpressionNode) {
$startPosition = $newExpressionNode->getAttribute('startTokenPos');
$metadata->tokenStream[$startPosition][1] = '\\' . __CLASS__ . '::getInstance()->{';
if ($metadata->tokenStream[$startPosition+1][0] === T_WHITESPACE) {
unset($metadata->tokenStream[$startPosition+1]);
}
$isExplicitClass = $newExpressionNode->class instanceof Node\Name;
$endClassNamePos = $newExpressionNode->class->getAttribute('endTokenPos');
$expressionSuffix = $isExplicitClass ? '::class}' : '}';
$metadata->tokenStream[$endClassNamePos][1] .= $expressionSuffix;
}
return self::RESULT_TRANSFORMED;
} | [
"public",
"function",
"transform",
"(",
"StreamMetaData",
"$",
"metadata",
")",
":",
"string",
"{",
"$",
"newExpressionFinder",
"=",
"new",
"NodeFinderVisitor",
"(",
"[",
"Node",
"\\",
"Expr",
"\\",
"New_",
"::",
"class",
"]",
")",
";",
"// TODO: move this log... | Rewrites all "new" expressions with our implementation
@return string See RESULT_XXX constants in the interface | [
"Rewrites",
"all",
"new",
"expressions",
"with",
"our",
"implementation"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/ConstructorExecutionTransformer.php#L52-L82 |
goaop/framework | src/Instrument/Transformer/ConstructorExecutionTransformer.php | ConstructorExecutionTransformer.construct | protected static function construct(string $fullClassName, array $arguments = []): object
{
$fullClassName = ltrim($fullClassName, '\\');
if (!isset(self::$constructorInvocationsCache[$fullClassName])) {
$invocation = null;
$dynamicInit = AspectContainer::INIT_PREFIX . ':root';
try {
$joinPointsRef = new \ReflectionProperty($fullClassName, '__joinPoints');
$joinPointsRef->setAccessible(true);
$joinPoints = $joinPointsRef->getValue();
if (isset($joinPoints[$dynamicInit])) {
$invocation = $joinPoints[$dynamicInit];
}
} catch (\ReflectionException $e) {
$invocation = null;
}
if (!$invocation) {
$invocation = new ReflectionConstructorInvocation($fullClassName, 'root', []);
}
self::$constructorInvocationsCache[$fullClassName] = $invocation;
}
return self::$constructorInvocationsCache[$fullClassName]->__invoke($arguments);
} | php | protected static function construct(string $fullClassName, array $arguments = []): object
{
$fullClassName = ltrim($fullClassName, '\\');
if (!isset(self::$constructorInvocationsCache[$fullClassName])) {
$invocation = null;
$dynamicInit = AspectContainer::INIT_PREFIX . ':root';
try {
$joinPointsRef = new \ReflectionProperty($fullClassName, '__joinPoints');
$joinPointsRef->setAccessible(true);
$joinPoints = $joinPointsRef->getValue();
if (isset($joinPoints[$dynamicInit])) {
$invocation = $joinPoints[$dynamicInit];
}
} catch (\ReflectionException $e) {
$invocation = null;
}
if (!$invocation) {
$invocation = new ReflectionConstructorInvocation($fullClassName, 'root', []);
}
self::$constructorInvocationsCache[$fullClassName] = $invocation;
}
return self::$constructorInvocationsCache[$fullClassName]->__invoke($arguments);
} | [
"protected",
"static",
"function",
"construct",
"(",
"string",
"$",
"fullClassName",
",",
"array",
"$",
"arguments",
"=",
"[",
"]",
")",
":",
"object",
"{",
"$",
"fullClassName",
"=",
"ltrim",
"(",
"$",
"fullClassName",
",",
"'\\\\'",
")",
";",
"if",
"("... | Default implementation for accessing joinpoint or creating a new one on-fly | [
"Default",
"implementation",
"for",
"accessing",
"joinpoint",
"or",
"creating",
"a",
"new",
"one",
"on",
"-",
"fly"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Instrument/Transformer/ConstructorExecutionTransformer.php#L108-L131 |
goaop/framework | src/Console/Command/DebugAspectCommand.php | DebugAspectCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->loadAspectKernel($input, $output);
$io = new SymfonyStyle($input, $output);
$container = $this->aspectKernel->getContainer();
$aspects = [];
$io->title('Aspect debug information');
$aspectName = $input->getOption('aspect');
if (!$aspectName) {
$io->text('<info>' . get_class($this->aspectKernel) . '</info> has following enabled aspects:');
$aspects = $container->getByTag('aspect');
} else {
$aspect = $container->getAspect($aspectName);
$aspects[] = $aspect;
}
$this->showRegisteredAspectsInfo($io, $aspects);
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->loadAspectKernel($input, $output);
$io = new SymfonyStyle($input, $output);
$container = $this->aspectKernel->getContainer();
$aspects = [];
$io->title('Aspect debug information');
$aspectName = $input->getOption('aspect');
if (!$aspectName) {
$io->text('<info>' . get_class($this->aspectKernel) . '</info> has following enabled aspects:');
$aspects = $container->getByTag('aspect');
} else {
$aspect = $container->getAspect($aspectName);
$aspects[] = $aspect;
}
$this->showRegisteredAspectsInfo($io, $aspects);
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"loadAspectKernel",
"(",
"$",
"input",
",",
"$",
"output",
")",
";",
"$",
"io",
"=",
"new",
"SymfonyStyle",
"(",
... | {@inheritDoc} | [
"{"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Console/Command/DebugAspectCommand.php#L50-L69 |
goaop/framework | src/Console/Command/DebugAspectCommand.php | DebugAspectCommand.showRegisteredAspectsInfo | private function showRegisteredAspectsInfo(SymfonyStyle $io, array $aspects): void
{
foreach ($aspects as $aspect) {
$this->showAspectInfo($io, $aspect);
}
} | php | private function showRegisteredAspectsInfo(SymfonyStyle $io, array $aspects): void
{
foreach ($aspects as $aspect) {
$this->showAspectInfo($io, $aspect);
}
} | [
"private",
"function",
"showRegisteredAspectsInfo",
"(",
"SymfonyStyle",
"$",
"io",
",",
"array",
"$",
"aspects",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"aspects",
"as",
"$",
"aspect",
")",
"{",
"$",
"this",
"->",
"showAspectInfo",
"(",
"$",
"io",
"... | Shows an information about registered aspects
@param Aspect[] $aspects List of aspects | [
"Shows",
"an",
"information",
"about",
"registered",
"aspects"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Console/Command/DebugAspectCommand.php#L76-L81 |
goaop/framework | src/Console/Command/DebugAspectCommand.php | DebugAspectCommand.showAspectInfo | private function showAspectInfo(SymfonyStyle $io, Aspect $aspect): void
{
$refAspect = new ReflectionObject($aspect);
$aspectName = $refAspect->getName();
$io->section($aspectName);
$io->writeln('Defined in: <info>' . $refAspect->getFileName() . '</info>');
$docComment = $refAspect->getDocComment();
if ($docComment) {
$io->writeln($this->getPrettyText($docComment));
}
$this->showAspectPointcutsAndAdvisors($io, $aspect);
} | php | private function showAspectInfo(SymfonyStyle $io, Aspect $aspect): void
{
$refAspect = new ReflectionObject($aspect);
$aspectName = $refAspect->getName();
$io->section($aspectName);
$io->writeln('Defined in: <info>' . $refAspect->getFileName() . '</info>');
$docComment = $refAspect->getDocComment();
if ($docComment) {
$io->writeln($this->getPrettyText($docComment));
}
$this->showAspectPointcutsAndAdvisors($io, $aspect);
} | [
"private",
"function",
"showAspectInfo",
"(",
"SymfonyStyle",
"$",
"io",
",",
"Aspect",
"$",
"aspect",
")",
":",
"void",
"{",
"$",
"refAspect",
"=",
"new",
"ReflectionObject",
"(",
"$",
"aspect",
")",
";",
"$",
"aspectName",
"=",
"$",
"refAspect",
"->",
... | Displays an information about single aspect | [
"Displays",
"an",
"information",
"about",
"single",
"aspect"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Console/Command/DebugAspectCommand.php#L86-L97 |
goaop/framework | src/Console/Command/DebugAspectCommand.php | DebugAspectCommand.showAspectPointcutsAndAdvisors | private function showAspectPointcutsAndAdvisors(SymfonyStyle $io, Aspect $aspect): void
{
/** @var AspectLoader $aspectLoader */
$container = $this->aspectKernel->getContainer();
$aspectLoader = $container->get('aspect.loader');
$io->writeln('<comment>Pointcuts and advices</comment>');
$aspectItems = $aspectLoader->load($aspect);
$aspectItemsInfo = [];
foreach ($aspectItems as $itemId => $item) {
$itemType = 'Unknown';
if ($item instanceof Pointcut) {
$itemType = 'Pointcut';
}
if ($item instanceof Advisor) {
$itemType = 'Advisor';
}
$aspectItemsInfo[] = [$itemType, $itemId];
}
$io->table(['Type', 'Identifier'], $aspectItemsInfo);
} | php | private function showAspectPointcutsAndAdvisors(SymfonyStyle $io, Aspect $aspect): void
{
/** @var AspectLoader $aspectLoader */
$container = $this->aspectKernel->getContainer();
$aspectLoader = $container->get('aspect.loader');
$io->writeln('<comment>Pointcuts and advices</comment>');
$aspectItems = $aspectLoader->load($aspect);
$aspectItemsInfo = [];
foreach ($aspectItems as $itemId => $item) {
$itemType = 'Unknown';
if ($item instanceof Pointcut) {
$itemType = 'Pointcut';
}
if ($item instanceof Advisor) {
$itemType = 'Advisor';
}
$aspectItemsInfo[] = [$itemType, $itemId];
}
$io->table(['Type', 'Identifier'], $aspectItemsInfo);
} | [
"private",
"function",
"showAspectPointcutsAndAdvisors",
"(",
"SymfonyStyle",
"$",
"io",
",",
"Aspect",
"$",
"aspect",
")",
":",
"void",
"{",
"/** @var AspectLoader $aspectLoader */",
"$",
"container",
"=",
"$",
"this",
"->",
"aspectKernel",
"->",
"getContainer",
"(... | Shows an information about aspect pointcuts and advisors | [
"Shows",
"an",
"information",
"about",
"aspect",
"pointcuts",
"and",
"advisors"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Console/Command/DebugAspectCommand.php#L102-L122 |
goaop/framework | src/Console/Command/DebugAdvisorCommand.php | DebugAdvisorCommand.execute | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->loadAspectKernel($input, $output);
$io = new SymfonyStyle($input, $output);
$io->title('Advisor debug information');
$advisorId = $input->getOption('advisor');
if (!$advisorId) {
$this->showAdvisorsList($io);
} else {
$this->showAdvisorInformation($io, $advisorId);
}
} | php | protected function execute(InputInterface $input, OutputInterface $output)
{
$this->loadAspectKernel($input, $output);
$io = new SymfonyStyle($input, $output);
$io->title('Advisor debug information');
$advisorId = $input->getOption('advisor');
if (!$advisorId) {
$this->showAdvisorsList($io);
} else {
$this->showAdvisorInformation($io, $advisorId);
}
} | [
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"this",
"->",
"loadAspectKernel",
"(",
"$",
"input",
",",
"$",
"output",
")",
";",
"$",
"io",
"=",
"new",
"SymfonyStyle",
"(",
... | {@inheritDoc} | [
"{"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Console/Command/DebugAdvisorCommand.php#L54-L67 |
goaop/framework | src/Console/Command/DebugAdvisorCommand.php | DebugAdvisorCommand.loadAdvisorsList | private function loadAdvisorsList(AspectContainer $aspectContainer): array
{
/** @var AspectLoader $aspectLoader */
$aspectLoader = $aspectContainer->get('aspect.cached.loader');
$aspects = $aspectLoader->getUnloadedAspects();
foreach ($aspects as $aspect) {
$aspectLoader->loadAndRegister($aspect);
}
$advisors = $aspectContainer->getByTag('advisor');
return $advisors;
} | php | private function loadAdvisorsList(AspectContainer $aspectContainer): array
{
/** @var AspectLoader $aspectLoader */
$aspectLoader = $aspectContainer->get('aspect.cached.loader');
$aspects = $aspectLoader->getUnloadedAspects();
foreach ($aspects as $aspect) {
$aspectLoader->loadAndRegister($aspect);
}
$advisors = $aspectContainer->getByTag('advisor');
return $advisors;
} | [
"private",
"function",
"loadAdvisorsList",
"(",
"AspectContainer",
"$",
"aspectContainer",
")",
":",
"array",
"{",
"/** @var AspectLoader $aspectLoader */",
"$",
"aspectLoader",
"=",
"$",
"aspectContainer",
"->",
"get",
"(",
"'aspect.cached.loader'",
")",
";",
"$",
"a... | Collects list of advisors from the given aspect container
@return Advisor[] List of advisors in the container | [
"Collects",
"list",
"of",
"advisors",
"from",
"the",
"given",
"aspect",
"container"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Console/Command/DebugAdvisorCommand.php#L145-L156 |
goaop/framework | src/Aop/Framework/AbstractInterceptor.php | AbstractInterceptor.serializeAdvice | public static function serializeAdvice(Closure $adviceMethod): array
{
$refAdvice = new ReflectionFunction($adviceMethod);
return [
'method' => $refAdvice->name,
'class' => $refAdvice->getClosureScopeClass()->name
];
} | php | public static function serializeAdvice(Closure $adviceMethod): array
{
$refAdvice = new ReflectionFunction($adviceMethod);
return [
'method' => $refAdvice->name,
'class' => $refAdvice->getClosureScopeClass()->name
];
} | [
"public",
"static",
"function",
"serializeAdvice",
"(",
"Closure",
"$",
"adviceMethod",
")",
":",
"array",
"{",
"$",
"refAdvice",
"=",
"new",
"ReflectionFunction",
"(",
"$",
"adviceMethod",
")",
";",
"return",
"[",
"'method'",
"=>",
"$",
"refAdvice",
"->",
"... | Serialize advice method into array | [
"Serialize",
"advice",
"method",
"into",
"array"
] | train | https://github.com/goaop/framework/blob/f75d99479da94489384c9e99ad642294031263d9/src/Aop/Framework/AbstractInterceptor.php#L83-L91 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.